Oxygen Engine
Modern C++ 3D Engine using OpenGL
Loading...
Searching...
No Matches
endian.h
1#ifndef OE_UTIL_ENDIAN_H
2#define OE_UTIL_ENDIAN_H
3
4#include <concepts>
5#include <span>
6#include <algorithm>
7#include <cstddef>
8
9#include <bit>
10
11namespace oe::util::endian
12{
16 [[nodiscard]] constexpr bool isLittleEndianHost() noexcept
17 {
18 return std::endian::native == std::endian::little;
19 }
20
24 [[nodiscard]] constexpr bool isBigEndianHost() noexcept
25 {
26 return std::endian::native == std::endian::big;
27 }
28
29 template <typename T>
30 concept NumericType = std::integral<T> || std::floating_point<T>;
31
35 template <NumericType T>
36 [[nodiscard]] constexpr T swapEndianess(const T& input) noexcept
37 {
38 #if defined(__cpp_lib_byteswap) && __cpp_lib_byteswap >= 202110L
39 return std::byteswap(input);
40 #else
41 T result;
42
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)};
45
46 std::ranges::reverse_copy(input_bytes, result_bytes.begin());
47
48 return result;
49 #endif
50 }
51
57 template <NumericType T>
58 [[nodiscard]] constexpr T convertLittleEndianToHost(const T& data) noexcept
59 {
60 if (isBigEndianHost())
61 {
62 return swapEndianess(data);
63 }
64
65 return data;
66 }
67
73 template <NumericType T>
74 [[nodiscard]] constexpr T convertBigEndianToHost(const T& data) noexcept
75 {
76 if (isLittleEndianHost())
77 {
78 return swapEndianess(data);
79 }
80
81 return data;
82 }
83
89 template <NumericType T>
90 [[nodiscard]] constexpr T convertHostToLittleEndian(const T& data) noexcept
91 {
92 if (isBigEndianHost())
93 {
94 return swapEndianess(data);
95 }
96
97 return data;
98 }
99
105 template <NumericType T>
106 [[nodiscard]] constexpr T convertHostToBigEndian(const T& data) noexcept
107 {
108 if (isLittleEndianHost())
109 {
110 return swapEndianess(data);
111 }
112
113 return data;
114 }
115
116
117}
118#endif
Definition endian.h:30