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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
pub mod test_helper;
use failure::prelude::*;
use protobuf::Message;
pub trait IntoProto {
type ProtoType;
fn into_proto(self) -> Self::ProtoType;
}
pub trait FromProto: Sized {
type ProtoType;
fn from_proto(object: Self::ProtoType) -> Result<Self>;
}
pub trait IntoProtoBytes<P> {
fn into_proto_bytes(self) -> Result<Vec<u8>>;
}
impl<P, T> IntoProtoBytes<P> for T
where
P: Message,
T: IntoProto<ProtoType = P>,
{
fn into_proto_bytes(self) -> Result<Vec<u8>> {
Ok(self.into_proto().write_to_bytes()?)
}
}
pub trait FromProtoBytes<P>: Sized {
fn from_proto_bytes(bytes: &[u8]) -> Result<Self>;
}
impl<P, T> FromProtoBytes<P> for T
where
P: Message,
T: FromProto<ProtoType = P>,
{
fn from_proto_bytes(bytes: &[u8]) -> Result<Self> {
Self::from_proto(protobuf::parse_from_bytes(bytes)?)
}
}
#[cfg(feature = "derive")]
pub use proto_conv_derive::{FromProto, IntoProto};
macro_rules! impl_direct_conversion {
($type_name: ty) => {
impl FromProto for $type_name {
type ProtoType = $type_name;
fn from_proto(object: Self::ProtoType) -> Result<Self> {
Ok(object)
}
}
impl IntoProto for $type_name {
type ProtoType = $type_name;
fn into_proto(self) -> Self::ProtoType {
self
}
}
};
}
impl_direct_conversion!(u32);
impl_direct_conversion!(u64);
impl_direct_conversion!(i32);
impl_direct_conversion!(i64);
impl_direct_conversion!(bool);
impl_direct_conversion!(String);
impl_direct_conversion!(Vec<u8>);
impl<P, T> FromProto for Vec<T>
where
P: protobuf::Message,
T: FromProto<ProtoType = P>,
{
type ProtoType = protobuf::RepeatedField<P>;
fn from_proto(object: Self::ProtoType) -> Result<Self> {
object
.into_iter()
.map(T::from_proto)
.collect::<Result<Vec<_>>>()
}
}
impl<P, T> IntoProto for Vec<T>
where
P: protobuf::Message,
T: IntoProto<ProtoType = P>,
{
type ProtoType = protobuf::RepeatedField<P>;
fn into_proto(self) -> Self::ProtoType {
self.into_iter().map(T::into_proto).collect()
}
}