On Tue, 5 Nov 2024 16:54:05 +0200 Alexandru Ardelean <aardelean@xxxxxxxxxxxx> wrote: > A bug was found in the find_closest() (find_closest_descending() is also > affected after some testing), where for certain values with small > progressions, the rounding (done by averaging 2 values) causes an incorrect > index to be returned. Convincing changelog, thanks. > -#define find_closest(x, a, as) __find_closest(x, a, as, <=) > +#define find_closest(x, a, as) \ > +({ \ > + typeof(as) __fc_i, __fc_as = (as) - 1; \ > + long __fc_mid_x, __fc_x = (x); \ > + long __fc_left, __fc_right; \ > + typeof(*a) const *__fc_a = (a); \ > + for (__fc_i = 0; __fc_i < __fc_as; __fc_i++) { \ > + __fc_mid_x = (__fc_a[__fc_i] + __fc_a[__fc_i + 1]) / 2; \ > + if (__fc_x <= __fc_mid_x) { \ > + __fc_left = __fc_x - __fc_a[__fc_i]; \ > + __fc_right = __fc_a[__fc_i + 1] - __fc_x; \ > + if (__fc_right < __fc_left) \ > + __fc_i++; \ > + break; \ > + } \ > + } \ > + (__fc_i); \ > +}) > > ... > > +#define find_closest_descending(x, a, as) \ Boy these things are hard to read. They're also bloaty and I'm counting 36ish callsites! Can we fix both issues by just giving up on the macro approach and reimplement them in out-of-line C code? All the sites I looked at are using 32-bit quantities - a mix of signed and unsigned. It's separate from this bugfix of course, but would it be feasible for someone to go switch all callers to use u32's then reimplement these in lib/find_closest.c?