2016-03-07 06:18:06 +00:00
|
|
|
#pragma once
|
|
|
|
|
2017-02-02 22:08:19 +00:00
|
|
|
#include <cstddef>
|
2019-06-12 17:12:08 +00:00
|
|
|
#include <type_traits>
|
2016-08-07 06:10:15 +00:00
|
|
|
|
|
|
|
|
|
|
|
/** Returns log2 of number, rounded down.
|
|
|
|
* Compiles to single 'bsr' instruction on x86.
|
|
|
|
* For zero argument, result is unspecified.
|
|
|
|
*/
|
|
|
|
inline unsigned int bitScanReverse(unsigned int x)
|
2016-03-07 06:18:06 +00:00
|
|
|
{
|
2017-04-01 07:20:54 +00:00
|
|
|
return sizeof(unsigned int) * 8 - 1 - __builtin_clz(x);
|
2016-03-07 06:18:06 +00:00
|
|
|
}
|
2016-08-07 06:10:15 +00:00
|
|
|
|
|
|
|
|
|
|
|
/** For zero argument, result is zero.
|
|
|
|
* For arguments with most significand bit set, result is zero.
|
|
|
|
* For other arguments, returns value, rounded up to power of two.
|
|
|
|
*/
|
|
|
|
inline size_t roundUpToPowerOfTwoOrZero(size_t n)
|
|
|
|
{
|
2017-04-01 07:20:54 +00:00
|
|
|
--n;
|
|
|
|
n |= n >> 1;
|
|
|
|
n |= n >> 2;
|
|
|
|
n |= n >> 4;
|
|
|
|
n |= n >> 8;
|
|
|
|
n |= n >> 16;
|
|
|
|
n |= n >> 32;
|
|
|
|
++n;
|
2016-08-07 06:10:15 +00:00
|
|
|
|
2017-04-01 07:20:54 +00:00
|
|
|
return n;
|
2016-08-07 06:10:15 +00:00
|
|
|
}
|
2019-06-12 17:12:08 +00:00
|
|
|
|
|
|
|
|
|
|
|
template <typename T>
|
|
|
|
inline std::enable_if_t<std::is_integral_v<T> && (sizeof(T) <= sizeof(unsigned int)), int>
|
|
|
|
getLeadingZeroBits(T x)
|
|
|
|
{
|
|
|
|
return x == 0 ? sizeof(x) * 8 : __builtin_clz(x);
|
|
|
|
}
|
|
|
|
|
|
|
|
template <typename T>
|
|
|
|
inline std::enable_if_t<std::is_integral_v<T> && (sizeof(T) == sizeof(unsigned long long int)), int>
|
|
|
|
getLeadingZeroBits(T x)
|
|
|
|
{
|
|
|
|
return x == 0 ? sizeof(x) * 8 : __builtin_clzll(x);
|
|
|
|
}
|
|
|
|
|
|
|
|
template <typename T>
|
|
|
|
inline std::enable_if_t<std::is_integral_v<T> && (sizeof(T) <= sizeof(unsigned int)), int>
|
|
|
|
getTrailingZeroBits(T x)
|
|
|
|
{
|
|
|
|
return x == 0 ? sizeof(x) * 8 : __builtin_ctz(x);
|
|
|
|
}
|
|
|
|
|
|
|
|
template <typename T>
|
|
|
|
inline std::enable_if_t<std::is_integral_v<T> && (sizeof(T) == sizeof(unsigned long long int)), int>
|
|
|
|
getTrailingZeroBits(T x)
|
|
|
|
{
|
|
|
|
return x == 0 ? sizeof(x) * 8 : __builtin_ctzll(x);
|
|
|
|
}
|