1 /*
2 * Copyright (c) 2022, The OpenThread Authors.
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * 3. Neither the name of the copyright holder nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 * POSSIBILITY OF SUCH DAMAGE.
27 */
28
29 /**
30 * @file
31 * This file includes definitions for generic number utility functions (min, max, clamp).
32 */
33
34 #ifndef NUM_UTILS_HPP_
35 #define NUM_UTILS_HPP_
36
37 #include "common/numeric_limits.hpp"
38 #include "common/type_traits.hpp"
39
40 namespace ot {
41
42 /**
43 * This template function returns the minimum of two given values.
44 *
45 * Uses `operator<` to compare the values.
46 *
47 * @tparam Type The value type.
48 *
49 * @param[in] aFirst The first value.
50 * @param[in] aSecond The second value.
51 *
52 * @returns The minimum of @p aFirst and @p aSecond.
53 */
Min(Type aFirst,Type aSecond)54 template <typename Type> Type Min(Type aFirst, Type aSecond) { return (aFirst < aSecond) ? aFirst : aSecond; }
55
56 /**
57 * This template function returns the maximum of two given values.
58 *
59 * Uses `operator<` to compare the values.
60 *
61 * @tparam Type The value type.
62 *
63 * @param[in] aFirst The first value.
64 * @param[in] aSecond The second value.
65 *
66 * @returns The maximum of @p aFirst and @p aSecond.
67 */
Max(Type aFirst,Type aSecond)68 template <typename Type> Type Max(Type aFirst, Type aSecond) { return (aFirst < aSecond) ? aSecond : aFirst; }
69
70 /**
71 * This template function returns clamped version of a given value to a given closed range [min, max].
72 *
73 * Uses `operator<` to compare the values. The behavior is undefined if the value of @p aMin is greater than @p aMax.
74 *
75 * @tparam Type The value type.
76 *
77 * @param[in] aValue The value to clamp.
78 * @param[in] aMin The minimum value.
79 * @param[in] aMax The maximum value.
80 *
81 * @returns The clamped version of @aValue to the closed range [@p aMin, @p aMax].
82 */
Clamp(Type aValue,Type aMin,Type aMax)83 template <typename Type> Type Clamp(Type aValue, Type aMin, Type aMax)
84 {
85 Type value = Max(aValue, aMin);
86
87 return Min(value, aMax);
88 }
89
90 /**
91 * This template function returns a clamped version of given integer to a `uint8_t`.
92 *
93 * If @p aValue is greater than max value of a `uint8_t`, the max value is returned.
94 *
95 * @tparam UintType The value type (MUST be `uint16_t`, `uint32_t`, or `uint64_t`).
96 *
97 * @param[in] aValue The value to clamp.
98 *
99 * @returns The clamped version of @p aValue to `uint8_t`.
100 */
ClampToUint8(UintType aValue)101 template <typename UintType> uint8_t ClampToUint8(UintType aValue)
102 {
103 static_assert(TypeTraits::IsSame<UintType, uint16_t>::kValue || TypeTraits::IsSame<UintType, uint32_t>::kValue ||
104 TypeTraits::IsSame<UintType, uint64_t>::kValue,
105 "UintType must be `uint16_t, `uint32_t`, or `uint64_t`");
106
107 return static_cast<uint8_t>(Min(aValue, static_cast<UintType>(NumericLimits<uint8_t>::kMax)));
108 }
109
110 /**
111 * This template function returns a clamped version of given integer to a `uint16_t`.
112 *
113 * If @p aValue is greater than max value of a `uint16_t`, the max value is returned.
114 *
115 * @tparam UintType The value type (MUST be `uint32_t`, or `uint64_t`).
116 *
117 * @param[in] aValue The value to clamp.
118 *
119 * @returns The clamped version of @p aValue to `uint16_t`.
120 */
ClampToUint16(UintType aValue)121 template <typename UintType> uint16_t ClampToUint16(UintType aValue)
122 {
123 static_assert(TypeTraits::IsSame<UintType, uint32_t>::kValue || TypeTraits::IsSame<UintType, uint64_t>::kValue,
124 "UintType must be `uint32_t` or `uint64_t`");
125
126 return static_cast<uint16_t>(Min(aValue, static_cast<UintType>(NumericLimits<uint16_t>::kMax)));
127 }
128
129 /**
130 * Returns a clamped version of given integer to a `int8_t`.
131 *
132 * If @p aValue is smaller than min value of a `int8_t`, the min value of `int8_t` is returned.
133 * If @p aValue is larger than max value of a `int8_t`, the max value of `int8_t` is returned.
134 *
135 * @tparam IntType The value type (MUST be `int16_t`, `int32_t`, or `int64_t`).
136 *
137 * @param[in] aValue The value to clamp.
138 *
139 * @returns The clamped version of @p aValue to `int8_t`.
140 */
ClampToInt8(IntType aValue)141 template <typename IntType> int8_t ClampToInt8(IntType aValue)
142 {
143 static_assert(TypeTraits::IsSame<IntType, int16_t>::kValue || TypeTraits::IsSame<IntType, int32_t>::kValue ||
144 TypeTraits::IsSame<IntType, int64_t>::kValue,
145 "IntType must be `int16_t, `int32_t`, or `int64_t`");
146
147 return static_cast<int8_t>(Clamp(aValue, static_cast<IntType>(NumericLimits<int8_t>::kMin),
148 static_cast<IntType>(NumericLimits<int8_t>::kMax)));
149 }
150
151 /**
152 * This template function checks whether a given value is in a given closed range [min, max].
153 *
154 * Uses `operator<=` to compare the values. The behavior is undefined if the value of @p aMin is greater than @p aMax.
155 *
156 * @tparam Type The value type.
157 *
158 * @param[in] aValue The value to check
159 * @param[in] aMin The minimum value.
160 * @param[in] aMax The maximum value.
161 *
162 * @retval TRUE If @p aValue is within `[aMin, aMax]` (inclusive).
163 * @retval FALSE If @p aValue is not within `[aMin, aMax]` (inclusive).
164 */
IsValueInRange(Type aValue,Type aMin,Type aMax)165 template <typename Type> Type IsValueInRange(Type aValue, Type aMin, Type aMax)
166 {
167 return (aMin <= aValue) && (aValue <= aMax);
168 }
169
170 /**
171 * This template function performs a three-way comparison between two values.
172 *
173 * @tparam Type The value type.
174 *
175 * @param[in] aFirst The first value.
176 * @param[in] aSecond The second value.
177 *
178 * @retval 1 If @p aFirst > @p aSecond.
179 * @retval 0 If @p aFirst == @p aSecond.
180 * @retval -1 If @p aFirst < @p aSecond.
181 */
ThreeWayCompare(Type aFirst,Type aSecond)182 template <typename Type> int ThreeWayCompare(Type aFirst, Type aSecond)
183 {
184 return (aFirst == aSecond) ? 0 : ((aFirst > aSecond) ? 1 : -1);
185 }
186
187 /**
188 * This is template specialization of three-way comparison between two boolean values.
189 *
190 * @param[in] aFirst The first boolean value.
191 * @param[in] aSecond The second boolean value.
192 *
193 * @retval 1 If @p aFirst is true and @p aSecond is false (true > false).
194 * @retval 0 If both @p aFirst and @p aSecond are true, or both are false (they are equal).
195 * @retval -1 If @p aFirst is false and @p aSecond is true (false < true).
196 */
ThreeWayCompare(bool aFirst,bool aSecond)197 template <> inline int ThreeWayCompare(bool aFirst, bool aSecond)
198 {
199 return (aFirst == aSecond) ? 0 : (aFirst ? 1 : -1);
200 }
201
202 /**
203 * This template function divides two numbers and rounds the result to the closest integer.
204 *
205 * @tparam IntType The integer type.
206 *
207 * @param[in] aDividend The dividend value.
208 * @param[in] aDivisor The divisor value.
209 *
210 * @return The result of division and rounding to the closest integer.
211 */
DivideAndRoundToClosest(IntType aDividend,IntType aDivisor)212 template <typename IntType> inline IntType DivideAndRoundToClosest(IntType aDividend, IntType aDivisor)
213 {
214 return (aDividend + (aDivisor / 2)) / aDivisor;
215 }
216
217 /**
218 * This template function divides two numbers and always rounds the result up.
219 *
220 * @tparam IntType The integer type.
221 *
222 * @param[in] aDividend The dividend value.
223 * @param[in] aDivisor The divisor value.
224 *
225 * @return The result of division and rounding up.
226 */
DivideAndRoundUp(IntType aDividend,IntType aDivisor)227 template <typename IntType> inline IntType DivideAndRoundUp(IntType aDividend, IntType aDivisor)
228 {
229 return (aDividend + (aDivisor - 1)) / aDivisor;
230 }
231
232 /**
233 * Casts a given `uint32_t` to `unsigned long`.
234 *
235 * @param[in] aUint32 A `uint32_t` value.
236 *
237 * @returns The @p aUint32 value as `unsigned long`.
238 */
ToUlong(uint32_t aUint32)239 inline unsigned long ToUlong(uint32_t aUint32) { return static_cast<unsigned long>(aUint32); }
240
241 /**
242 * Counts the number of `1` bits in the binary representation of a given unsigned int bit-mask value.
243 *
244 * @tparam UintType The unsigned int type (MUST be `uint8_t`, uint16_t`, uint32_t`, or `uint64_t`).
245 *
246 * @param[in] aMask A bit mask.
247 *
248 * @returns The number of `1` bits in @p aMask.
249 */
CountBitsInMask(UintType aMask)250 template <typename UintType> uint8_t CountBitsInMask(UintType aMask)
251 {
252 static_assert(TypeTraits::IsSame<UintType, uint8_t>::kValue || TypeTraits::IsSame<UintType, uint16_t>::kValue ||
253 TypeTraits::IsSame<UintType, uint32_t>::kValue || TypeTraits::IsSame<UintType, uint64_t>::kValue,
254 "UintType must be `uint8_t`, `uint16_t`, `uint32_t`, or `uint64_t`");
255
256 uint8_t count = 0;
257
258 while (aMask != 0)
259 {
260 aMask &= aMask - 1;
261 count++;
262 }
263
264 return count;
265 }
266
267 } // namespace ot
268
269 #endif // NUM_UTILS_HPP_
270