R-Type  2
Doom but in better
Loading...
Searching...
No Matches
message_codec.hpp
Go to the documentation of this file.
1#pragma once
2#include "message.hpp"
3#include <cstring>
4#include <vector>
5
13inline bool decodeMessage(const char* data, size_t length, Message& out) {
14 uint8_t netType;
15 std::memcpy(&netType, data, 1);
16
17 // If needed, do ntohs here:
18 // netType = ntohs(netType);
19 // netLen = ntohs(netLen);
20
21 out.type = netType;
22 out.payload.resize(length);
23 std::memcpy(out.payload.data(), data, length);
24 return true;
25}
26
32inline std::vector<uint8_t> encodeMessage(const Message& msg) {
33 // If needed, do htons
34 uint8_t netType = msg.type;
35
36 size_t size = msg.payload.size();
37 std::vector<uint8_t> buffer(size + 1);
38 std::memcpy(buffer.data(), &netType, 1);
39 if (size > 0) {
40 std::memcpy(buffer.data() + 1, msg.payload.data(), size);
41 }
42 return buffer;
43}
std::vector< uint8_t > encodeMessage(const Message &msg)
Encodes a Message into a raw buffer (2-byte type, 2-byte length, then payload).
bool decodeMessage(const char *data, size_t length, Message &out)
Decodes a raw buffer into a Message (2-byte type, 2-byte length, then payload).
Minimal network message with a 4-byte header (type + length) and a payload.
Definition message.hpp:9
uint8_t type
Could map to messageType in GameMessage.hpp (CONNECT, DISCONNECT, etc.)
Definition message.hpp:10
std::vector< uint8_t > payload
Arbitrary payload bytes.
Definition message.hpp:11