byteswap.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // -*- C++ -*-
  2. //===----------------------------------------------------------------------===//
  3. //
  4. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  5. // See https://llvm.org/LICENSE.txt for license information.
  6. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #ifndef _LIBCPP___BIT_BYTESWAP_H
  10. #define _LIBCPP___BIT_BYTESWAP_H
  11. #include <__concepts/arithmetic.h>
  12. #include <__config>
  13. #include <cstdint>
  14. #include <cstdlib>
  15. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  16. # pragma GCC system_header
  17. #endif
  18. _LIBCPP_BEGIN_NAMESPACE_STD
  19. #if _LIBCPP_STD_VER > 20
  20. template <integral _Tp>
  21. _LIBCPP_HIDE_FROM_ABI constexpr _Tp byteswap(_Tp __val) noexcept {
  22. if constexpr (sizeof(_Tp) == 1) {
  23. return __val;
  24. } else if constexpr (sizeof(_Tp) == 2) {
  25. return __builtin_bswap16(__val);
  26. } else if constexpr (sizeof(_Tp) == 4) {
  27. return __builtin_bswap32(__val);
  28. } else if constexpr (sizeof(_Tp) == 8) {
  29. return __builtin_bswap64(__val);
  30. #ifndef _LIBCPP_HAS_NO_INT128
  31. } else if constexpr (sizeof(_Tp) == 16) {
  32. #if __has_builtin(__builtin_bswap128)
  33. return __builtin_bswap128(__val);
  34. #else
  35. return static_cast<_Tp>(byteswap(static_cast<uint64_t>(__val))) << 64 |
  36. static_cast<_Tp>(byteswap(static_cast<uint64_t>(__val >> 64)));
  37. #endif // __has_builtin(__builtin_bswap128)
  38. #endif // _LIBCPP_HAS_NO_INT128
  39. } else {
  40. static_assert(sizeof(_Tp) == 0, "byteswap is unimplemented for integral types of this size");
  41. }
  42. }
  43. #endif // _LIBCPP_STD_VER > 20
  44. _LIBCPP_END_NAMESPACE_STD
  45. #endif // _LIBCPP___BIT_BYTESWAP_H