[linked-list] range-based for loop iteration over all entries (#6945)

This commit enables use of range-based `for` loop for iterating over
all the entries in a `LinkedList`. It adds private implementations of
`Iterator` and `ConstIterator` which inherit from `ItemPtrIterator`
and use the `GetNext()` to go to the next entry. The range-based
`for` loop practically acts as a syntactic sugar helping simplify the
code and does not add any code size (or any expected run-time)
overhead.
This commit is contained in:
Abtin Keshavarzian
2021-08-23 14:50:14 -07:00
committed by GitHub
parent 34366834b0
commit 6895edda59
21 changed files with 241 additions and 197 deletions
+2 -2
View File
@@ -79,7 +79,7 @@ const otNetifAddress *otIp6GetUnicastAddresses(otInstance *aInstance)
{
Instance &instance = *static_cast<Instance *>(aInstance);
return instance.Get<ThreadNetif>().GetUnicastAddresses();
return instance.Get<ThreadNetif>().GetUnicastAddresses().GetHead();
}
otError otIp6AddUnicastAddress(otInstance *aInstance, const otNetifAddress *aAddress)
@@ -101,7 +101,7 @@ const otNetifMulticastAddress *otIp6GetMulticastAddresses(otInstance *aInstance)
{
Instance &instance = *static_cast<Instance *>(aInstance);
return instance.Get<ThreadNetif>().GetMulticastAddresses();
return instance.Get<ThreadNetif>().GetMulticastAddresses().GetHead();
}
otError otIp6SubscribeMulticastAddress(otInstance *aInstance, const otIp6Address *aAddress)
+12 -12
View File
@@ -1319,24 +1319,24 @@ void CoapBase::ProcessReceivedRequest(Message &aMessage, const Ip6::MessageInfo
curUriPath[0] = '\0';
for (const ResourceBlockWise *resource = mBlockWiseResources.GetHead(); resource; resource = resource->GetNext())
for (const ResourceBlockWise &resource : mBlockWiseResources)
{
if (strcmp(resource->GetUriPath(), uriPath) != 0)
if (strcmp(resource.GetUriPath(), uriPath) != 0)
{
continue;
}
if ((resource->mReceiveHook != nullptr || resource->mTransmitHook != nullptr) && blockOptionType != 0)
if ((resource.mReceiveHook != nullptr || resource.mTransmitHook != nullptr) && blockOptionType != 0)
{
switch (blockOptionType)
{
case 1:
if (resource->mReceiveHook != nullptr)
if (resource.mReceiveHook != nullptr)
{
switch (ProcessBlock1Request(aMessage, aMessageInfo, *resource, totalTransfereSize))
switch (ProcessBlock1Request(aMessage, aMessageInfo, resource, totalTransfereSize))
{
case kErrorNone:
resource->HandleRequest(aMessage, aMessageInfo);
resource.HandleRequest(aMessage, aMessageInfo);
// Fall through
case kErrorBusy:
error = kErrorNone;
@@ -1357,9 +1357,9 @@ void CoapBase::ProcessReceivedRequest(Message &aMessage, const Ip6::MessageInfo
}
break;
case 2:
if (resource->mTransmitHook != nullptr)
if (resource.mTransmitHook != nullptr)
{
if ((error = ProcessBlock2Request(aMessage, aMessageInfo, *resource)) != kErrorNone)
if ((error = ProcessBlock2Request(aMessage, aMessageInfo, resource)) != kErrorNone)
{
IgnoreReturnValue(SendHeaderResponse(kCodeInternalError, aMessage, aMessageInfo));
error = kErrorDrop;
@@ -1371,7 +1371,7 @@ void CoapBase::ProcessReceivedRequest(Message &aMessage, const Ip6::MessageInfo
}
else
{
resource->HandleRequest(aMessage, aMessageInfo);
resource.HandleRequest(aMessage, aMessageInfo);
error = kErrorNone;
ExitNow();
}
@@ -1380,11 +1380,11 @@ void CoapBase::ProcessReceivedRequest(Message &aMessage, const Ip6::MessageInfo
SuccessOrExit(error = aMessage.ReadUriPathOptions(uriPath));
#endif // OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE
for (const Resource *resource = mResources.GetHead(); resource; resource = resource->GetNext())
for (const Resource &resource : mResources)
{
if (strcmp(resource->mUriPath, uriPath) == 0)
if (strcmp(resource.mUriPath, uriPath) == 0)
{
resource->HandleRequest(aMessage, aMessageInfo);
resource.HandleRequest(aMessage, aMessageInfo);
error = kErrorNone;
ExitNow();
}
+2 -2
View File
@@ -61,7 +61,7 @@ namespace ot {
* would set the pointer to `nullptr` when there's no more elements.
*
*/
template <class ItemType, class IteratorType> class ItemPtrIterator
template <typename ItemType, typename IteratorType> class ItemPtrIterator
{
public:
/**
@@ -148,7 +148,7 @@ protected:
}
/**
* Contructor with an Item pointer.
* Constructor with an Item pointer.
*
*/
explicit ItemPtrIterator(ItemType *item)
+44
View File
@@ -39,6 +39,7 @@
#include <stdio.h>
#include "common/error.hpp"
#include "common/iterator_utils.hpp"
namespace ot {
@@ -101,6 +102,9 @@ public:
*/
template <typename Type> class LinkedList
{
class Iterator;
class ConstIterator;
public:
/**
* This constructor initializes the linked list.
@@ -573,7 +577,47 @@ public:
*/
Type *GetTail(void) { return const_cast<Type *>(const_cast<const LinkedList *>(this)->GetTail()); }
// The following methods are intended to support range-based `for`
// loop iteration over the linked-list entries and should not be
// used directly.
Iterator begin(void) { return Iterator(GetHead()); }
Iterator end(void) { return Iterator(nullptr); }
ConstIterator begin(void) const { return ConstIterator(GetHead()); }
ConstIterator end(void) const { return ConstIterator(nullptr); }
private:
class Iterator : public ItemPtrIterator<Type, Iterator>
{
friend class LinkedList;
friend class ItemPtrIterator<Type, Iterator>;
using ItemPtrIterator<Type, Iterator>::mItem;
explicit Iterator(Type *aItem)
: ItemPtrIterator<Type, Iterator>(aItem)
{
}
void Advance(void) { mItem = mItem->GetNext(); }
};
class ConstIterator : public ItemPtrIterator<const Type, ConstIterator>
{
friend class LinkedList;
friend class ItemPtrIterator<const Type, ConstIterator>;
using ItemPtrIterator<const Type, ConstIterator>::mItem;
explicit ConstIterator(const Type *aItem)
: ItemPtrIterator<const Type, ConstIterator>(aItem)
{
}
void Advance(void) { mItem = mItem->GetNext(); }
};
Type *mHead;
};
+4 -2
View File
@@ -119,12 +119,14 @@ void Timer::Scheduler::Add(Timer &aTimer, const AlarmApi &aAlarmApi)
Remove(aTimer, aAlarmApi);
for (Timer *cur = mTimerList.GetHead(); cur; prev = cur, cur = cur->GetNext())
for (Timer &cur : mTimerList)
{
if (aTimer.DoesFireBefore(*cur, now))
if (aTimer.DoesFireBefore(cur, now))
{
break;
}
prev = &cur;
}
if (prev == nullptr)
+2 -2
View File
@@ -139,9 +139,9 @@ Error Icmp::HandleMessage(Message &aMessage, MessageInfo &aMessageInfo)
aMessage.MoveOffset(sizeof(icmp6Header));
for (Handler *handler = mHandlers.GetHead(); handler; handler = handler->GetNext())
for (Handler &handler : mHandlers)
{
handler->HandleReceiveMessage(aMessage, aMessageInfo, icmp6Header);
handler.HandleReceiveMessage(aMessage, aMessageInfo, icmp6Header);
}
exit:
+18 -18
View File
@@ -1381,9 +1381,9 @@ const Netif::UnicastAddress *Ip6::SelectSourceAddress(MessageInfo &aMessageInfo)
const Netif::UnicastAddress *rvalAddr = nullptr;
uint8_t rvalPrefixMatched = 0;
for (const Netif::UnicastAddress *addr = Get<ThreadNetif>().GetUnicastAddresses(); addr; addr = addr->GetNext())
for (const Netif::UnicastAddress &addr : Get<ThreadNetif>().GetUnicastAddresses())
{
const Address *candidateAddr = &addr->GetAddress();
const Address *candidateAddr = &addr.GetAddress();
uint8_t candidatePrefixMatched;
uint8_t overrideScope;
@@ -1395,10 +1395,10 @@ const Netif::UnicastAddress *Ip6::SelectSourceAddress(MessageInfo &aMessageInfo)
candidatePrefixMatched = destination->PrefixMatch(*candidateAddr);
if (candidatePrefixMatched >= addr->mPrefixLength)
if (candidatePrefixMatched >= addr.mPrefixLength)
{
candidatePrefixMatched = addr->mPrefixLength;
overrideScope = addr->GetScope();
candidatePrefixMatched = addr.mPrefixLength;
overrideScope = addr.GetScope();
}
else
{
@@ -1408,21 +1408,21 @@ const Netif::UnicastAddress *Ip6::SelectSourceAddress(MessageInfo &aMessageInfo)
if (rvalAddr == nullptr)
{
// Rule 0: Prefer any address
rvalAddr = addr;
rvalAddr = &addr;
rvalPrefixMatched = candidatePrefixMatched;
}
else if (*candidateAddr == *destination)
{
// Rule 1: Prefer same address
rvalAddr = addr;
rvalAddr = &addr;
ExitNow();
}
else if (addr->GetScope() < rvalAddr->GetScope())
else if (addr.GetScope() < rvalAddr->GetScope())
{
// Rule 2: Prefer appropriate scope
if (addr->GetScope() >= overrideScope)
if (addr.GetScope() >= overrideScope)
{
rvalAddr = addr;
rvalAddr = &addr;
rvalPrefixMatched = candidatePrefixMatched;
}
else
@@ -1430,11 +1430,11 @@ const Netif::UnicastAddress *Ip6::SelectSourceAddress(MessageInfo &aMessageInfo)
continue;
}
}
else if (addr->GetScope() > rvalAddr->GetScope())
else if (addr.GetScope() > rvalAddr->GetScope())
{
if (rvalAddr->GetScope() < overrideScope)
{
rvalAddr = addr;
rvalAddr = &addr;
rvalPrefixMatched = candidatePrefixMatched;
}
else
@@ -1442,10 +1442,10 @@ const Netif::UnicastAddress *Ip6::SelectSourceAddress(MessageInfo &aMessageInfo)
continue;
}
}
else if (addr->mPreferred && !rvalAddr->mPreferred)
else if (addr.mPreferred && !rvalAddr->mPreferred)
{
// Rule 3: Avoid deprecated addresses
rvalAddr = addr;
rvalAddr = &addr;
rvalPrefixMatched = candidatePrefixMatched;
}
else if (candidatePrefixMatched > rvalPrefixMatched)
@@ -1453,14 +1453,14 @@ const Netif::UnicastAddress *Ip6::SelectSourceAddress(MessageInfo &aMessageInfo)
// Rule 6: Prefer matching label
// Rule 7: Prefer public address
// Rule 8: Use longest prefix matching
rvalAddr = addr;
rvalAddr = &addr;
rvalPrefixMatched = candidatePrefixMatched;
}
else if ((candidatePrefixMatched == rvalPrefixMatched) &&
(destinationIsRoutingLocator == Get<Mle::Mle>().IsRoutingLocator(*candidateAddr)))
{
// Additional rule: Prefer RLOC source for RLOC destination, EID source for anything else
rvalAddr = addr;
rvalAddr = &addr;
rvalPrefixMatched = candidatePrefixMatched;
}
else
@@ -1488,9 +1488,9 @@ bool Ip6::IsOnLink(const Address &aAddress) const
ExitNow(rval = true);
}
for (const Netif::UnicastAddress *cur = Get<ThreadNetif>().GetUnicastAddresses(); cur; cur = cur->GetNext())
for (const Netif::UnicastAddress &cur : Get<ThreadNetif>().GetUnicastAddresses())
{
if (cur->GetAddress().PrefixMatch(aAddress) >= cur->mPrefixLength)
if (cur.GetAddress().PrefixMatch(aAddress) >= cur.mPrefixLength)
{
ExitNow(rval = true);
}
+1 -1
View File
@@ -589,7 +589,7 @@ Netif::ExternalMulticastAddress::Iterator::Iterator(const Netif &aNetif, Address
, mNetif(aNetif)
, mFilter(aFilter)
{
AdvanceFrom(mNetif.GetMulticastAddresses());
AdvanceFrom(mNetif.GetMulticastAddresses().GetHead());
}
void Netif::ExternalMulticastAddress::Iterator::AdvanceFrom(const MulticastAddress *aAddr)
+7 -7
View File
@@ -68,7 +68,7 @@ class Ip6;
* This class implements an IPv6 network interface.
*
*/
class Netif : public InstanceLocator, public LinkedListEntry<Netif>, private NonCopyable
class Netif : public InstanceLocator, private NonCopyable
{
friend class Ip6;
friend class Address;
@@ -342,12 +342,12 @@ public:
void SetAddressCallback(otIp6AddressCallback aCallback, void *aCallbackContext);
/**
* This method returns a pointer to the head of the linked list of unicast addresses.
* This method returns the linked list of unicast addresses.
*
* @returns A pointer to the head of the linked list of unicast addresses.
* @returns The linked list of unicast addresses.
*
*/
const UnicastAddress *GetUnicastAddresses(void) const { return mUnicastAddresses.GetHead(); }
const LinkedList<UnicastAddress> &GetUnicastAddresses(void) const { return mUnicastAddresses; }
/**
* This method adds a unicast address to the network interface.
@@ -469,12 +469,12 @@ public:
void UnsubscribeAllRoutersMulticast(void);
/**
* This method returns a pointer to the head of the linked list of multicast addresses.
* This method returns the linked list of multicast addresses.
*
* @returns A pointer to the head of the linked list of multicast addresses.
* @returns The linked list of multicast addresses.
*
*/
const MulticastAddress *GetMulticastAddresses(void) const { return mMulticastAddresses.GetHead(); }
const LinkedList<MulticastAddress> &GetMulticastAddresses(void) const { return mMulticastAddresses; }
/**
* This method indicates whether a multicast address is an external or internal address.
+15 -15
View File
@@ -518,9 +518,9 @@ Error Client::RemoveHostAndServices(bool aShouldRemoveKeyLease)
mShouldRemoveKeyLease = aShouldRemoveKeyLease;
for (Service *service = mServices.GetHead(); service != nullptr; service = service->GetNext())
for (Service &service : mServices)
{
UpdateServiceStateToRemove(*service);
UpdateServiceStateToRemove(service);
}
if (mHostInfo.GetState() == kToAdd)
@@ -602,9 +602,9 @@ void Client::ChangeHostAndServiceStates(const ItemState *aNewStates)
mHostInfo.SetState(aNewStates[mHostInfo.GetState()]);
for (Service *service = mServices.GetHead(); service != nullptr; service = service->GetNext())
for (Service &service : mServices)
{
service->SetState(aNewStates[service->GetState()]);
service.SetState(aNewStates[service.GetState()]);
}
#if OPENTHREAD_CONFIG_SRP_CLIENT_AUTO_START_API_ENABLE && OPENTHREAD_CONFIG_SRP_CLIENT_SAVE_SELECTED_SERVER_ENABLE
@@ -768,9 +768,9 @@ Error Client::PrepareUpdateMessage(Message &aMessage)
if (mHostInfo.GetState() != kToRemove)
{
for (Service *service = mServices.GetHead(); service != nullptr; service = service->GetNext())
for (Service &service : mServices)
{
SuccessOrExit(error = AppendServiceInstructions(*service, aMessage, info));
SuccessOrExit(error = AppendServiceInstructions(service, aMessage, info));
}
}
@@ -1310,11 +1310,11 @@ void Client::ProcessResponse(Message &aMessage)
mLeaseRenewTime += Time::SecToMsec(mAcceptedLeaseInterval) / 2;
}
for (Service *service = mServices.GetHead(); service != nullptr; service = service->GetNext())
for (Service &service : mServices)
{
if ((service->GetState() == kAdding) || (service->GetState() == kRefreshing))
if ((service.GetState() == kAdding) || (service.GetState() == kRefreshing))
{
service->SetLeaseRenewTime(mLeaseRenewTime);
service.SetLeaseRenewTime(mLeaseRenewTime);
}
}
@@ -1499,9 +1499,9 @@ void Client::UpdateState(void)
if (mHostInfo.GetState() != kRemoving)
{
for (Service *service = mServices.GetHead(); service != nullptr; service = service->GetNext())
for (Service &service : mServices)
{
switch (service->GetState())
switch (service.GetState())
{
case kToAdd:
case kToRefresh:
@@ -1510,14 +1510,14 @@ void Client::UpdateState(void)
break;
case kRegistered:
if (service->GetLeaseRenewTime() <= now)
if (service.GetLeaseRenewTime() <= now)
{
service->SetState(kToRefresh);
service.SetState(kToRefresh);
shouldUpdate = true;
}
else if (service->GetLeaseRenewTime() < earliestRenewTime)
else if (service.GetLeaseRenewTime() < earliestRenewTime)
{
earliestRenewTime = service->GetLeaseRenewTime();
earliestRenewTime = service.GetLeaseRenewTime();
}
break;
+39 -39
View File
@@ -272,18 +272,17 @@ bool Server::HasNameConflictsWith(Host &aHost) const
ExitNow(hasConflicts = true);
}
for (const Service::Description *desc = aHost.mServiceDescriptions.GetHead(); desc != nullptr;
desc = desc->GetNext())
for (const Service::Description &desc : aHost.mServiceDescriptions)
{
// Check on all hosts for a matching service description with
// the same instance name and if found, verify that it has the
// same key.
for (const Host *host = mHosts.GetHead(); host != nullptr; host = host->GetNext())
for (const Host &host : mHosts)
{
if (host->FindServiceDescription(desc->GetInstanceName()) != nullptr)
if (host.FindServiceDescription(desc.GetInstanceName()) != nullptr)
{
VerifyOrExit(*aHost.GetKey() == *host->GetKey(), hasConflicts = true);
VerifyOrExit(*aHost.GetKey() == *host.GetKey(), hasConflicts = true);
}
}
}
@@ -343,10 +342,11 @@ void Server::CommitSrpUpdate(Error aError,
aHost.SetLease(grantedLease);
aHost.SetKeyLease(grantedKeyLease);
for (Service::Description *desc = aHost.mServiceDescriptions.GetHead(); desc != nullptr; desc = desc->GetNext())
for (Service::Description &desc : aHost.mServiceDescriptions)
{
desc->mLease = grantedLease;
desc->mKeyLease = grantedKeyLease;
desc.mLease = grantedLease;
desc.mKeyLease = grantedKeyLease;
}
existingHost = mHosts.FindMatching(aHost.GetFullName());
@@ -363,9 +363,9 @@ void Server::CommitSrpUpdate(Error aError,
existingHost->SetKeyLease(aHost.GetKeyLease());
RemoveHost(existingHost, /* aRetainName */ true, /* aNotifyServiceHandler */ false);
for (Service *service = existingHost->mServices.GetHead(); service != nullptr; service = service->GetNext())
for (Service &service : existingHost->mServices)
{
existingHost->RemoveService(service, /* aRetainName */ true, /* aNotifyServiceHandler */ false);
existingHost->RemoveService(&service, /* aRetainName */ true, /* aNotifyServiceHandler */ false);
}
}
}
@@ -377,10 +377,10 @@ void Server::CommitSrpUpdate(Error aError,
{
otLogInfoSrp("[server] add new host %s", aHost.GetFullName());
for (Service *service = aHost.GetServices(); service != nullptr; service = service->GetNext())
for (Service &service : aHost.GetServices())
{
service->mIsCommitted = true;
service->Log(Service::kAddNew);
service.mIsCommitted = true;
service.Log(Service::kAddNew);
}
AddHost(aHost);
@@ -508,13 +508,13 @@ const Server::UpdateMetadata *Server::FindOutstandingUpdate(const Ip6::MessageIn
{
const UpdateMetadata *ret = nullptr;
for (const UpdateMetadata *update = mOutstandingUpdates.GetHead(); update != nullptr; update = update->GetNext())
for (const UpdateMetadata &update : mOutstandingUpdates)
{
if (aDnsMessageId == update->GetDnsHeader().GetMessageId() &&
aMessageInfo.GetPeerAddr() == update->GetMessageInfo().GetPeerAddr() &&
aMessageInfo.GetPeerPort() == update->GetMessageInfo().GetPeerPort())
if (aDnsMessageId == update.GetDnsHeader().GetMessageId() &&
aMessageInfo.GetPeerAddr() == update.GetMessageInfo().GetPeerAddr() &&
aMessageInfo.GetPeerPort() == update.GetMessageInfo().GetPeerPort())
{
ExitNow(ret = update);
ExitNow(ret = &update);
}
}
@@ -781,14 +781,14 @@ Error Server::ProcessServiceDescriptionInstructions(Host & aHo
const Dns::Zone & aZone,
uint16_t & aOffset) const
{
Service::Description *desc;
Error error = kErrorNone;
TimeMilli now = TimerMilli::GetNow();
Error error = kErrorNone;
TimeMilli now = TimerMilli::GetNow();
for (uint16_t numRecords = aDnsHeader.GetUpdateRecordCount(); numRecords > 0; numRecords--)
{
char name[Dns::Name::kMaxNameSize];
Dns::ResourceRecord record;
Service::Description *desc;
char name[Dns::Name::kMaxNameSize];
Dns::ResourceRecord record;
SuccessOrExit(error = Dns::Name::ReadName(aMessage, aOffset, name, sizeof(name)));
SuccessOrExit(error = aMessage.Read(aOffset, record));
@@ -855,15 +855,15 @@ Error Server::ProcessServiceDescriptionInstructions(Host & aHo
// that `mTimeLastUpdate` on a new `Service::Description` is set to
// `GetNow().GetDistantPast()`.
for (desc = aHost.mServiceDescriptions.GetHead(); desc != nullptr; desc = desc->GetNext())
for (Service::Description &desc : aHost.mServiceDescriptions)
{
VerifyOrExit(desc->mTimeLastUpdate == now, error = kErrorFailed);
VerifyOrExit(desc.mTimeLastUpdate == now, error = kErrorFailed);
// Check that either both `mPort` and `mTxtData` are set
// (i.e., we saw both SRV and TXT record) or both are default
// (cleared) value (i.e., we saw neither of them).
VerifyOrExit((desc->mPort == 0) == (desc->mTxtData == nullptr), error = kErrorFailed);
VerifyOrExit((desc.mPort == 0) == (desc.mTxtData == nullptr), error = kErrorFailed);
}
exit:
@@ -1003,17 +1003,17 @@ void Server::HandleUpdate(const Dns::UpdateHeader &aDnsHeader, Host &aHost, cons
// when removing a host. We copy and append any missing services to
// `aHost` from the `existingHost` and mark them as deleted.
for (Service *service = existingHost->mServices.GetHead(); service != nullptr; service = service->GetNext())
for (Service &service : existingHost->mServices)
{
if (service->mIsDeleted)
if (service.mIsDeleted)
{
continue;
}
if (aHost.FindService(service->GetServiceName(), service->GetInstanceName()) == nullptr)
if (aHost.FindService(service.GetServiceName(), service.GetInstanceName()) == nullptr)
{
Service *newService =
aHost.AddNewService(service->GetServiceName(), service->GetInstanceName(), service->IsSubType());
aHost.AddNewService(service.GetServiceName(), service.GetInstanceName(), service.IsSubType());
VerifyOrExit(newService != nullptr, error = kErrorNoBufs);
newService->mDescription.mTimeLastUpdate = TimerMilli::GetNow();
@@ -1212,10 +1212,10 @@ void Server::HandleLeaseTimer(void)
otLogInfoSrp("[server] LEASE of host %s expired", host->GetFullName());
// If the host expired, delete all resources of this host and its services.
for (Service *service = host->mServices.GetHead(); service != nullptr; service = service->GetNext())
for (Service &service : host->mServices)
{
// Don't need to notify the service handler as `RemoveHost` at below will do.
host->RemoveService(service, /* aRetainName */ true, /* aNotifyServiceHandler */ false);
host->RemoveService(&service, /* aRetainName */ true, /* aNotifyServiceHandler */ false);
}
RemoveHost(host, /* aRetainName */ true, /* aNotifyServiceHandler */ true);
@@ -1614,7 +1614,7 @@ const Server::Service *Server::Host::FindNextService(const Service *aPrevService
const char * aServiceName,
const char * aInstanceName) const
{
const Service *service = (aPrevService == nullptr) ? GetServices() : aPrevService->GetNext();
const Service *service = (aPrevService == nullptr) ? GetServices().GetHead() : aPrevService->GetNext();
for (; service != nullptr; service = service->GetNext())
{
@@ -1750,12 +1750,12 @@ Error Server::Host::MergeServicesAndResourcesFrom(Host &aHost)
mKeyLease = aHost.mKeyLease;
mTimeLastUpdate = TimerMilli::GetNow();
for (Service *service = aHost.mServices.GetHead(); service != nullptr; service = service->GetNext())
for (Service &service : aHost.mServices)
{
Service *existingService = FindService(service->GetServiceName(), service->GetInstanceName());
Service *existingService = FindService(service.GetServiceName(), service.GetInstanceName());
Service *newService;
if (service->mIsDeleted)
if (service.mIsDeleted)
{
// `RemoveService()` does nothing if `exitsingService` is `nullptr`.
RemoveService(existingService, /* aRetainName */ true, /* aNotifyServiceHandler */ false);
@@ -1766,7 +1766,7 @@ Error Server::Host::MergeServicesAndResourcesFrom(Host &aHost)
newService = (existingService != nullptr)
? existingService
: AddNewService(service->GetServiceName(), service->GetInstanceName(), service->IsSubType());
: AddNewService(service.GetServiceName(), service.GetInstanceName(), service.IsSubType());
VerifyOrExit(newService != nullptr, error = kErrorNoBufs);
@@ -1774,12 +1774,12 @@ Error Server::Host::MergeServicesAndResourcesFrom(Host &aHost)
newService->mIsCommitted = true;
newService->mTimeLastUpdate = TimerMilli::GetNow();
if (!service->mIsSubType)
if (!service.mIsSubType)
{
// (1) Service description is shared across a base type and all its subtypes.
// (2) `TakeResourcesFrom()` releases resources pinned to its argument.
// Therefore, make sure the function is called only for the base type.
newService->mDescription.TakeResourcesFrom(service->mDescription);
newService->mDescription.TakeResourcesFrom(service.mDescription);
}
newService->Log((existingService != nullptr) ? Service::kUpdateExisting : Service::kAddNew);
+4 -4
View File
@@ -429,12 +429,12 @@ public:
TimeMilli GetKeyExpireTime(void) const;
/**
* This method returns the head of `Service` linked list associated with the host.
* This method returns the `Service` linked list associated with the host.
*
* @returns A pointer to the head of `Service` linked list.
* @returns The `Service` linked list.
*
*/
const Service *GetServices(void) const { return mServices.GetHead(); }
const LinkedList<Service> &GetServices(void) const { return mServices; }
/**
* This method finds the next matching service on the host.
@@ -473,7 +473,7 @@ public:
void SetKey(Dns::Ecdsa256KeyRecord &aKey);
void SetLease(uint32_t aLease) { mLease = aLease; }
void SetKeyLease(uint32_t aKeyLease) { mKeyLease = aKeyLease; }
Service * GetServices(void) { return mServices.GetHead(); }
LinkedList<Service> & GetServices(void) { return mServices; }
Service * AddNewService(const char *aServiceName, const char *aInstanceName, bool aIsSubType);
void RemoveService(Service *aService, bool aRetainName, bool aNotifyServiceHandler);
void FreeAllServices(void);
+7 -5
View File
@@ -309,12 +309,14 @@ Error Tcp::HandleMessage(ot::Ip6::Header &aIp6Header, Message &aMessage, Message
Error error = kErrorNotImplemented;
for (Endpoint *active = mEndpoints.GetHead(); active != nullptr; active = active->GetNext())
for (Endpoint &active : mEndpoints)
{
OT_UNUSED_VARIABLE(active);
}
for (Listener *passive = mListeners.GetHead(); passive != nullptr; passive = passive->GetNext())
for (Listener &passive : mListeners)
{
OT_UNUSED_VARIABLE(passive);
}
return error;
@@ -332,7 +334,6 @@ void Tcp::ProcessTimers()
TimeMilli now = TimerMilli::GetNow();
bool pendingTimer;
TimeMilli earliestPendingTimerExpiry;
Endpoint *endpoint;
OT_ASSERT(!mTimer.IsRunning());
@@ -354,9 +355,10 @@ void Tcp::ProcessTimers()
restart:
pendingTimer = false;
earliestPendingTimerExpiry = now.GetDistantFuture();
for (endpoint = mEndpoints.GetHead(); endpoint != nullptr; endpoint = endpoint->GetNext())
for (Endpoint &endpoint : mEndpoints)
{
if (endpoint->FirePendingTimers(now, pendingTimer, earliestPendingTimerExpiry))
if (endpoint.FirePendingTimers(now, pendingTimer, earliestPendingTimerExpiry))
{
/*
* If a non-OpenThread callback is called --- which, in practice,
+4 -4
View File
@@ -492,9 +492,9 @@ Error Udp::HandleMessage(Message &aMessage, MessageInfo &aMessageInfo)
VerifyOrExit(!ShouldUsePlatformUdp(aMessageInfo.mSockPort) || IsPortInUse(aMessageInfo.mSockPort));
#endif
for (Receiver *receiver = mReceivers.GetHead(); receiver; receiver = receiver->GetNext())
for (Receiver &receiver : mReceivers)
{
VerifyOrExit(!receiver->HandleMessage(aMessage, aMessageInfo));
VerifyOrExit(!receiver.HandleMessage(aMessage, aMessageInfo));
}
HandlePayload(aMessage, aMessageInfo);
@@ -543,9 +543,9 @@ bool Udp::IsPortInUse(uint16_t aPort) const
{
bool found = false;
for (const SocketHandle *socket = mSockets.GetHead(); socket != nullptr; socket = socket->GetNext())
for (const SocketHandle &socket : mSockets)
{
if (socket->GetSockName().GetPort() == aPort)
if (socket.GetSockName().GetPort() == aPort)
{
found = true;
break;
+57 -56
View File
@@ -395,9 +395,9 @@ void AddressResolver::UpdateSnoopedCacheEntry(const Ip6::Address &aEid,
entry = NewCacheEntry(/* aSnoopedEntry */ true);
VerifyOrExit(entry != nullptr);
for (CacheEntry *snooped = mSnoopedList.GetHead(); snooped != nullptr; snooped = snooped->GetNext())
for (CacheEntry &snooped : mSnoopedList)
{
if (!snooped->CanEvict())
if (!snooped.CanEvict())
{
numNonEvictable++;
}
@@ -448,13 +448,13 @@ void AddressResolver::RestartAddressQueries(void)
mQueryRetryList.Clear();
for (CacheEntry *entry = mQueryList.GetHead(); entry != nullptr; entry = entry->GetNext())
for (CacheEntry &entry : mQueryList)
{
IgnoreError(SendAddressQuery(entry->GetTarget()));
IgnoreError(SendAddressQuery(entry.GetTarget()));
entry->SetTimeout(kAddressQueryTimeout);
entry->SetRetryDelay(kAddressQueryInitialRetryDelay);
entry->SetCanEvict(false);
entry.SetTimeout(kAddressQueryTimeout);
entry.SetRetryDelay(kAddressQueryInitialRetryDelay);
entry.SetCanEvict(false);
}
}
@@ -726,22 +726,22 @@ void AddressResolver::HandleAddressError(Coap::Message &aMessage, const Ip6::Mes
SuccessOrExit(error = Tlv::Find<ThreadTargetTlv>(aMessage, target));
SuccessOrExit(error = Tlv::Find<ThreadMeshLocalEidTlv>(aMessage, meshLocalIid));
for (const Ip6::Netif::UnicastAddress *address = Get<ThreadNetif>().GetUnicastAddresses(); address;
address = address->GetNext())
for (const Ip6::Netif::UnicastAddress &address : Get<ThreadNetif>().GetUnicastAddresses())
{
if (address->GetAddress() == target && Get<Mle::MleRouter>().GetMeshLocal64().GetIid() != meshLocalIid)
if (address.GetAddress() == target && Get<Mle::MleRouter>().GetMeshLocal64().GetIid() != meshLocalIid)
{
// Target EID matches address and Mesh Local EID differs
#if OPENTHREAD_CONFIG_DUA_ENABLE
if (Get<BackboneRouter::Leader>().IsDomainUnicast(address->GetAddress()))
if (Get<BackboneRouter::Leader>().IsDomainUnicast(address.GetAddress()))
{
Get<DuaManager>().NotifyDuplicateDomainUnicastAddress();
}
else
#endif
{
Get<ThreadNetif>().RemoveUnicastAddress(*address);
Get<ThreadNetif>().RemoveUnicastAddress(address);
}
ExitNow();
}
}
@@ -871,77 +871,78 @@ exit:
void AddressResolver::HandleTimeTick(void)
{
bool continueRxingTicks = false;
CacheEntry *prev;
CacheEntry *entry;
bool continueRxingTicks = false;
for (entry = mSnoopedList.GetHead(); entry != nullptr; entry = entry->GetNext())
for (CacheEntry &entry : mSnoopedList)
{
if (entry->IsTimeoutZero())
if (entry.IsTimeoutZero())
{
continue;
}
continueRxingTicks = true;
entry->DecrementTimeout();
entry.DecrementTimeout();
if (entry->IsTimeoutZero())
if (entry.IsTimeoutZero())
{
entry->SetCanEvict(true);
entry.SetCanEvict(true);
}
}
for (entry = mQueryRetryList.GetHead(); entry != nullptr; entry = entry->GetNext())
for (CacheEntry &entry : mQueryRetryList)
{
if (entry->IsTimeoutZero())
if (entry.IsTimeoutZero())
{
continue;
}
continueRxingTicks = true;
entry->DecrementTimeout();
entry.DecrementTimeout();
}
prev = nullptr;
while ((entry = GetEntryAfter(prev, mQueryList)) != nullptr)
{
OT_ASSERT(!entry->IsTimeoutZero());
CacheEntry *prev = nullptr;
CacheEntry *entry;
continueRxingTicks = true;
entry->DecrementTimeout();
if (entry->IsTimeoutZero())
while ((entry = GetEntryAfter(prev, mQueryList)) != nullptr)
{
uint16_t retryDelay = entry->GetRetryDelay();
OT_ASSERT(!entry->IsTimeoutZero());
entry->SetTimeout(retryDelay);
continueRxingTicks = true;
entry->DecrementTimeout();
retryDelay <<= 1;
if (retryDelay > kAddressQueryMaxRetryDelay)
if (entry->IsTimeoutZero())
{
retryDelay = kAddressQueryMaxRetryDelay;
uint16_t retryDelay = entry->GetRetryDelay();
entry->SetTimeout(retryDelay);
retryDelay <<= 1;
if (retryDelay > kAddressQueryMaxRetryDelay)
{
retryDelay = kAddressQueryMaxRetryDelay;
}
entry->SetRetryDelay(retryDelay);
entry->SetCanEvict(true);
// Move the entry from `mQueryList` to `mQueryRetryList`
mQueryList.PopAfter(prev);
mQueryRetryList.Push(*entry);
otLogInfoArp("Timed out waiting for address notification for %s, retry: %d",
entry->GetTarget().ToString().AsCString(), entry->GetTimeout());
Get<MeshForwarder>().HandleResolved(entry->GetTarget(), kErrorDrop);
// When the entry is removed from `mQueryList`
// we keep the `prev` pointer same as before.
}
else
{
prev = entry;
}
entry->SetRetryDelay(retryDelay);
entry->SetCanEvict(true);
// Move the entry from `mQueryList` to `mQueryRetryList`
mQueryList.PopAfter(prev);
mQueryRetryList.Push(*entry);
otLogInfoArp("Timed out waiting for address notification for %s, retry: %d",
entry->GetTarget().ToString().AsCString(), entry->GetTimeout());
Get<MeshForwarder>().HandleResolved(entry->GetTarget(), kErrorDrop);
// When the entry is removed from `mQueryList`
// we keep the `prev` pointer same as before.
}
else
{
prev = entry;
}
}
+10 -12
View File
@@ -1254,11 +1254,10 @@ bool Mle::HasUnregisteredAddress(void)
// Checks whether there are any addresses in addition to the mesh-local
// address that need to be registered.
for (const Ip6::Netif::UnicastAddress *addr = Get<ThreadNetif>().GetUnicastAddresses(); addr;
addr = addr->GetNext())
for (const Ip6::Netif::UnicastAddress &addr : Get<ThreadNetif>().GetUnicastAddresses())
{
if (!addr->GetAddress().IsLinkLocal() && !IsRoutingLocator(addr->GetAddress()) &&
!IsAnycastLocator(addr->GetAddress()) && addr->GetAddress() != GetMeshLocal64())
if (!addr.GetAddress().IsLinkLocal() && !IsRoutingLocator(addr.GetAddress()) &&
!IsAnycastLocator(addr.GetAddress()) && addr.GetAddress() != GetMeshLocal64())
{
ExitNow(retval = true);
}
@@ -1321,34 +1320,33 @@ Error Mle::AppendAddressRegistration(Message &aMessage, AddressRegistrationMode
}
#endif // OPENTHREAD_CONFIG_DUA_ENABLE
for (const Ip6::Netif::UnicastAddress *addr = Get<ThreadNetif>().GetUnicastAddresses(); addr;
addr = addr->GetNext())
for (const Ip6::Netif::UnicastAddress &addr : Get<ThreadNetif>().GetUnicastAddresses())
{
if (addr->GetAddress().IsLinkLocal() || IsRoutingLocator(addr->GetAddress()) ||
IsAnycastLocator(addr->GetAddress()) || addr->GetAddress() == GetMeshLocal64())
if (addr.GetAddress().IsLinkLocal() || IsRoutingLocator(addr.GetAddress()) ||
IsAnycastLocator(addr.GetAddress()) || addr.GetAddress() == GetMeshLocal64())
{
continue;
}
#if OPENTHREAD_CONFIG_DUA_ENABLE
// Skip DUA that was already appended above.
if (addr->GetAddress() == domainUnicastAddress)
if (addr.GetAddress() == domainUnicastAddress)
{
continue;
}
#endif
if (Get<NetworkData::Leader>().GetContext(addr->GetAddress(), context) == kErrorNone)
if (Get<NetworkData::Leader>().GetContext(addr.GetAddress(), context) == kErrorNone)
{
// compressed entry
entry.SetContextId(context.mContextId);
entry.SetIid(addr->GetAddress().GetIid());
entry.SetIid(addr.GetAddress().GetIid());
}
else
{
// uncompressed entry
entry.SetUncompressed();
entry.SetIp6Address(addr->GetAddress());
entry.SetIp6Address(addr.GetAddress());
}
SuccessOrExit(error = aMessage.AppendBytes(&entry, entry.GetLength()));
+4 -5
View File
@@ -190,19 +190,18 @@ Error NetworkDiagnostic::AppendIp6AddressList(Message &aMessage)
tlv.Init();
for (const Ip6::Netif::UnicastAddress *addr = Get<ThreadNetif>().GetUnicastAddresses(); addr;
addr = addr->GetNext())
for (const Ip6::Netif::UnicastAddress &addr : Get<ThreadNetif>().GetUnicastAddresses())
{
OT_UNUSED_VARIABLE(addr);
count++;
}
tlv.SetLength(count * sizeof(Ip6::Address));
SuccessOrExit(error = aMessage.Append(tlv));
for (const Ip6::Netif::UnicastAddress *addr = Get<ThreadNetif>().GetUnicastAddresses(); addr;
addr = addr->GetNext())
for (const Ip6::Netif::UnicastAddress &addr : Get<ThreadNetif>().GetUnicastAddresses())
{
SuccessOrExit(error = aMessage.Append(addr->GetAddress()));
SuccessOrExit(error = aMessage.Append(addr.GetAddress()));
}
exit:
+3 -4
View File
@@ -163,12 +163,11 @@ void Neighbor::GenerateChallenge(void)
#if OPENTHREAD_CONFIG_MLE_LINK_METRICS_INITIATOR_ENABLE || OPENTHREAD_CONFIG_MLE_LINK_METRICS_SUBJECT_ENABLE
void Neighbor::AggregateLinkMetrics(uint8_t aSeriesId, uint8_t aFrameType, uint8_t aLqi, int8_t aRss)
{
for (LinkMetrics::SeriesInfo *entry = mLinkMetricsSeriesInfoList.GetHead(); entry != nullptr;
entry = entry->GetNext())
for (LinkMetrics::SeriesInfo &entry : mLinkMetricsSeriesInfoList)
{
if (aSeriesId == 0 || aSeriesId == entry->GetSeriesId())
if (aSeriesId == 0 || aSeriesId == entry.GetSeriesId())
{
entry->AggregateLinkMetrics(aFrameType, aLqi, aRss);
entry.AggregateLinkMetrics(aFrameType, aLqi, aRss);
}
}
}
+2 -3
View File
@@ -208,10 +208,9 @@ void Slaac::Update(UpdateMode aMode)
found = false;
for (const Ip6::Netif::UnicastAddress *netifAddr = Get<ThreadNetif>().GetUnicastAddresses();
netifAddr != nullptr; netifAddr = netifAddr->GetNext())
for (const Ip6::Netif::UnicastAddress &netifAddr : Get<ThreadNetif>().GetUnicastAddresses())
{
if (DoesConfigMatchNetifAddr(config, *netifAddr))
if (DoesConfigMatchNetifAddr(config, netifAddr))
{
found = true;
break;
+2 -2
View File
@@ -74,11 +74,11 @@ void VerifyLinkedListContent(const ot::LinkedList<Entry> *aList, ...)
va_start(args, aList);
for (const Entry *entry = aList->GetHead(); entry; entry = entry->GetNext())
for (const Entry &entry : *aList)
{
argEntry = va_arg(args, Entry *);
VerifyOrQuit(argEntry != nullptr, "List contains more entries than expected");
VerifyOrQuit(argEntry == entry, "List does not contain the same entry");
VerifyOrQuit(argEntry == &entry, "List does not contain the same entry");
VerifyOrQuit(aList->Contains(*argEntry));
VerifyOrQuit(aList->ContainsMatching(argEntry->GetName()));
VerifyOrQuit(aList->ContainsMatching(argEntry->GetId()));
+2 -2
View File
@@ -65,13 +65,13 @@ void VerifyMulticastAddressList(const Ip6::Netif &aNetif, Ip6::Address aAddresse
VerifyOrQuit(aNetif.IsMulticastSubscribed(aAddresses[i]));
}
for (const Ip6::Netif::MulticastAddress *addr = aNetif.GetMulticastAddresses(); addr; addr = addr->GetNext())
for (const Ip6::Netif::MulticastAddress &addr : aNetif.GetMulticastAddresses())
{
bool didFind = false;
for (uint8_t i = 0; i < aLength; i++)
{
if (addr->GetAddress() == aAddresses[i])
if (addr.GetAddress() == aAddresses[i])
{
didFind = true;
break;