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___BIT_ROTATE_H |
10 | #define _LIBCPP___BIT_ROTATE_H |
11 | |
12 | #include <__concepts/arithmetic.h> |
13 | #include <__config> |
14 | #include <__type_traits/is_unsigned_integer.h> |
15 | #include <limits> |
16 | |
17 | #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) |
18 | # pragma GCC system_header |
19 | #endif |
20 | |
21 | _LIBCPP_BEGIN_NAMESPACE_STD |
22 | |
23 | // Writing two full functions for rotl and rotr makes it easier for the compiler |
24 | // to optimize the code. On x86 this function becomes the ROL instruction and |
25 | // the rotr function becomes the ROR instruction. |
26 | template <class _Tp> |
27 | _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 _Tp __rotl(_Tp __x, int __s) _NOEXCEPT { |
28 | static_assert(__libcpp_is_unsigned_integer<_Tp>::value, "__rotl requires an unsigned integer type" ); |
29 | const int __N = numeric_limits<_Tp>::digits; |
30 | int __r = __s % __N; |
31 | |
32 | if (__r == 0) |
33 | return __x; |
34 | |
35 | if (__r > 0) |
36 | return (__x << __r) | (__x >> (__N - __r)); |
37 | |
38 | return (__x >> -__r) | (__x << (__N + __r)); |
39 | } |
40 | |
41 | template <class _Tp> |
42 | _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 _Tp __rotr(_Tp __x, int __s) _NOEXCEPT { |
43 | static_assert(__libcpp_is_unsigned_integer<_Tp>::value, "__rotr requires an unsigned integer type" ); |
44 | const int __N = numeric_limits<_Tp>::digits; |
45 | int __r = __s % __N; |
46 | |
47 | if (__r == 0) |
48 | return __x; |
49 | |
50 | if (__r > 0) |
51 | return (__x >> __r) | (__x << (__N - __r)); |
52 | |
53 | return (__x << -__r) | (__x >> (__N + __r)); |
54 | } |
55 | |
56 | #if _LIBCPP_STD_VER >= 20 |
57 | |
58 | template <__libcpp_unsigned_integer _Tp> |
59 | [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr _Tp rotl(_Tp __t, int __cnt) noexcept { |
60 | return std::__rotl(__t, __cnt); |
61 | } |
62 | |
63 | template <__libcpp_unsigned_integer _Tp> |
64 | [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr _Tp rotr(_Tp __t, int __cnt) noexcept { |
65 | return std::__rotr(__t, __cnt); |
66 | } |
67 | |
68 | #endif // _LIBCPP_STD_VER >= 20 |
69 | |
70 | _LIBCPP_END_NAMESPACE_STD |
71 | |
72 | #endif // _LIBCPP___BIT_ROTATE_H |
73 | |