userver: userver/chaotic/variant.hpp Source File
Loading...
Searching...
No Matches
variant.hpp
1#pragma once
2
3#include <variant>
4
5#include <userver/formats/json/value.hpp>
6#include <userver/formats/parse/to.hpp>
7#include <userver/formats/serialize/to.hpp>
8#include <userver/utils/meta.hpp>
9#include <userver/utils/overloaded.hpp>
10
11USERVER_NAMESPACE_BEGIN
12
13namespace chaotic {
14
15template <typename... T>
16auto& GetVariant(std::variant<T...>& arg) {
17 return arg;
18}
19
20template <typename... T>
21const auto& GetVariant(const std::variant<T...>& arg) {
22 return arg;
23}
24
25template <typename T>
26decltype(T().AsVariant()) GetVariant(T& arg) {
27 return arg.AsVariant();
28}
29
30template <typename... T>
31struct Variant final {
32 const std::variant<decltype(Parse(std::declval<formats::json::Value>(), formats::parse::To<T>{}))...>& value;
33};
34
35template <typename Value, typename... T>
36auto Parse(const Value& value, formats::parse::To<Variant<T...>>) {
37 return value.template As<std::variant<T...>>();
38}
39
40template <typename Value, typename... T>
41Value Serialize(const Variant<T...>& var, formats::serialize::To<Value>) {
42 return std::visit(
43 utils::Overloaded{[](const formats::common::ParseType<Value, T>& item) {
44 return typename Value::Builder(T{item}).ExtractValue();
45 }...},
46 var.value
47 );
48}
49
50} // namespace chaotic
51
52USERVER_NAMESPACE_END