xref: /freebsd/contrib/llvm-project/libcxx/include/__bit/rotate.h (revision f5f40dd63bc7acbb5312b26ac1ea1103c12352a6)
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 template <class _Tp>
24 _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 _Tp __rotr(_Tp __t, int __cnt) _NOEXCEPT {
25   static_assert(__libcpp_is_unsigned_integer<_Tp>::value, "__rotr requires an unsigned integer type");
26   const unsigned int __dig = numeric_limits<_Tp>::digits;
27   if ((__cnt % __dig) == 0)
28     return __t;
29 
30   if (__cnt < 0) {
31     __cnt *= -1;
32     return (__t << (__cnt % __dig)) | (__t >> (__dig - (__cnt % __dig))); // rotr with negative __cnt is similar to rotl
33   }
34 
35   return (__t >> (__cnt % __dig)) | (__t << (__dig - (__cnt % __dig)));
36 }
37 
38 template <class _Tp>
39 _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 _Tp __rotl(_Tp __t, int __cnt) _NOEXCEPT {
40   return std::__rotr(__t, -__cnt);
41 }
42 
43 #if _LIBCPP_STD_VER >= 20
44 
45 template <__libcpp_unsigned_integer _Tp>
46 [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr _Tp rotl(_Tp __t, int __cnt) noexcept {
47   return std::__rotl(__t, __cnt);
48 }
49 
50 template <__libcpp_unsigned_integer _Tp>
51 [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr _Tp rotr(_Tp __t, int __cnt) noexcept {
52   return std::__rotr(__t, __cnt);
53 }
54 
55 #endif // _LIBCPP_STD_VER >= 20
56 
57 _LIBCPP_END_NAMESPACE_STD
58 
59 #endif // _LIBCPP___BIT_ROTATE_H
60