Re: [PATCH v5 01/38] minmax: Add in_range() macro

From: Matthew Wilcox
Date: Mon Jul 10 2023 - 22:14:52 EST


On Mon, Jul 10, 2023 at 04:13:41PM -0700, Andrew Morton wrote:
> > +/**
> > + * in_range - Determine if a value lies within a range.
> > + * @val: Value to test.
> > + * @start: First value in range.
> > + * @len: Number of values in range.
> > + *
> > + * This is more efficient than "if (start <= val && val < (start + len))".
> > + * It also gives a different answer if @start + @len overflows the size of
> > + * the type by a sufficient amount to encompass @val. Decide for yourself
> > + * which behaviour you want, or prove that start + len never overflow.
> > + * Do not blindly replace one form with the other.
> > + */
> > +#define in_range(val, start, len) \
> > + sizeof(start) <= sizeof(u32) ? in_range32(val, start, len) : \
> > + in_range64(val, start, len)
>
> There's nothing here to prevent callers from passing a mixture of
> 32-bit and 64-bit values, possibly resulting in truncation of `val' or
> `len'.
>
> Obviously caller is being dumb, but I think it's cost-free to check all
> three of the arguments for 64-bitness?
>
> Or do a min()/max()-style check for consistently typed arguments?

How about

#define in_range(val, start, len) \
(sizeof(val) | sizeof(start) | size(len)) <= sizeof(u32) ? \
in_range32(val, start, len) : in_range64(val, start, len)