diff --git a/src/core/api/ip6_api.cpp b/src/core/api/ip6_api.cpp index f595cd78f..b27d350d9 100644 --- a/src/core/api/ip6_api.cpp +++ b/src/core/api/ip6_api.cpp @@ -79,7 +79,7 @@ const otNetifAddress *otIp6GetUnicastAddresses(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.Get().GetUnicastAddresses(); + return instance.Get().GetUnicastAddresses().GetHead(); } otError otIp6AddUnicastAddress(otInstance *aInstance, const otNetifAddress *aAddress) @@ -101,7 +101,7 @@ const otNetifMulticastAddress *otIp6GetMulticastAddresses(otInstance *aInstance) { Instance &instance = *static_cast(aInstance); - return instance.Get().GetMulticastAddresses(); + return instance.Get().GetMulticastAddresses().GetHead(); } otError otIp6SubscribeMulticastAddress(otInstance *aInstance, const otIp6Address *aAddress) diff --git a/src/core/coap/coap.cpp b/src/core/coap/coap.cpp index 111383ef5..ea83e7b70 100644 --- a/src/core/coap/coap.cpp +++ b/src/core/coap/coap.cpp @@ -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(); } diff --git a/src/core/common/iterator_utils.hpp b/src/core/common/iterator_utils.hpp index dbee0aad7..d6d45dedb 100644 --- a/src/core/common/iterator_utils.hpp +++ b/src/core/common/iterator_utils.hpp @@ -61,7 +61,7 @@ namespace ot { * would set the pointer to `nullptr` when there's no more elements. * */ -template class ItemPtrIterator +template class ItemPtrIterator { public: /** @@ -148,7 +148,7 @@ protected: } /** - * Contructor with an Item pointer. + * Constructor with an Item pointer. * */ explicit ItemPtrIterator(ItemType *item) diff --git a/src/core/common/linked_list.hpp b/src/core/common/linked_list.hpp index 4e48597ad..8974a9d53 100644 --- a/src/core/common/linked_list.hpp +++ b/src/core/common/linked_list.hpp @@ -39,6 +39,7 @@ #include #include "common/error.hpp" +#include "common/iterator_utils.hpp" namespace ot { @@ -101,6 +102,9 @@ public: */ template class LinkedList { + class Iterator; + class ConstIterator; + public: /** * This constructor initializes the linked list. @@ -573,7 +577,47 @@ public: */ Type *GetTail(void) { return const_cast(const_cast(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 + { + friend class LinkedList; + friend class ItemPtrIterator; + + using ItemPtrIterator::mItem; + + explicit Iterator(Type *aItem) + : ItemPtrIterator(aItem) + { + } + + void Advance(void) { mItem = mItem->GetNext(); } + }; + + class ConstIterator : public ItemPtrIterator + { + friend class LinkedList; + friend class ItemPtrIterator; + + using ItemPtrIterator::mItem; + + explicit ConstIterator(const Type *aItem) + : ItemPtrIterator(aItem) + { + } + + void Advance(void) { mItem = mItem->GetNext(); } + }; + Type *mHead; }; diff --git a/src/core/common/timer.cpp b/src/core/common/timer.cpp index d560f6de0..252a4e69b 100644 --- a/src/core/common/timer.cpp +++ b/src/core/common/timer.cpp @@ -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) diff --git a/src/core/net/icmp6.cpp b/src/core/net/icmp6.cpp index 6861e7c67..f41737459 100644 --- a/src/core/net/icmp6.cpp +++ b/src/core/net/icmp6.cpp @@ -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: diff --git a/src/core/net/ip6.cpp b/src/core/net/ip6.cpp index d7e615702..23ddee29f 100644 --- a/src/core/net/ip6.cpp +++ b/src/core/net/ip6.cpp @@ -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().GetUnicastAddresses(); addr; addr = addr->GetNext()) + for (const Netif::UnicastAddress &addr : Get().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().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().GetUnicastAddresses(); cur; cur = cur->GetNext()) + for (const Netif::UnicastAddress &cur : Get().GetUnicastAddresses()) { - if (cur->GetAddress().PrefixMatch(aAddress) >= cur->mPrefixLength) + if (cur.GetAddress().PrefixMatch(aAddress) >= cur.mPrefixLength) { ExitNow(rval = true); } diff --git a/src/core/net/netif.cpp b/src/core/net/netif.cpp index 06ada4452..3ca5859ff 100644 --- a/src/core/net/netif.cpp +++ b/src/core/net/netif.cpp @@ -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) diff --git a/src/core/net/netif.hpp b/src/core/net/netif.hpp index 6846e691c..d7a361b37 100644 --- a/src/core/net/netif.hpp +++ b/src/core/net/netif.hpp @@ -68,7 +68,7 @@ class Ip6; * This class implements an IPv6 network interface. * */ -class Netif : public InstanceLocator, public LinkedListEntry, 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 &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 &GetMulticastAddresses(void) const { return mMulticastAddresses; } /** * This method indicates whether a multicast address is an external or internal address. diff --git a/src/core/net/srp_client.cpp b/src/core/net/srp_client.cpp index ac9e12856..1f7d5e287 100644 --- a/src/core/net/srp_client.cpp +++ b/src/core/net/srp_client.cpp @@ -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; diff --git a/src/core/net/srp_server.cpp b/src/core/net/srp_server.cpp index b0b1b2007..4914a848c 100644 --- a/src/core/net/srp_server.cpp +++ b/src/core/net/srp_server.cpp @@ -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); diff --git a/src/core/net/srp_server.hpp b/src/core/net/srp_server.hpp index 63bd40015..357bb614f 100644 --- a/src/core/net/srp_server.hpp +++ b/src/core/net/srp_server.hpp @@ -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 &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 & 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); diff --git a/src/core/net/tcp6.cpp b/src/core/net/tcp6.cpp index 1d078fae6..41cb1f63d 100644 --- a/src/core/net/tcp6.cpp +++ b/src/core/net/tcp6.cpp @@ -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, diff --git a/src/core/net/udp6.cpp b/src/core/net/udp6.cpp index 53b397fc5..1dea10e05 100644 --- a/src/core/net/udp6.cpp +++ b/src/core/net/udp6.cpp @@ -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; diff --git a/src/core/thread/address_resolver.cpp b/src/core/thread/address_resolver.cpp index 845635980..a19fbb591 100644 --- a/src/core/thread/address_resolver.cpp +++ b/src/core/thread/address_resolver.cpp @@ -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(aMessage, target)); SuccessOrExit(error = Tlv::Find(aMessage, meshLocalIid)); - for (const Ip6::Netif::UnicastAddress *address = Get().GetUnicastAddresses(); address; - address = address->GetNext()) + for (const Ip6::Netif::UnicastAddress &address : Get().GetUnicastAddresses()) { - if (address->GetAddress() == target && Get().GetMeshLocal64().GetIid() != meshLocalIid) + if (address.GetAddress() == target && Get().GetMeshLocal64().GetIid() != meshLocalIid) { // Target EID matches address and Mesh Local EID differs #if OPENTHREAD_CONFIG_DUA_ENABLE - if (Get().IsDomainUnicast(address->GetAddress())) + if (Get().IsDomainUnicast(address.GetAddress())) { Get().NotifyDuplicateDomainUnicastAddress(); } else #endif { - Get().RemoveUnicastAddress(*address); + Get().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().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().HandleResolved(entry->GetTarget(), kErrorDrop); - - // When the entry is removed from `mQueryList` - // we keep the `prev` pointer same as before. - } - else - { - prev = entry; } } diff --git a/src/core/thread/mle.cpp b/src/core/thread/mle.cpp index b9d88db12..49235ee8b 100644 --- a/src/core/thread/mle.cpp +++ b/src/core/thread/mle.cpp @@ -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().GetUnicastAddresses(); addr; - addr = addr->GetNext()) + for (const Ip6::Netif::UnicastAddress &addr : Get().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().GetUnicastAddresses(); addr; - addr = addr->GetNext()) + for (const Ip6::Netif::UnicastAddress &addr : Get().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().GetContext(addr->GetAddress(), context) == kErrorNone) + if (Get().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())); diff --git a/src/core/thread/network_diagnostic.cpp b/src/core/thread/network_diagnostic.cpp index 8168c787e..14a4b2652 100644 --- a/src/core/thread/network_diagnostic.cpp +++ b/src/core/thread/network_diagnostic.cpp @@ -190,19 +190,18 @@ Error NetworkDiagnostic::AppendIp6AddressList(Message &aMessage) tlv.Init(); - for (const Ip6::Netif::UnicastAddress *addr = Get().GetUnicastAddresses(); addr; - addr = addr->GetNext()) + for (const Ip6::Netif::UnicastAddress &addr : Get().GetUnicastAddresses()) { + OT_UNUSED_VARIABLE(addr); count++; } tlv.SetLength(count * sizeof(Ip6::Address)); SuccessOrExit(error = aMessage.Append(tlv)); - for (const Ip6::Netif::UnicastAddress *addr = Get().GetUnicastAddresses(); addr; - addr = addr->GetNext()) + for (const Ip6::Netif::UnicastAddress &addr : Get().GetUnicastAddresses()) { - SuccessOrExit(error = aMessage.Append(addr->GetAddress())); + SuccessOrExit(error = aMessage.Append(addr.GetAddress())); } exit: diff --git a/src/core/thread/topology.cpp b/src/core/thread/topology.cpp index 8417e2e71..c8ea45b47 100644 --- a/src/core/thread/topology.cpp +++ b/src/core/thread/topology.cpp @@ -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); } } } diff --git a/src/core/utils/slaac_address.cpp b/src/core/utils/slaac_address.cpp index c2fed3645..6e162dffc 100644 --- a/src/core/utils/slaac_address.cpp +++ b/src/core/utils/slaac_address.cpp @@ -208,10 +208,9 @@ void Slaac::Update(UpdateMode aMode) found = false; - for (const Ip6::Netif::UnicastAddress *netifAddr = Get().GetUnicastAddresses(); - netifAddr != nullptr; netifAddr = netifAddr->GetNext()) + for (const Ip6::Netif::UnicastAddress &netifAddr : Get().GetUnicastAddresses()) { - if (DoesConfigMatchNetifAddr(config, *netifAddr)) + if (DoesConfigMatchNetifAddr(config, netifAddr)) { found = true; break; diff --git a/tests/unit/test_linked_list.cpp b/tests/unit/test_linked_list.cpp index f143ba429..b0b297009 100644 --- a/tests/unit/test_linked_list.cpp +++ b/tests/unit/test_linked_list.cpp @@ -74,11 +74,11 @@ void VerifyLinkedListContent(const ot::LinkedList *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())); diff --git a/tests/unit/test_netif.cpp b/tests/unit/test_netif.cpp index 91edab11a..121f4acb6 100644 --- a/tests/unit/test_netif.cpp +++ b/tests/unit/test_netif.cpp @@ -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;