userver: userver/formats/common/conversion_stack.hpp Source File
Loading...
Searching...
No Matches
conversion_stack.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/formats/common/conversion_stack.hpp
4/// @brief @copybrief formats::common::ConversionStack
5
6#include <cstdint>
7#include <optional>
8#include <string>
9#include <type_traits>
10#include <utility>
11
12#include <fmt/format.h>
13#include <boost/container/deque.hpp>
14#include <boost/container/options.hpp>
15
16#include <userver/compiler/demangle.hpp>
17#include <userver/formats/common/type.hpp>
18#include <userver/utils/assert.hpp>
19
20USERVER_NAMESPACE_BEGIN
21
22/// @brief Shared types and helpers for JSON/YAML format layers.
23namespace formats::common {
24
25namespace impl {
26
27template <class ValueBuilder>
28concept HasEmplaceNocheck = requires(ValueBuilder builder, ValueBuilder value) {
29 builder.EmplaceNocheck("key", std::move(value));
30};
31
32} // namespace impl
33
34/// @brief Used in the implementation of functions that convert between
35/// different formats, e.g. formats::yaml::Value to formats::json::Value, etc.
36///
37/// Does not use recursion, so stack overflow will never happen with deeply
38/// nested or wide objects or arrays.
39///
40/// @tparam ValueFrom the Value type, FROM which we convert,
41/// e.g. formats::yaml::Value
42/// \tparam ValueToBuilder the ValueBuilder type, TO which we convert,
43/// e.g. formats::json::ValueBuilder
44///
45/// How to build the conversion function:
46/// 1. Start by constructing the ConversionStack from the source `ValueFrom`
47/// 2. While `!IsParsed`:
48/// 1. call `GetNextFrom`
49/// 2. analyse the kind of the current `ValueFrom`
50/// 3. call one of:
51/// - CastCurrentPrimitive
52/// - SetCurrent
53/// - EnterItems
54/// 3. Call `GetParsed`
55///
56/// See the implementation of PerformMinimalFormatConversion as an example.
57template <typename ValueFrom, typename ValueToBuilder>
58class ConversionStack final {
59public:
60 /// Start the conversion from `value`.
61 explicit ConversionStack(ValueFrom value)
62 : stack_()
63 {
64 stack_.emplace_back(std::move(value));
65 }
66
67 ConversionStack(ConversionStack&&) = delete;
68 ConversionStack& operator=(ConversionStack&&) = delete;
69
70 /// Check whether the whole source ValueFrom has been parsed.
71 bool IsParsed() const { return stack_.front().is_parsed; }
72
73 /// Get the parsing result, precondition: `IsParsed()`.
74 ValueToBuilder&& GetParsed() && {
76 return std::move(stack_.front().to).value();
77 }
78
79 /// Get the current sub-`ValueFrom` to convert.
80 const ValueFrom& GetNextFrom() const {
81 if (stack_.front().is_parsed) {
82 return stack_.front().from;
83 } else if (!stack_.back().is_parsed) {
84 return stack_.back().from;
85 } else {
86 return stack_[stack_.size() - 2].from;
87 }
88 }
89
90 /// Use for when it's discovered that the current `ValueFrom` type is
91 /// available and has the same semantics in ValueFrom and ValueToBuilder,
92 /// e.g. `std::int64_t`, `std::string`, etc.
93 template <typename T>
95 UASSERT(!stack_.front().is_parsed && !stack_.back().is_parsed);
96 SetCurrent(stack_.back().from.template As<T>());
97 }
98
99 /// Use for when it's discovered that the current `ValueFrom` type is not
100 /// directly convertible to `ValueToBuilder`, but can be converted manually
101 /// (this might be an inexact conversion). For example, ValueFrom could have a
102 /// special representation for datetime, and we manually convert it to string
103 /// using some arbitrary format.
104 template <typename T>
105 void SetCurrent(T&& value) {
106 stack_.back().to.emplace(std::forward<T>(value));
107 stack_.back().is_parsed = true;
108 }
109
110 /// Use for when an object or an array `ValueFrom` is encountered.
111 void EnterItems() {
112 if (!stack_.back().is_parsed) {
113 if (!stack_.back().to) {
114 if (stack_.back().from.IsObject()) {
115 stack_.back().to.emplace(common::Type::kObject);
116 } else if (stack_.back().from.IsArray()) {
117 stack_.back().to.emplace(common::Type::kArray);
118 } else {
119 UINVARIANT(false, "Type mismatch");
120 }
121 }
122 const bool is_first_item = !stack_.back().current_parsing_elem;
123 if (is_first_item) {
124 stack_.back().current_parsing_elem = stack_.back().from.begin();
125 } else {
126 ++*stack_.back().current_parsing_elem;
127 }
128 if (stack_.back().current_parsing_elem.value() == stack_.back().from.end()) {
129 stack_.back().is_parsed = true;
130 return;
131 }
132 if (is_first_item) {
133 auto& frame = stack_.back();
134 if constexpr (requires { frame.to->Reserve(frame.from.GetSize()); }) {
135 frame.to->Reserve(frame.from.GetSize());
136 }
137 }
138 auto new_from = *stack_.back().current_parsing_elem.value();
139 stack_.emplace_back(std::move(new_from));
140 return;
141 }
142 UASSERT(stack_.size() > 1);
143 auto& current_docs = stack_[stack_.size() - 2];
144 if (current_docs.from.IsObject()) {
145 auto& builder = current_docs.to.value();
146 auto& child = stack_.back().to.value();
147 const auto key = current_docs.current_parsing_elem->GetName();
148 UASSERT_MSG(!builder.HasMember(key), "Duplicate object key during format conversion");
149 if constexpr (impl::HasEmplaceNocheck<ValueToBuilder>) {
150 builder.EmplaceNocheck(key, std::move(child));
151 } else {
152 builder[key] = std::move(child);
153 }
154 } else if (current_docs.from.IsArray()) {
155 current_docs.to->PushBack(std::move(stack_.back().to.value()));
156 } else {
157 UASSERT_MSG(false, "Type mismatch");
158 }
159 stack_.pop_back();
160 }
161
162private:
163 struct StackFrame final {
164 explicit StackFrame(ValueFrom&& from)
165 : from(std::move(from))
166 {}
167 explicit StackFrame(const ValueFrom& from)
168 : from(from)
169 {}
170
171 const ValueFrom from;
172 std::optional<ValueToBuilder> to{};
173 std::optional<typename ValueFrom::const_iterator> current_parsing_elem{};
174 bool is_parsed{false};
175 };
176
177 // The container must have stable references. For example, YamlConfig::const_iterator stores a pointer
178 // to the YamlConfig node that is being iterated over. If a stack frame moves, then the next frame's
179 // `current_parsing_elem` will be invalidated. Updating iterators in such cases would be complex and expensive.
180 boost::container::deque<StackFrame, void, boost::container::deque_options<boost::container::block_size<16>>::type>
181 stack_;
182};
183
184/// @brief Performs the conversion between different formats. Only supports
185/// basic formats node types, throws on any non-standard ones.
186///
187/// @note This is intended as a building block for conversion functions. Prefer
188/// calling `value.As<AnotherFormat>()` or `value.ConvertTo<AnotherFormat>()`.
189template <typename ValueTo, typename ValueFrom>
190ValueTo PerformMinimalFormatConversion(ValueFrom&& value) {
191 if (value.IsMissing()) {
192 throw typename std::decay_t<ValueFrom>::Exception(fmt::format(
193 "Failed to convert value at '{}' from {} to {}: missing value",
194 value.GetPath(),
195 compiler::GetTypeName<std::decay_t<ValueFrom>>(),
196 compiler::GetTypeName<ValueTo>()
197 ));
198 }
199 formats::common::ConversionStack<std::decay_t<ValueFrom>, typename ValueTo::Builder>
200 conversion_stack(std::forward<ValueFrom>(value));
201 while (!conversion_stack.IsParsed()) {
202 const auto& from = conversion_stack.GetNextFrom();
203 if (from.IsBool()) {
204 conversion_stack.template CastCurrentPrimitive<bool>();
205 } else if (from.IsInt()) {
206 conversion_stack.template CastCurrentPrimitive<int>();
207 } else if (from.IsInt64()) {
208 conversion_stack.template CastCurrentPrimitive<std::int64_t>();
209 } else if (from.IsUInt64()) {
210 conversion_stack.template CastCurrentPrimitive<std::uint64_t>();
211 } else if (from.IsDouble()) {
212 conversion_stack.template CastCurrentPrimitive<double>();
213 } else if (from.IsString()) {
214 conversion_stack.template CastCurrentPrimitive<std::string>();
215 } else if (from.IsNull()) {
216 conversion_stack.SetCurrent(common::Type::kNull);
217 } else if (from.IsArray() || from.IsObject()) {
218 conversion_stack.EnterItems();
219 } else {
220 throw typename std::decay_t<ValueFrom>::Exception(fmt::format(
221 "Failed to convert value at '{}' from {} to {}: unknown node type",
222 from.GetPath(),
223 compiler::GetTypeName<std::decay_t<ValueFrom>>(),
224 compiler::GetTypeName<ValueTo>()
225 ));
226 }
227 }
228 return std::move(conversion_stack).GetParsed().ExtractValue();
229}
230
231} // namespace formats::common
232
233USERVER_NAMESPACE_END