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
#![crate_type = "lib"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![crate_name = "strason"]
#![deny(non_upper_case_globals)]
#![deny(non_camel_case_types)]
#![deny(non_snake_case)]
#![deny(unused_mut)]
#![warn(missing_docs)]
extern crate encoding;
extern crate serde;
use std::{io, ops};
pub mod parser;
pub mod serializer;
#[derive(Clone, PartialEq, Eq, Debug)]
enum JsonInner {
Null,
Bool(bool),
Number(String),
String(String),
Array(Vec<Json>),
Object(Vec<(String, Json)>)
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Json(JsonInner);
impl Json {
pub fn from_iter<I: Iterator<Item=io::Result<u8>>>(it: I) -> Result<Json, parser::Error> {
parser::Parser::new(it).parse()
}
pub fn from_str(s: &str) -> Result<Json, parser::Error> {
Json::from_iter(s.bytes().map(|u| Ok(u)))
}
pub fn from_reader<R: io::Read>(r: R) -> Result<Json, parser::Error> {
Json::from_iter(r.bytes())
}
pub fn null(&self) -> Option<()> { if let JsonInner::Null = self.0 { Some(()) } else { None } }
pub fn bool(&self) -> Option<bool> { if let JsonInner::Bool(x) = self.0 { Some(x) } else { None } }
pub fn num(&self) -> Option<&str> { if let JsonInner::Number(ref x) = self.0 { Some(&x[..]) } else { None } }
pub fn string(&self) -> Option<&str> { if let JsonInner::String(ref x) = self.0 { Some(&x[..]) } else { None } }
pub fn array(&self) -> Option<&[Json]> { if let JsonInner::Array(ref x) = self.0 { Some(&x[..]) } else { None } }
pub fn object(&self) -> Option<&[(String, Json)]> { if let JsonInner::Object(ref x) = self.0 { Some(&x[..]) } else { None } }
pub fn len(&self) -> usize {
match self.0 {
JsonInner::Null => 0,
JsonInner::Bool(_) => 1,
JsonInner::String(_) => 1,
JsonInner::Number(_) => 1,
JsonInner::Array(ref v) => v.len(),
JsonInner::Object(ref v) => v.len()
}
}
pub fn is_empty(&self) -> bool {
match self.0 {
JsonInner::Null => true,
JsonInner::Bool(_) => false,
JsonInner::String(_) => false,
JsonInner::Number(_) => false,
JsonInner::Array(ref v) => v.is_empty(),
JsonInner::Object(ref v) => v.is_empty()
}
}
pub fn write_to<W: io::Write>(&self, mut w: W) -> io::Result<()> {
serializer::serialize(self, &mut w)
}
pub fn to_bytes(&self) -> Vec<u8> {
let mut ret = vec![];
self.write_to(&mut ret).unwrap();
ret
}
}
impl<'a> ops::Index<&'a str> for Json {
type Output = Json;
#[inline]
fn index(&self, index: &'a str) -> &Json {
if let JsonInner::Object(ref v) = self.0 {
for &(ref key, ref obj) in v {
if key == index {
return obj;
}
}
panic!("Json object accessed with non-existent index!");
} else {
panic!("Tried to index a non-object Json object as an object!");
}
}
}
impl ops::Index<usize> for Json {
type Output = Json;
#[inline]
fn index(&self, index: usize) -> &Json {
if let JsonInner::Array(ref v) = self.0 {
&v[index]
} else {
panic!("Tried to index a non-array Json object as an array!");
}
}
}
impl ops::Index<ops::Range<usize>> for Json {
type Output = [Json];
#[inline]
fn index(&self, index: ops::Range<usize>) -> &[Json] {
if let JsonInner::Array(ref v) = self.0 {
&v[index]
} else {
panic!("Tried to index a non-array Json object as an array!");
}
}
}
impl ops::Index<ops::RangeTo<usize>> for Json {
type Output = [Json];
#[inline]
fn index(&self, index: ops::RangeTo<usize>) -> &[Json] {
if let JsonInner::Array(ref v) = self.0 {
&v[index]
} else {
panic!("Tried to index a non-array Json object as an array!");
}
}
}
impl ops::Index<ops::RangeFrom<usize>> for Json {
type Output = [Json];
#[inline]
fn index(&self, index: ops::RangeFrom<usize>) -> &[Json] {
if let JsonInner::Array(ref v) = self.0 {
&v[index]
} else {
panic!("Tried to index a non-array Json object as an array!");
}
}
}
impl ops::Index<ops::RangeFull> for Json {
type Output = [Json];
#[inline]
fn index(&self, index: ops::RangeFull) -> &[Json] {
if let JsonInner::Array(ref v) = self.0 {
&v[index]
} else {
panic!("Tried to index a non-array Json object as an array!");
}
}
}
#[cfg(test)]
mod tests {
use {Json, JsonInner};
fn ck_null(obj: &Json) {
assert!(obj.null().is_some());
assert!(obj.bool().is_none());
assert!(obj.num().is_none());
assert!(obj.string().is_none());
assert!(obj.array().is_none());
assert!(obj.object().is_none());
}
fn ck_bool(obj: &Json) {
assert!(obj.null().is_none());
assert!(obj.bool().is_some());
assert!(obj.num().is_none());
assert!(obj.string().is_none());
assert!(obj.array().is_none());
assert!(obj.object().is_none());
}
fn ck_num(obj: &Json) {
assert!(obj.null().is_none());
assert!(obj.bool().is_none());
assert!(obj.num().is_some());
assert!(obj.string().is_none());
assert!(obj.array().is_none());
assert!(obj.object().is_none());
}
fn ck_string(obj: &Json) {
assert!(obj.null().is_none());
assert!(obj.bool().is_none());
assert!(obj.num().is_none());
assert!(obj.string().is_some());
assert!(obj.array().is_none());
assert!(obj.object().is_none());
}
fn ck_array(obj: &Json) {
assert!(obj.null().is_none());
assert!(obj.bool().is_none());
assert!(obj.num().is_none());
assert!(obj.string().is_none());
assert!(obj.array().is_some());
assert!(obj.object().is_none());
}
fn ck_object(obj: &Json) {
assert!(obj.null().is_none());
assert!(obj.bool().is_none());
assert!(obj.num().is_none());
assert!(obj.string().is_none());
assert!(obj.array().is_none());
assert!(obj.object().is_some());
}
#[test]
fn test_is() {
ck_null(&Json::from_str("null").unwrap());
ck_bool(&Json::from_str("true").unwrap());
ck_bool(&Json::from_str("false").unwrap());
ck_num(&Json::from_str("-10").unwrap());
ck_num(&Json::from_str("10").unwrap());
ck_num(&Json::from_str("0.100e9").unwrap());
ck_string(&Json::from_str("\"str\"").unwrap());
ck_array(&Json::from_str("[]").unwrap());
ck_array(&Json::from_str("[\"t\"]").unwrap());
ck_array(&Json::from_str("[\"t\", true, false]").unwrap());
ck_object(&Json::from_str("{}").unwrap());
ck_object(&Json::from_str("{\"key\": true}").unwrap());
}
#[test]
fn test_index() {
let arr = Json::from_str("[1, 2, 3]").unwrap();
assert_eq!(arr[0].0, JsonInner::Number("1".to_owned()));
assert_eq!(arr[1].0, JsonInner::Number("2".to_owned()));
assert_eq!(arr[2].0, JsonInner::Number("3".to_owned()));
assert_eq!(arr.len(), 3);
assert!(!arr.is_empty());
let obj = Json::from_str("{\"vrai\": true, \"faux\": false}").unwrap();
assert_eq!(obj["vrai"].0, JsonInner::Bool(true));
assert_eq!(obj["faux"].0, JsonInner::Bool(false));
assert_eq!(obj.len(), 2);
assert!(!obj.is_empty());
let val = Json::from_str("null").unwrap();
assert_eq!(val.len(), 0);
assert!(val.is_empty());
let mt_arr = Json::from_str("[]").unwrap();
assert!(mt_arr.is_empty());
let mt_obj = Json::from_str("{}").unwrap();
assert!(mt_obj.is_empty());
}
}