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
20/// Common serializers
21namespace formats::serialize {
22
23/// Common containers serialization (vector/set)
24template <typename T, typename Value>
27 Value>
29 typename Value::Builder builder(formats::common::Type::kArray);
30 for (const auto& item : value) {
31 // explicit cast for vector<bool> shenanigans
32 builder.PushBack(static_cast<const meta::RangeValueType<T>&>(item));
33 }
34 return builder.ExtractValue();
35}
36
37/// Mappings serialization
38template <typename T, typename Value>
40 To<Value>) {
41 typename Value::Builder builder(formats::common::Type::kObject);
42 for (const auto& [key, value] : value) {
43 builder[key] = value;
44 }
45 return builder.ExtractValue();
46}
47
48/// std::optional serialization
49template <typename T, typename Value>
50Value Serialize(const std::optional<T>& value, To<Value>) {
51 if (!value) return {};
52
53 return typename Value::Builder(*value).ExtractValue();
54}
55
56} // namespace formats::serialize
57
58USERVER_NAMESPACE_END