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  *
54  */
Min(Type aFirst,Type aSecond)55 template <typename Type> Type Min(Type aFirst, Type aSecond) { return (aFirst < aSecond) ? aFirst : aSecond; }
56 
57 /**
58  * This template function returns the maximum of two given values.
59  *
60  * Uses `operator<` to compare the values.
61  *
62  * @tparam Type   The value type.
63  *
64  * @param[in] aFirst  The first value.
65  * @param[in] aSecond The second value.
66  *
67  * @returns The maximum of @p aFirst and @p aSecond.
68  *
69  */
Max(Type aFirst,Type aSecond)70 template <typename Type> Type Max(Type aFirst, Type aSecond) { return (aFirst < aSecond) ? aSecond : aFirst; }
71 
72 /**
73  * This template function returns clamped version of a given value to a given closed range [min, max].
74  *
75  * Uses `operator<` to compare the values. The behavior is undefined if the value of @p aMin is greater than @p aMax.
76  *
77  * @tparam Type   The value type.
78  *
79  * @param[in] aValue   The value to clamp.
80  * @param[in] aMin     The minimum value.
81  * @param[in] aMax     The maximum value.
82  *
83  * @returns The clamped version of @aValue to the closed range [@p aMin, @p aMax].
84  *
85  */
Clamp(Type aValue,Type aMin,Type aMax)86 template <typename Type> Type Clamp(Type aValue, Type aMin, Type aMax)
87 {
88     Type value = Max(aValue, aMin);
89 
90     return Min(value, aMax);
91 }
92 
93 /**
94  * This template function returns a clamped version of given integer to a `uint8_t`.
95  *
96  * If @p aValue is greater than max value of a `uint8_t`, the max value is returned.
97  *
98  * @tparam UintType   The value type (MUST be `uint16_t`, `uint32_t`, or `uint64_t`).
99  *
100  * @param[in] aValue  The value to clamp.
101  *
102  * @returns The clamped version of @p aValue to `uint8_t`.
103  *
104  */
ClampToUint8(UintType aValue)105 template <typename UintType> uint8_t ClampToUint8(UintType aValue)
106 {
107     static_assert(TypeTraits::IsSame<UintType, uint16_t>::kValue || TypeTraits::IsSame<UintType, uint32_t>::kValue ||
108                       TypeTraits::IsSame<UintType, uint64_t>::kValue,
109                   "UintType must be `uint16_t, `uint32_t`, or `uint64_t`");
110 
111     return static_cast<uint8_t>(Min(aValue, static_cast<UintType>(NumericLimits<uint8_t>::kMax)));
112 }
113 
114 /**
115  * This template function returns a clamped version of given integer to a `uint16_t`.
116  *
117  * If @p aValue is greater than max value of a `uint16_t`, the max value is returned.
118  *
119  * @tparam UintType   The value type (MUST be `uint32_t`, or `uint64_t`).
120  *
121  * @param[in] aValue  The value to clamp.
122  *
123  * @returns The clamped version of @p aValue to `uint16_t`.
124  *
125  */
ClampToUint16(UintType aValue)126 template <typename UintType> uint16_t ClampToUint16(UintType aValue)
127 {
128     static_assert(TypeTraits::IsSame<UintType, uint32_t>::kValue || TypeTraits::IsSame<UintType, uint64_t>::kValue,
129                   "UintType must be `uint32_t` or `uint64_t`");
130 
131     return static_cast<uint16_t>(Min(aValue, static_cast<UintType>(NumericLimits<uint16_t>::kMax)));
132 }
133 
134 /**
135  * This template function performs a three-way comparison between two values.
136  *
137  * @tparam Type   The value type.
138  *
139  * @param[in] aFirst  The first value.
140  * @param[in] aSecond The second value.
141  *
142  * @retval 1    If @p aFirst >  @p aSecond.
143  * @retval 0    If @p aFirst == @p aSecond.
144  * @retval -1   If @p aFirst <  @p aSecond.
145  *
146  */
ThreeWayCompare(Type aFirst,Type aSecond)147 template <typename Type> int ThreeWayCompare(Type aFirst, Type aSecond)
148 {
149     return (aFirst == aSecond) ? 0 : ((aFirst > aSecond) ? 1 : -1);
150 }
151 
152 /**
153  * This is template specialization of three-way comparison between two boolean values.
154  *
155  * @param[in] aFirst  The first boolean value.
156  * @param[in] aSecond The second boolean value.
157  *
158  * @retval 1    If @p aFirst is true and @p aSecond is false (true > false).
159  * @retval 0    If both @p aFirst and @p aSecond are true, or both are false (they are equal).
160  * @retval -1   If @p aFirst is false and @p aSecond is true (false < true).
161  *
162  */
ThreeWayCompare(bool aFirst,bool aSecond)163 template <> inline int ThreeWayCompare(bool aFirst, bool aSecond)
164 {
165     return (aFirst == aSecond) ? 0 : (aFirst ? 1 : -1);
166 }
167 
168 /**
169  * This template function divides two numbers and rounds the result to the closest integer.
170  *
171  * @tparam IntType   The integer type.
172  *
173  * @param[in] aDividend   The dividend value.
174  * @param[in] aDivisor    The divisor value.
175  *
176  * @return The result of division and rounding to the closest integer.
177  *
178  */
DivideAndRoundToClosest(IntType aDividend,IntType aDivisor)179 template <typename IntType> inline IntType DivideAndRoundToClosest(IntType aDividend, IntType aDivisor)
180 {
181     return (aDividend + (aDivisor / 2)) / aDivisor;
182 }
183 
184 /**
185  * This function casts a given `uint32_t` to `unsigned long`.
186  *
187  * @param[in] aUint32   A `uint32_t` value.
188  *
189  * @returns The @p aUint32 value as `unsigned long`.
190  *
191  */
ToUlong(uint32_t aUint32)192 inline unsigned long ToUlong(uint32_t aUint32) { return static_cast<unsigned long>(aUint32); }
193 
194 /**
195  * This function counts the number of `1` bits in the binary representation of a given unsigned int bit-mask value.
196  *
197  * @tparam UintType   The unsigned int type (MUST be `uint8_t`, uint16_t`, uint32_t`, or `uint64_t`).
198  *
199  * @param[in] aMask   A bit mask.
200  *
201  * @returns The number of `1` bits in @p aMask.
202  *
203  */
CountBitsInMask(UintType aMask)204 template <typename UintType> uint8_t CountBitsInMask(UintType aMask)
205 {
206     static_assert(TypeTraits::IsSame<UintType, uint8_t>::kValue || TypeTraits::IsSame<UintType, uint16_t>::kValue ||
207                       TypeTraits::IsSame<UintType, uint32_t>::kValue || TypeTraits::IsSame<UintType, uint64_t>::kValue,
208                   "UintType must be `uint8_t`, `uint16_t`, `uint32_t`, or `uint64_t`");
209 
210     uint8_t count = 0;
211 
212     while (aMask != 0)
213     {
214         aMask &= aMask - 1;
215         count++;
216     }
217 
218     return count;
219 }
220 
221 } // namespace ot
222 
223 #endif // NUM_UTILS_HPP_
224