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, typename... Validators>
22UserType Parse(const Value& value, formats::parse::To<Array<ItemType, UserType, Validators...>>) {
23 UserType arr;
24 auto inserter = std::inserter(arr, arr.end());
25 if constexpr (meta::kIsReservable<UserType>) {
26 arr.reserve(value.GetSize());
27 }
28 for (const auto& item : value) {
29 *inserter = item.template As<ItemType>();
30 ++inserter;
31 }
32
33 chaotic::Validate<Validators...>(arr, value);
34
35 return arr;
36}
37
38template <typename Value, typename ItemType, typename... Validators>
39std::vector<formats::common::ParseType<Value, ItemType>>
40Parse(const Value& value, formats::parse::To<Array<ItemType, std::vector<formats::common::ParseType<Value, ItemType>>, Validators...>>) {
41 std::vector<formats::common::ParseType<Value, ItemType>> arr;
42 arr.reserve(value.GetSize());
43 for (const auto& item : value) {
44 arr.emplace_back(item.template As<ItemType>());
45 }
46
47 chaotic::Validate<Validators...>(arr, value);
48
49 return arr;
50}
51
52template <typename Value, typename ItemType, typename UserType, typename... Validators>
53Value Serialize(const Array<ItemType, UserType, Validators...>& ps, formats::serialize::To<Value>) {
54 typename Value::Builder vb{formats::common::Type::kArray};
55 for (const auto& item : ps.value) {
56 vb.PushBack(ItemType{item});
57 }
58 return vb.ExtractValue();
59}
60
61} // namespace chaotic
62
63USERVER_NAMESPACE_END