codex
Loading...
Searching...
No Matches
packet_reader.hpp
Go to the documentation of this file.
1#ifndef CODEX_PACKET_READER_PACKET_READER_HPP
2#define CODEX_PACKET_READER_PACKET_READER_HPP
3
4#include <array>
5#include <cassert>
6#include <cstdint>
7#include <cstdio>
8#include <cstring>
9#include <span>
10
11namespace codex {
12
14enum class Type : uint8_t { INVALID, INT, FLOAT };
15
17template<typename T> constexpr Type type_to_enum = Type::INVALID;
18template<> constexpr Type type_to_enum<int> = Type::INT;
19template<> constexpr Type type_to_enum<float> = Type::FLOAT;
20
22template<typename T> concept Readable = type_to_enum<T> != Type::INVALID;
23
25using ReadResult = bool;
26
37class Packet {
38public:
40 static constexpr std::size_t N = 32;
42 std::span<char, N> data() { return this->buf; }
44 auto get(Readable auto *...ps) { return (this->read(ps) && ...); }
45private:
47 template<typename T> void advance();
49 template<typename T> T read();
55 template<typename T> ReadResult read(T *p);
57 std::array<char, N> buf = {};
59 size_t i = {};
60};
61
62template<typename T>
64 const auto ni = this->i + sizeof(T);
65 assert(ni < this->buf.size());
66 this->i = ni;
67}
68
69template<typename T>
71 assert(this->i + sizeof(T) <= this->buf.size());
72 T ret = {};
73 std::memcpy(&ret, this->buf.data() + this->i, sizeof(T));
74 return ret;
75}
76
77template<typename T>
79 if(this->read<Type>() != type_to_enum<T>)
80 return false;
81 this->advance<Type>();
82 *p = this->read<T>();
83 this->advance<T>();
84 return true;
85}
86
87}
88
89#endif
#define T(f, T, C)
Definition bench.cpp:136
Wrapper for a raw byte buffer with methods to extract data from it.
Definition packet_reader.hpp:37
size_t i
Current offset into buf.
Definition packet_reader.hpp:59
std::span< char, N > data()
Provides direct access to the underlying buffer.
Definition packet_reader.hpp:42
std::array< char, N > buf
Raw byte buffer.
Definition packet_reader.hpp:57
void advance()
Advances i after reading a type T.
Definition packet_reader.hpp:63
T read()
Reads a sngle value of type T from the buffer.
Definition packet_reader.hpp:70
auto get(Readable auto *...ps)
Extracts typed data from the underlying raw byte buffer.
Definition packet_reader.hpp:44
Identifies whether a C++ type can be read from a buffer.
Definition packet_reader.hpp:22
Definition main.cpp:7
Definition rotate.hpp:6
constexpr Type type_to_enum< float >
Definition packet_reader.hpp:19
Type
Data types that can be read from a buffer.
Definition packet_reader.hpp:14
constexpr Type type_to_enum
Mapping from Type to C++ types.
Definition packet_reader.hpp:17
bool ReadResult
Arbitrary return type which could be replaced with a more detailed type.
Definition packet_reader.hpp:25
constexpr Type type_to_enum< int >
Definition packet_reader.hpp:18
codex::refl::field_tuple_t< E > T
Definition soa.cpp:9
#define p()
Definition std2.c:11