diff options
Diffstat (limited to 'runtime/base/bit_utils.h')
-rw-r--r-- | runtime/base/bit_utils.h | 27 |
1 files changed, 27 insertions, 0 deletions
diff --git a/runtime/base/bit_utils.h b/runtime/base/bit_utils.h index 1b0d774419..9c78ee59dd 100644 --- a/runtime/base/bit_utils.h +++ b/runtime/base/bit_utils.h @@ -263,6 +263,33 @@ static constexpr bool IsAbsoluteUint(T value) { : static_cast<unsigned_type>(value)); } +// Generate maximum/minimum values for signed/unsigned n-bit integers +template <typename T> +static constexpr T MaxInt(size_t bits) { + return + DCHECK_CONSTEXPR(bits > 0, "bits cannot be zero", 0) + DCHECK_CONSTEXPR(bits <= BitSizeOf<T>(), "kBits must be < max.", 0) + bits == BitSizeOf<T>() + ? std::numeric_limits<T>::max() + : std::is_signed<T>::value + ? (bits == 1 + ? 0 + : static_cast<T>(MaxInt<typename std::make_unsigned<T>::type>(bits - 1))) + : static_cast<T>(UINT64_C(1) << bits) - static_cast<T>(1); +} + +template <typename T> +static constexpr T MinInt(size_t bits) { + return + DCHECK_CONSTEXPR(bits > 0, "bits cannot be zero", 0) + DCHECK_CONSTEXPR(bits <= BitSizeOf<T>(), "kBits must be < max.", 0) + bits == BitSizeOf<T>() + ? std::numeric_limits<T>::min() + : std::is_signed<T>::value + ? (bits == 1 ? -1 : static_cast<T>(-1) - MaxInt<T>(bits)) + : static_cast<T>(0); +} + // Using the Curiously Recurring Template Pattern to implement everything shared // by LowToHighBitIterator and HighToLowBitIterator, i.e. everything but operator*(). template <typename T, typename Iter> |