log2.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. //===----------------------------------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #ifndef _LIBCPP___RANDOM_LOG2_H
  9. #define _LIBCPP___RANDOM_LOG2_H
  10. #include <__config>
  11. #include <__type_traits/conditional.h>
  12. #include <cstddef>
  13. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  14. # pragma GCC system_header
  15. #endif
  16. _LIBCPP_BEGIN_NAMESPACE_STD
  17. template <class _UIntType, _UIntType _Xp, size_t _Rp>
  18. struct __log2_imp;
  19. template <unsigned long long _Xp, size_t _Rp>
  20. struct __log2_imp<unsigned long long, _Xp, _Rp> {
  21. static const size_t value =
  22. _Xp & ((unsigned long long)(1) << _Rp) ? _Rp : __log2_imp<unsigned long long, _Xp, _Rp - 1>::value;
  23. };
  24. template <unsigned long long _Xp>
  25. struct __log2_imp<unsigned long long, _Xp, 0> {
  26. static const size_t value = 0;
  27. };
  28. template <size_t _Rp>
  29. struct __log2_imp<unsigned long long, 0, _Rp> {
  30. static const size_t value = _Rp + 1;
  31. };
  32. #ifndef _LIBCPP_HAS_NO_INT128
  33. template <__uint128_t _Xp, size_t _Rp>
  34. struct __log2_imp<__uint128_t, _Xp, _Rp> {
  35. static const size_t value =
  36. (_Xp >> 64) ? (64 + __log2_imp<unsigned long long, (_Xp >> 64), 63>::value)
  37. : __log2_imp<unsigned long long, _Xp, 63>::value;
  38. };
  39. #endif // _LIBCPP_HAS_NO_INT128
  40. template <class _UIntType, _UIntType _Xp>
  41. struct __log2 {
  42. static const size_t value = __log2_imp<
  43. #ifndef _LIBCPP_HAS_NO_INT128
  44. __conditional_t<sizeof(_UIntType) <= sizeof(unsigned long long), unsigned long long, __uint128_t>,
  45. #else
  46. unsigned long long,
  47. #endif // _LIBCPP_HAS_NO_INT128
  48. _Xp,
  49. sizeof(_UIntType) * __CHAR_BIT__ - 1>::value;
  50. };
  51. _LIBCPP_END_NAMESPACE_STD
  52. #endif // _LIBCPP___RANDOM_LOG2_H