Nexus Engine  v0.0.1
Loading...
Searching...
No Matches
Packet.inl
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2
3#pragma once
4
5namespace Nexus::Network {
6 namespace Wire {
7 template <std::integral T>
8 [[nodiscard]] constexpr T HostToBigEndian(T value) noexcept {
9 if constexpr (std::endian::native == std::endian::little && sizeof(T) > 1) {
10 return std::byteswap(value);
11 } else {
12 return value;
13 }
14 }
15
16 template <std::integral T>
17 [[nodiscard]] constexpr T BigEndianToHost(T value) noexcept {
18 return HostToBigEndian(value);
19 }
20
21 template <std::integral T>
22 void Append(std::vector<byte>& buffer, T value) {
23 const T wireValue = HostToBigEndian(value);
24 const auto* bytes = reinterpret_cast<const byte*>(&wireValue);
25 buffer.insert(buffer.end(), bytes, bytes + sizeof(T));
26 }
27
28 template <std::integral T>
29 [[nodiscard]] bool Read(std::span<const byte> data, usize& offset, T& out) {
30 if (offset > data.size() || sizeof(T) > data.size() - offset) {
31 return false;
32 }
33
34 T wireValue{};
35 std::memcpy(&wireValue, data.data() + offset, sizeof(T));
36 offset += sizeof(T);
37 out = BigEndianToHost(wireValue);
38 return true;
39 }
40 } // namespace Wire
41
42 template <typename T>
43 void Packet::Write(const T& value) {
44 static_assert(std::is_trivially_copyable_v<T>);
45
46 if constexpr (std::integral<T>) {
47 Wire::Append(m_storage, value);
48 } else {
49 const auto* bytes = reinterpret_cast<const byte*>(&value);
50 m_storage.insert(m_storage.end(), bytes, bytes + sizeof(T));
51 }
52 }
53
54 template <typename T>
55 [[nodiscard]] bool Packet::Read(T& out) {
56 static_assert(std::is_trivially_copyable_v<T>);
57
58 if constexpr (std::integral<T>) {
59 return Wire::Read(m_storage, m_readPos, out);
60 } else {
61 if (m_readPos > m_storage.size() || sizeof(T) > m_storage.size() - m_readPos) {
62 return false;
63 }
64 std::memcpy(&out, m_storage.data() + m_readPos, sizeof(T));
65 m_readPos += sizeof(T);
66 return true;
67 }
68 }
69} // namespace Nexus::Network
bool Read(T &out)
Definition Packet.inl:55
void Write(const T &value)
Definition Packet.inl:43
Wire values are always sent big-endian.
Definition Packet.cppm:39
bool Read(std::span< const byte > data, usize &offset, T &out)
Definition Packet.inl:29
void Append(std::vector< byte > &buffer, T value)
Definition Packet.inl:22
constexpr T HostToBigEndian(T value) noexcept
Definition Packet.inl:8
constexpr T BigEndianToHost(T value) noexcept
Definition Packet.inl:17
Definition NetworkAddress.cpp:9
std::size_t usize
Definition Types.cppm:25