log2.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 <cstddef>
  12. #include <limits>
  13. #include <type_traits>
  14. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  15. # pragma GCC system_header
  16. #endif
  17. _LIBCPP_BEGIN_NAMESPACE_STD
  18. template <class _UIntType, _UIntType _Xp, size_t _Rp>
  19. struct __log2_imp;
  20. template <unsigned long long _Xp, size_t _Rp>
  21. struct __log2_imp<unsigned long long, _Xp, _Rp>
  22. {
  23. static const size_t value = _Xp & ((unsigned long long)(1) << _Rp) ? _Rp
  24. : __log2_imp<unsigned long long, _Xp, _Rp - 1>::value;
  25. };
  26. template <unsigned long long _Xp>
  27. struct __log2_imp<unsigned long long, _Xp, 0>
  28. {
  29. static const size_t value = 0;
  30. };
  31. template <size_t _Rp>
  32. struct __log2_imp<unsigned long long, 0, _Rp>
  33. {
  34. static const size_t value = _Rp + 1;
  35. };
  36. #ifndef _LIBCPP_HAS_NO_INT128
  37. template <__uint128_t _Xp, size_t _Rp>
  38. struct __log2_imp<__uint128_t, _Xp, _Rp>
  39. {
  40. static const size_t value = (_Xp >> 64)
  41. ? (64 + __log2_imp<unsigned long long, (_Xp >> 64), 63>::value)
  42. : __log2_imp<unsigned long long, _Xp, 63>::value;
  43. };
  44. #endif // _LIBCPP_HAS_NO_INT128
  45. template <class _UIntType, _UIntType _Xp>
  46. struct __log2
  47. {
  48. static const size_t value = __log2_imp<
  49. #ifndef _LIBCPP_HAS_NO_INT128
  50. typename conditional<
  51. sizeof(_UIntType) <= sizeof(unsigned long long),
  52. unsigned long long,
  53. __uint128_t
  54. >::type,
  55. #else
  56. unsigned long long,
  57. #endif // _LIBCPP_HAS_NO_INT128
  58. _Xp, sizeof(_UIntType) * __CHAR_BIT__ - 1>::value;
  59. };
  60. _LIBCPP_END_NAMESPACE_STD
  61. #endif // _LIBCPP___RANDOM_LOG2_H