userver: userver/formats/serialize/common_containers.hpp Source File
Loading...
Searching...
No Matches
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 meta::kIsRange<T> && !meta::kIsMap<T> && !std::is_same_v<T, boost::uuids::uuid> &&
32 Value>
34 typename Value::Builder builder(formats::common::Type::kArray);
35 for (const auto& item : value) {
36 // explicit cast for vector<bool> shenanigans
37 builder.PushBack(static_cast<const meta::RangeValueType<T>&>(item));
38 }
39 return builder.ExtractValue();
40}
41
42/// Mappings serialization
43template <typename T, typename Value>
45 typename Value::Builder builder(formats::common::Type::kObject);
46 for (const auto& [key, value] : value) {
47 builder[key] = value;
48 }
49 return builder.ExtractValue();
50}
51
52/// std::optional serialization
53template <typename T, typename Value>
54Value Serialize(const std::optional<T>& value, To<Value>) {
55 if (!value) return {};
56
57 return typename Value::Builder(*value).ExtractValue();
58}
59
60} // namespace formats::serialize
61
62USERVER_NAMESPACE_END