Messages in this thread Patch in this message | | | From | David Laight <> | Subject | [PATCH v3 1/5] minmax: Add min_unsigned(a, b) and max_unsigned(a, b) | Date | Fri, 4 Aug 2023 10:53:33 +0000 |
| |
These can be used when min()/max() errors a signed v unsigned compare when the signed value is known to be non-negative.
Unlike min_t(some_unsigned_type, a, b) min_unsigned() will never mask off high bits if an inappropriate type is selected.
The '+ 0u + 0ul + 0ull' may look strange. The '+ 0u' is needed for 'signed int' on 64bit systems. The '+ 0ul' is needed for 'signed long' on 32bit systems. The '+ 0ull' is needed for 'signed long long'.
Signed-off-by: David Laight <david.laight@aculab.com> --- v3: No change. v2: Updated commit message. include/linux/minmax.h | 17 +++++++++++++++++ 1 file changed, 17 insertions(+)
diff --git a/include/linux/minmax.h b/include/linux/minmax.h index 396df1121bff..531860e9cc55 100644 --- a/include/linux/minmax.h +++ b/include/linux/minmax.h @@ -73,6 +73,23 @@ */ #define max(x, y) __careful_cmp(x, y, >) +/** + * min_unsigned - return minimum of two non-negative values + * Signed types are zero extended to match a larger unsigned type. + * @x: first value + * @y: second value + */ +#define min_unsigned(x, y) \ + __careful_cmp((x) + 0u + 0ul + 0ull, (y) + 0u + 0ul + 0ull, <) + +/** + * max_unsigned - return maximum of two non-negative values + * @x: first value + * @y: second value + */ +#define max_unsigned(x, y) \ + __careful_cmp((x) + 0u + 0ul + 0ull, (y) + 0u + 0ul + 0ull, >) + /** * min3 - return minimum of three values * @x: first value -- 2.17.1 - Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, UK Registration No: 1397386 (Wales)
| |