1#ifndef OE_UTIL_ENDIAN_H
2#define OE_UTIL_ENDIAN_H
11namespace oe::util::endian
16 [[nodiscard]]
constexpr bool isLittleEndianHost() noexcept
18 return std::endian::native == std::endian::little;
24 [[nodiscard]]
constexpr bool isBigEndianHost() noexcept
26 return std::endian::native == std::endian::big;
30 concept NumericType = std::integral<T> || std::floating_point<T>;
35 template <NumericType T>
36 [[nodiscard]]
constexpr T swapEndianess(
const T& input)
noexcept
38 #if defined(__cpp_lib_byteswap) && __cpp_lib_byteswap >= 202110L
39 return std::byteswap(input);
43 std::span input_bytes = {
reinterpret_cast<const std::byte*
>(&input),
sizeof(T)};
44 std::span result_bytes = {
reinterpret_cast<std::byte*
>(&result),
sizeof(T)};
46 std::ranges::reverse_copy(input_bytes, result_bytes.begin());
57 template <NumericType T>
58 [[nodiscard]]
constexpr T convertLittleEndianToHost(
const T& data)
noexcept
60 if (isBigEndianHost())
62 return swapEndianess(data);
73 template <NumericType T>
74 [[nodiscard]]
constexpr T convertBigEndianToHost(
const T& data)
noexcept
76 if (isLittleEndianHost())
78 return swapEndianess(data);
89 template <NumericType T>
90 [[nodiscard]]
constexpr T convertHostToLittleEndian(
const T& data)
noexcept
92 if (isBigEndianHost())
94 return swapEndianess(data);
105 template <NumericType T>
106 [[nodiscard]]
constexpr T convertHostToBigEndian(
const T& data)
noexcept
108 if (isLittleEndianHost())
110 return swapEndianess(data);