steam-min-cpp
Loading...
Searching...
No Matches
msgbase.hpp
1// GPT
2#pragma once
3#include <cstdint>
4#include <cstring>
5#include <memory>
6#include <optional>
7#include <sstream>
8#include <stdexcept>
9#include <steamclient/types/generated/SteamLanguageInternal.hpp>
10#include <string>
11#include <vector>
12
13
14namespace Steam::Messaging::Messages {
15// Base message class for payload handling
16class MsgBase {
17 protected:
18 std::vector<uint8_t> payload;
19 size_t readPos = 0;
20
21 public:
22 MsgBase(size_t reserve = 0) { payload.reserve(reserve); }
23
24 // Payload access
25 std::vector<uint8_t>& Payload() { return payload; }
26 const std::vector<uint8_t>& Payload() const { return payload; }
27
28 // Writing helpers
29 void WriteByte(uint8_t b) { payload.push_back(b); }
30 void WriteBytes(const std::vector<uint8_t>& data) {
31 payload.insert(payload.end(), data.begin(), data.end());
32 }
33 template <typename T>
34 void WriteValue(const T& value) {
35 const uint8_t* ptr = reinterpret_cast<const uint8_t*>(&value);
36 payload.insert(payload.end(), ptr, ptr + sizeof(T));
37 }
38 void WriteString(const std::string& str) {
39 payload.insert(payload.end(), str.begin(), str.end());
40 }
41 void WriteNullTermString(const std::string& str) {
42 WriteString(str);
43 payload.push_back(0);
44 }
45
46 // Reading helpers
47 uint8_t ReadByte() {
48 if (readPos >= payload.size()) throw std::out_of_range("Read past end");
49 return payload[readPos++];
50 }
51 template <typename T>
52 T ReadValue() {
53 if (readPos + sizeof(T) > payload.size())
54 throw std::out_of_range("Read past end");
55 T val;
56 std::memcpy(&val, payload.data() + readPos, sizeof(T));
57 readPos += sizeof(T);
58 return val;
59 }
60 std::string ReadNullTermString() {
61 size_t start = readPos;
62 while (readPos < payload.size() && payload[readPos] != 0) readPos++;
63 std::string result(payload.begin() + start, payload.begin() + readPos);
64 if (readPos < payload.size()) readPos++; // skip null
65 return result;
66 }
67
68 void Seek(size_t pos) { readPos = pos; }
69 size_t Tell() const { return readPos; }
70};
71
72// Templated message class with header
73template <typename THeader>
74class MsgBaseHdr : public MsgBase {
75 public:
76 THeader Header;
77
78 virtual bool IsProto() const = 0;
79 virtual Steam::Internal::Enums::EMsg MsgType() const = 0;
80
81 std::optional<Steam::Internal::SteamID> steam_id;
82 int SessionID = 0;
83 uint64_t targetJobID = 0;
84 uint64_t sourceJobID = 0;
85
86 MsgBaseHdr(size_t reserve = 0) : MsgBase(reserve), Header() {}
87
88 virtual std::vector<uint8_t> Serialize() const {
89 Steam::Utils::Stream stream;
90 Header.Serialize(stream);
91 stream.Write(payload);
92 return stream.MoveBuffer();
93 }
94
95 virtual ~MsgBaseHdr() = default;
96};
97} // namespace Steam::Messaging::Messages