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