userver: userver/formats/yaml/value.hpp Source File
Loading...
Searching...
No Matches
value.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/formats/yaml/value.hpp
4/// @brief @copybrief formats::yaml::Value
5
6#include <type_traits>
7
8#include <userver/formats/common/items.hpp>
9#include <userver/formats/common/meta.hpp>
10#include <userver/formats/parse/common.hpp>
11#include <userver/formats/yaml/exception.hpp>
12#include <userver/formats/yaml/iterator.hpp>
13#include <userver/formats/yaml/types.hpp>
14#include <userver/utils/fast_pimpl.hpp>
15
16USERVER_NAMESPACE_BEGIN
17
18namespace formats::yaml {
19
20class ValueBuilder;
21
22/// @ingroup userver_universal userver_containers userver_formats
23///
24/// @brief Non-mutable YAML value representation.
25///
26/// Class provides non mutable access YAML value. For modification and
27/// construction of new YAML values use formats::yaml::ValueBuilder.
28///
29/// ## Example usage:
30///
31/// @snippet formats/yaml/value_test.cpp Sample formats::yaml::Value usage
32///
33/// @see @ref scripts/docs/en/userver/formats.md
34class Value final {
35public:
36 struct IterTraits {
37 using native_iter = YAML::const_iterator;
38 using value_type = formats::yaml::Value;
39 using reference = const formats::yaml::Value&;
40 using pointer = const formats::yaml::Value*;
41 };
43
44 using const_iterator = Iterator<IterTraits>;
45 using Exception = formats::yaml::Exception;
46 using ParseException = formats::yaml::ParseException;
47 using ExceptionWithPath = formats::yaml::ExceptionWithPath;
48 using Builder = ValueBuilder;
49
50 /// @brief Constructs a Value that holds a Null.
51 Value() noexcept;
52
53 // NOLINTNEXTLINE(performance-noexcept-move-constructor)
54 Value(Value&&);
55 Value(const Value&);
56 // NOLINTNEXTLINE(performance-noexcept-move-constructor)
57 Value& operator=(Value&&);
58 Value& operator=(const Value&);
59
60 template <class T>
61 Value& operator=(T&&) && {
62 static_assert(
63 !sizeof(T),
64 "You're assigning to a temporary formats::yaml::Value! Use "
65 "formats::yaml::ValueBuilder for data modifications."
66 );
67 return *this;
68 }
69
70 ~Value();
71
72 /// @brief Copies `other`, appending `path_prefix` to the stored `path`
73 /// @warning `other` must have an empty (root) path
74 /// @throw `std::logic_error` if `other` has path other than the root path
75 /// @see GetPath
76 Value(Value&& other, std::string path_prefix);
77
78 /// @brief Access member by key for read.
79 /// @throw TypeMismatchException if not a missing value, an object, or Null.
80 Value operator[](std::string_view key) const;
81
82 /// @brief Access array member by index for read.
83 /// @throw TypeMismatchException if not an array value.
84 /// @throw `OutOfBoundsException` if index is greater or equal
85 /// than size.
86 Value operator[](std::size_t index) const;
87
88 /// @brief Returns an iterator to the beginning of the held array or map.
89 /// @throw TypeMismatchException if not an array or an object.
90 const_iterator begin() const;
91
92 /// @brief Returns an iterator to the end of the held array or map.
93 /// @throw TypeMismatchException if not an array or an object.
94 const_iterator end() const;
95
96 /// @brief Returns whether the array or object is empty.
97 /// @throw TypeMismatchException if not an array or an object.
98 bool IsEmpty() const;
99
100 /// @brief Returns array size or object members count.
101 /// @throw TypeMismatchException if not an array or an object.
102 std::size_t GetSize() const;
103
104 /// @brief Compares values.
105 /// @throw MemberMissingException if `*this` or `other` is missing.
106 bool operator==(const Value& other) const;
107 bool operator!=(const Value& other) const;
108
109 /// @brief Returns true if *this holds nothing. When `IsMissing()` returns
110 /// `true` any attempt to get the actual value or iterate over *this will
111 /// throw MemberMissingException.
112 bool IsMissing() const;
113
114 /// @brief Returns true if *this holds a Null (Type::kNull).
115 bool IsNull() const noexcept;
116
117 /// @brief Returns true if *this is convertible to bool.
118 bool IsBool() const noexcept;
119
120 /// @brief Returns true if *this is convertible to int.
121 bool IsInt() const noexcept;
122
123 /// @brief Returns true if *this is convertible to int64_t.
124 bool IsInt64() const noexcept;
125
126 /// @brief Returns true if *this is convertible to uint64_t.
127 bool IsUInt64() const noexcept;
128
129 /// @brief Returns true if *this is convertible to double.
130 bool IsDouble() const noexcept;
131
132 /// @brief Returns true if *this is convertible to std::string.
133 bool IsString() const noexcept;
134
135 /// @brief Returns true if *this is an array (Type::kArray).
136 bool IsArray() const noexcept;
137
138 /// @brief Returns true if *this is a map (Type::kObject).
139 bool IsObject() const noexcept;
140
141 // clang-format off
142
143 /// @brief Returns value of *this converted to the result type of
144 /// Parse(const Value&, parse::To<T>). Almost always it is T.
145 /// @throw Anything derived from std::exception.
146 ///
147 /// ## Example usage:
148 ///
149 /// @snippet formats/yaml/value_test.cpp Sample formats::yaml::Value::As<T>() usage
150 ///
151 /// @see @ref scripts/docs/en/userver/formats.md
152
153 // clang-format on
154
155 template <typename T>
156 auto As() const;
157
158 /// @brief Returns value of *this converted to T or T(args) if
159 /// this->IsMissing().
160 /// @throw Anything derived from std::exception.
161 template <typename T, typename First, typename... Rest>
162 auto As(First&& default_arg, Rest&&... more_default_args) const;
163
164 /// @brief Returns value of *this converted to T or T() if this->IsMissing().
165 /// @throw Anything derived from std::exception.
166 /// @note Use as `value.As<T>({})`
167 template <typename T>
168 auto As(DefaultConstructed) const;
169
170 /// @brief Returns true if *this holds a `key`.
171 bool HasMember(std::string_view key) const;
172
173 /// @brief Returns full path to this value.
174 std::string GetPath() const;
175
176 /// @brief Returns 0-based column number of this `Value` in the original
177 /// document. Returns `-1` if `this->IsMissing()`. If `Value` was created
178 /// using formats::yaml::ValueBuilder, returns `0`.
179 /// @note This method available **only** for formats::yaml::Value.
180 int GetColumn() const;
181
182 /// @brief Returns 0-based line number of this `Value` in the original
183 /// document. Returns `-1` if `this->IsMissing()`. If `Value` was created
184 /// using formats::yaml::ValueBuilder, returns `0`.
185 /// @note This method available **only** for formats::yaml::Value.
186 int GetLine() const;
187
188 /// @brief Returns YAML tag of this node.
189 /// If tag is not explicitly specified, its value depends on node value. For
190 /// explicitly specified tags, its value depends on used `TAG` directives and
191 /// node value. There is an implicit `TAG` derictive for `!!` with prefix
192 /// `tag:yaml.org,2002:`.
193 ///
194 /// For example:
195 /// - `""` if field is null, even when tag is specified
196 /// - `"!"` for quoted and block strings if tag is not specified
197 /// - `"?"` for other fields if tag is not specified
198 /// - `"tag:yaml.org,2002:str"` for `!!str` tag
199 /// - `"!!str"` for `!<!!str>` tag
200 /// - `"!custom_tag"` for `!custom_tag` tag, if no additional `TAG` directives
201 /// are specified
202 ///
203 /// For details see YAML specification.
204 /// @throws MemberMissingException if `this->IsMissing()`.
205 /// @note This method available **only** for formats::yaml::Value.
207
208 /// @brief Returns new value that is an exact copy if the existing one
209 /// but references different memory (a deep copy of a *this). The returned
210 /// value is a root value with path '/'.
211 /// @throws MemberMissingException if `this->IsMissing()`.
212 Value Clone() const;
213
214 /// @throw MemberMissingException if `this->IsMissing()`.
215 void CheckNotMissing() const;
216
217 /// @throw MemberMissingException if `*this` is not an array.
218 void CheckArray() const;
219
220 /// @throw MemberMissingException if `*this` is not an array or Null.
221 void CheckArrayOrNull() const;
222
223 /// @throw TypeMismatchException if `*this` is not a map or Null.
224 void CheckObjectOrNull() const;
225
226 /// @throw TypeMismatchException if `*this` is not a map.
227 void CheckObject() const;
228
229 /// @throw TypeMismatchException if `*this` is not convertible to std::string.
230 void CheckString() const;
231
232 /// @throw TypeMismatchException if `*this` is not a map, array or Null.
234
235 /// @throw TypeMismatchException if `*this` is not a map, array or Null;
236 /// `OutOfBoundsException` if `index >= this->GetSize()`.
237 void CheckInBounds(std::size_t index) const;
238
239 /// @brief Returns true if *this is a first (root) value.
240 bool IsRoot() const noexcept;
241
242 /// @brief Returns true if `*this` and `other` reference the value by the same
243 /// pointer.
244 bool DebugIsReferencingSameMemory(const Value& other) const;
245
246private:
247 class EmplaceEnabler {};
248
249public:
250 /// @cond
251 Value(EmplaceEnabler, const YAML::Node& value, const formats::yaml::Path& path, std::string_view key);
252
253 Value(EmplaceEnabler, const YAML::Node& value, const formats::yaml::Path& path, size_t index);
254 /// @endcond
255
256private:
257 Value(const YAML::Node& root) noexcept;
258
259 static Value MakeNonRoot(const YAML::Node& value, const formats::yaml::Path& path, std::string_view key);
260 static Value MakeNonRoot(const YAML::Node& val, const formats::yaml::Path& path, size_t index);
261
262 const YAML::Node& GetNative() const;
263 YAML::Node& GetNative();
264 int GetExtendedType() const;
265
266 template <class T>
267 bool IsConvertibleToArithmetic() const;
268
269 template <class T>
270 T ValueAsArithmetic() const;
271
272 static constexpr std::size_t kNativeNodeSize = 64;
273 static constexpr std::size_t kNativeAlignment = alignof(void*);
274
275 utils::FastPimpl<YAML::Node, kNativeNodeSize, kNativeAlignment> value_pimpl_;
276 formats::yaml::Path path_;
277
278 friend class Iterator<IterTraits>;
279 friend class ValueBuilder;
280
281 friend bool Parse(const Value& value, parse::To<bool>);
282 friend int64_t Parse(const Value& value, parse::To<int64_t>);
283 friend uint64_t Parse(const Value& value, parse::To<uint64_t>);
284 friend double Parse(const Value& value, parse::To<double>);
285 friend std::string Parse(const Value& value, parse::To<std::string>);
286
287 friend formats::yaml::Value FromString(const std::string&);
288 friend formats::yaml::Value FromStream(std::istream&);
289 friend void Serialize(const formats::yaml::Value&, std::ostream&);
290};
291
292template <typename T>
293auto Value::As() const {
294 static_assert(
295 formats::common::impl::kHasParse<Value, T>,
296 "There is no `Parse(const Value&, formats::parse::To<T>)` in "
297 "namespace of `T` or `formats::parse`. "
298 "Probably you forgot to include the "
299 "<userver/formats/parse/common_containers.hpp> or you "
300 "have not provided a `Parse` function overload."
301 );
302
303 return Parse(*this, formats::parse::To<T>{});
304}
305
306bool Parse(const Value& value, parse::To<bool>);
307
308int64_t Parse(const Value& value, parse::To<int64_t>);
309
310uint64_t Parse(const Value& value, parse::To<uint64_t>);
311
312double Parse(const Value& value, parse::To<double>);
313
314std::string Parse(const Value& value, parse::To<std::string>);
315
316template <typename T, typename First, typename... Rest>
317auto Value::As(First&& default_arg, Rest&&... more_default_args) const {
318 if (IsMissing() || IsNull()) {
319 // intended raw ctor call, sometimes casts
320 // NOLINTNEXTLINE(google-readability-casting)
321 return decltype(As<T>())(std::forward<First>(default_arg), std::forward<Rest>(more_default_args)...);
322 }
323 return As<T>();
324}
325
326template <typename T>
327auto Value::As(Value::DefaultConstructed) const {
328 return (IsMissing() || IsNull()) ? decltype(As<T>())() : As<T>();
329}
330
331/// @brief Wrapper for handy python-like iteration over a map
332///
333/// @code
334/// for (const auto& [name, value]: Items(map)) ...
335/// @endcode
336using formats::common::Items;
337
338} // namespace formats::yaml
339
340/// Although we provide user defined literals, please beware that
341/// 'using namespace ABC' may contradict code style of your company.
342namespace formats::literals {
343
344yaml::Value operator"" _yaml(const char* str, std::size_t len);
345
346} // namespace formats::literals
347
348USERVER_NAMESPACE_END