master
 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.
25template <class _Tp>
26_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 _Tp __rotl(_Tp __x, int __s) _NOEXCEPT {
27  static_assert(__is_unsigned_integer_v<_Tp>, "__rotl requires an unsigned integer type");
28  const int __n = numeric_limits<_Tp>::digits;
29  int __r       = __s % __n;
30
31  if (__r == 0)
32    return __x;
33
34  if (__r > 0)
35    return (__x << __r) | (__x >> (__n - __r));
36
37  return (__x >> -__r) | (__x << (__n + __r));
38}
39
40template <class _Tp>
41_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 _Tp __rotr(_Tp __x, int __s) _NOEXCEPT {
42  static_assert(__is_unsigned_integer_v<_Tp>, "__rotr requires an unsigned integer type");
43  const int __n = numeric_limits<_Tp>::digits;
44  int __r       = __s % __n;
45
46  if (__r == 0)
47    return __x;
48
49  if (__r > 0)
50    return (__x >> __r) | (__x << (__n - __r));
51
52  return (__x << -__r) | (__x >> (__n + __r));
53}
54
55#if _LIBCPP_STD_VER >= 20
56
57template <__unsigned_integer _Tp>
58[[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr _Tp rotl(_Tp __t, int __cnt) noexcept {
59  return std::__rotl(__t, __cnt);
60}
61
62template <__unsigned_integer _Tp>
63[[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr _Tp rotr(_Tp __t, int __cnt) noexcept {
64  return std::__rotr(__t, __cnt);
65}
66
67#endif // _LIBCPP_STD_VER >= 20
68
69_LIBCPP_END_NAMESPACE_STD
70
71#endif // _LIBCPP___BIT_ROTATE_H