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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
pub use protobuf_convert::*;
use proto::common::BitVec;
pub mod proto;
#[macro_use]
extern crate failure;
#[macro_use]
extern crate serde_derive;
#[macro_use]
mod macros;
#[cfg(test)]
mod tests;
use chrono::{DateTime, TimeZone, Utc};
use failure::Error;
use protobuf::well_known_types;
use std::collections::HashMap;
pub trait ProtobufConvert: Sized {
type ProtoStruct;
fn to_pb(&self) -> Self::ProtoStruct;
fn from_pb(pb: Self::ProtoStruct) -> Result<Self, Error>;
}
impl ProtobufConvert for DateTime<Utc> {
type ProtoStruct = well_known_types::Timestamp;
fn to_pb(&self) -> well_known_types::Timestamp {
let mut ts = well_known_types::Timestamp::new();
ts.set_seconds(self.timestamp());
ts.set_nanos(self.timestamp_subsec_nanos() as i32);
ts
}
fn from_pb(pb: well_known_types::Timestamp) -> Result<Self, Error> {
Utc.timestamp_opt(pb.get_seconds(), pb.get_nanos() as u32)
.single()
.ok_or_else(|| format_err!("Failed to convert timestamp from bytes"))
}
}
impl ProtobufConvert for String {
type ProtoStruct = Self;
fn to_pb(&self) -> Self::ProtoStruct {
self.clone()
}
fn from_pb(pb: Self::ProtoStruct) -> Result<Self, Error> {
Ok(pb)
}
}
impl ProtobufConvert for u16 {
type ProtoStruct = u32;
fn to_pb(&self) -> Self::ProtoStruct {
u32::from(*self)
}
fn from_pb(pb: Self::ProtoStruct) -> Result<Self, Error> {
ensure!(
pb <= u32::from(u16::max_value()),
"u32 is out of range for valid u16"
);
Ok(pb as u16)
}
}
impl ProtobufConvert for i16 {
type ProtoStruct = i32;
fn to_pb(&self) -> Self::ProtoStruct {
i32::from(*self)
}
fn from_pb(pb: Self::ProtoStruct) -> Result<Self, Error> {
ensure!(
pb >= i32::from(i16::min_value()) && pb <= i32::from(i16::max_value()),
"i32 is out of range for valid i16"
);
Ok(pb as i16)
}
}
impl<T> ProtobufConvert for Vec<T>
where
T: ProtobufConvert,
{
type ProtoStruct = Vec<T::ProtoStruct>;
fn to_pb(&self) -> Self::ProtoStruct {
self.iter().map(ProtobufConvert::to_pb).collect()
}
fn from_pb(pb: Self::ProtoStruct) -> Result<Self, Error> {
pb.into_iter()
.map(ProtobufConvert::from_pb)
.collect::<Result<Vec<_>, _>>()
}
}
impl ProtobufConvert for () {
type ProtoStruct = protobuf::well_known_types::Empty;
fn to_pb(&self) -> Self::ProtoStruct {
Self::ProtoStruct::default()
}
fn from_pb(_pb: Self::ProtoStruct) -> Result<Self, Error> {
Ok(())
}
}
impl ProtobufConvert for Vec<u8> {
type ProtoStruct = Vec<u8>;
fn to_pb(&self) -> Self::ProtoStruct {
self.clone()
}
fn from_pb(pb: Self::ProtoStruct) -> Result<Self, Error> {
Ok(pb)
}
}
impl<K, T, S> ProtobufConvert for HashMap<K, T, S>
where
K: Eq + std::hash::Hash + std::fmt::Debug + Clone,
T: ProtobufConvert,
S: Default + std::hash::BuildHasher,
{
type ProtoStruct = HashMap<K, T::ProtoStruct, S>;
fn to_pb(&self) -> Self::ProtoStruct {
self.iter().map(|(k, v)| (k.clone(), v.to_pb())).collect()
}
fn from_pb(mut pb: Self::ProtoStruct) -> Result<Self, failure::Error> {
pb.drain()
.map(|(k, v)| ProtobufConvert::from_pb(v).map(|v| (k, v)))
.collect::<Result<HashMap<_, _, _>, _>>()
}
}
impl ProtobufConvert for bit_vec::BitVec {
type ProtoStruct = BitVec;
fn to_pb(&self) -> Self::ProtoStruct {
let mut bit_vec = BitVec::new();
bit_vec.set_data(self.to_bytes());
bit_vec.set_len(self.len() as u64);
bit_vec
}
fn from_pb(pb: Self::ProtoStruct) -> Result<Self, Error> {
let data = pb.get_data();
let mut bit_vec = bit_vec::BitVec::from_bytes(data);
bit_vec.truncate(pb.get_len() as usize);
Ok(bit_vec)
}
}
macro_rules! impl_protobuf_convert_scalar {
( $( $name:tt ),* )=> {
$(
impl ProtobufConvert for $name {
type ProtoStruct = $name;
fn to_pb(&self) -> Self::ProtoStruct {
*self
}
fn from_pb(pb: Self::ProtoStruct) -> Result<Self, Error> {
Ok(pb)
}
}
)*
};
}
impl_protobuf_convert_scalar! { bool, u32, u64, i32, i64, f32, f64 }
macro_rules! impl_protobuf_convert_fixed_byte_array {
( $( $arr_len:expr ),* ) => {
$(
impl ProtobufConvert for [u8; $arr_len] {
type ProtoStruct = Vec<u8>;
fn to_pb(&self) -> Self::ProtoStruct {
self.to_vec()
}
fn from_pb(pb: Self::ProtoStruct) -> Result<Self, Error> {
ensure!(
pb.len() == $arr_len,
"wrong array size: actual {}, expected {}",
pb.len(),
$arr_len
);
Ok({
let mut array = [0; $arr_len];
array.copy_from_slice(&pb);
array
})
}
}
)*
};
}
impl_protobuf_convert_fixed_byte_array! {
8, 16, 24, 32, 40, 48, 56, 64,
72, 80, 88, 96, 104, 112, 120, 128,
160, 256, 512, 1024, 2048
}