rotate.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. #ifndef _LIBCPP___BIT_ROTATE_H
  9. #define _LIBCPP___BIT_ROTATE_H
  10. #include <__concepts/arithmetic.h>
  11. #include <__config>
  12. #include <__type_traits/is_unsigned_integer.h>
  13. #include <limits>
  14. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  15. # pragma GCC system_header
  16. #endif
  17. _LIBCPP_BEGIN_NAMESPACE_STD
  18. template <class _Tp>
  19. _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 _Tp __rotr(_Tp __t, int __cnt) _NOEXCEPT {
  20. static_assert(__libcpp_is_unsigned_integer<_Tp>::value, "__rotr requires an unsigned integer type");
  21. const unsigned int __dig = numeric_limits<_Tp>::digits;
  22. if ((__cnt % __dig) == 0)
  23. return __t;
  24. if (__cnt < 0) {
  25. __cnt *= -1;
  26. return (__t << (__cnt % __dig)) | (__t >> (__dig - (__cnt % __dig))); // rotr with negative __cnt is similar to rotl
  27. }
  28. return (__t >> (__cnt % __dig)) | (__t << (__dig - (__cnt % __dig)));
  29. }
  30. template <class _Tp>
  31. _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 _Tp __rotl(_Tp __t, int __cnt) _NOEXCEPT {
  32. return std::__rotr(__t, -__cnt);
  33. }
  34. #if _LIBCPP_STD_VER >= 20
  35. template <__libcpp_unsigned_integer _Tp>
  36. [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr _Tp rotl(_Tp __t, int __cnt) noexcept {
  37. return std::__rotl(__t, __cnt);
  38. }
  39. template <__libcpp_unsigned_integer _Tp>
  40. [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr _Tp rotr(_Tp __t, int __cnt) noexcept {
  41. return std::__rotr(__t, __cnt);
  42. }
  43. #endif // _LIBCPP_STD_VER >= 20
  44. _LIBCPP_END_NAMESPACE_STD
  45. #endif // _LIBCPP___BIT_ROTATE_H