From 8ff5d342097a164780e9b0388e82a7c6e78773ae Mon Sep 17 00:00:00 2001 From: Tatsuhiro Tsujikawa Date: Thu, 19 Sep 2024 22:57:49 +0900 Subject: [PATCH] ispow2: Better fallback implementation --- lib/nghttp3_ringbuf.c | 29 +++++++++++------------------ 1 file changed, 11 insertions(+), 18 deletions(-) diff --git a/lib/nghttp3_ringbuf.c b/lib/nghttp3_ringbuf.c index 4888039..7d3ab39 100644 --- a/lib/nghttp3_ringbuf.c +++ b/lib/nghttp3_ringbuf.c @@ -33,26 +33,23 @@ #include "nghttp3_macro.h" +static int ispow2(size_t n) { #if defined(_MSC_VER) && !defined(__clang__) && \ (defined(_M_ARM) || (defined(_M_ARM64) && _MSC_VER < 1941)) -unsigned int __popcnt(unsigned int x) { - unsigned int c = 0; - for (; x; ++c) { - x &= x - 1; - } - return c; + return n && !(n & (n - 1)); +#elif defined(WIN32) + return 1 == __popcnt((unsigned int)n); +#else /* !((defined(_MSC_VER) && !defined(__clang__) && (defined(_M_ARM) || \ + (defined(_M_ARM64) && _MSC_VER < 1941))) || defined(WIN32)) */ + return 1 == __builtin_popcount((unsigned int)n); +#endif /* !((defined(_MSC_VER) && !defined(__clang__) && (defined(_M_ARM) || \ + (defined(_M_ARM64) && _MSC_VER < 1941))) || defined(WIN32)) */ } -#endif /* defined(_MSC_VER) && !defined(__clang__) && (defined(_M_ARM) || \ - (defined(_M_ARM64) && _MSC_VER < 1941)) */ int nghttp3_ringbuf_init(nghttp3_ringbuf *rb, size_t nmemb, size_t size, const nghttp3_mem *mem) { if (nmemb) { -#ifdef WIN32 - assert(1 == __popcnt((unsigned int)nmemb)); -#else /* !defined(WIN32) */ - assert(1 == __builtin_popcount((unsigned int)nmemb)); -#endif /* !defined(WIN32) */ + assert(ispow2(nmemb)); rb->buf = nghttp3_mem_malloc(mem, nmemb * size); if (rb->buf == NULL) { @@ -128,11 +125,7 @@ int nghttp3_ringbuf_reserve(nghttp3_ringbuf *rb, size_t nmemb) { return 0; } -#ifdef WIN32 - assert(1 == __popcnt((unsigned int)nmemb)); -#else /* !defined(WIN32) */ - assert(1 == __builtin_popcount((unsigned int)nmemb)); -#endif /* !defined(WIN32) */ + assert(ispow2(nmemb)); buf = nghttp3_mem_malloc(rb->mem, nmemb * rb->size); if (buf == NULL) {