Botcraft 1.21.5
Loading...
Searching...
No Matches
Either.hpp
Go to the documentation of this file.
1#if PROTOCOL_VERSION > 766 /* > 1.20.6 */
2#pragma once
4
5#include <optional>
6
7namespace ProtocolCraft
8{
9 template<typename T, typename U>
10 class Either : public NetworkType
11 {
12 public:
13 virtual ~Either()
14 {
15
16 }
17
18
19 const std::optional<T>& GetLeft() const
20 {
21 return left;
22 }
23
24 const std::optional<T>& GetRight() const
25 {
26 return right;
27 }
28
29
30 auto& SetLeft(const std::optional<T>& left_)
31 {
32 left = left_;
33 if (left.has_value())
34 {
35 right = std::nullopt;
36 }
37 return *this;
38 }
39
40 auto& SetRight(const std::optional<T>& right_)
41 {
42 right = right_;
43 if (right.has_value())
44 {
45 left = std::nullopt;
46 }
47 return *this;
48 }
49
50 protected:
51 virtual void ReadImpl(ReadIterator& iter, size_t& length) override
52 {
53 const bool is_left = ReadData<bool>(iter, length);
54 if (is_left)
55 {
56 left = ReadData<T>(iter, length);
57 right = std::nullopt;
58 }
59 else
60 {
61 left = std::nullopt;
62 right = ReadData<U>(iter, length);
63 }
64 }
65
66 virtual void WriteImpl(WriteContainer& container) const override
67 {
68 WriteData<bool>(left.has_value(), container);
69 if (left.has_value())
70 {
71 WriteData<T>(left.value(), container);
72 }
73 else // Right should have a value
74 {
75 WriteData<U>(right.value(), container);
76 }
77 }
78
79 virtual Json::Value SerializeImpl() const override
80 {
81 Json::Value output;
82
83 if (left.has_value())
84 {
85 output["left"] = left.value();
86 }
87 else if (right.has_value())
88 {
89 output["right"] = right.value();
90 }
91
92 return output;
93 }
94
95 private:
96 std::optional<T> left;
97 std::optional<U> right;
98
99 };
100}
101#endif
auto & SetLeft(const std::optional< T > &left_)
Definition Either.hpp:30
std::optional< T > left
Definition Either.hpp:96
const std::optional< T > & GetRight() const
Definition Either.hpp:24
auto & SetRight(const std::optional< T > &right_)
Definition Either.hpp:40
virtual void WriteImpl(WriteContainer &container) const override
Definition Either.hpp:66
const std::optional< T > & GetLeft() const
Definition Either.hpp:19
virtual Json::Value SerializeImpl() const override
Definition Either.hpp:79
virtual void ReadImpl(ReadIterator &iter, size_t &length) override
Definition Either.hpp:51
std::optional< U > right
Definition Either.hpp:97
Main class, basically a JsonVariant with extra utility functions it doesn't inherit JsonVariant direc...
Definition Json.hpp:45
std::vector< unsigned char > WriteContainer
std::vector< unsigned char >::const_iterator ReadIterator