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