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
#![deny(missing_docs)]
#![deny(rust_2018_compatibility)]
#![deny(rust_2018_idioms)]
pub mod de;
pub mod ser;
#[doc(inline)]
pub use self::de::{from_slice, from_str};
#[doc(inline)]
pub use self::ser::{to_string, to_vec};
#[cfg(test)]
mod test {
use super::*;
use serde_derive::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize, PartialEq)]
struct Address(String);
#[derive(Debug, Deserialize, Serialize, PartialEq)]
struct CommentId(u32);
#[derive(Debug, Deserialize, Serialize, PartialEq)]
enum Model {
Comment,
Post { category: String, author: Address },
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
struct Stats {
views: u64,
score: i64,
}
#[derive(Debug, Deserialize, Serialize, PartialEq)]
struct Item {
model: Model,
title: String,
content: Option<String>,
list: Vec<u32>,
published: bool,
comments: Vec<CommentId>,
stats: Stats,
}
#[test]
fn can_serde() {
let min = Item {
model: Model::Comment,
title: "".to_string(),
content: None,
list: vec![],
published: false,
comments: vec![],
stats: Stats { views: 0, score: 0 },
};
let max = Item {
model: Model::Post {
category: "fun".to_string(),
author: Address("sunnyboy85".to_string()),
},
title: "Nice message".to_string(),
content: Some("Happy \"blogging\" 👏\n\n\tCheers, I'm out\0\0\0".to_string()),
list: vec![0, 1, 2, 3, 42, 154841, std::u32::MAX],
published: true,
comments: vec![CommentId(2), CommentId(700)],
stats: Stats {
views: std::u64::MAX,
score: std::i64::MIN,
},
};
assert_eq!(from_slice::<Item>(&to_vec(&min).unwrap()).unwrap(), min);
assert_eq!(from_slice::<Item>(&to_vec(&max).unwrap()).unwrap(), max);
assert_eq!(from_str::<Item>(&to_string(&min).unwrap()).unwrap(), min);
assert_eq!(from_str::<Item>(&to_string(&max).unwrap()).unwrap(), max);
}
}