R-Type 0.1
Loading...
Searching...
No Matches
BigEndian.hpp
1#pragma once
2
8#include <array>
9#include <bit>
10#include <concepts>
11#include <cstddef>
12#include <cstdint>
13
14namespace rtype::protocol {
20namespace detail {
26template <std::unsigned_integral T> constexpr T byteswap(T value) {
27 if constexpr (sizeof(T) == 1) {
28 return value;
29 } else if constexpr (sizeof(T) == 2) {
30 return __builtin_bswap16(value);
31 } else if constexpr (sizeof(T) == 4) {
32 return __builtin_bswap32(value);
33 } else {
34 return __builtin_bswap64(value);
35 }
36}
37
38template <std::unsigned_integral T> constexpr T hostToBig(T value) {
39 if constexpr (std::endian::native == std::endian::little)
40 return byteswap(value);
41 else
42 return value;
43}
44
46} // namespace detail
47
56template <std::unsigned_integral T> struct BigEndian {
57 std::array<std::uint8_t, sizeof(T)> bytes{};
58
62 constexpr BigEndian() = default;
63
68 constexpr BigEndian(T value)
69 : bytes(std::bit_cast<std::array<std::uint8_t, sizeof(T)>>(
70 detail::hostToBig(value))) {}
71
76 constexpr T get() const { return detail::hostToBig(std::bit_cast<T>(bytes)); }
77
81 constexpr operator T() const { return get(); }
82};
83
88
90} // namespace rtype::protocol
91
Unsigned integer stored as big-endian bytes, with an alignment of 1.
Definition BigEndian.hpp:56
constexpr T get() const
Returns the value in host byte order.
Definition BigEndian.hpp:76
constexpr BigEndian(T value)
Stores a host value in big-endian order.
Definition BigEndian.hpp:68
std::array< std::uint8_t, sizeof(T)> bytes
Value in big-endian order.
Definition BigEndian.hpp:57
constexpr BigEndian()=default
Creates a zero value.