Re: [PATCH 02/17] bitops: Add generic parity calculation for u64

Yury Norov
2025-02-26T18:33:27Z

On Wed, Feb 26, 2025 at 08:14:14AM +0100, Jiri Slaby wrote:
> On 25. 02. 25, 14:29, Kuan-Wei Chiu wrote:
> > > +#define parity(val) \
> > > +({ \
> > > + u64 __v = (val); \
> > > + int __ret; \
> > > + switch (BITS_PER_TYPE(val)) { \
> > > + case 64: \
> > > + __v ^= __v >> 32; \
> > > + fallthrough; \
> > > + case 32: \
> > > + __v ^= __v >> 16; \
> > > + fallthrough; \
> > > + case 16: \
> > > + __v ^= __v >> 8; \
> > > + fallthrough; \
> > > + case 8: \
> > > + __v ^= __v >> 4; \
> > > + __ret = (0x6996 >> (__v & 0xf)) & 1; \
> > > + break; \
> > > + default: \
> > > + BUILD_BUG(); \
> > > + } \
> > > + __ret; \
> > > +})
> > > +
> > > +#define parity8(val) parity((u8)(val))
> > > +#define parity32(val) parity((u32)(val))
> > > +#define parity64(val) parity((u64)(val))
> > What do you think about using these inline functions instead of macros?
> > Except for parity8(), each function is a single line and follows the
> > same logic. I find inline functions more readable, and coding-style.rst
> > also recommends them over macros.
>
> Not in cases where macros are inevitable. I mean, do we need parityXX() for
> XX in (8, 16, 32, 64) at all? Isn't the parity() above enough for everybody?

The existing codebase has something like:

int ret;

ret = i3c_master_get_free_addr(m, last_addr + 1);
ret |= parity8(ret) ? 0 : BIT(7)

So if we'll switch it to a macro like one above, it will become a
32-bit parity. It wouldn't be an error because i3c_master_get_free_addr()
returns an u8 or -ENOMEM, and the error code is checked explicitly.

But if we decide to go with parity() only, some users will have to
call it like parity((u8)val) explicitly. Which is not bad actually.

> And if not, you can have all those parityXX() as inlines as you suggest, but
> also provide a macro such as the above to call (optimized) parityXX() as per
> datatype len.

Yes, if we need fixed-type parity's, they should all be one-liners
calling the same macro. Macros or inline functions - no preference for
me.

Thanks,
Yury