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 <__config>
13#include <__type_traits/integer_traits.h>
14#include <limits>
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// Writing two full functions for rotl and rotr makes it easier for the compiler
23// to optimize the code. On x86 this function becomes the ROL instruction and
24// the rotr function becomes the ROR instruction.
25
26#if _LIBCPP_STD_VER >= 20
27
28template <__unsigned_integer _Tp>
29[[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr _Tp rotl(_Tp __t, int __cnt) noexcept {
30 const int __n = numeric_limits<_Tp>::digits;
31 int __r = __cnt % __n;
32
33 if (__r == 0)
34 return __t;
35
36 if (__r > 0)
37 return (__t << __r) | (__t >> (__n - __r));
38
39 return (__t >> -__r) | (__t << (__n + __r));
40}
41
42template <__unsigned_integer _Tp>
43[[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr _Tp rotr(_Tp __t, int __cnt) noexcept {
44 const int __n = numeric_limits<_Tp>::digits;
45 int __r = __cnt % __n;
46
47 if (__r == 0)
48 return __t;
49
50 if (__r > 0)
51 return (__t >> __r) | (__t << (__n - __r));
52
53 return (__t << -__r) | (__t >> (__n + __r));
54}
55
56#endif // _LIBCPP_STD_VER >= 20
57
58_LIBCPP_END_NAMESPACE_STD
59
60#endif // _LIBCPP___BIT_ROTATE_H
61