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