xref: /linux-6.15/include/linux/minmax.h (revision 5e57418a)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef _LINUX_MINMAX_H
3 #define _LINUX_MINMAX_H
4 
5 #include <linux/compiler_types.h>
6 #include <linux/const.h>
7 #include <linux/types.h>
8 
9 /*
10  * min()/max()/clamp() macros must accomplish three things:
11  *
12  * - avoid multiple evaluations of the arguments (so side-effects like
13  *   "x++" happen only once) when non-constant.
14  * - perform strict type-checking (to generate warnings instead of
15  *   nasty runtime surprises). See the "unnecessary" pointer comparison
16  *   in __typecheck().
17  * - retain result as a constant expressions when called with only
18  *   constant expressions (to avoid tripping VLA warnings in stack
19  *   allocation usage).
20  */
21 #define __typecheck(x, y) \
22 	(!!(sizeof((typeof(x) *)1 == (typeof(y) *)1)))
23 
24 #define __no_side_effects(x, y) \
25 		(__is_constexpr(x) && __is_constexpr(y))
26 
27 #define __safe_cmp(x, y) \
28 		(__typecheck(x, y) && __no_side_effects(x, y))
29 
30 #define __cmp(x, y, op)	((x) op (y) ? (x) : (y))
31 
32 #define __cmp_once(x, y, unique_x, unique_y, op) ({	\
33 		typeof(x) unique_x = (x);		\
34 		typeof(y) unique_y = (y);		\
35 		__cmp(unique_x, unique_y, op); })
36 
37 #define __careful_cmp(x, y, op) \
38 	__builtin_choose_expr(__safe_cmp(x, y), \
39 		__cmp(x, y, op), \
40 		__cmp_once(x, y, __UNIQUE_ID(__x), __UNIQUE_ID(__y), op))
41 
42 #define __clamp(val, lo, hi)	\
43 	((val) >= (hi) ? (hi) : ((val) <= (lo) ? (lo) : (val)))
44 
45 #define __clamp_once(val, lo, hi, unique_val, unique_lo, unique_hi) ({	\
46 		typeof(val) unique_val = (val);				\
47 		typeof(lo) unique_lo = (lo);				\
48 		typeof(hi) unique_hi = (hi);				\
49 		__clamp(unique_val, unique_lo, unique_hi); })
50 
51 #define __clamp_input_check(lo, hi)					\
52         (BUILD_BUG_ON_ZERO(__builtin_choose_expr(			\
53                 __is_constexpr((lo) > (hi)), (lo) > (hi), false)))
54 
55 #define __careful_clamp(val, lo, hi) ({					\
56 	__clamp_input_check(lo, hi) +					\
57 	__builtin_choose_expr(__typecheck(val, lo) && __typecheck(val, hi) && \
58 			      __typecheck(hi, lo) && __is_constexpr(val) && \
59 			      __is_constexpr(lo) && __is_constexpr(hi),	\
60 		__clamp(val, lo, hi),					\
61 		__clamp_once(val, lo, hi, __UNIQUE_ID(__val),		\
62 			     __UNIQUE_ID(__lo), __UNIQUE_ID(__hi))); })
63 
64 /**
65  * min - return minimum of two values of the same or compatible types
66  * @x: first value
67  * @y: second value
68  */
69 #define min(x, y)	__careful_cmp(x, y, <)
70 
71 /**
72  * max - return maximum of two values of the same or compatible types
73  * @x: first value
74  * @y: second value
75  */
76 #define max(x, y)	__careful_cmp(x, y, >)
77 
78 /**
79  * min3 - return minimum of three values
80  * @x: first value
81  * @y: second value
82  * @z: third value
83  */
84 #define min3(x, y, z) min((typeof(x))min(x, y), z)
85 
86 /**
87  * max3 - return maximum of three values
88  * @x: first value
89  * @y: second value
90  * @z: third value
91  */
92 #define max3(x, y, z) max((typeof(x))max(x, y), z)
93 
94 /**
95  * min_not_zero - return the minimum that is _not_ zero, unless both are zero
96  * @x: value1
97  * @y: value2
98  */
99 #define min_not_zero(x, y) ({			\
100 	typeof(x) __x = (x);			\
101 	typeof(y) __y = (y);			\
102 	__x == 0 ? __y : ((__y == 0) ? __x : min(__x, __y)); })
103 
104 /**
105  * clamp - return a value clamped to a given range with strict typechecking
106  * @val: current value
107  * @lo: lowest allowable value
108  * @hi: highest allowable value
109  *
110  * This macro does strict typechecking of @lo/@hi to make sure they are of the
111  * same type as @val.  See the unnecessary pointer comparisons.
112  */
113 #define clamp(val, lo, hi) __careful_clamp(val, lo, hi)
114 
115 /*
116  * ..and if you can't take the strict
117  * types, you can specify one yourself.
118  *
119  * Or not use min/max/clamp at all, of course.
120  */
121 
122 /**
123  * min_t - return minimum of two values, using the specified type
124  * @type: data type to use
125  * @x: first value
126  * @y: second value
127  */
128 #define min_t(type, x, y)	__careful_cmp((type)(x), (type)(y), <)
129 
130 /**
131  * max_t - return maximum of two values, using the specified type
132  * @type: data type to use
133  * @x: first value
134  * @y: second value
135  */
136 #define max_t(type, x, y)	__careful_cmp((type)(x), (type)(y), >)
137 
138 /*
139  * Do not check the array parameter using __must_be_array().
140  * In the following legit use-case where the "array" passed is a simple pointer,
141  * __must_be_array() will return a failure.
142  * --- 8< ---
143  * int *buff
144  * ...
145  * min = min_array(buff, nb_items);
146  * --- 8< ---
147  *
148  * The first typeof(&(array)[0]) is needed in order to support arrays of both
149  * 'int *buff' and 'int buff[N]' types.
150  *
151  * The array can be an array of const items.
152  * typeof() keeps the const qualifier. Use __unqual_scalar_typeof() in order
153  * to discard the const qualifier for the __element variable.
154  */
155 #define __minmax_array(op, array, len) ({				\
156 	typeof(&(array)[0]) __array = (array);				\
157 	typeof(len) __len = (len);					\
158 	__unqual_scalar_typeof(__array[0]) __element = __array[--__len];\
159 	while (__len--)							\
160 		__element = op(__element, __array[__len]);		\
161 	__element; })
162 
163 /**
164  * min_array - return minimum of values present in an array
165  * @array: array
166  * @len: array length
167  *
168  * Note that @len must not be zero (empty array).
169  */
170 #define min_array(array, len) __minmax_array(min, array, len)
171 
172 /**
173  * max_array - return maximum of values present in an array
174  * @array: array
175  * @len: array length
176  *
177  * Note that @len must not be zero (empty array).
178  */
179 #define max_array(array, len) __minmax_array(max, array, len)
180 
181 /**
182  * clamp_t - return a value clamped to a given range using a given type
183  * @type: the type of variable to use
184  * @val: current value
185  * @lo: minimum allowable value
186  * @hi: maximum allowable value
187  *
188  * This macro does no typechecking and uses temporary variables of type
189  * @type to make all the comparisons.
190  */
191 #define clamp_t(type, val, lo, hi) __careful_clamp((type)(val), (type)(lo), (type)(hi))
192 
193 /**
194  * clamp_val - return a value clamped to a given range using val's type
195  * @val: current value
196  * @lo: minimum allowable value
197  * @hi: maximum allowable value
198  *
199  * This macro does no typechecking and uses temporary variables of whatever
200  * type the input argument @val is.  This is useful when @val is an unsigned
201  * type and @lo and @hi are literals that will otherwise be assigned a signed
202  * integer type.
203  */
204 #define clamp_val(val, lo, hi) clamp_t(typeof(val), val, lo, hi)
205 
206 static inline bool in_range64(u64 val, u64 start, u64 len)
207 {
208 	return (val - start) < len;
209 }
210 
211 static inline bool in_range32(u32 val, u32 start, u32 len)
212 {
213 	return (val - start) < len;
214 }
215 
216 /**
217  * in_range - Determine if a value lies within a range.
218  * @val: Value to test.
219  * @start: First value in range.
220  * @len: Number of values in range.
221  *
222  * This is more efficient than "if (start <= val && val < (start + len))".
223  * It also gives a different answer if @start + @len overflows the size of
224  * the type by a sufficient amount to encompass @val.  Decide for yourself
225  * which behaviour you want, or prove that start + len never overflow.
226  * Do not blindly replace one form with the other.
227  */
228 #define in_range(val, start, len)					\
229 	((sizeof(start) | sizeof(len) | sizeof(val)) <= sizeof(u32) ?	\
230 		in_range32(val, start, len) : in_range64(val, start, len))
231 
232 /**
233  * swap - swap values of @a and @b
234  * @a: first value
235  * @b: second value
236  */
237 #define swap(a, b) \
238 	do { typeof(a) __tmp = (a); (a) = (b); (b) = __tmp; } while (0)
239 
240 #endif	/* _LINUX_MINMAX_H */
241