byteswap.h 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  15. # pragma GCC system_header
  16. #endif
  17. _LIBCPP_BEGIN_NAMESPACE_STD
  18. #if _LIBCPP_STD_VER >= 23
  19. template <integral _Tp>
  20. _LIBCPP_NODISCARD_EXT _LIBCPP_HIDE_FROM_ABI constexpr _Tp byteswap(_Tp __val) noexcept {
  21. if constexpr (sizeof(_Tp) == 1) {
  22. return __val;
  23. } else if constexpr (sizeof(_Tp) == 2) {
  24. return __builtin_bswap16(__val);
  25. } else if constexpr (sizeof(_Tp) == 4) {
  26. return __builtin_bswap32(__val);
  27. } else if constexpr (sizeof(_Tp) == 8) {
  28. return __builtin_bswap64(__val);
  29. #ifndef _LIBCPP_HAS_NO_INT128
  30. } else if constexpr (sizeof(_Tp) == 16) {
  31. #if __has_builtin(__builtin_bswap128)
  32. return __builtin_bswap128(__val);
  33. #else
  34. return static_cast<_Tp>(byteswap(static_cast<uint64_t>(__val))) << 64 |
  35. static_cast<_Tp>(byteswap(static_cast<uint64_t>(__val >> 64)));
  36. #endif // __has_builtin(__builtin_bswap128)
  37. #endif // _LIBCPP_HAS_NO_INT128
  38. } else {
  39. static_assert(sizeof(_Tp) == 0, "byteswap is unimplemented for integral types of this size");
  40. }
  41. }
  42. #endif // _LIBCPP_STD_VER >= 23
  43. _LIBCPP_END_NAMESPACE_STD
  44. #endif // _LIBCPP___BIT_BYTESWAP_H