Gamedev Framework (gf) 1.2.0
A C++17 framework for 2D games
Packet.h
1/*
2 * Gamedev Framework (gf)
3 * Copyright (C) 2016-2022 Julien Bernard
4 *
5 * This software is provided 'as-is', without any express or implied
6 * warranty. In no event will the authors be held liable for any damages
7 * arising from the use of this software.
8 *
9 * Permission is granted to anyone to use this software for any purpose,
10 * including commercial applications, and to alter it and redistribute it
11 * freely, subject to the following restrictions:
12 *
13 * 1. The origin of this software must not be misrepresented; you must not
14 * claim that you wrote the original software. If you use this software
15 * in a product, an acknowledgment in the product documentation would be
16 * appreciated but is not required.
17 * 2. Altered source versions must be plainly marked as such, and must not be
18 * misrepresented as being the original software.
19 * 3. This notice may not be removed or altered from any source distribution.
20 */
21#ifndef GF_PACKET_H
22#define GF_PACKET_H
23
24#include <cassert>
25#include <cstdint>
26#include <vector>
27
28#include "Id.h"
29#include "NetApi.h"
30#include "Packet.h"
31#include "Streams.h"
32#include "Serialization.h"
33#include "SerializationOps.h"
34
35namespace gf {
36#ifndef DOXYGEN_SHOULD_SKIP_THIS
37inline namespace v1 {
38#endif
39
44 struct GF_NET_API Packet {
45 Id type = InvalidId;
46 std::vector<uint8_t> bytes;
47
52 if (type != InvalidId) {
53 return type;
54 }
55
56 BufferInputStream stream(&bytes);
57 Deserializer deserializer(stream);
58 deserializer | type;
59 return type;
60 }
61
65 template<typename T>
66 T as() {
67 BufferInputStream stream(&bytes);
68 Deserializer deserializer(stream);
69
70 T data;
71 deserializer | type | data;
72 assert(T::type == type);
73 return data;
74 }
75
79 template<typename T>
80 void is(const T& data) {
81 bytes.clear();
82 type = T::type;
83 gf::BufferOutputStream stream(&bytes);
84 gf::Serializer serializer(stream);
85 serializer | type | const_cast<T&>(data);
86 }
87
88 };
89
90#ifndef DOXYGEN_SHOULD_SKIP_THIS
91}
92#endif
93}
94
95#endif // GF_PACKET_H
Buffer input stream.
Definition: Streams.h:140
Buffer output stream.
Definition: Streams.h:266
A deserializer from a binary file.
Definition: Serialization.h:151
A serializer to a binary file.
Definition: Serialization.h:43
uint64_t Id
An identifier.
Definition: Id.h:37
constexpr Id InvalidId
The invalid id (which is 0)
Definition: Id.h:43
The namespace for gf classes.
A packet of bytes.
Definition: Packet.h:44
std::vector< uint8_t > bytes
The bytes representing the object.
Definition: Packet.h:46
Id getType()
Get the type of the underlying bytes.
Definition: Packet.h:51
void is(const T &data)
Serialize the object into bytes.
Definition: Packet.h:80
T as()
Deserialize the underlying bytes into an object.
Definition: Packet.h:66