userver: userver/chaotic/array.hpp Source File
Loading...
Searching...
No Matches
array.hpp
1#pragma once
2
3#include <vector>
4
5#include <userver/formats/json/value.hpp>
6#include <userver/formats/parse/common_containers.hpp>
7#include <userver/formats/parse/to.hpp>
8#include <userver/utils/meta.hpp>
9
10#include <userver/chaotic/validators.hpp>
11
12USERVER_NAMESPACE_BEGIN
13
14namespace chaotic {
15
16template <typename ItemType, typename UserType, typename... Validators>
17struct Array final {
18 const UserType& value;
19};
20
21template <typename Value, typename ItemType, typename UserType,
22 typename... Validators>
23UserType Parse(const Value& value,
24 formats::parse::To<Array<ItemType, UserType, Validators...>>) {
25 UserType arr;
26 auto inserter = std::inserter(arr, arr.end());
27 if constexpr (meta::kIsReservable<UserType>) {
28 arr.reserve(value.GetSize());
29 }
30 for (const auto& item : value) {
31 *inserter = item.template As<ItemType>();
32 ++inserter;
33 }
34
35 chaotic::Validate<Validators...>(arr, value);
36
37 return arr;
38}
39
40template <typename Value, typename ItemType, typename... Validators>
41std::vector<formats::common::ParseType<Value, ItemType>> Parse(
42 const Value& value,
43 formats::parse::To<Array<
44 ItemType, std::vector<formats::common::ParseType<Value, ItemType>>,
45 Validators...>>) {
46 std::vector<formats::common::ParseType<Value, ItemType>> arr;
47 arr.reserve(value.GetSize());
48 for (const auto& item : value) {
49 arr.emplace_back(item.template As<ItemType>());
50 }
51
52 chaotic::Validate<Validators...>(arr, value);
53
54 return arr;
55}
56
57template <typename Value, typename ItemType, typename UserType,
58 typename... Validators>
59Value Serialize(const Array<ItemType, UserType, Validators...>& ps,
60 formats::serialize::To<Value>) {
61 typename Value::Builder vb{formats::common::Type::kArray};
62 for (const auto& item : ps.value) {
63 vb.PushBack(ItemType{item});
64 }
65 return vb.ExtractValue();
66}
67
68} // namespace chaotic
69
70USERVER_NAMESPACE_END