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 performs a three-way comparison between two values.
153  *
154  * @tparam Type   The value type.
155  *
156  * @param[in] aFirst  The first value.
157  * @param[in] aSecond The second value.
158  *
159  * @retval 1    If @p aFirst >  @p aSecond.
160  * @retval 0    If @p aFirst == @p aSecond.
161  * @retval -1   If @p aFirst <  @p aSecond.
162  */
ThreeWayCompare(Type aFirst,Type aSecond)163 template <typename Type> int ThreeWayCompare(Type aFirst, Type aSecond)
164 {
165     return (aFirst == aSecond) ? 0 : ((aFirst > aSecond) ? 1 : -1);
166 }
167 
168 /**
169  * This is template specialization of three-way comparison between two boolean values.
170  *
171  * @param[in] aFirst  The first boolean value.
172  * @param[in] aSecond The second boolean value.
173  *
174  * @retval 1    If @p aFirst is true and @p aSecond is false (true > false).
175  * @retval 0    If both @p aFirst and @p aSecond are true, or both are false (they are equal).
176  * @retval -1   If @p aFirst is false and @p aSecond is true (false < true).
177  */
ThreeWayCompare(bool aFirst,bool aSecond)178 template <> inline int ThreeWayCompare(bool aFirst, bool aSecond)
179 {
180     return (aFirst == aSecond) ? 0 : (aFirst ? 1 : -1);
181 }
182 
183 /**
184  * This template function divides two numbers and rounds the result to the closest integer.
185  *
186  * @tparam IntType   The integer type.
187  *
188  * @param[in] aDividend   The dividend value.
189  * @param[in] aDivisor    The divisor value.
190  *
191  * @return The result of division and rounding to the closest integer.
192  */
DivideAndRoundToClosest(IntType aDividend,IntType aDivisor)193 template <typename IntType> inline IntType DivideAndRoundToClosest(IntType aDividend, IntType aDivisor)
194 {
195     return (aDividend + (aDivisor / 2)) / aDivisor;
196 }
197 
198 /**
199  * This template function divides two numbers and always rounds the result up.
200  *
201  * @tparam IntType   The integer type.
202  *
203  * @param[in] aDividend   The dividend value.
204  * @param[in] aDivisor    The divisor value.
205  *
206  * @return The result of division and rounding up.
207  */
DivideAndRoundUp(IntType aDividend,IntType aDivisor)208 template <typename IntType> inline IntType DivideAndRoundUp(IntType aDividend, IntType aDivisor)
209 {
210     return (aDividend + (aDivisor - 1)) / aDivisor;
211 }
212 
213 /**
214  * Casts a given `uint32_t` to `unsigned long`.
215  *
216  * @param[in] aUint32   A `uint32_t` value.
217  *
218  * @returns The @p aUint32 value as `unsigned long`.
219  */
ToUlong(uint32_t aUint32)220 inline unsigned long ToUlong(uint32_t aUint32) { return static_cast<unsigned long>(aUint32); }
221 
222 /**
223  * Counts the number of `1` bits in the binary representation of a given unsigned int bit-mask value.
224  *
225  * @tparam UintType   The unsigned int type (MUST be `uint8_t`, uint16_t`, uint32_t`, or `uint64_t`).
226  *
227  * @param[in] aMask   A bit mask.
228  *
229  * @returns The number of `1` bits in @p aMask.
230  */
CountBitsInMask(UintType aMask)231 template <typename UintType> uint8_t CountBitsInMask(UintType aMask)
232 {
233     static_assert(TypeTraits::IsSame<UintType, uint8_t>::kValue || TypeTraits::IsSame<UintType, uint16_t>::kValue ||
234                       TypeTraits::IsSame<UintType, uint32_t>::kValue || TypeTraits::IsSame<UintType, uint64_t>::kValue,
235                   "UintType must be `uint8_t`, `uint16_t`, `uint32_t`, or `uint64_t`");
236 
237     uint8_t count = 0;
238 
239     while (aMask != 0)
240     {
241         aMask &= aMask - 1;
242         count++;
243     }
244 
245     return count;
246 }
247 
248 } // namespace ot
249 
250 #endif // NUM_UTILS_HPP_
251