From fda4549df77c00360f6b2b3e2014b901aabc4e96 Mon Sep 17 00:00:00 2001 From: Abtin Keshavarzian Date: Fri, 12 Aug 2022 09:22:18 -0700 Subject: [PATCH] [core] add new generic `Min()`, `Max()` and `Clamp()` functions (#8017) This commit adds generic helper functions: - `Min()` to get the minimum of two values, - `Max()` to get the maximum of two values, and - `Clamp()` to clamp a value to a given closed range from a minimum up to a maximum value. It also adds functions - `ClampToUint8()` and `ClampToUint16()` to clamp a `uint` value to a smaller bit-size (`uint8_t` or `uint16_t`) range. --- src/core/BUILD.gn | 1 + src/core/Makefile.am | 1 + src/core/backbone_router/bbr_manager.cpp | 3 +- src/core/backbone_router/ndproxy_table.cpp | 8 +- src/core/border_router/routing_manager.cpp | 19 +-- src/core/common/data.hpp | 3 +- src/core/common/log.cpp | 3 +- src/core/common/min_max.hpp | 142 +++++++++++++++++++++ src/core/mac/data_poll_sender.cpp | 13 +- src/core/mac/sub_mac.cpp | 4 +- src/core/meshcop/meshcop_tlvs.cpp | 3 +- src/core/net/dns_dso.cpp | 15 ++- src/core/net/dns_dso.hpp | 3 +- src/core/net/dns_types.cpp | 3 +- src/core/net/ip6_address.cpp | 3 +- src/core/net/srp_client.cpp | 3 +- src/core/net/srp_server.cpp | 21 +-- src/core/net/srp_server.hpp | 4 +- src/core/net/tcp6.cpp | 3 +- src/core/thread/link_quality.cpp | 4 +- src/core/thread/mesh_forwarder_ftd.cpp | 3 +- src/core/thread/mle.cpp | 5 +- src/core/utils/history_tracker.cpp | 3 +- src/core/utils/ping_sender.cpp | 10 +- tests/unit/test_serial_number.cpp | 48 +++++++ 25 files changed, 271 insertions(+), 57 deletions(-) create mode 100644 src/core/common/min_max.hpp diff --git a/src/core/BUILD.gn b/src/core/BUILD.gn index 4f4886709..cbffbb775 100644 --- a/src/core/BUILD.gn +++ b/src/core/BUILD.gn @@ -421,6 +421,7 @@ openthread_core_files = [ "common/logging.hpp", "common/message.cpp", "common/message.hpp", + "common/min_max.hpp", "common/new.hpp", "common/non_copyable.hpp", "common/notifier.cpp", diff --git a/src/core/Makefile.am b/src/core/Makefile.am index b2dd5281f..47146708d 100644 --- a/src/core/Makefile.am +++ b/src/core/Makefile.am @@ -455,6 +455,7 @@ HEADERS_COMMON = \ common/log.hpp \ common/logging.hpp \ common/message.hpp \ + common/min_max.hpp \ common/new.hpp \ common/non_copyable.hpp \ common/notifier.hpp \ diff --git a/src/core/backbone_router/bbr_manager.cpp b/src/core/backbone_router/bbr_manager.cpp index 2de2f6f82..a4914b99f 100644 --- a/src/core/backbone_router/bbr_manager.cpp +++ b/src/core/backbone_router/bbr_manager.cpp @@ -40,6 +40,7 @@ #include "common/instance.hpp" #include "common/locator_getters.hpp" #include "common/log.hpp" +#include "common/min_max.hpp" #include "common/random.hpp" #include "thread/mle_types.hpp" #include "thread/thread_netif.hpp" @@ -224,7 +225,7 @@ void Manager::HandleMulticastListenerRegistration(const Coap::Message &aMessage, { uint32_t origTimeout = timeout; - timeout = OT_MIN(timeout, static_cast(Mle::kMlrTimeoutMax)); + timeout = Min(timeout, Mle::kMlrTimeoutMax); if (timeout != origTimeout) { diff --git a/src/core/backbone_router/ndproxy_table.cpp b/src/core/backbone_router/ndproxy_table.cpp index 89c044225..6d8a6c9e5 100644 --- a/src/core/backbone_router/ndproxy_table.cpp +++ b/src/core/backbone_router/ndproxy_table.cpp @@ -38,6 +38,7 @@ #include "common/array.hpp" #include "common/locator_getters.hpp" #include "common/log.hpp" +#include "common/min_max.hpp" namespace ot { @@ -66,10 +67,9 @@ void NdProxyTable::NdProxy::Update(uint16_t aRloc16, uint32_t aTimeSinceLastTran { OT_ASSERT(mValid); - mRloc16 = aRloc16; - aTimeSinceLastTransaction = - OT_MIN(aTimeSinceLastTransaction, static_cast(Mle::kTimeSinceLastTransactionMax)); - mLastRegistrationTime = TimerMilli::GetNow() - TimeMilli::SecToMsec(aTimeSinceLastTransaction); + mRloc16 = aRloc16; + aTimeSinceLastTransaction = Min(aTimeSinceLastTransaction, Mle::kTimeSinceLastTransactionMax); + mLastRegistrationTime = TimerMilli::GetNow() - TimeMilli::SecToMsec(aTimeSinceLastTransaction); } bool NdProxyTable::MatchesFilter(const NdProxy &aProxy, Filter aFilter) diff --git a/src/core/border_router/routing_manager.cpp b/src/core/border_router/routing_manager.cpp index 48a7808c3..9d2ec8454 100644 --- a/src/core/border_router/routing_manager.cpp +++ b/src/core/border_router/routing_manager.cpp @@ -45,6 +45,7 @@ #include "common/instance.hpp" #include "common/locator_getters.hpp" #include "common/log.hpp" +#include "common/min_max.hpp" #include "common/random.hpp" #include "common/settings.hpp" #include "meshcop/extended_panid.hpp" @@ -654,7 +655,7 @@ void RoutingManager::StartRoutingPolicyEvaluationDelay(uint32_t aDelayMilli) TimeMilli evaluateTime = now + aDelayMilli; TimeMilli earliestTime = mLastRouterAdvertisementSendTime + kMinDelayBetweenRtrAdvs; - evaluateTime = OT_MAX(evaluateTime, earliestTime); + evaluateTime = Max(evaluateTime, earliestTime); LogInfo("Start evaluating routing policy, scheduled in %u milliseconds", evaluateTime - now); @@ -1254,9 +1255,9 @@ void RoutingManager::ResetDiscoveredPrefixStaleTimer(void) // Check for stale Router Advertisement Message if learnt from Host. if (mLearntRouterAdvMessageFromHost) { - TimeMilli raStaleTime = OT_MAX(now, mTimeRouterAdvMessageLastUpdate + Time::SecToMsec(kRtrAdvStaleTime)); + TimeMilli raStaleTime = Max(now, mTimeRouterAdvMessageLastUpdate + Time::SecToMsec(kRtrAdvStaleTime)); - nextStaleTime = OT_MIN(nextStaleTime, raStaleTime); + nextStaleTime = Min(nextStaleTime, raStaleTime); } if (nextStaleTime == now.GetDistantFuture()) @@ -1646,22 +1647,22 @@ TimeMilli RoutingManager::DiscoveredPrefixTable::CalculateNextStaleTime(TimeMill { for (const Entry &entry : router.mEntries) { - TimeMilli entryStaleTime = OT_MAX(aNow, entry.GetStaleTime()); + TimeMilli entryStaleTime = Max(aNow, entry.GetStaleTime()); if (entry.IsOnLinkPrefix() && !entry.IsDeprecated()) { - onLinkStaleTime = OT_MAX(onLinkStaleTime, entryStaleTime); + onLinkStaleTime = Max(onLinkStaleTime, entryStaleTime); foundOnLink = true; } if (!entry.IsOnLinkPrefix()) { - routeStaleTime = OT_MIN(routeStaleTime, entryStaleTime); + routeStaleTime = Min(routeStaleTime, entryStaleTime); } } } - return foundOnLink ? OT_MIN(onLinkStaleTime, routeStaleTime) : routeStaleTime; + return foundOnLink ? Min(onLinkStaleTime, routeStaleTime) : routeStaleTime; } void RoutingManager::DiscoveredPrefixTable::RemoveRoutersWithNoEntries(void) @@ -1801,7 +1802,7 @@ void RoutingManager::DiscoveredPrefixTable::RemoveExpiredEntries(void) { for (const Entry &entry : router.mEntries) { - nextExpireTime = OT_MIN(nextExpireTime, entry.GetExpireTime()); + nextExpireTime = Min(nextExpireTime, entry.GetExpireTime()); } } @@ -1920,7 +1921,7 @@ TimeMilli RoutingManager::DiscoveredPrefixTable::Entry::GetExpireTime(void) cons TimeMilli RoutingManager::DiscoveredPrefixTable::Entry::GetStaleTime(void) const { - uint32_t delay = OT_MIN(kRtrAdvStaleTime, IsOnLinkPrefix() ? GetPreferredLifetime() : mValidLifetime); + uint32_t delay = Min(kRtrAdvStaleTime, IsOnLinkPrefix() ? GetPreferredLifetime() : mValidLifetime); return mLastUpdateTime + TimeMilli::SecToMsec(delay); } diff --git a/src/core/common/data.hpp b/src/core/common/data.hpp index 59b37a3a3..d763307e7 100644 --- a/src/core/common/data.hpp +++ b/src/core/common/data.hpp @@ -44,6 +44,7 @@ #include "common/const_cast.hpp" #include "common/equatable.hpp" #include "common/error.hpp" +#include "common/min_max.hpp" #include "common/type_traits.hpp" namespace ot { @@ -360,7 +361,7 @@ public: { Error error = (mLength >= aLength) ? kErrorNone : kErrorNoBufs; - mLength = OT_MIN(mLength, aLength); + mLength = Min(mLength, aLength); memcpy(AsNonConst(mBuffer), aBuffer, mLength); return error; diff --git a/src/core/common/log.cpp b/src/core/common/log.cpp index a0a126a66..5e920315e 100644 --- a/src/core/common/log.cpp +++ b/src/core/common/log.cpp @@ -39,6 +39,7 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" +#include "common/min_max.hpp" #include "common/string.hpp" /* @@ -244,7 +245,7 @@ void Logger::DumpInModule(const char *aModuleName, for (uint16_t i = 0; i < aDataLength; i += kDumpBytesPerLine) { DumpLine(aModuleName, aLogLevel, static_cast(aData) + i, - OT_MIN((aDataLength - i), kDumpBytesPerLine)); + Min(static_cast(aDataLength - i), kDumpBytesPerLine)); } string.Clear(); diff --git a/src/core/common/min_max.hpp b/src/core/common/min_max.hpp new file mode 100644 index 000000000..20dfb44a2 --- /dev/null +++ b/src/core/common/min_max.hpp @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2022, The OpenThread Authors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @file + * This file includes definitions for generic min, max and clamp functions. + */ + +#ifndef MIN_MAX_HPP_ +#define MIN_MAX_HPP_ + +#include "common/numeric_limits.hpp" +#include "common/type_traits.hpp" + +namespace ot { + +/** + * This template method returns the minimum of two given values. + * + * Uses `operator<` to compare the values. + * + * @tparam Type The value type. + * + * @param[in] aFirst The first value. + * @param[in] aSecond The second value. + * + * @returns The minimum of @p aFirst and @p aSecond. + * + */ +template Type Min(Type aFirst, Type aSecond) +{ + return (aFirst < aSecond) ? aFirst : aSecond; +} + +/** + * This template method returns the maximum of two given values. + * + * Uses `operator<` to compare the values. + * + * @tparam Type The value type. + * + * @param[in] aFirst The first value. + * @param[in] aSecond The second value. + * + * @returns The maximum of @p aFirst and @p aSecond. + * + */ +template Type Max(Type aFirst, Type aSecond) +{ + return (aFirst < aSecond) ? aSecond : aFirst; +} + +/** + * This template method returns clamped version of a given value to a given closed range [min, max]. + * + * Uses `operator<` to compare the values. The behavior is undefined if the value of @p aMin is greater than @p aMax. + * + * @tparam Type The value type. + * + * @param[in] aValue The value to clamp. + * @param[in] aMin The minimum value. + * @param[in] aMax The maximum value. + * + * @returns The clamped version of @aValue to the closed range [@p aMin, @p aMax]. + * + */ +template Type Clamp(Type aValue, Type aMin, Type aMax) +{ + Type value = Max(aValue, aMin); + + return Min(value, aMax); +} + +/** + * This template method returns a clamped version of given integer to a `uint8_t`. + * + * If @p aValue is greater than max value of a `uint8_t`, the max value is returned. + * + * @tparam UintType The value type (MUST be `uint16_t`, `uint32_t`, or `uint64_t`). + * + * @param[in] aValue The value to clamp. + * + * @returns The clamped version of @p aValue to `uint8_t`. + * + */ +template uint8_t ClampToUint8(UintType aValue) +{ + static_assert(TypeTraits::IsSame::kValue || TypeTraits::IsSame::kValue || + TypeTraits::IsSame::kValue, + "UintType must be `uint16_t, `uint32_t`, or `uint64_t`"); + + return static_cast(Min(aValue, static_cast(NumericLimits::kMax))); +} + +/** + * This template method returns a clamped version of given integer to a `uint16_t`. + * + * If @p aValue is greater than max value of a `uint16_t`, the max value is returned. + * + * @tparam UintType The value type (MUST be `uint32_t`, or `uint64_t`). + * + * @param[in] aValue The value to clamp. + * + * @returns The clamped version of @p aValue to `uint16_t`. + * + */ +template uint16_t ClampToUint16(UintType aValue) +{ + static_assert(TypeTraits::IsSame::kValue || TypeTraits::IsSame::kValue, + "UintType must be `uint32_t` or `uint64_t`"); + + return static_cast(Min(aValue, static_cast(NumericLimits::kMax))); +} + +} // namespace ot + +#endif // MIN_MAX_HPP_ diff --git a/src/core/mac/data_poll_sender.cpp b/src/core/mac/data_poll_sender.cpp index 2c5b0899f..825d88f1e 100644 --- a/src/core/mac/data_poll_sender.cpp +++ b/src/core/mac/data_poll_sender.cpp @@ -38,6 +38,7 @@ #include "common/locator_getters.hpp" #include "common/log.hpp" #include "common/message.hpp" +#include "common/min_max.hpp" #include "net/ip6.hpp" #include "net/netif.hpp" #include "thread/mesh_forwarder.hpp" @@ -197,7 +198,7 @@ uint32_t DataPollSender::GetKeepAlivePollPeriod(void) const if (mExternalPollPeriod != 0) { - period = OT_MIN(period, mExternalPollPeriod); + period = Min(period, mExternalPollPeriod); } return period; @@ -506,22 +507,22 @@ uint32_t DataPollSender::CalculatePollPeriod(void) const if (mAttachMode) { - period = OT_MIN(period, kAttachDataPollPeriod); + period = Min(period, kAttachDataPollPeriod); } if (mRetxMode) { - period = OT_MIN(period, kRetxPollPeriod); + period = Min(period, kRetxPollPeriod); } if (mRemainingFastPolls != 0) { - period = OT_MIN(period, kFastPollPeriod); + period = Min(period, kFastPollPeriod); } if (mExternalPollPeriod != 0) { - period = OT_MIN(period, mExternalPollPeriod); + period = Min(period, mExternalPollPeriod); } if (period == 0) @@ -545,7 +546,7 @@ uint32_t DataPollSender::GetDefaultPollPeriod(void) const #if OPENTHREAD_CONFIG_MAC_CSL_RECEIVER_ENABLE && OPENTHREAD_CONFIG_MAC_CSL_AUTO_SYNC_ENABLE if (Get().IsCslEnabled()) { - period = OT_MIN(period, Time::SecToMsec(Get().GetCslTimeout())); + period = Min(period, Time::SecToMsec(Get().GetCslTimeout())); pollAhead = static_cast(kRetxPollPeriod); } #endif diff --git a/src/core/mac/sub_mac.cpp b/src/core/mac/sub_mac.cpp index 7d5cccdc9..2beb755a3 100644 --- a/src/core/mac/sub_mac.cpp +++ b/src/core/mac/sub_mac.cpp @@ -42,6 +42,7 @@ #include "common/instance.hpp" #include "common/locator_getters.hpp" #include "common/log.hpp" +#include "common/min_max.hpp" #include "common/random.hpp" #include "common/time.hpp" #include "mac/mac_frame.hpp" @@ -612,7 +613,8 @@ void SubMac::HandleTransmitDone(TxFrame &aFrame, RxFrame *aAckFrame, Error aErro { SetState(kStateDelayBeforeRetx); StartTimerForBackoff(mRetxDelayBackOffExponent); - mRetxDelayBackOffExponent = OT_MIN(mRetxDelayBackOffExponent + 1, kRetxDelayMaxBackoffExponent); + mRetxDelayBackOffExponent = + Min(static_cast(mRetxDelayBackOffExponent + 1), kRetxDelayMaxBackoffExponent); ExitNow(); } #endif diff --git a/src/core/meshcop/meshcop_tlvs.cpp b/src/core/meshcop/meshcop_tlvs.cpp index c047ed9f4..abdfc9bf0 100644 --- a/src/core/meshcop/meshcop_tlvs.cpp +++ b/src/core/meshcop/meshcop_tlvs.cpp @@ -35,6 +35,7 @@ #include "common/const_cast.hpp" #include "common/debug.hpp" +#include "common/min_max.hpp" #include "common/string.hpp" #include "meshcop/meshcop.hpp" @@ -154,7 +155,7 @@ bool SecurityPolicyTlv::IsValid(void) const SecurityPolicy SecurityPolicyTlv::GetSecurityPolicy(void) const { SecurityPolicy securityPolicy; - uint8_t length = OT_MIN(static_cast(sizeof(mFlags)), GetFlagsLength()); + uint8_t length = Min(static_cast(sizeof(mFlags)), GetFlagsLength()); securityPolicy.mRotationTime = GetRotationTime(); securityPolicy.SetFlags(mFlags, length); diff --git a/src/core/net/dns_dso.cpp b/src/core/net/dns_dso.cpp index a18b45938..a42d8f144 100644 --- a/src/core/net/dns_dso.cpp +++ b/src/core/net/dns_dso.cpp @@ -37,6 +37,7 @@ #include "common/instance.hpp" #include "common/locator_getters.hpp" #include "common/log.hpp" +#include "common/min_max.hpp" #include "common/random.hpp" /** @@ -1125,7 +1126,7 @@ void Dso::Connection::AdjustInactivityTimeout(uint32_t aNewTimeout) // five seconds or one quarter of the new inactivity // timeout, whichever is greater [RFC 8490 - 7.1.1]. - newExpiration = now + OT_MAX(kMinServerInactivityWaitTime, aNewTimeout / 4); + newExpiration = now + Max(kMinServerInactivityWaitTime, aNewTimeout / 4); } } @@ -1143,7 +1144,7 @@ uint32_t Dso::Connection::CalculateServerInactivityWaitTime(void) const OT_ASSERT(mInactivity.IsUsed()); - return OT_MAX(mInactivity.GetInterval() * 2, kMinServerInactivityWaitTime); + return Max(mInactivity.GetInterval() * 2, kMinServerInactivityWaitTime); } void Dso::Connection::ResetTimeouts(bool aIsKeepAliveMessage) @@ -1219,12 +1220,12 @@ TimeMilli Dso::Connection::GetNextFireTime(TimeMilli aNow) const case kStateConnectedButSessionless: case kStateEstablishingSession: case kStateSessionEstablished: - nextTime = OT_MIN(nextTime, mPendingRequests.GetNextFireTime(aNow)); + nextTime = Min(nextTime, mPendingRequests.GetNextFireTime(aNow)); if (mKeepAlive.IsUsed()) { VerifyOrExit(mKeepAlive.GetExpirationTime() > aNow, nextTime = aNow); - nextTime = OT_MIN(nextTime, mKeepAlive.GetExpirationTime()); + nextTime = Min(nextTime, mKeepAlive.GetExpirationTime()); } if (mInactivity.IsUsed() && mPendingRequests.IsEmpty() && !mLongLivedOperation) @@ -1234,7 +1235,7 @@ TimeMilli Dso::Connection::GetNextFireTime(TimeMilli aNow) const // active long-lived operation. VerifyOrExit(mInactivity.GetExpirationTime() > aNow, nextTime = aNow); - nextTime = OT_MIN(nextTime, mInactivity.GetExpirationTime()); + nextTime = Min(nextTime, mInactivity.GetExpirationTime()); } break; @@ -1311,7 +1312,7 @@ void Dso::Connection::HandleTimer(TimeMilli aNow, TimeMilli &aNextTime) } exit: - aNextTime = OT_MIN(aNextTime, GetNextFireTime(aNow)); + aNextTime = Min(aNextTime, GetNextFireTime(aNow)); SignalAnyStateChange(); } @@ -1435,7 +1436,7 @@ TimeMilli Dso::Connection::PendingRequests::GetNextFireTime(TimeMilli aNow) cons for (const Entry &entry : mRequests) { VerifyOrExit(entry.mTimeout > aNow, nextTime = aNow); - nextTime = OT_MIN(entry.mTimeout, nextTime); + nextTime = Min(entry.mTimeout, nextTime); } exit: diff --git a/src/core/net/dns_dso.hpp b/src/core/net/dns_dso.hpp index d9ff458cd..05ff9eeca 100644 --- a/src/core/net/dns_dso.hpp +++ b/src/core/net/dns_dso.hpp @@ -42,6 +42,7 @@ #include "common/linked_list.hpp" #include "common/locator.hpp" #include "common/message.hpp" +#include "common/min_max.hpp" #include "common/non_copyable.hpp" #include "common/timer.hpp" #include "net/dns_types.hpp" @@ -773,7 +774,7 @@ public: // If it is not infinite, limit the interval to `kMaxInterval`. // The max limit ensures that even twice the interval is less // than max OpenThread timer duration. - return (aInterval == kInfinite) ? aInterval : OT_MIN(aInterval, kMaxInterval); + return (aInterval == kInfinite) ? aInterval : Min(aInterval, kMaxInterval); } uint32_t mInterval; diff --git a/src/core/net/dns_types.cpp b/src/core/net/dns_types.cpp index e65cd035a..0aaa45246 100644 --- a/src/core/net/dns_types.cpp +++ b/src/core/net/dns_types.cpp @@ -36,6 +36,7 @@ #include "common/code_utils.hpp" #include "common/debug.hpp" #include "common/instance.hpp" +#include "common/min_max.hpp" #include "common/random.hpp" #include "common/string.hpp" @@ -334,7 +335,7 @@ Error Name::ReadName(const Message &aMessage, uint16_t &aOffset, char *aNameBuff // here since `iterator.ReadLabel()` would verify it. } - labelLength = static_cast(OT_MIN(static_cast(kMaxLabelSize), aNameBufferSize)); + labelLength = static_cast(Min(static_cast(kMaxLabelSize), aNameBufferSize)); SuccessOrExit(error = iterator.ReadLabel(aNameBuffer, labelLength, /* aAllowDotCharInLabel */ false)); aNameBuffer += labelLength; aNameBufferSize -= labelLength; diff --git a/src/core/net/ip6_address.cpp b/src/core/net/ip6_address.cpp index cbf657df2..848a49244 100644 --- a/src/core/net/ip6_address.cpp +++ b/src/core/net/ip6_address.cpp @@ -40,6 +40,7 @@ #include "common/code_utils.hpp" #include "common/encoding.hpp" #include "common/instance.hpp" +#include "common/min_max.hpp" #include "common/numeric_limits.hpp" #include "common/random.hpp" #include "net/ip4_types.hpp" @@ -112,7 +113,7 @@ bool Prefix::operator<(const Prefix &aOther) const uint8_t minLength; uint8_t matchedLength; - minLength = OT_MIN(GetLength(), aOther.GetLength()); + minLength = Min(GetLength(), aOther.GetLength()); matchedLength = MatchLength(GetBytes(), aOther.GetBytes(), SizeForLength(minLength)); if (matchedLength >= minLength) diff --git a/src/core/net/srp_client.cpp b/src/core/net/srp_client.cpp index 5bf507be1..ac4bfb6cf 100644 --- a/src/core/net/srp_client.cpp +++ b/src/core/net/srp_client.cpp @@ -35,6 +35,7 @@ #include "common/debug.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" +#include "common/min_max.hpp" #include "common/random.hpp" #include "common/settings.hpp" #include "common/string.hpp" @@ -1725,7 +1726,7 @@ uint32_t Client::GetBoundedLeaseInterval(uint32_t aInterval, uint32_t aDefaultIn if (aInterval != 0) { - boundedInterval = OT_MIN(aInterval, static_cast(kMaxLease)); + boundedInterval = Min(aInterval, kMaxLease); } return boundedInterval; diff --git a/src/core/net/srp_server.cpp b/src/core/net/srp_server.cpp index cdcee311f..e1af200b6 100644 --- a/src/core/net/srp_server.cpp +++ b/src/core/net/srp_server.cpp @@ -40,6 +40,7 @@ #include "common/instance.hpp" #include "common/locator_getters.hpp" #include "common/log.hpp" +#include "common/min_max.hpp" #include "common/new.hpp" #include "common/random.hpp" #include "net/dns_types.hpp" @@ -189,7 +190,7 @@ uint32_t Server::TtlConfig::GrantTtl(uint32_t aLease, uint32_t aTtl) const { OT_ASSERT(mMinTtl <= mMaxTtl); - return OT_MAX(mMinTtl, OT_MIN(OT_MIN(mMaxTtl, aLease), aTtl)); + return Clamp(Min(aTtl, aLease), mMinTtl, mMaxTtl); } Server::LeaseConfig::LeaseConfig(void) @@ -222,14 +223,14 @@ uint32_t Server::LeaseConfig::GrantLease(uint32_t aLease) const { OT_ASSERT(mMinLease <= mMaxLease); - return (aLease == 0) ? 0 : OT_MAX(mMinLease, OT_MIN(mMaxLease, aLease)); + return (aLease == 0) ? 0 : Clamp(aLease, mMinLease, mMaxLease); } uint32_t Server::LeaseConfig::GrantKeyLease(uint32_t aKeyLease) const { OT_ASSERT(mMinKeyLease <= mMaxKeyLease); - return (aKeyLease == 0) ? 0 : OT_MAX(mMinKeyLease, OT_MIN(mMaxKeyLease, aKeyLease)); + return (aKeyLease == 0) ? 0 : Clamp(aKeyLease, mMinKeyLease, mMaxKeyLease); } Error Server::SetLeaseConfig(const LeaseConfig &aLeaseConfig) @@ -1482,7 +1483,7 @@ void Server::HandleLeaseTimer(void) Service *next; - earliestExpireTime = OT_MIN(earliestExpireTime, host->GetKeyExpireTime()); + earliestExpireTime = Min(earliestExpireTime, host->GetKeyExpireTime()); // Check if any service instance name expired. for (Service *service = host->mServices.GetHead(); service != nullptr; service = next) @@ -1498,7 +1499,7 @@ void Server::HandleLeaseTimer(void) } else { - earliestExpireTime = OT_MIN(earliestExpireTime, service->GetKeyExpireTime()); + earliestExpireTime = Min(earliestExpireTime, service->GetKeyExpireTime()); } } } @@ -1515,7 +1516,7 @@ void Server::HandleLeaseTimer(void) RemoveHost(host, kRetainName, kNotifyServiceHandler); - earliestExpireTime = OT_MIN(earliestExpireTime, host->GetKeyExpireTime()); + earliestExpireTime = Min(earliestExpireTime, host->GetKeyExpireTime()); } else { @@ -1525,7 +1526,7 @@ void Server::HandleLeaseTimer(void) OT_ASSERT(!host->IsDeleted()); - earliestExpireTime = OT_MIN(earliestExpireTime, host->GetExpireTime()); + earliestExpireTime = Min(earliestExpireTime, host->GetExpireTime()); for (Service *service = host->mServices.GetHead(); service != nullptr; service = next) { @@ -1539,7 +1540,7 @@ void Server::HandleLeaseTimer(void) else if (service->mIsDeleted) { // The service has been deleted but the name retains. - earliestExpireTime = OT_MIN(earliestExpireTime, service->GetKeyExpireTime()); + earliestExpireTime = Min(earliestExpireTime, service->GetKeyExpireTime()); } else if (service->GetExpireTime() <= now) { @@ -1547,11 +1548,11 @@ void Server::HandleLeaseTimer(void) // The service is expired, delete it. host->RemoveService(service, kRetainName, kNotifyServiceHandler); - earliestExpireTime = OT_MIN(earliestExpireTime, service->GetKeyExpireTime()); + earliestExpireTime = Min(earliestExpireTime, service->GetKeyExpireTime()); } else { - earliestExpireTime = OT_MIN(earliestExpireTime, service->GetExpireTime()); + earliestExpireTime = Min(earliestExpireTime, service->GetExpireTime()); } } } diff --git a/src/core/net/srp_server.hpp b/src/core/net/srp_server.hpp index b2c371688..7e8cfc6ed 100644 --- a/src/core/net/srp_server.hpp +++ b/src/core/net/srp_server.hpp @@ -63,6 +63,7 @@ #include "common/heap_string.hpp" #include "common/linked_list.hpp" #include "common/locator.hpp" +#include "common/min_max.hpp" #include "common/non_copyable.hpp" #include "common/notifier.hpp" #include "common/numeric_limits.hpp" @@ -472,7 +473,8 @@ public: */ const Ip6::Address *GetAddresses(uint8_t &aAddressesNum) const { - aAddressesNum = static_cast(OT_MIN(mAddresses.GetLength(), NumericLimits::kMax)); + aAddressesNum = ClampToUint8(mAddresses.GetLength()); + return mAddresses.AsCArray(); } diff --git a/src/core/net/tcp6.cpp b/src/core/net/tcp6.cpp index 9b18a06dd..4264e9ebd 100644 --- a/src/core/net/tcp6.cpp +++ b/src/core/net/tcp6.cpp @@ -43,6 +43,7 @@ #include "common/instance.hpp" #include "common/locator_getters.hpp" #include "common/log.hpp" +#include "common/min_max.hpp" #include "common/random.hpp" #include "net/checksum.hpp" #include "net/ip6.hpp" @@ -431,7 +432,7 @@ bool Tcp::Endpoint::FirePendingTimers(TimeMilli aNow, bool &aHasFutureTimer, Tim else { aHasFutureTimer = true; - aEarliestFutureExpiry = OT_MIN(aEarliestFutureExpiry, expiry); + aEarliestFutureExpiry = Min(aEarliestFutureExpiry, expiry); } } } diff --git a/src/core/thread/link_quality.cpp b/src/core/thread/link_quality.cpp index f3e1cb291..26549a419 100644 --- a/src/core/thread/link_quality.cpp +++ b/src/core/thread/link_quality.cpp @@ -38,6 +38,7 @@ #include "common/code_utils.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" +#include "common/min_max.hpp" namespace ot { @@ -123,7 +124,8 @@ void LqiAverager::Add(uint8_t aLqi) { mCount++; } - count = OT_MIN((1 << kCoeffBitShift), mCount); + + count = Min(static_cast(1 << kCoeffBitShift), mCount); mAverage = static_cast(((mAverage * (count - 1)) + aLqi) / count); } diff --git a/src/core/thread/mesh_forwarder_ftd.cpp b/src/core/thread/mesh_forwarder_ftd.cpp index 09ea455f8..2ef170f51 100644 --- a/src/core/thread/mesh_forwarder_ftd.cpp +++ b/src/core/thread/mesh_forwarder_ftd.cpp @@ -36,6 +36,7 @@ #if OPENTHREAD_FTD #include "common/locator_getters.hpp" +#include "common/min_max.hpp" #include "meshcop/meshcop.hpp" #include "net/ip6.hpp" #include "net/tcp6.hpp" @@ -456,7 +457,7 @@ void MeshForwarder::EvaluateRoutingCost(uint16_t aDest, uint8_t &aBestCost, uint } // Choose the minimum cost - curCost = OT_MIN(curCost, cost); + curCost = Min(curCost, cost); } if ((aBestDest == Mac::kShortAddrInvalid) || (curCost < aBestCost)) diff --git a/src/core/thread/mle.cpp b/src/core/thread/mle.cpp index 65722dbe8..0a59e1bd1 100644 --- a/src/core/thread/mle.cpp +++ b/src/core/thread/mle.cpp @@ -43,6 +43,7 @@ #include "common/encoding.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" +#include "common/min_max.hpp" #include "common/random.hpp" #include "common/serial_number.hpp" #include "common/settings.hpp" @@ -1358,7 +1359,7 @@ bool Mle::HasAcceptableParentCandidate(void) const // in Parent Request was sent to routers, we will keep the // candidate and forward to REED stage to potentially find a // better parent. - linkQuality = OT_MIN(mParentCandidate.GetLinkInfo().GetLinkQuality(), mParentCandidate.GetLinkQualityOut()); + linkQuality = Min(mParentCandidate.GetLinkInfo().GetLinkQuality(), mParentCandidate.GetLinkQualityOut()); VerifyOrExit(linkQuality == kLinkQuality3); } @@ -2986,7 +2987,7 @@ bool Mle::IsBetterParent(uint16_t aRloc16, bool rval = false; LinkQuality candidateLinkQualityIn = mParentCandidate.GetLinkInfo().GetLinkQuality(); - LinkQuality candidateTwoWayLinkQuality = OT_MIN(candidateLinkQualityIn, mParentCandidate.GetLinkQualityOut()); + LinkQuality candidateTwoWayLinkQuality = Min(candidateLinkQualityIn, mParentCandidate.GetLinkQualityOut()); #if OPENTHREAD_CONFIG_MAC_CSL_RECEIVER_ENABLE uint64_t candidateCslMetric = 0; uint64_t cslMetric = 0; diff --git a/src/core/utils/history_tracker.cpp b/src/core/utils/history_tracker.cpp index 199146569..a93fa7946 100644 --- a/src/core/utils/history_tracker.cpp +++ b/src/core/utils/history_tracker.cpp @@ -40,6 +40,7 @@ #include "common/debug.hpp" #include "common/instance.hpp" #include "common/locator_getters.hpp" +#include "common/min_max.hpp" #include "common/string.hpp" #include "common/timer.hpp" #include "net/ip6_headers.hpp" @@ -436,7 +437,7 @@ void HistoryTracker::Timestamp::SetToNow(void) uint32_t HistoryTracker::Timestamp::GetDurationTill(TimeMilli aTime) const { - return IsDistantPast() ? kMaxAge : OT_MIN(aTime - mTime, kMaxAge); + return IsDistantPast() ? kMaxAge : Min(aTime - mTime, kMaxAge); } //--------------------------------------------------------------------------------------------------------------------- diff --git a/src/core/utils/ping_sender.cpp b/src/core/utils/ping_sender.cpp index a0fe9c6e1..e731f995c 100644 --- a/src/core/utils/ping_sender.cpp +++ b/src/core/utils/ping_sender.cpp @@ -38,6 +38,7 @@ #include "common/as_core_type.hpp" #include "common/encoding.hpp" #include "common/locator_getters.hpp" +#include "common/min_max.hpp" #include "common/random.hpp" namespace ot { @@ -208,17 +209,16 @@ void PingSender::HandleIcmpReceive(const Message & aMessage, SuccessOrExit(aMessage.Read(aMessage.GetOffset(), timestamp)); timestamp = HostSwap32(timestamp); - reply.mSenderAddress = aMessageInfo.GetPeerAddr(); - reply.mRoundTripTime = - static_cast(OT_MIN(TimerMilli::GetNow() - TimeMilli(timestamp), NumericLimits::kMax)); + reply.mSenderAddress = aMessageInfo.GetPeerAddr(); + reply.mRoundTripTime = ClampToUint16(TimerMilli::GetNow() - TimeMilli(timestamp)); reply.mSize = aMessage.GetLength() - aMessage.GetOffset(); reply.mSequenceNumber = aIcmpHeader.GetSequence(); reply.mHopLimit = aMessageInfo.GetHopLimit(); mStatistics.mReceivedCount++; mStatistics.mTotalRoundTripTime += reply.mRoundTripTime; - mStatistics.mMaxRoundTripTime = OT_MAX(mStatistics.mMaxRoundTripTime, reply.mRoundTripTime); - mStatistics.mMinRoundTripTime = OT_MIN(mStatistics.mMinRoundTripTime, reply.mRoundTripTime); + mStatistics.mMaxRoundTripTime = Max(mStatistics.mMaxRoundTripTime, reply.mRoundTripTime); + mStatistics.mMinRoundTripTime = Min(mStatistics.mMinRoundTripTime, reply.mRoundTripTime); #if OPENTHREAD_CONFIG_OTNS_ENABLE Get().EmitPingReply(aMessageInfo.GetPeerAddr(), reply.mSize, timestamp, reply.mHopLimit); diff --git a/tests/unit/test_serial_number.cpp b/tests/unit/test_serial_number.cpp index dc8d7a1eb..8a59b6b63 100644 --- a/tests/unit/test_serial_number.cpp +++ b/tests/unit/test_serial_number.cpp @@ -32,6 +32,7 @@ #include "test_util.h" #include "common/code_utils.hpp" +#include "common/min_max.hpp" #include "common/numeric_limits.hpp" #include "common/serial_number.hpp" @@ -65,6 +66,52 @@ template void TestSerialNumber(const char *aName) printf("TestSerialNumber<%s>() passed\n", aName); } +void TestMinMaxClamp(void) +{ + uint16_t u16; + uint32_t u32; + + VerifyOrQuit(Min(1, 2) == 1); + VerifyOrQuit(Min(2, 1) == 1); + VerifyOrQuit(Min(1, 1) == 1); + + VerifyOrQuit(Max(1, 2) == 2); + VerifyOrQuit(Max(2, 1) == 2); + VerifyOrQuit(Max(1, 1) == 1); + + VerifyOrQuit(Clamp(1, 5, 10) == 5); + VerifyOrQuit(Clamp(5, 5, 10) == 5); + VerifyOrQuit(Clamp(7, 5, 10) == 7); + VerifyOrQuit(Clamp(10, 5, 10) == 10); + VerifyOrQuit(Clamp(12, 5, 10) == 10); + + VerifyOrQuit(Clamp(10, 10, 10) == 10); + VerifyOrQuit(Clamp(9, 10, 10) == 10); + VerifyOrQuit(Clamp(11, 10, 10) == 10); + + u16 = 100; + VerifyOrQuit(ClampToUint8(u16) == 100); + u16 = 255; + VerifyOrQuit(ClampToUint8(u16) == 255); + u16 = 256; + VerifyOrQuit(ClampToUint8(u16) == 255); + u16 = 400; + VerifyOrQuit(ClampToUint8(u16) == 255); + + u32 = 100; + VerifyOrQuit(ClampToUint16(u32) == 100); + u32 = 256; + VerifyOrQuit(ClampToUint16(u32) == 256); + u32 = 0xffff; + VerifyOrQuit(ClampToUint16(u32) == 0xffff); + u32 = 0x10000; + VerifyOrQuit(ClampToUint16(u32) == 0xffff); + u32 = 0xfff0000; + VerifyOrQuit(ClampToUint16(u32) == 0xffff); + + printf("TestMinMaxClamp() passed\n"); +} + } // namespace ot int main(void) @@ -73,6 +120,7 @@ int main(void) ot::TestSerialNumber("uint16_t"); ot::TestSerialNumber("uint32_t"); ot::TestSerialNumber("uint64_t"); + ot::TestMinMaxClamp(); printf("\nAll tests passed.\n"); return 0; }