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