[PATCH 1/2] minmax: Add in_range_incl() 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 function/macro to reach for and either hand-roll the comparison or convert it to in_range()'s (start, len) form themselves. Add in_range_incl(val, start, end), computing len as end - start + 1 and forwarding to in_range() so it inherits the existing 32-bit/64-bit type dispatch rather than risking silent truncation from a fresh hand-rolled comparison. val, start and end are each assigned to a temporary variable before use, so each is evaluated exactly once regardless of how many times it appears in the expansion (matching swap()'s __tmp below). Assisted-by: Claude-Code:claude-sonnet-5 Signed-off-by: Guru Das Srinagesh <[email protected]> --- include/linux/minmax.h | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/include/linux/minmax.h b/include/linux/minmax.h index a0158db54a04..71900d688a06 100644 --- a/include/linux/minmax.h +++ b/include/linux/minmax.h @@ -299,6 +299,27 @@ 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)) +/** + * in_range_incl - 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. + * + * Same caveats as in_range() apply. In particular, if @end sits at the + * maximum value representable by the common type of @start and @end, + * "@end - @start + 1" wraps to 0, silently rejecting every @val instead + * of accepting all of them. Callers must ensure @end - @start + 1 does + * not overflow, and that @end >= @start. + */ +#define in_range_incl(val, start, end) ({ \ + typeof(val) __val = (val); \ + typeof(start) __start = (start); \ + typeof(end) __end = (end); \ + in_range(__val, __start, __end - __start + 1); \ +}) + /** * swap - swap values of @a and @b * @a: first value -- 2.55.0