userver: userver/formats/serialize/common_containers.hpp Source File
⚠️ This is the documentation for an old userver version. Click here to switch to the latest version.
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages Concepts
common_containers.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/formats/serialize/common_containers.hpp
4/// @brief Serializers for standard containers and optional
5/// @ingroup userver_universal userver_formats_serialize
6
7#include <optional>
8#include <type_traits>
9
10#include <userver/formats/common/type.hpp>
11#include <userver/formats/serialize/to.hpp>
12#include <userver/utils/meta.hpp>
13
14namespace boost::uuids {
15struct uuid;
16}
17
18USERVER_NAMESPACE_BEGIN
19
20namespace utils::impl::strong_typedef {
21struct StrongTypedefTag;
22}
23
24/// Common serializers
25namespace formats::serialize {
26
27/// Common containers serialization (vector/set)
28template <typename T, typename Value>
30 !std::is_same_v<T, boost::uuids::uuid> &&
33 Value>
35 typename Value::Builder builder(formats::common::Type::kArray);
36 for (const auto& item : value) {
37 // explicit cast for vector<bool> shenanigans
38 builder.PushBack(static_cast<const meta::RangeValueType<T>&>(item));
39 }
40 return builder.ExtractValue();
41}
42
43/// Mappings serialization
44template <typename T, typename Value>
46 To<Value>) {
47 typename Value::Builder builder(formats::common::Type::kObject);
48 for (const auto& [key, value] : value) {
49 builder[key] = value;
50 }
51 return builder.ExtractValue();
52}
53
54/// std::optional serialization
55template <typename T, typename Value>
56Value Serialize(const std::optional<T>& value, To<Value>) {
57 if (!value) return {};
58
59 return typename Value::Builder(*value).ExtractValue();
60}
61
62} // namespace formats::serialize
63
64USERVER_NAMESPACE_END