-
Notifications
You must be signed in to change notification settings - Fork 93
/
Copy pathserial.rs
316 lines (266 loc) · 7.43 KB
/
serial.rs
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
//! Serde integration support.
use std::fmt;
use std::marker::PhantomData;
use serde::de::{Error, Unexpected, Visitor};
use serde::*;
fn i64_to_u64<'d, V: Visitor<'d>, E: Error>(v: V, n: i64) -> Result<V::Value, E> {
if n >= 0 {
v.visit_u64(n as u64)
} else {
Err(E::invalid_value(Unexpected::Signed(n), &v))
}
}
/// Ignore deserialization errors and revert to default.
pub fn ignore_errors<'d, T: Deserialize<'d> + Default, D: Deserializer<'d>>(
d: D,
) -> Result<T, D::Error> {
use serde_json::Value;
let v = Value::deserialize(d)?;
Ok(T::deserialize(v).ok().unwrap_or_default())
}
/// Deserialize a maybe-string ID into a u64.
pub fn deserialize_id<'d, D: Deserializer<'d>>(d: D) -> Result<u64, D::Error> {
struct IdVisitor;
impl<'d> Visitor<'d> for IdVisitor {
type Value = u64;
fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "a u64 or parseable string")
}
fn visit_i64<E: Error>(self, v: i64) -> Result<u64, E> {
i64_to_u64(self, v)
}
fn visit_u64<E: Error>(self, v: u64) -> Result<u64, E> {
Ok(v)
}
fn visit_str<E: Error>(self, v: &str) -> Result<u64, E> {
v.parse::<u64>()
.map_err(|_| E::invalid_value(Unexpected::Str(v), &self))
}
}
d.deserialize_any(IdVisitor)
}
/// Deserialize a maybe-string discriminator into a u16.
/// Also enforces 0 <= N <= 9999.
#[allow(unused_comparisons)]
pub fn deserialize_discrim_opt<'d, D: Deserializer<'d>>(d: D) -> Result<Option<u16>, D::Error> {
macro_rules! check {
($self:ident, $v:ident, $wrong:expr) => {
if $v >= 0 && $v <= 9999 {
Ok(Some($v as u16))
} else {
Err(E::invalid_value($wrong, &$self))
}
};
}
struct DiscrimVisitor;
impl<'d> Visitor<'d> for DiscrimVisitor {
type Value = Option<u16>;
fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "a u16 in [0, 9999] or parseable string")
}
fn visit_i64<E: Error>(self, v: i64) -> Result<Self::Value, E> {
check!(self, v, Unexpected::Signed(v))
}
fn visit_u64<E: Error>(self, v: u64) -> Result<Self::Value, E> {
check!(self, v, Unexpected::Unsigned(v))
}
fn visit_str<E: Error>(self, v: &str) -> Result<Self::Value, E> {
v.parse::<u16>()
.map_err(|_| E::invalid_value(Unexpected::Str(v), &self))
.and_then(|v| self.visit_u16(v))
}
}
d.deserialize_any(DiscrimVisitor)
}
pub fn deserialize_discrim<'d, D: Deserializer<'d>>(d: D) -> Result<u16, D::Error> {
match deserialize_discrim_opt(d) {
Ok(Some(result)) => Ok(result),
Err(e) => Err(e),
Ok(None) => Err(D::Error::missing_field("discriminator")),
}
}
/// Deserialize a single-field struct like a newtype struct.
macro_rules! serial_single_field {
($typ:ident as $field:ident: $inner:path) => {
impl ::serde::Serialize for $typ {
fn serialize<S: ::serde::ser::Serializer>(
&self,
s: S,
) -> ::std::result::Result<S::Ok, S::Error> {
self.$field.serialize(s)
}
}
impl<'d> ::serde::Deserialize<'d> for $typ {
fn deserialize<D: ::serde::de::Deserializer<'d>>(
d: D,
) -> ::std::result::Result<$typ, D::Error> {
<$inner as ::serde::de::Deserialize>::deserialize(d).map(|v| $typ { $field: v })
}
}
};
}
/// Special support for the oddly complex `ReactionEmoji`.
pub mod reaction_emoji {
use super::*;
use model::{EmojiId, ReactionEmoji};
#[derive(Serialize)]
struct EmojiSer<'s> {
name: &'s str,
id: Option<EmojiId>,
}
#[derive(Deserialize)]
struct EmojiDe {
name: String,
id: Option<EmojiId>,
}
pub fn serialize<S: Serializer>(v: &ReactionEmoji, s: S) -> Result<S::Ok, S::Error> {
(match *v {
ReactionEmoji::Unicode(ref name) => EmojiSer {
name: name,
id: None,
},
ReactionEmoji::Custom { ref name, id } => EmojiSer {
name: name,
id: Some(id),
},
})
.serialize(s)
}
pub fn deserialize<'d, D: Deserializer<'d>>(d: D) -> Result<ReactionEmoji, D::Error> {
Ok(match EmojiDe::deserialize(d)? {
EmojiDe { name, id: None } => ReactionEmoji::Unicode(name),
EmojiDe { name, id: Some(id) } => ReactionEmoji::Custom { name: name, id: id },
})
}
}
/// Support for named enums.
pub mod named {
use super::*;
pub trait NamedEnum: Sized {
fn name(&self) -> &'static str;
fn from_name(name: &str) -> Option<Self>;
fn typename() -> &'static str;
}
pub fn serialize<T: NamedEnum, S: Serializer>(v: &T, s: S) -> Result<S::Ok, S::Error> {
v.name().serialize(s)
}
pub fn deserialize<'d, T: NamedEnum, D: Deserializer<'d>>(d: D) -> Result<T, D::Error> {
struct NameVisitor<T>(PhantomData<T>);
impl<'d, T: NamedEnum> Visitor<'d> for NameVisitor<T> {
type Value = T;
fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "a valid {} name", T::typename())
}
fn visit_str<E: Error>(self, v: &str) -> Result<T, E> {
T::from_name(v).ok_or_else(|| E::invalid_value(Unexpected::Str(v), &self))
}
}
d.deserialize_any(NameVisitor(PhantomData))
}
}
macro_rules! serial_names {
($typ:ident; $($entry:ident, $value:expr;)*) => {
impl $typ {
pub fn name(&self) -> &'static str {
match *self {
$($typ::$entry => $value,)*
}
}
pub fn from_name(name: &str) -> Option<Self> {
match name {
$($value => Some($typ::$entry),)*
_ => None,
}
}
}
impl ::serial::named::NamedEnum for $typ {
fn name(&self) -> &'static str {
self.name()
}
fn from_name(name: &str) -> Option<Self> {
Self::from_name(name)
}
fn typename() -> &'static str {
stringify!($typ)
}
}
}
}
/// Support for numeric enums.
pub mod numeric {
use super::*;
pub trait NumericEnum: Sized {
fn num(&self) -> u64;
fn from_num(num: u64) -> Option<Self>;
fn typename() -> &'static str;
}
pub fn serialize<T: NumericEnum, S: Serializer>(v: &T, s: S) -> Result<S::Ok, S::Error> {
v.num().serialize(s)
}
pub fn deserialize<'d, T: NumericEnum, D: Deserializer<'d>>(d: D) -> Result<T, D::Error> {
struct NumVisitor<T>(PhantomData<T>);
impl<'d, T: NumericEnum> Visitor<'d> for NumVisitor<T> {
type Value = T;
fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "a valid {} number", T::typename())
}
fn visit_i64<E: Error>(self, v: i64) -> Result<T, E> {
i64_to_u64(self, v)
}
fn visit_u64<E: Error>(self, v: u64) -> Result<T, E> {
T::from_num(v).ok_or_else(|| E::invalid_value(Unexpected::Unsigned(v), &self))
}
}
d.deserialize_any(NumVisitor(PhantomData))
}
}
macro_rules! serial_numbers {
($typ:ident; $($entry:ident, $value:expr;)*) => {
impl $typ {
pub fn num(&self) -> u64 {
match *self {
$($typ::$entry => $value,)*
}
}
pub fn from_num(num: u64) -> Option<Self> {
match num {
$($value => Some($typ::$entry),)*
_ => None,
}
}
}
impl ::serial::numeric::NumericEnum for $typ {
fn num(&self) -> u64 {
self.num()
}
fn from_num(num: u64) -> Option<Self> {
Self::from_num(num)
}
fn typename() -> &'static str {
stringify!($typ)
}
}
}
}
/// Support for using "named" or "numeric" as the default ser/de impl.
macro_rules! serial_use_mapping {
($typ:ident, $which:ident) => {
impl ::serde::Serialize for $typ {
#[inline]
fn serialize<S: ::serde::ser::Serializer>(
&self,
s: S,
) -> ::std::result::Result<S::Ok, S::Error> {
::serial::$which::serialize(self, s)
}
}
impl<'d> ::serde::Deserialize<'d> for $typ {
#[inline]
fn deserialize<D: ::serde::de::Deserializer<'d>>(
d: D,
) -> ::std::result::Result<$typ, D::Error> {
::serial::$which::deserialize(d)
}
}
};
}