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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
#![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)]
#![cfg_attr(feature = "clippy", allow(match_same_arms))]
extern crate serde;
#[cfg(test)] extern crate serde_json;
use serde::{de, ser};
use std::{error, fmt, io, ops};
pub mod parser;
pub mod serializer;
pub mod object;
mod sentinel;
pub use object::{Deserializer, Serializer};
use sentinel::{IsSentinel, SENTINEL_STR};
pub struct Error(ErrorInner);
enum ErrorInner {
Parser(parser::Error),
Other(String),
Sentinel
}
impl From<parser::Error> for Error {
fn from(e: parser::Error) -> Error {
Error(ErrorInner::Parser(e))
}
}
impl error::Error for Error {
fn cause(&self) -> Option<&error::Error> {
match self.0 {
ErrorInner::Parser(ref e) => Some(e),
_ => None
}
}
fn description(&self) -> &str {
match self.0 {
ErrorInner::Parser(ref e) => e.description(),
ErrorInner::Other(ref s) => s,
ErrorInner::Sentinel => SENTINEL_STR
}
}
}
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(error::Error::description(self))
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(self, f)
}
}
impl de::Error for Error {
fn custom<T: fmt::Display>(error: T) -> Error {
if error.is_sentinel() {
Error(ErrorInner::Sentinel)
} else {
Error(ErrorInner::Other(error.to_string()))
}
}
}
impl ser::Error for Error {
fn custom<T: fmt::Display>(error: T) -> Error {
if error.is_sentinel() {
Error(ErrorInner::Sentinel)
} else {
Error(ErrorInner::Other(error.to_string()))
}
}
}
#[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, Error> {
parser::Parser::new(it).parse()
}
pub fn from_str(s: &str) -> Result<Json, Error> {
Json::from_iter(s.bytes().map(Ok))
}
pub fn from_reader<R: io::Read>(r: R) -> Result<Json, Error> {
Json::from_iter(r.bytes())
}
pub fn from_serialize<T: serde::Serialize>(val: T) -> Result<Json, Error> {
val.serialize(Serializer::new())
}
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 get(&self, index: &str) -> Option<&Json> {
if let JsonInner::Object(ref v) = self.0 {
for &(ref key, ref obj) in v {
if key == index {
return Some(obj);
}
}
}
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
}
pub fn into_deserialize<'a, T: serde::Deserialize<'a>>(self) -> Result<T, Error> {
de::Deserialize::deserialize(Deserializer::new(self))
}
}
impl From<()> for Json {
fn from(_: ()) -> Json {
Json(JsonInner::Null)
}
}
impl From<bool> for Json {
fn from(t: bool) -> Json {
Json(JsonInner::Bool(t))
}
}
macro_rules! format_from_impl(
($t:ty) => {
impl From<$t> for Json {
fn from(n: $t) -> Json {
Json(JsonInner::Number(format!("{}", n)))
}
}
}
);
format_from_impl!(usize);
format_from_impl!(u64);
format_from_impl!(u32);
format_from_impl!(u16);
format_from_impl!(u8);
format_from_impl!(isize);
format_from_impl!(i64);
format_from_impl!(i32);
format_from_impl!(i16);
format_from_impl!(i8);
format_from_impl!(f64);
format_from_impl!(f32);
impl From<String> for Json {
fn from(s: String) -> Json {
Json(JsonInner::String(s))
}
}
impl<'a> From<&'a str> for Json {
fn from(s: &'a str) -> Json {
Json(JsonInner::String(s.to_owned()))
}
}
impl From<Vec<Json>> for Json {
fn from(v: Vec<Json>) -> Json {
Json(JsonInner::Array(v))
}
}
impl From<Vec<(String, Json)>> for Json {
fn from(v: Vec<(String, Json)>) -> Json {
Json(JsonInner::Object(v))
}
}
impl fmt::Display for Json {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut v = vec![];
serializer::serialize(self, &mut v).unwrap();
f.write_str(unsafe { std::str::from_utf8_unchecked(&v) })
}
}
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());
}
#[test]
fn from() {
assert_eq!(Json::from_str("123").unwrap(), From::from(123u8));
assert_eq!(Json::from_str("123").unwrap(), From::from(123u16));
assert_eq!(Json::from_str("123").unwrap(), From::from(123u32));
assert_eq!(Json::from_str("123").unwrap(), From::from(123u64));
assert_eq!(Json::from_str("-123").unwrap(), From::from(-123i8));
assert_eq!(Json::from_str("-123").unwrap(), From::from(-123i16));
assert_eq!(Json::from_str("-123").unwrap(), From::from(-123i32));
assert_eq!(Json::from_str("-123").unwrap(), From::from(-123i64));
assert_eq!(Json::from_str("-103.375").unwrap(), From::from(-103.375f32));
assert_eq!(Json::from_str("-103.375").unwrap(), From::from(-103.375f64));
assert_eq!(Json::from_str("true").unwrap(), From::from(true));
assert_eq!(Json::from_str("false").unwrap(), From::from(false));
assert_eq!(Json::from_str("null").unwrap(), From::from(()));
assert_eq!(Json::from_str("[]").unwrap(), From::from(Json::from_str("[]").unwrap()));
}
#[test]
fn format() {
macro_rules! format_roundtrip (
($s:expr) => (
assert_eq!(format!("{}", Json::from_str($s).unwrap()), $s);
)
);
format_roundtrip!("null");
format_roundtrip!("true");
format_roundtrip!("false");
format_roundtrip!("[]");
format_roundtrip!("{}");
format_roundtrip!("[true, false, true, true]");
format_roundtrip!("0");
format_roundtrip!("1000");
format_roundtrip!("\"Andrew\"");
format_roundtrip!("{\"Andrew\": 10, \"Jonas\": 100}");
}
}