Re: [PATCH v2] libbpf: Fix is_pow_of_2

From: Joe Perches
Date: Fri Jun 03 2022 - 12:48:31 EST


On Thu, 2022-06-02 at 22:57 -0700, Ian Rogers wrote:
> On Thu, Jun 2, 2022 at 10:52 PM Ian Rogers <irogers@xxxxxxxxxx> wrote:
> > From: Yuze Chi <chiyuze@xxxxxxxxxx>
[]
> > diff --git a/tools/lib/bpf/libbpf_internal.h b/tools/lib/bpf/libbpf_internal.h
[]
> > @@ -580,4 +580,9 @@ struct bpf_link * usdt_manager_attach_usdt(struct usdt_manager *man,
> > const char *usdt_provider, const char *usdt_name,
> > __u64 usdt_cookie);
> >
> > +static inline bool is_pow_of_2(size_t x)
> > +{
> > + return x && (x & (x - 1)) == 0;
> > +}
> > +
> > #endif /* __LIBBPF_LIBBPF_INTERNAL_H */

If speed of execution is a potential issue, maybe:

#if __has_builtin(__builtin_popcount)
return __builtin_popcount(x) == 1;
#else
return x && (x & (x-1)) == 0;
#endif