Re: [PATCH v6 01/38] minmax: Add in_range() macro
From: Matthew Wilcox
Date: Thu Aug 03 2023 - 09:23:12 EST
On Thu, Aug 03, 2023 at 09:00:35PM +0800, Phi Nguyen wrote:
> On 8/2/2023 11:13 PM, Matthew Wilcox (Oracle) wrote:
> > +static inline bool in_range64(u64 val, u64 start, u64 len)
> > +{
> > + return (val - start) < len;
> > +}
> > +
> > +static inline bool in_range32(u32 val, u32 start, u32 len)
> > +{
> > + return (val - start) < len;
> > +}
> > +
>
> I think these two functions return wrong result if val is smaller than start
> and len is big enough.
How is it that you stopped reading at exactly the point where I explained
that this is intentional?
+/**
+ * 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.
+ */