xref: /freebsd/contrib/llvm-project/libcxx/include/__random/log2.h (revision 5fb307d29b364982acbde82cbf77db3cae486f8c)
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 
9 #ifndef _LIBCPP___RANDOM_LOG2_H
10 #define _LIBCPP___RANDOM_LOG2_H
11 
12 #include <__config>
13 #include <__type_traits/conditional.h>
14 #include <cstddef>
15 
16 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
17 #  pragma GCC system_header
18 #endif
19 
20 _LIBCPP_BEGIN_NAMESPACE_STD
21 
22 template <class _UIntType, _UIntType _Xp, size_t _Rp>
23 struct __log2_imp;
24 
25 template <unsigned long long _Xp, size_t _Rp>
26 struct __log2_imp<unsigned long long, _Xp, _Rp>
27 {
28     static const size_t value = _Xp & ((unsigned long long)(1) << _Rp) ? _Rp
29                                            : __log2_imp<unsigned long long, _Xp, _Rp - 1>::value;
30 };
31 
32 template <unsigned long long _Xp>
33 struct __log2_imp<unsigned long long, _Xp, 0>
34 {
35     static const size_t value = 0;
36 };
37 
38 template <size_t _Rp>
39 struct __log2_imp<unsigned long long, 0, _Rp>
40 {
41     static const size_t value = _Rp + 1;
42 };
43 
44 #ifndef _LIBCPP_HAS_NO_INT128
45 
46 template <__uint128_t _Xp, size_t _Rp>
47 struct __log2_imp<__uint128_t, _Xp, _Rp>
48 {
49     static const size_t value = (_Xp >> 64)
50         ? (64 + __log2_imp<unsigned long long, (_Xp >> 64), 63>::value)
51         : __log2_imp<unsigned long long, _Xp, 63>::value;
52 };
53 
54 #endif // _LIBCPP_HAS_NO_INT128
55 
56 template <class _UIntType, _UIntType _Xp>
57 struct __log2
58 {
59     static const size_t value = __log2_imp<
60 #ifndef _LIBCPP_HAS_NO_INT128
61         __conditional_t<sizeof(_UIntType) <= sizeof(unsigned long long), unsigned long long, __uint128_t>,
62 #else
63         unsigned long long,
64 #endif // _LIBCPP_HAS_NO_INT128
65         _Xp,
66         sizeof(_UIntType) * __CHAR_BIT__ - 1>::value;
67 };
68 
69 _LIBCPP_END_NAMESPACE_STD
70 
71 #endif // _LIBCPP___RANDOM_LOG2_H
72