From f6eb790eec107064798b9e54552f1ef5966f6359 Mon Sep 17 00:00:00 2001 From: Max Graey Date: Thu, 18 Jun 2020 04:13:59 +0300 Subject: Optimize bit count polyfills (#2914) --- src/support/bits.h | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) (limited to 'src/support/bits.h') diff --git a/src/support/bits.h b/src/support/bits.h index f2241bea8..bd91fdec6 100644 --- a/src/support/bits.h +++ b/src/support/bits.h @@ -65,17 +65,21 @@ template int CountTrailingZeroes(T v) { template int CountLeadingZeroes(T v) { return CountLeadingZeroes(typename std::make_unsigned::type(v)); } -template bool IsPowerOf2(T v) { return v != 0 && PopCount(v) == 1; } +template bool IsPowerOf2(T v) { + return v != 0 && (v & (v - 1)) == 0; +} template inline static T RotateLeft(T val, U count) { - T mask = sizeof(T) * CHAR_BIT - 1; + auto value = typename std::make_unsigned::type(val); + U mask = sizeof(T) * CHAR_BIT - 1; count &= mask; - return (val << count) | (val >> (-count & mask)); + return (value << count) | (value >> (-count & mask)); } template inline static T RotateRight(T val, U count) { - T mask = sizeof(T) * CHAR_BIT - 1; + auto value = typename std::make_unsigned::type(val); + U mask = sizeof(T) * CHAR_BIT - 1; count &= mask; - return (val >> count) | (val << (-count & mask)); + return (value >> count) | (value << (-count & mask)); } extern uint32_t Log2(uint32_t v); -- cgit v1.2.3