61 lines · c
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-exception6//7//===----------------------------------------------------------------------===//8 9#ifndef _LIBCPP___BIT_ROTATE_H10#define _LIBCPP___BIT_ROTATE_H11 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_header18#endif19 20_LIBCPP_BEGIN_NAMESPACE_STD21 22// Writing two full functions for rotl and rotr makes it easier for the compiler23// to optimize the code. On x86 this function becomes the ROL instruction and24// the rotr function becomes the ROR instruction.25 26#if _LIBCPP_STD_VER >= 2027 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 >= 2057 58_LIBCPP_END_NAMESPACE_STD59 60#endif // _LIBCPP___BIT_ROTATE_H61