Repository navigation
Expand file tree
/
Copy pathschema_value.hpp
More file actions
120 lines (100 loc) · 2.46 KB
/
Copy pathschema_value.hpp
File metadata and controls
120 lines (100 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
// Generated by tools/generate_protocol_types.py. DO NOT EDIT.
#pragma once
#include <algorithm>
#include <array>
#include <nlohmann/json.hpp>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
namespace copilot::generated
{
enum class SchemaKind
{
Alias,
Array,
Boolean,
Enum,
Integer,
Map,
Null,
Number,
Object,
Opaque,
String,
Union,
};
namespace detail
{
template <typename Tag>
class SchemaValue
{
public:
SchemaValue()
: value_(default_value())
{
}
explicit SchemaValue(nlohmann::json value)
: value_(std::move(value))
{
}
const nlohmann::json& raw() const noexcept
{
return value_;
}
nlohmann::json& raw() noexcept
{
return value_;
}
template <typename T>
T as() const
{
return value_.template get<T>();
}
bool is_known_string_value() const
{
return value_.is_string() && contains_known(value_.template get_ref<const std::string&>());
}
std::optional<std::string> discriminator(std::string_view key = "type") const
{
if (!value_.is_object())
return std::nullopt;
const auto it = value_.find(std::string(key));
if (it == value_.end() || !it->is_string())
return std::nullopt;
return it->template get<std::string>();
}
bool has_known_discriminator(std::string_view key = "type") const
{
const auto value = discriminator(key);
return value && contains_known(*value);
}
bool operator==(const SchemaValue&) const = default;
private:
static nlohmann::json default_value()
{
if constexpr (Tag::kind == SchemaKind::Object || Tag::kind == SchemaKind::Map)
return nlohmann::json::object();
if constexpr (Tag::kind == SchemaKind::Array)
return nlohmann::json::array();
return nullptr;
}
static bool contains_known(std::string_view value)
{
return std::find(Tag::known_string_values.begin(), Tag::known_string_values.end(), value) !=
Tag::known_string_values.end();
}
nlohmann::json value_;
};
template <typename Tag>
inline void to_json(nlohmann::json& j, const SchemaValue<Tag>& value)
{
j = value.raw();
}
template <typename Tag>
inline void from_json(const nlohmann::json& j, SchemaValue<Tag>& value)
{
value = SchemaValue<Tag>(j);
}
} // namespace detail
} // namespace copilot::generated