1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
|
#pragma once
#include <grpc++/impl/codegen/byte_buffer.h>
#include <grpc++/impl/codegen/proto_utils.h>
#include <variant>
namespace NGrpc {
/**
* Universal response that owns underlying message or buffer.
*/
template <typename TMsg>
class TUniversalResponse: public TAtomicRefCount<TUniversalResponse<TMsg>>, public TMoveOnly {
friend class grpc::SerializationTraits<TUniversalResponse<TMsg>>;
public:
explicit TUniversalResponse(NProtoBuf::Message* msg) noexcept
: Data_{TMsg{}}
{
std::get<TMsg>(Data_).Swap(static_cast<TMsg*>(msg));
}
explicit TUniversalResponse(grpc::ByteBuffer* buffer) noexcept
: Data_{grpc::ByteBuffer{}}
{
std::get<grpc::ByteBuffer>(Data_).Swap(buffer);
}
private:
std::variant<TMsg, grpc::ByteBuffer> Data_;
};
/**
* Universal response that only keeps reference to underlying message or buffer.
*/
template <typename TMsg>
class TUniversalResponseRef: private TMoveOnly {
friend class grpc::SerializationTraits<TUniversalResponseRef<TMsg>>;
public:
explicit TUniversalResponseRef(const NProtoBuf::Message* msg)
: Data_{msg}
{
}
explicit TUniversalResponseRef(const grpc::ByteBuffer* buffer)
: Data_{buffer}
{
}
private:
std::variant<const NProtoBuf::Message*, const grpc::ByteBuffer*> Data_;
};
} // namespace NGrpc
namespace grpc {
template <typename TMsg>
class SerializationTraits<NGrpc::TUniversalResponse<TMsg>> {
public:
static Status Serialize(
const NGrpc::TUniversalResponse<TMsg>& resp,
ByteBuffer* buffer,
bool* ownBuffer)
{
return std::visit([&](const auto& data) {
using T = std::decay_t<decltype(data)>;
return SerializationTraits<T>::Serialize(data, buffer, ownBuffer);
}, resp.Data_);
}
};
template <typename TMsg>
class SerializationTraits<NGrpc::TUniversalResponseRef<TMsg>> {
public:
static Status Serialize(
const NGrpc::TUniversalResponseRef<TMsg>& resp,
ByteBuffer* buffer,
bool* ownBuffer)
{
return std::visit([&](const auto* data) {
using T = std::decay_t<std::remove_pointer_t<decltype(data)>>;
return SerializationTraits<T>::Serialize(*data, buffer, ownBuffer);
}, resp.Data_);
}
};
} // namespace grpc
|