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