userver: userver/formats/bson/inline.hpp Source File
Loading...
Searching...
No Matches
inline.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/formats/bson/inline.hpp
4/// @brief Inline value builders
5
6#include <string_view>
7
8#include <userver/formats/bson/bson_builder.hpp>
9#include <userver/formats/bson/document.hpp>
10#include <userver/formats/bson/types.hpp>
11#include <userver/formats/bson/value.hpp>
12#include <userver/utils/fast_pimpl.hpp>
13
14USERVER_NAMESPACE_BEGIN
15
16namespace formats::bson {
17
18/// Constructs a Document from provided key-value pairs
19template <typename... Args>
20Document MakeDoc(Args&&...);
21
22/// Constructs an array Value from provided element list
23template <typename... Args>
24Value MakeArray(Args&&...);
25
26namespace impl {
27
28class InlineDocBuilder {
29 public:
30 using Key = std::string_view;
31
32 Document Build();
33
34 template <typename FieldValue, typename... Tail>
35 Document Build(Key key, FieldValue&& value, Tail&&... tail) {
36 builder_.Append(key, std::forward<FieldValue>(value));
37 return Build(std::forward<Tail>(tail)...);
38 }
39
40 private:
41 BsonBuilder builder_;
42};
43
44class InlineArrayBuilder {
45 public:
46 InlineArrayBuilder();
47 ~InlineArrayBuilder();
48
49 Value Build();
50
51 template <typename Element, typename... Tail>
52 Value Build(Element&& element, Tail&&... tail) {
53 builder_.Append(GetKey(), std::forward<Element>(element));
54 return Build(std::forward<Tail>(tail)...);
55 }
56
57 private:
58 std::string_view GetKey();
59
60 class Helper;
61 static constexpr size_t kSize = 20;
62 static constexpr size_t kAlignment = 4;
63 utils::FastPimpl<Helper, kSize, kAlignment, true> helper_;
64 BsonBuilder builder_;
65};
66
67} // namespace impl
68
69/// @cond
70template <typename... Args>
71Document MakeDoc(Args&&... args) {
72 return impl::InlineDocBuilder().Build(std::forward<Args>(args)...);
73}
74
75template <typename... Args>
76Value MakeArray(Args&&... args) {
77 return impl::InlineArrayBuilder().Build(std::forward<Args>(args)...);
78}
79/// @endcond
80
81} // namespace formats::bson
82
83USERVER_NAMESPACE_END