Botcraft 26.3
Loading...
Searching...
No Matches
DynamicType.hpp
Go to the documentation of this file.
1#pragma once
2
7
8#include <memory>
9
10namespace ProtocolCraft
11{
12 namespace Internal
13 {
14 /// @brief A dynamic field that can hold different data inheriting a common BaseType (derived from NetworkType). Cannot be used inside a container like a vector
15 /// @tparam BaseType Common base class of every possible data type
16 /// @tparam TypeField Pointer to the type field (e.g. &MyNetworkClass::Type)
17 /// @tparam Factory Function pointer. Should have a signature std::shared_ptr<Base>(TypeValue)
18 template <typename BaseType, auto TypeField, auto Factory>
20 {
21 template <typename C>
22 static std::shared_ptr<BaseType> Read(
23 const C* c,
24 std::vector<unsigned char>::const_iterator& iter,
25 size_t& length
26#ifdef PROTOCOLCRAFT_DETAILED_PARSING
27 ,
28 typename OffsetType<std::shared_ptr<BaseType>>::type* start_offset = nullptr,
29 typename OffsetType<std::shared_ptr<BaseType>>::type* end_offset = nullptr
30#endif
31 )
32 {
33
34#ifdef PROTOCOLCRAFT_DETAILED_PARSING
35 if (start_offset != nullptr)
36 {
37 *start_offset = length;
38 }
39#endif
40 std::shared_ptr<BaseType> data = Factory(c->*TypeField);
41 if (data != nullptr)
42 {
43 data->Read(iter, length);
44 }
45#ifdef PROTOCOLCRAFT_DETAILED_PARSING
46 if (end_offset != nullptr)
47 {
48 *end_offset = length;
49 }
50#endif
51 return data;
52 }
53
54 template <typename C>
55 static void Write(const C* c, const std::shared_ptr<BaseType>& val, std::vector<unsigned char>& container)
56 {
57 if (val != nullptr)
58 {
59 val->Write(container);
60 }
61 else
62 {
63 // No data have been set after the type: write the default payload so the bytes stay readable
64 Factory(c->*TypeField)->Write(container);
65 }
66 }
67
68 template <typename C>
69 static std::optional<Json::Value> Serialize(
70 const C* c,
71 const std::shared_ptr<BaseType>& val
72#ifdef PROTOCOLCRAFT_DETAILED_PARSING
73 ,
74 const typename OffsetType<std::shared_ptr<BaseType>>::type* start_offset = nullptr,
75 const typename OffsetType<std::shared_ptr<BaseType>>::type* end_offset = nullptr
76#endif
77 )
78 {
79 return SerializeType<std::shared_ptr<BaseType>>(val
80#ifdef PROTOCOLCRAFT_DETAILED_PARSING
81 , start_offset, end_offset
82#endif
83 );
84 }
85 };
86 }
87}
A dynamic field that can hold different data inheriting a common BaseType (derived from NetworkType).
static void Write(const C *c, const std::shared_ptr< BaseType > &val, std::vector< unsigned char > &container)
static std::optional< Json::Value > Serialize(const C *c, const std::shared_ptr< BaseType > &val)
static std::shared_ptr< BaseType > Read(const C *c, std::vector< unsigned char >::const_iterator &iter, size_t &length)