Skip to content

Commit

Permalink
minmax: simplify and clarify min_t()/max_t() implementation
Browse files Browse the repository at this point in the history
This simplifies the min_t() and max_t() macros by no longer making them
work in the context of a C constant expression.

That means that you can no longer use them for static initializers or
for array sizes in type definitions, but there were only a couple of
such uses, and all of them were converted (famous last words) to use
MIN_T/MAX_T instead.

Cc: David Laight <David.Laight@aculab.com>
Cc: Lorenzo Stoakes <lorenzo.stoakes@oracle.com>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
  • Loading branch information
torvalds committed Jul 28, 2024
1 parent 4477b39 commit 017fa3e
Showing 1 changed file with 11 additions and 8 deletions.
19 changes: 11 additions & 8 deletions include/linux/minmax.h
Original file line number Diff line number Diff line change
Expand Up @@ -45,17 +45,20 @@

#define __cmp(op, x, y) ((x) __cmp_op_##op (y) ? (x) : (y))

#define __cmp_once(op, x, y, unique_x, unique_y) ({ \
typeof(x) unique_x = (x); \
typeof(y) unique_y = (y); \
#define __cmp_once_unique(op, type, x, y, ux, uy) \
({ type ux = (x); type uy = (y); __cmp(op, ux, uy); })

#define __cmp_once(op, type, x, y) \
__cmp_once_unique(op, type, x, y, __UNIQUE_ID(x_), __UNIQUE_ID(y_))

#define __careful_cmp_once(op, x, y) ({ \
static_assert(__types_ok(x, y), \
#op "(" #x ", " #y ") signedness error, fix types or consider u" #op "() before " #op "_t()"); \
__cmp(op, unique_x, unique_y); })
__cmp_once(op, __auto_type, x, y); })

#define __careful_cmp(op, x, y) \
__builtin_choose_expr(__is_constexpr((x) - (y)), \
__cmp(op, x, y), \
__cmp_once(op, x, y, __UNIQUE_ID(__x), __UNIQUE_ID(__y)))
__cmp(op, x, y), __careful_cmp_once(op, x, y))

#define __clamp(val, lo, hi) \
((val) >= (hi) ? (hi) : ((val) <= (lo) ? (lo) : (val)))
Expand Down Expand Up @@ -158,15 +161,15 @@
* @x: first value
* @y: second value
*/
#define min_t(type, x, y) __careful_cmp(min, (type)(x), (type)(y))
#define min_t(type, x, y) __cmp_once(min, type, x, y)

/**
* max_t - return maximum of two values, using the specified type
* @type: data type to use
* @x: first value
* @y: second value
*/
#define max_t(type, x, y) __careful_cmp(max, (type)(x), (type)(y))
#define max_t(type, x, y) __cmp_once(max, type, x, y)

/*
* Do not check the array parameter using __must_be_array().
Expand Down

0 comments on commit 017fa3e

Please sign in to comment.