Gamedev Framework (gf)  0.17.0
A C++14 framework for 2D games
Packet.h
1 /*
2  * Gamedev Framework (gf)
3  * Copyright (C) 2016-2019 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 "Packet.h"
30 #include "Portability.h"
31 #include "Streams.h"
32 #include "Serialization.h"
33 #include "SerializationOps.h"
34 
35 namespace gf {
36 #ifndef DOXYGEN_SHOULD_SKIP_THIS
37 inline namespace v1 {
38 #endif
39 
44  struct GF_API Packet {
45  Id type = InvalidId;
46  std::vector<uint8_t> bytes;
47 
48  Id getType() {
49  if (type != InvalidId) {
50  return type;
51  }
52 
53  BufferInputStream stream(&bytes);
54  Deserializer deserializer(stream);
55  deserializer | type;
56  return type;
57  }
58 
59  template<typename T>
60  T as() {
61  BufferInputStream stream(&bytes);
62  Deserializer deserializer(stream);
63 
64  T data;
65  deserializer | type | data;
66  assert(T::type == type);
67  return data;
68  }
69 
70  template<typename T>
71  void is(const T& data) {
72  bytes.clear();
73  type = T::type;
74  gf::BufferOutputStream stream(&bytes);
75  gf::Serializer serializer(stream);
76  serializer | type | const_cast<T&>(data);
77  }
78 
79  };
80 
81 #ifndef DOXYGEN_SHOULD_SKIP_THIS
82 }
83 #endif
84 }
85 
86 #endif // GF_PACKET_H
A deserializer from a binary file.
Definition: Serialization.h:153
Id getType()
Definition: Packet.h:48
void is(const T &data)
Definition: Packet.h:71
Buffer input stream.
Definition: Streams.h:140
uint64_t Id
An identifier.
Definition: Id.h:39
A packet of bytes.
Definition: Packet.h:44
A serializer to a binary file.
Definition: Serialization.h:45
The namespace for gf classes.
Definition: Action.h:35
Buffer output stream.
Definition: Streams.h:266
constexpr Id InvalidId
The invalid id (which is 0)
Definition: Id.h:45
std::vector< uint8_t > bytes
Definition: Packet.h:46
T as()
Definition: Packet.h:60