[PATCH v2 1/2] minmax: Add in_range_inclusive() for inclusive range checks
Guru Das Srinagesh <[email protected]>
| Newsgroups | org.kernel.vger.linux-iio,org.kernel.vger.linux-kernel |
|---|---|
| Message-ID | <[email protected]> |
in_range(val, start, len) takes a start and a length, i.e. a half-open range. Callers that instead have an inclusive [start, end] bound have no ready helper to reach for and either hand-roll the comparison or convert it to in_range()'s (start, len) form themselves. Add in_range_inclusive(val, start, end) as a direct comparison rather than a wrapper around in_range(): computing len as end - start + 1 and forwarding it to in_range() subverts in_range()'s 32-bit/64-bit dispatch for sub-32-bit types via integer promotion, and overflows to 0 when @end is the type's maximum value, silently rejecting every input instead of accepting all of them. val, start and end are each assigned to a __UNIQUE_ID()-generated temporary before use, matching the __cmp_once()/__cmp_once_unique() pattern: each argument is evaluated exactly once, and the temporary can't be shadowed by a caller's own same-named local variable. Assisted-by: Claude-Code:claude-sonnet-5 Signed-off-by: Guru Das Srinagesh <[email protected]> --- include/linux/minmax.h | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/include/linux/minmax.h b/include/linux/minmax.h index a0158db54a04..cb042733f253 100644 --- a/include/linux/minmax.h +++ b/include/linux/minmax.h @@ -299,6 +299,25 @@ static inline bool in_range32(u32 val, u32 start, u32 len) ((sizeof(start) | sizeof(len) | sizeof(val)) <= sizeof(u32) ? \ in_range32(val, start, len) : in_range64(val, start, len)) +#define __in_range_inclusive(val, start, end, uval, ustart, uend) ({ \ + typeof(val) uval = (val); \ + typeof(start) ustart = (start); \ + typeof(end) uend = (end); \ + uval >= ustart && uval <= uend; \ +}) + +/** + * in_range_inclusive - Determine if a value lies within an inclusive range. + * @val: Value to test. + * @start: First value in range. + * @end: Last value in range. + * + * @val, @start and @end are each evaluated exactly once. + */ +#define in_range_inclusive(val, start, end) \ + __in_range_inclusive(val, start, end, __UNIQUE_ID(val_), \ + __UNIQUE_ID(start_), __UNIQUE_ID(end_)) + /** * swap - swap values of @a and @b * @a: first value -- 2.55.0