]> Git Repo - linux.git/blob - include/linux/minmax.h
minmax: improve macro expansion and type checking
[linux.git] / include / linux / minmax.h
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 /*
30  * __sign_use for integer expressions:
31  *   bit #0 set if ok for unsigned comparisons
32  *   bit #1 set if ok for signed comparisons
33  *
34  * In particular, statically non-negative signed integer
35  * expressions are ok for both.
36  *
37  * NOTE! Unsigned types smaller than 'int' are implicitly
38  * converted to 'int' in expressions, and are accepted for
39  * signed conversions for now. This is debatable.
40  *
41  * Note that 'x' is the original expression, and 'ux' is
42  * the unique variable that contains the value.
43  *
44  * We use 'ux' for pure type checking, and 'x' for when
45  * we need to look at the value (but without evaluating
46  * it for side effects! Careful to only ever evaluate it
47  * with sizeof() or __builtin_constant_p() etc).
48  *
49  * Pointers end up being checked by the normal C type
50  * rules at the actual comparison, and these expressions
51  * only need to be careful to not cause warnings for
52  * pointer use.
53  */
54 #define __signed_type_use(x,ux) (2+__is_nonneg(x,ux))
55 #define __unsigned_type_use(x,ux) (1+2*(sizeof(ux)<4))
56 #define __sign_use(x,ux) (is_signed_type(typeof(ux))? \
57         __signed_type_use(x,ux):__unsigned_type_use(x,ux))
58
59 /*
60  * To avoid warnings about casting pointers to integers
61  * of different sizes, we need that special sign type.
62  *
63  * On 64-bit we can just always use 'long', since any
64  * integer or pointer type can just be cast to that.
65  *
66  * This does not work for 128-bit signed integers since
67  * the cast would truncate them, but we do not use s128
68  * types in the kernel (we do use 'u128', but they will
69  * be handled by the !is_signed_type() case).
70  *
71  * NOTE! The cast is there only to avoid any warnings
72  * from when values that aren't signed integer types.
73  */
74 #ifdef CONFIG_64BIT
75   #define __signed_type(ux) long
76 #else
77   #define __signed_type(ux) typeof(__builtin_choose_expr(sizeof(ux)>4,1LL,1L))
78 #endif
79 #define __is_nonneg(x,ux) statically_true((__signed_type(ux))(x)>=0)
80
81 #define __types_ok(x,y,ux,uy) \
82         (__sign_use(x,ux) & __sign_use(y,uy))
83
84 #define __types_ok3(x,y,z,ux,uy,uz) \
85         (__sign_use(x,ux) & __sign_use(y,uy) & __sign_use(z,uz))
86
87 #define __cmp_op_min <
88 #define __cmp_op_max >
89
90 #define __cmp(op, x, y) ((x) __cmp_op_##op (y) ? (x) : (y))
91
92 #define __cmp_once_unique(op, type, x, y, ux, uy) \
93         ({ type ux = (x); type uy = (y); __cmp(op, ux, uy); })
94
95 #define __cmp_once(op, type, x, y) \
96         __cmp_once_unique(op, type, x, y, __UNIQUE_ID(x_), __UNIQUE_ID(y_))
97
98 #define __careful_cmp_once(op, x, y, ux, uy) ({         \
99         __auto_type ux = (x); __auto_type uy = (y);     \
100         BUILD_BUG_ON_MSG(!__types_ok(x,y,ux,uy),        \
101                 #op"("#x", "#y") signedness error");    \
102         __cmp(op, ux, uy); })
103
104 #define __careful_cmp(op, x, y) \
105         __careful_cmp_once(op, x, y, __UNIQUE_ID(x_), __UNIQUE_ID(y_))
106
107 #define __clamp(val, lo, hi)    \
108         ((val) >= (hi) ? (hi) : ((val) <= (lo) ? (lo) : (val)))
109
110 #define __clamp_once(val, lo, hi, uval, ulo, uhi) ({                            \
111         __auto_type uval = (val);                                               \
112         __auto_type ulo = (lo);                                                 \
113         __auto_type uhi = (hi);                                                 \
114         static_assert(__builtin_choose_expr(__is_constexpr((lo) > (hi)),        \
115                         (lo) <= (hi), true),                                    \
116                 "clamp() low limit " #lo " greater than high limit " #hi);      \
117         BUILD_BUG_ON_MSG(!__types_ok3(val,lo,hi,uval,ulo,uhi),                  \
118                 "clamp("#val", "#lo", "#hi") signedness error");                \
119         __clamp(uval, ulo, uhi); })
120
121 #define __careful_clamp(val, lo, hi) \
122         __clamp_once(val, lo, hi, __UNIQUE_ID(v_), __UNIQUE_ID(l_), __UNIQUE_ID(h_))
123
124 /**
125  * min - return minimum of two values of the same or compatible types
126  * @x: first value
127  * @y: second value
128  */
129 #define min(x, y)       __careful_cmp(min, x, y)
130
131 /**
132  * max - return maximum of two values of the same or compatible types
133  * @x: first value
134  * @y: second value
135  */
136 #define max(x, y)       __careful_cmp(max, x, y)
137
138 /**
139  * umin - return minimum of two non-negative values
140  *   Signed types are zero extended to match a larger unsigned type.
141  * @x: first value
142  * @y: second value
143  */
144 #define umin(x, y)      \
145         __careful_cmp(min, (x) + 0u + 0ul + 0ull, (y) + 0u + 0ul + 0ull)
146
147 /**
148  * umax - return maximum of two non-negative values
149  * @x: first value
150  * @y: second value
151  */
152 #define umax(x, y)      \
153         __careful_cmp(max, (x) + 0u + 0ul + 0ull, (y) + 0u + 0ul + 0ull)
154
155 /**
156  * min3 - return minimum of three values
157  * @x: first value
158  * @y: second value
159  * @z: third value
160  */
161 #define min3(x, y, z) min((typeof(x))min(x, y), z)
162
163 /**
164  * max3 - return maximum of three values
165  * @x: first value
166  * @y: second value
167  * @z: third value
168  */
169 #define max3(x, y, z) max((typeof(x))max(x, y), z)
170
171 /**
172  * min_not_zero - return the minimum that is _not_ zero, unless both are zero
173  * @x: value1
174  * @y: value2
175  */
176 #define min_not_zero(x, y) ({                   \
177         typeof(x) __x = (x);                    \
178         typeof(y) __y = (y);                    \
179         __x == 0 ? __y : ((__y == 0) ? __x : min(__x, __y)); })
180
181 /**
182  * clamp - return a value clamped to a given range with strict typechecking
183  * @val: current value
184  * @lo: lowest allowable value
185  * @hi: highest allowable value
186  *
187  * This macro does strict typechecking of @lo/@hi to make sure they are of the
188  * same type as @val.  See the unnecessary pointer comparisons.
189  */
190 #define clamp(val, lo, hi) __careful_clamp(val, lo, hi)
191
192 /*
193  * ..and if you can't take the strict
194  * types, you can specify one yourself.
195  *
196  * Or not use min/max/clamp at all, of course.
197  */
198
199 /**
200  * min_t - return minimum of two values, using the specified type
201  * @type: data type to use
202  * @x: first value
203  * @y: second value
204  */
205 #define min_t(type, x, y) __cmp_once(min, type, x, y)
206
207 /**
208  * max_t - return maximum of two values, using the specified type
209  * @type: data type to use
210  * @x: first value
211  * @y: second value
212  */
213 #define max_t(type, x, y) __cmp_once(max, type, x, y)
214
215 /*
216  * Do not check the array parameter using __must_be_array().
217  * In the following legit use-case where the "array" passed is a simple pointer,
218  * __must_be_array() will return a failure.
219  * --- 8< ---
220  * int *buff
221  * ...
222  * min = min_array(buff, nb_items);
223  * --- 8< ---
224  *
225  * The first typeof(&(array)[0]) is needed in order to support arrays of both
226  * 'int *buff' and 'int buff[N]' types.
227  *
228  * The array can be an array of const items.
229  * typeof() keeps the const qualifier. Use __unqual_scalar_typeof() in order
230  * to discard the const qualifier for the __element variable.
231  */
232 #define __minmax_array(op, array, len) ({                               \
233         typeof(&(array)[0]) __array = (array);                          \
234         typeof(len) __len = (len);                                      \
235         __unqual_scalar_typeof(__array[0]) __element = __array[--__len];\
236         while (__len--)                                                 \
237                 __element = op(__element, __array[__len]);              \
238         __element; })
239
240 /**
241  * min_array - return minimum of values present in an array
242  * @array: array
243  * @len: array length
244  *
245  * Note that @len must not be zero (empty array).
246  */
247 #define min_array(array, len) __minmax_array(min, array, len)
248
249 /**
250  * max_array - return maximum of values present in an array
251  * @array: array
252  * @len: array length
253  *
254  * Note that @len must not be zero (empty array).
255  */
256 #define max_array(array, len) __minmax_array(max, array, len)
257
258 /**
259  * clamp_t - return a value clamped to a given range using a given type
260  * @type: the type of variable to use
261  * @val: current value
262  * @lo: minimum allowable value
263  * @hi: maximum allowable value
264  *
265  * This macro does no typechecking and uses temporary variables of type
266  * @type to make all the comparisons.
267  */
268 #define clamp_t(type, val, lo, hi) __careful_clamp((type)(val), (type)(lo), (type)(hi))
269
270 /**
271  * clamp_val - return a value clamped to a given range using val's type
272  * @val: current value
273  * @lo: minimum allowable value
274  * @hi: maximum allowable value
275  *
276  * This macro does no typechecking and uses temporary variables of whatever
277  * type the input argument @val is.  This is useful when @val is an unsigned
278  * type and @lo and @hi are literals that will otherwise be assigned a signed
279  * integer type.
280  */
281 #define clamp_val(val, lo, hi) clamp_t(typeof(val), val, lo, hi)
282
283 static inline bool in_range64(u64 val, u64 start, u64 len)
284 {
285         return (val - start) < len;
286 }
287
288 static inline bool in_range32(u32 val, u32 start, u32 len)
289 {
290         return (val - start) < len;
291 }
292
293 /**
294  * in_range - Determine if a value lies within a range.
295  * @val: Value to test.
296  * @start: First value in range.
297  * @len: Number of values in range.
298  *
299  * This is more efficient than "if (start <= val && val < (start + len))".
300  * It also gives a different answer if @start + @len overflows the size of
301  * the type by a sufficient amount to encompass @val.  Decide for yourself
302  * which behaviour you want, or prove that start + len never overflow.
303  * Do not blindly replace one form with the other.
304  */
305 #define in_range(val, start, len)                                       \
306         ((sizeof(start) | sizeof(len) | sizeof(val)) <= sizeof(u32) ?   \
307                 in_range32(val, start, len) : in_range64(val, start, len))
308
309 /**
310  * swap - swap values of @a and @b
311  * @a: first value
312  * @b: second value
313  */
314 #define swap(a, b) \
315         do { typeof(a) __tmp = (a); (a) = (b); (b) = __tmp; } while (0)
316
317 /*
318  * Use these carefully: no type checking, and uses the arguments
319  * multiple times. Use for obvious constants only.
320  */
321 #define MIN(a,b) __cmp(min,a,b)
322 #define MAX(a,b) __cmp(max,a,b)
323 #define MIN_T(type,a,b) __cmp(min,(type)(a),(type)(b))
324 #define MAX_T(type,a,b) __cmp(max,(type)(a),(type)(b))
325
326 #endif  /* _LINUX_MINMAX_H */
This page took 0.05906 seconds and 4 git commands to generate.