diff options
author | Thomas Voss <mail@thomasvoss.com> | 2024-01-23 15:45:29 +0100 |
---|---|---|
committer | Thomas Voss <mail@thomasvoss.com> | 2024-01-23 15:45:29 +0100 |
commit | 99730d885fd26db9213bd29dfc9e8f6b75485951 (patch) | |
tree | bfbb28c12e8b612c8b8b835f2c7d2ff817259385 | |
parent | 44c9787d8487c153d1eed1902caa1b504b5b180b (diff) |
Improve next pow2 impl
-rw-r--r-- | cbs.h | 25 |
1 files changed, 18 insertions, 7 deletions
@@ -421,15 +421,26 @@ cbsinit(int argc, char **argv) } static size_t -_next_powerof2(size_t n) +_next_powerof2(size_t x) { - if (n && !(n & (n - 1))) - return n; +#if defined(__has_builtin) && __has_builtin(__builtin_clzl) + x = x <= 1 ? 1 : 1 << (64 - __builtin_clzl(x - 1)); +#else + if (x) { + x--; + x |= x >> 1; + x |= x >> 2; + x |= x >> 4; + x |= x >> 8; + if (sizeof(size_t) >= 4) + x |= x >> 16; + if (sizeof(size_t) >= 8) + x |= x >> 32; + } + x++; +#endif - n--; - for (size_t i = 1; i < sizeof(size_t); i <<= 1) - n |= n >> i; - return n + 1; + return x; } bool |