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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
// Stringly-Typed JSON Library for Rust
// Written in 2015 by
//   Andrew Poelstra <apoelstra@wpsoftware.net>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication
// along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
//

//! # Serde de/serialization support to/from Json objects
//!

use std::vec;

use serde::{de, ser};
use parser::{Error, ErrorType};
use {Json, JsonInner};

static EVIL_SENTINEL: &'static str = "$$$STRASON$$$EVIL$$$MODE$$$";

impl de::Deserialize for Json {
    fn deserialize<D: de::Deserializer>(d: &mut D) -> Result<Json, D::Error> {
        if <D as de::Deserializer>::format() == "strason" {
            // This `EvilVisitor` type is a nasty hack to get a reference
            // to the deserializer's inner state, which will be a Json
            // object if the deserializer is our Deserializer. It has to
            // do this via the de::Visitor trait, which lets us return
            // Json values no problem but not input arbitrary data (just
            // Rust primitive types, none of which are pointers). So we
            // signal the deserializer using the string input of
            // `Deserializer::visit_unit_struct` to say "hey, it's us, Json"
            // and it'll respond by passing a reference to its inner state
            // hidden inside a usize.
            struct EvilVisitor;
            impl de::Visitor for EvilVisitor {
                type Value = Json;
                fn visit_usize<E: de::Error>(&mut self, v: usize) -> Result<Json, E> {
                   unsafe {
                       let ptr = v as *mut Option<Json>;
                       Ok((*ptr).take().unwrap())
                   }
                }
            }

            d.visit_unit_struct(EVIL_SENTINEL, EvilVisitor)
        // After that madness, actual deserialization code follows
        } else {
            struct GoodVisitor;
            impl de::Visitor for GoodVisitor {
                type Value = Json;
                fn visit_bool<E>(&mut self, val: bool) -> Result<Json, E> {
                    Ok(Json(JsonInner::Bool(val)))
                }

                fn visit_i64<E>(&mut self, val: i64) -> Result<Json, E> {
                    Ok(Json(JsonInner::Number(format!("{}", val))))
                }

                fn visit_u64<E>(&mut self, val: u64) -> Result<Json, E> {
                    Ok(Json(JsonInner::Number(format!("{}", val))))
                }

                fn visit_f64<E>(&mut self, val: f64) -> Result<Json, E> {
                    Ok(Json(JsonInner::Number(format!("{}", val))))
                }

                fn visit_str<E>(&mut self, val: &str) -> Result<Json, E> {
                    Ok(Json(JsonInner::String(val.to_owned())))
                }

                fn visit_string<E>(&mut self, val: String) -> Result<Json, E> {
                    Ok(Json(JsonInner::String(val)))
                }

                fn visit_unit<E>(&mut self) -> Result<Json, E> {
                    Ok(Json(JsonInner::Null))
                }

                fn visit_none<E>(&mut self) -> Result<Json, E> {
                    Ok(Json(JsonInner::Null))
                }

                fn visit_some<D: de::Deserializer>(&mut self, d: &mut D) -> Result<Json, D::Error> {
                    de::Deserialize::deserialize(d)
                }

                fn visit_seq<V: de::SeqVisitor>(&mut self, v: V) -> Result<Json, V::Error> {
                    let arr = try!(de::impls::VecVisitor::new().visit_seq(v));
                    Ok(Json(JsonInner::Array(arr)))
                }

                fn visit_map<V: de::MapVisitor>(&mut self, mut v: V) -> Result<Json, V::Error> {
                    let mut ret = vec![];
                    while let Some(keyval) = try!(v.visit()) {
                        ret.push(keyval);
                    }
                    try!(v.end());
                    Ok(Json(JsonInner::Object(ret)))
                }
            }

            d.visit(GoodVisitor)
        }
    }
}

impl ser::Serialize for Json {
    fn serialize<S: ser::Serializer>(&self, s: &mut S) -> Result<(), S::Error> {
        // If we are dealing with our own Serializer, we know the output will
        // be Json, so we pass our self-pointer to the serializer to just be
        // cloned. The motivation for this hack is as above in the `Deserialize`
        // impl.
        if <S as ser::Serializer>::format() == "strason" {
            s.visit_unit_variant(EVIL_SENTINEL, self as *const _ as usize, "")
        // After the mess, honest serialization code. Note that this will
        // serialize numbers as strings
        } else {
            match self.0 {
                JsonInner::Null => s.visit_unit(),
                JsonInner::Bool(b) => s.visit_bool(b),
                JsonInner::Number(ref st) => s.visit_str(st),
                JsonInner::String(ref st) => s.visit_str(st),
                JsonInner::Array(ref arr) => arr.serialize(s),
                JsonInner::Object(ref arr) => {
                    struct MapVisitor<'a>(&'a [(String, Json)]);
                    impl<'a> ser::MapVisitor for MapVisitor<'a> {
                        fn visit<S: ser::Serializer>(&mut self, s: &mut S) -> Result<Option<()>, S::Error> {
                            if self.len() == Some(0) {
                                Ok(None)
                            } else {
                                let (ref key, ref val) = self.0[0];
                                self.0 = &self.0[1..];
                                s.visit_map_elt(key, val).map(Some)
                            }
                        }
                        fn len(&self) -> Option<usize> { Some(self.0.len()) }
                    }

                    s.visit_map(MapVisitor(arr))
                }
            }
        }
    }
}

/// A "Json to whatever" deserializer
pub struct Deserializer {
    current: Option<Json>
}

impl Deserializer {
    /// Creates a new deserializer from a Json value
    pub fn new(val: Json) -> Deserializer {
        Deserializer { current: Some(val) }
    }
}

impl de::Deserializer for Deserializer {
    type Error = Error;

    fn visit<V: de::Visitor>(&mut self, mut v: V) -> Result<V::Value, Error> {
        // Extract current value so we can manipulate it without borrowing self
        let current = match self.current.take() {
            Some(val) => val,
            None => { return Err(de::Error::end_of_stream()); }
        };
        // Unwrap it from the outer type
        let Json(current) = current;

        match current {
            JsonInner::Null => v.visit_unit(),
            JsonInner::Bool(b) => v.visit_bool(b),
            JsonInner::Number(s) => v.visit_string(s),
            JsonInner::String(s) => v.visit_string(s),
            JsonInner::Array(arr) => {
                v.visit_seq(SeqVisitor {
                    iter: arr.into_iter()
                })
            }
            JsonInner::Object(map) => {
                v.visit_map(MapVisitor {
                    iter: map.into_iter(),
                    next_val: None
                })
            }
        }
    }

    // Special-case Option to allow absenteeism
    fn visit_option<V: de::Visitor>(&mut self,  mut v: V) -> Result<V::Value, Error> {
       match self.current {
           Some(Json(JsonInner::Null)) => v.visit_none(),
           Some(_) => v.visit_some(self),
           None => { return Err(de::Error::end_of_stream()); }
       }
    }

    fn format() -> &'static str { "strason" }

    // Special-case for evil visitor: if we have a specially-constructed Visitor,
    // which will signal its presence by calling this function with a specific
    // struct name, return our inner state to it disguised as a usize. The
    // visitor will interpret the usize as a pointer and use it to clone our
    // state, allowing us to "deserialize a Json as a Json" without actually
    // doing any deserialization (which'd destroy numeric values)
    fn visit_unit_struct<V: de::Visitor>(&mut self, name: &'static str, mut v: V) -> Result<V::Value, Error> {
        if name == EVIL_SENTINEL {
            match self.current {
                Some(_) => { v.visit_usize(&mut self.current as *mut _ as usize) }
                None => { return Err(de::Error::end_of_stream()); }
            }
        } else {
            self.visit(v)
        }
    }
}

struct SeqVisitor {
    iter: vec::IntoIter<Json>
}

impl de::SeqVisitor for SeqVisitor {
    type Error = Error;

    fn visit<T: de::Deserialize>(&mut self) -> Result<Option<T>, Error> {
        match self.iter.next() {
            Some(val) => Ok(Some(try!(de::Deserialize::deserialize(&mut Deserializer::new(val))))),
            None => Ok(None)
        }
    }

    fn end(&mut self) -> Result<(), Error> {
       let (rem, _) = self.iter.size_hint();
       if rem == 0 { Ok(()) } else { Err(de::Error::length_mismatch(rem)) }
    }

    fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
}

struct MapVisitor {
    iter: vec::IntoIter<(String, Json)>,
    next_val: Option<Json>
}

impl de::MapVisitor for MapVisitor {
    type Error = Error;

    fn visit_key<T: de::Deserialize>(&mut self) -> Result<Option<T>, Error> {
        match self.iter.next() {
            Some((key, val)) => {
                self.next_val = Some(val);
                let mut de = Deserializer::new(Json(JsonInner::String(key)));
                Ok(Some(try!(de::Deserialize::deserialize(&mut de))))
            }
            None => Ok(None)
        }
    }

    fn visit_value<T: de::Deserialize>(&mut self) -> Result<T, Error> {
        let val = self.next_val.take().unwrap();
        Ok(try!(de::Deserialize::deserialize(&mut Deserializer::new(val))))
    }

    fn end(&mut self) -> Result<(), Error> {
       let (rem, _) = self.iter.size_hint();
       if rem == 0 { Ok(()) } else { Err(de::Error::length_mismatch(rem)) }
    }

    fn missing_field<T: de::Deserialize>(&mut self, _: &'static str) -> Result<T, Error> {
        // Try an alternate deserializer that parses everything as a unit;
        // so "missing field" and "field: null" will be equivalent
        struct UnitDeserializer;
        impl de::Deserializer for UnitDeserializer {
            type Error = Error;

            // With no hint, deserialize as a unit
            fn visit<V: de::Visitor>(&mut self, mut v: V) -> Result<V::Value, Error> { v.visit_unit() }
            // With an "expect option" hint, deserialize as a None
            fn visit_option<V: de::Visitor>(&mut self, mut v: V) -> Result<V::Value, Error> { v.visit_none() }
        }
        Ok(try!(de::Deserialize::deserialize(&mut UnitDeserializer)))
    }

    fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
}

enum State {
    // terminal value
    Value(Json),
    // building an array,
    Array(Vec<Json>),
    // building an object,
    Object(Vec<(String, Json)>)
}

/// A "whatever to Json" serializer
pub struct Serializer {
    // stack-based state machine stack
    state: Vec<State>
}

impl Serializer {
    /// Creates a new serializer
    pub fn new() -> Serializer {
        Serializer { state: vec![] }
    }

    /// Unwraps the serialized value. Guaranteed to work iff serialize() was called and did not error.
    pub fn unwrap(mut self) -> Json {
        assert_eq!(self.state.len(), 1);
        match self.state.pop() {
            Some(State::Value(val)) => val,
            _ => panic!("Unwrap on a bad Json serializer")
        }
    }
}

impl ser::Serializer for Serializer {
    type Error = Error;

    fn visit_bool(&mut self, val: bool) -> Result<(), Error> {
        self.state.push(State::Value(Json(JsonInner::Bool(val))));
        Ok(())
    }

    fn visit_i64(&mut self, val: i64) -> Result<(), Error> {
        self.state.push(State::Value(Json(JsonInner::Number(format!("{}", val)))));
        Ok(())
    }

    fn visit_u64(&mut self, val: u64) -> Result<(), Error> {
        self.state.push(State::Value(Json(JsonInner::Number(format!("{}", val)))));
        Ok(())
    }

    fn visit_f64(&mut self, val: f64) -> Result<(), Error> {
        self.state.push(State::Value(Json(JsonInner::Number(format!("{}", val)))));
        Ok(())
    }

    fn visit_str(&mut self, val: &str) -> Result<(), Error> {
        self.state.push(State::Value(Json(JsonInner::String(val.to_owned()))));
        Ok(())
    }

    fn visit_unit(&mut self) -> Result<(), Error> {
        self.state.push(State::Value(Json(JsonInner::Null)));
        Ok(())
    }

    fn visit_none(&mut self) -> Result<(), Error> {
        self.state.push(State::Value(Json(JsonInner::Null)));
        Ok(())
    }

    fn visit_some<V: ser::Serialize>(&mut self, val: V) -> Result<(), Error> {
        val.serialize(self)
    }

    fn visit_seq<V: ser::SeqVisitor>(&mut self, mut v: V) -> Result<(), Error> {
        let arr = Vec::with_capacity(v.len().unwrap_or(0));
        // Push the array onto our stack machine
        self.state.push(State::Array(arr));
        // Parse all the values into this array
        while try!(v.visit(self)).is_some() {}
        // Pop the array off
        let arr = if let Some(State::Array(arr)) = self.state.pop() { arr } else { unreachable!() };
        // Return
        self.state.push(State::Value(Json(JsonInner::Array(arr))));
        Ok(())
    }

    fn visit_seq_elt<T: ser::Serialize>(&mut self, value: T) -> Result<(), Error> {
        try!(value.serialize(self));

        let val = if let Some(State::Value(val)) = self.state.pop() { val } else { unreachable!() };
        if let Some(&mut State::Array(ref mut arr)) = self.state.last_mut() {
            arr.push(val);
        } else {
            unreachable!()
        };
        Ok(())
    }

    fn visit_map<V: ser::MapVisitor>(&mut self, mut v: V) -> Result<(), Error> {
        let map = Vec::with_capacity(v.len().unwrap_or(0));
        // Push the array onto our stack machine
        self.state.push(State::Object(map));
        // Parse all the values into this array
        while try!(v.visit(self)).is_some() {}
        // Pop the array off
        let map = if let Some(State::Object(map)) = self.state.pop() { map } else { unreachable!() };
        // Return
        self.state.push(State::Value(Json(JsonInner::Object(map))));
        Ok(())
    }

    fn visit_map_elt<K: ser::Serialize, V: ser::Serialize>(&mut self, key: K, val: V) -> Result<(), Error> {
        // Serialize key
        try!(key.serialize(self));
        let key = match self.state.pop() {
            Some(State::Value(Json(JsonInner::String(s)))) => s,
            Some(State::Value(_)) => { return Err(From::from(ErrorType::ExpectedString)); }
            _ => unreachable!()
        };

        // Serialize value
        try!(val.serialize(self));
        let val = if let Some(State::Value(val)) = self.state.pop() { val } else { unreachable!() };

        // Add (key, value) to map
        if let Some(&mut State::Object(ref mut arr)) = self.state.last_mut() {
            arr.push((key, val));
        } else {
            unreachable!()
        };
        Ok(())
    }

    fn format() -> &'static str { "strason" }

    // Special case if we are serializing a Json, it will signal this to
    // us by passing a sentinel value as the field name in `visit_uint_variant`,
    // and give us a pointer to itself disguised as a usize in the `index`
    // field. We unwrap this and "serialize" it by just cloning it.
    fn visit_unit_variant(&mut self, name: &'static str, index: usize, _: &'static str) -> Result<(), Error> {
        if name == EVIL_SENTINEL {
            unsafe {
                let ptr = index as *const Json;
                self.state.push(State::Value((*ptr).clone()));
            }
            Ok(())
        } else {
            self.visit_unit()
        }
    }
}

/// Convert an arbitrary object to a Json structure
pub fn from_serialize<T: ser::Serialize>(obj: &T) -> Result<Json, Error> {
    let mut s = Serializer::new();
    try!(obj.serialize(&mut s));
    Ok(s.unwrap())
}

/// Convert a Json structure to an arbitary object
pub fn into_deserialize<T: de::Deserialize>(json: Json) -> Result<T, Error> {
    let mut d = Deserializer::new(json);
    de::Deserialize::deserialize(&mut d)
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;
    use Json;

    macro_rules! roundtrip_success(
        ($t:ty, $e:expr) => ({
            let obj = $e;
            match super::from_serialize(&obj) {
                Ok(val) => {
                    use serde::ser::Serialize;
                    // "Deserialize" as Json
                    let alt_json: Result<Json, _> = val.clone().into_deserialize();
                    assert!(alt_json.is_ok());
                    assert_eq!(alt_json.unwrap(), val);
                    // "Serialize" as Json
                    let mut s = super::Serializer::new();
                    assert!(val.serialize(&mut s).is_ok());
                    assert_eq!(s.unwrap(), val);
                    // Deserialize as object
                    let res: Result<$t, _> = val.into_deserialize();
                    assert!(res.is_ok());
                    assert_eq!(res.unwrap(), obj);
                }
                Err(e) => { panic!("Serializing into Json failed: {:?}", e); }
            }
        })
    );

    #[test]
    fn serde_roundtrip() {
        roundtrip_success!((), ());
        roundtrip_success!(String, "");
        roundtrip_success!(String, "Thing");
        roundtrip_success!(bool, false);
        roundtrip_success!(bool, true);
        roundtrip_success!(f64, 1.125);
        roundtrip_success!(f32, 1.125);

        macro_rules! check_num(
           ($t:ident) => ({
               use std::$t;
               roundtrip_success!($t, 0);
               roundtrip_success!($t, 100);
               roundtrip_success!($t, $t::MIN);
               roundtrip_success!($t, $t::MAX);
           })
        );
        check_num!(usize);
        check_num!(isize);
        check_num!(u64);
        check_num!(i64);
        check_num!(u32);
        check_num!(i32);
        check_num!(u16);
        check_num!(i16);
        check_num!(u8);
        check_num!(i8);

        roundtrip_success!(Vec<bool>, vec![]);
        roundtrip_success!(Vec<bool>, vec![true, false, true, true]);
        roundtrip_success!(Vec<String>, vec!["b", "i", "t"]);

        roundtrip_success!(Vec<(String, bool)>, vec![("b".to_owned(), true), ("i".to_owned(), false)]);

        let mut map = HashMap::new();
        map.insert("Test".to_owned(), "Testval".to_owned());
        map.insert("Test2".to_owned(), "another".to_owned());
        roundtrip_success!(HashMap<String, String>, map);
    }

    macro_rules! deserialize_test(
        ($e:expr, $result:expr) => ({
            use serde::de;
            use std::str;
            let mut d = $e.into_deserializer();
            let json: Result<Json, _>  = de::Deserialize::deserialize(&mut d);
            assert!(json.is_ok());
            let json_vec = json.unwrap().to_bytes();
            let json_str = str::from_utf8(&json_vec[..]).unwrap();
            assert_eq!(json_str, $result);
        })
    );

    #[test]
    fn serde_deserialize() {
        use serde::de::value::ValueDeserializer;

        macro_rules! check_num(
           ($t:ident) => ({
               use std::$t;
               let mut val: $t;

               val = 0;
               deserialize_test!(val, format!("{}", val));
               val = 100;
               deserialize_test!(val, format!("{}", val));
               val = $t::MIN;
               deserialize_test!(val, format!("{}", val));
               val = $t::MAX;
               deserialize_test!(val, format!("{}", val));
           })
        );

        check_num!(u8);
        check_num!(u16);
        check_num!(u32);
        check_num!(u64);
        check_num!(usize);
        check_num!(i8);
        check_num!(i16);
        check_num!(i32);
        check_num!(i64);
        check_num!(isize);

        deserialize_test!(0.375f32, "0.375");
        deserialize_test!(0.375f64, "0.375");
        deserialize_test!("Test1".to_string(), "\"Test1\"");
        deserialize_test!((), "null");
        deserialize_test!(true, "true");
        deserialize_test!(false, "false");

        deserialize_test!(vec![true, false, true, true], "[true, false, true, true]");
        // TODO the ordering that HashMap gives us is unpredictable so we can't directly
        // test multiple values
        let mut map = HashMap::new();
        map.insert("Test".to_owned(), "Testval".to_owned());
        deserialize_test!(map, "{\"Test\": \"Testval\"}");
    }

    macro_rules! serialize_test(
        ($s:expr) => ({
            use serde_json;
            assert_eq!(serde_json::to_string(&Json::from_str($s).unwrap()).unwrap(), $s);
        })
    );

    #[test]
    fn serde_serialize() {
        serialize_test!("null");
        serialize_test!("true");
        serialize_test!("false");
        serialize_test!("\"test string\"");
        serialize_test!("[true,false,false,\"thing\"]");
        serialize_test!("{\"obj\":\"val\",\"obj2\":\"val2\"}");
    }
}