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