10 #include <type_traits>
18 using Bytes = std::vector<Byte>;
33 requires std::is_standard_layout_v<T> || std::is_same_v<std::decay_t<T>, std::string>
34 inline std::span<const uint8_t>
AsBytes(
const T& value)
36 return std::span{
reinterpret_cast<const std::uint8_t*
>(&value),
sizeof(T) };
45 inline std::span<const uint8_t> AsBytes<std::string>(
const std::string& value)
47 return std::span{
reinterpret_cast<const std::uint8_t*
>(value.data()), value.size() };
59 requires std::is_standard_layout_v<T> || std::is_same_v<std::decay_t<T>, std::string>
62 auto bytes = AsBytes<T>(value);
63 return Bytes{ bytes.begin(), bytes.end() };
84 if constexpr (std::is_same_v<std::string, std::decay_t<T>>) {
85 return std::string(bytes.begin(), bytes.end());
89 std::copy(bytes.begin(), bytes.end(),
reinterpret_cast<std::uint8_t*
>(&value));
101 buffer.reserve(buffer.size() + bytes.size());
102 buffer.insert(buffer.end(), bytes.begin(), bytes.end());
106 constexpr std::uint16_t
SwapBytes(
const std::uint16_t value)
108 if constexpr (std::endian::native == std::endian::big) {
112 return ((value >> 8) & 0x00FF) | ((value << 8) & 0xFF00);
116 constexpr std::uint32_t
SwapBytes(
const std::uint32_t value)
118 if constexpr (std::endian::native == std::endian::big) {
122 return ((value >> 24) & 0x000000FF) | ((value >> 8) & 0x0000FF00) | ((value << 8) & 0x00FF0000) |
123 ((value << 24) & 0xFF000000);
127 constexpr std::uint64_t
SwapBytes(
const std::uint64_t value)
129 if constexpr (std::endian::native == std::endian::big) {
133 return ((value >> 56) & 0x00000000000000FF) | ((value >> 40) & 0x000000000000FF00) |
134 ((value >> 24) & 0x0000000000FF0000) | ((value >> 8) & 0x00000000FF000000) |
135 ((value << 8) & 0x000000FF00000000) | ((value << 24) & 0x0000FF0000000000) |
136 ((value << 40) & 0x00FF000000000000) | ((value << 56) & 0xFF00000000000000);
Definition: attributes.h:13
T FromBytes(std::span< const uint8_t > bytes)
Constructs a value from bytes.
Definition: bytes.h:78
uint8_t Byte
One octet of binary data.
Definition: bytes.h:15
std::vector< Byte > Bytes
Owning contiguous byte buffer.
Definition: bytes.h:18
std::span< const Byte > BytesSpan
Non-owning, read-only view of contiguous bytes.
Definition: bytes.h:21
requires std::is_standard_layout_v< T > std::is_same_v< std::decay_t< T >, std::string > std::span< const uint8_t > AsBytes(const T &value)
Views a value's in-memory object representation as bytes.
Definition: bytes.h:34
requires std::is_standard_layout_v< T > std::is_same_v< std::decay_t< T >, std::string > Bytes AsOwnedBytes(const T &value)
Copies a value's native object representation into an owning byte buffer.
Definition: bytes.h:60
void AppendBytes(Bytes &buffer, BytesSpan bytes)
Appends bytes to an owning buffer.
Definition: bytes.h:99
constexpr std::uint16_t SwapBytes(const std::uint16_t value)
Converts a 16-bit value between native and big-endian byte order.
Definition: bytes.h:106