]> git.lizzy.rs Git - rust.git/blob - src/libserialize/tests/json.rs
Rollup merge of #68440 - matthiaskrgr:xpyclippy, r=Mark-Simulacrum
[rust.git] / src / libserialize / tests / json.rs
1 #![allow(rustc::internal)]
2
3 extern crate serialize as rustc_serialize;
4
5 use json::DecoderError::*;
6 use json::ErrorCode::*;
7 use json::Json::*;
8 use json::JsonEvent::*;
9 use json::ParserError::*;
10 use json::{
11     from_str, DecodeResult, Decoder, DecoderError, Encoder, EncoderError, Json, JsonEvent, Parser,
12     StackElement,
13 };
14 use rustc_serialize::json;
15 use rustc_serialize::{Decodable, Encodable};
16
17 use std::collections::BTreeMap;
18 use std::io::prelude::*;
19 use std::string;
20 use std::{f32, f64, i64, u64};
21 use Animal::*;
22
23 #[derive(RustcDecodable, Eq, PartialEq, Debug)]
24 struct OptionData {
25     opt: Option<usize>,
26 }
27
28 #[test]
29 fn test_decode_option_none() {
30     let s = "{}";
31     let obj: OptionData = json::decode(s).unwrap();
32     assert_eq!(obj, OptionData { opt: None });
33 }
34
35 #[test]
36 fn test_decode_option_some() {
37     let s = "{ \"opt\": 10 }";
38     let obj: OptionData = json::decode(s).unwrap();
39     assert_eq!(obj, OptionData { opt: Some(10) });
40 }
41
42 #[test]
43 fn test_decode_option_malformed() {
44     check_err::<OptionData>(
45         "{ \"opt\": [] }",
46         ExpectedError("Number".to_string(), "[]".to_string()),
47     );
48     check_err::<OptionData>(
49         "{ \"opt\": false }",
50         ExpectedError("Number".to_string(), "false".to_string()),
51     );
52 }
53
54 #[derive(PartialEq, RustcEncodable, RustcDecodable, Debug)]
55 enum Animal {
56     Dog,
57     Frog(string::String, isize),
58 }
59
60 #[derive(PartialEq, RustcEncodable, RustcDecodable, Debug)]
61 struct Inner {
62     a: (),
63     b: usize,
64     c: Vec<string::String>,
65 }
66
67 #[derive(PartialEq, RustcEncodable, RustcDecodable, Debug)]
68 struct Outer {
69     inner: Vec<Inner>,
70 }
71
72 fn mk_object(items: &[(string::String, Json)]) -> Json {
73     let mut d = BTreeMap::new();
74
75     for item in items {
76         match *item {
77             (ref key, ref value) => {
78                 d.insert((*key).clone(), (*value).clone());
79             }
80         }
81     }
82
83     Object(d)
84 }
85
86 #[test]
87 fn test_from_str_trait() {
88     let s = "null";
89     assert!(s.parse::<Json>().unwrap() == s.parse().unwrap());
90 }
91
92 #[test]
93 fn test_write_null() {
94     assert_eq!(Null.to_string(), "null");
95     assert_eq!(Null.pretty().to_string(), "null");
96 }
97
98 #[test]
99 fn test_write_i64() {
100     assert_eq!(U64(0).to_string(), "0");
101     assert_eq!(U64(0).pretty().to_string(), "0");
102
103     assert_eq!(U64(1234).to_string(), "1234");
104     assert_eq!(U64(1234).pretty().to_string(), "1234");
105
106     assert_eq!(I64(-5678).to_string(), "-5678");
107     assert_eq!(I64(-5678).pretty().to_string(), "-5678");
108
109     assert_eq!(U64(7650007200025252000).to_string(), "7650007200025252000");
110     assert_eq!(U64(7650007200025252000).pretty().to_string(), "7650007200025252000");
111 }
112
113 #[test]
114 fn test_write_f64() {
115     assert_eq!(F64(3.0).to_string(), "3.0");
116     assert_eq!(F64(3.0).pretty().to_string(), "3.0");
117
118     assert_eq!(F64(3.1).to_string(), "3.1");
119     assert_eq!(F64(3.1).pretty().to_string(), "3.1");
120
121     assert_eq!(F64(-1.5).to_string(), "-1.5");
122     assert_eq!(F64(-1.5).pretty().to_string(), "-1.5");
123
124     assert_eq!(F64(0.5).to_string(), "0.5");
125     assert_eq!(F64(0.5).pretty().to_string(), "0.5");
126
127     assert_eq!(F64(f64::NAN).to_string(), "null");
128     assert_eq!(F64(f64::NAN).pretty().to_string(), "null");
129
130     assert_eq!(F64(f64::INFINITY).to_string(), "null");
131     assert_eq!(F64(f64::INFINITY).pretty().to_string(), "null");
132
133     assert_eq!(F64(f64::NEG_INFINITY).to_string(), "null");
134     assert_eq!(F64(f64::NEG_INFINITY).pretty().to_string(), "null");
135 }
136
137 #[test]
138 fn test_write_str() {
139     assert_eq!(String("".to_string()).to_string(), "\"\"");
140     assert_eq!(String("".to_string()).pretty().to_string(), "\"\"");
141
142     assert_eq!(String("homura".to_string()).to_string(), "\"homura\"");
143     assert_eq!(String("madoka".to_string()).pretty().to_string(), "\"madoka\"");
144 }
145
146 #[test]
147 fn test_write_bool() {
148     assert_eq!(Boolean(true).to_string(), "true");
149     assert_eq!(Boolean(true).pretty().to_string(), "true");
150
151     assert_eq!(Boolean(false).to_string(), "false");
152     assert_eq!(Boolean(false).pretty().to_string(), "false");
153 }
154
155 #[test]
156 fn test_write_array() {
157     assert_eq!(Array(vec![]).to_string(), "[]");
158     assert_eq!(Array(vec![]).pretty().to_string(), "[]");
159
160     assert_eq!(Array(vec![Boolean(true)]).to_string(), "[true]");
161     assert_eq!(
162         Array(vec![Boolean(true)]).pretty().to_string(),
163         "\
164         [\n  \
165             true\n\
166         ]"
167     );
168
169     let long_test_array =
170         Array(vec![Boolean(false), Null, Array(vec![String("foo\nbar".to_string()), F64(3.5)])]);
171
172     assert_eq!(long_test_array.to_string(), "[false,null,[\"foo\\nbar\",3.5]]");
173     assert_eq!(
174         long_test_array.pretty().to_string(),
175         "\
176         [\n  \
177             false,\n  \
178             null,\n  \
179             [\n    \
180                 \"foo\\nbar\",\n    \
181                 3.5\n  \
182             ]\n\
183         ]"
184     );
185 }
186
187 #[test]
188 fn test_write_object() {
189     assert_eq!(mk_object(&[]).to_string(), "{}");
190     assert_eq!(mk_object(&[]).pretty().to_string(), "{}");
191
192     assert_eq!(mk_object(&[("a".to_string(), Boolean(true))]).to_string(), "{\"a\":true}");
193     assert_eq!(
194         mk_object(&[("a".to_string(), Boolean(true))]).pretty().to_string(),
195         "\
196         {\n  \
197             \"a\": true\n\
198         }"
199     );
200
201     let complex_obj = mk_object(&[(
202         "b".to_string(),
203         Array(vec![
204             mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
205             mk_object(&[("d".to_string(), String("".to_string()))]),
206         ]),
207     )]);
208
209     assert_eq!(
210         complex_obj.to_string(),
211         "{\
212             \"b\":[\
213                 {\"c\":\"\\f\\r\"},\
214                 {\"d\":\"\"}\
215             ]\
216         }"
217     );
218     assert_eq!(
219         complex_obj.pretty().to_string(),
220         "\
221         {\n  \
222             \"b\": [\n    \
223                 {\n      \
224                     \"c\": \"\\f\\r\"\n    \
225                 },\n    \
226                 {\n      \
227                     \"d\": \"\"\n    \
228                 }\n  \
229             ]\n\
230         }"
231     );
232
233     let a = mk_object(&[
234         ("a".to_string(), Boolean(true)),
235         (
236             "b".to_string(),
237             Array(vec![
238                 mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
239                 mk_object(&[("d".to_string(), String("".to_string()))]),
240             ]),
241         ),
242     ]);
243
244     // We can't compare the strings directly because the object fields be
245     // printed in a different order.
246     assert_eq!(a.clone(), a.to_string().parse().unwrap());
247     assert_eq!(a.clone(), a.pretty().to_string().parse().unwrap());
248 }
249
250 #[test]
251 fn test_write_enum() {
252     let animal = Dog;
253     assert_eq!(json::as_json(&animal).to_string(), "\"Dog\"");
254     assert_eq!(json::as_pretty_json(&animal).to_string(), "\"Dog\"");
255
256     let animal = Frog("Henry".to_string(), 349);
257     assert_eq!(
258         json::as_json(&animal).to_string(),
259         "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}"
260     );
261     assert_eq!(
262         json::as_pretty_json(&animal).to_string(),
263         "{\n  \
264            \"variant\": \"Frog\",\n  \
265            \"fields\": [\n    \
266              \"Henry\",\n    \
267              349\n  \
268            ]\n\
269          }"
270     );
271 }
272
273 macro_rules! check_encoder_for_simple {
274     ($value:expr, $expected:expr) => {{
275         let s = json::as_json(&$value).to_string();
276         assert_eq!(s, $expected);
277
278         let s = json::as_pretty_json(&$value).to_string();
279         assert_eq!(s, $expected);
280     }};
281 }
282
283 #[test]
284 fn test_write_some() {
285     check_encoder_for_simple!(Some("jodhpurs".to_string()), "\"jodhpurs\"");
286 }
287
288 #[test]
289 fn test_write_none() {
290     check_encoder_for_simple!(None::<string::String>, "null");
291 }
292
293 #[test]
294 fn test_write_char() {
295     check_encoder_for_simple!('a', "\"a\"");
296     check_encoder_for_simple!('\t', "\"\\t\"");
297     check_encoder_for_simple!('\u{0000}', "\"\\u0000\"");
298     check_encoder_for_simple!('\u{001b}', "\"\\u001b\"");
299     check_encoder_for_simple!('\u{007f}', "\"\\u007f\"");
300     check_encoder_for_simple!('\u{00a0}', "\"\u{00a0}\"");
301     check_encoder_for_simple!('\u{abcd}', "\"\u{abcd}\"");
302     check_encoder_for_simple!('\u{10ffff}', "\"\u{10ffff}\"");
303 }
304
305 #[test]
306 fn test_trailing_characters() {
307     assert_eq!(from_str("nulla"), Err(SyntaxError(TrailingCharacters, 1, 5)));
308     assert_eq!(from_str("truea"), Err(SyntaxError(TrailingCharacters, 1, 5)));
309     assert_eq!(from_str("falsea"), Err(SyntaxError(TrailingCharacters, 1, 6)));
310     assert_eq!(from_str("1a"), Err(SyntaxError(TrailingCharacters, 1, 2)));
311     assert_eq!(from_str("[]a"), Err(SyntaxError(TrailingCharacters, 1, 3)));
312     assert_eq!(from_str("{}a"), Err(SyntaxError(TrailingCharacters, 1, 3)));
313 }
314
315 #[test]
316 fn test_read_identifiers() {
317     assert_eq!(from_str("n"), Err(SyntaxError(InvalidSyntax, 1, 2)));
318     assert_eq!(from_str("nul"), Err(SyntaxError(InvalidSyntax, 1, 4)));
319     assert_eq!(from_str("t"), Err(SyntaxError(InvalidSyntax, 1, 2)));
320     assert_eq!(from_str("truz"), Err(SyntaxError(InvalidSyntax, 1, 4)));
321     assert_eq!(from_str("f"), Err(SyntaxError(InvalidSyntax, 1, 2)));
322     assert_eq!(from_str("faz"), Err(SyntaxError(InvalidSyntax, 1, 3)));
323
324     assert_eq!(from_str("null"), Ok(Null));
325     assert_eq!(from_str("true"), Ok(Boolean(true)));
326     assert_eq!(from_str("false"), Ok(Boolean(false)));
327     assert_eq!(from_str(" null "), Ok(Null));
328     assert_eq!(from_str(" true "), Ok(Boolean(true)));
329     assert_eq!(from_str(" false "), Ok(Boolean(false)));
330 }
331
332 #[test]
333 fn test_decode_identifiers() {
334     let v: () = json::decode("null").unwrap();
335     assert_eq!(v, ());
336
337     let v: bool = json::decode("true").unwrap();
338     assert_eq!(v, true);
339
340     let v: bool = json::decode("false").unwrap();
341     assert_eq!(v, false);
342 }
343
344 #[test]
345 fn test_read_number() {
346     assert_eq!(from_str("+"), Err(SyntaxError(InvalidSyntax, 1, 1)));
347     assert_eq!(from_str("."), Err(SyntaxError(InvalidSyntax, 1, 1)));
348     assert_eq!(from_str("NaN"), Err(SyntaxError(InvalidSyntax, 1, 1)));
349     assert_eq!(from_str("-"), Err(SyntaxError(InvalidNumber, 1, 2)));
350     assert_eq!(from_str("00"), Err(SyntaxError(InvalidNumber, 1, 2)));
351     assert_eq!(from_str("1."), Err(SyntaxError(InvalidNumber, 1, 3)));
352     assert_eq!(from_str("1e"), Err(SyntaxError(InvalidNumber, 1, 3)));
353     assert_eq!(from_str("1e+"), Err(SyntaxError(InvalidNumber, 1, 4)));
354
355     assert_eq!(from_str("18446744073709551616"), Err(SyntaxError(InvalidNumber, 1, 20)));
356     assert_eq!(from_str("-9223372036854775809"), Err(SyntaxError(InvalidNumber, 1, 21)));
357
358     assert_eq!(from_str("3"), Ok(U64(3)));
359     assert_eq!(from_str("3.1"), Ok(F64(3.1)));
360     assert_eq!(from_str("-1.2"), Ok(F64(-1.2)));
361     assert_eq!(from_str("0.4"), Ok(F64(0.4)));
362     assert_eq!(from_str("0.4e5"), Ok(F64(0.4e5)));
363     assert_eq!(from_str("0.4e+15"), Ok(F64(0.4e15)));
364     assert_eq!(from_str("0.4e-01"), Ok(F64(0.4e-01)));
365     assert_eq!(from_str(" 3 "), Ok(U64(3)));
366
367     assert_eq!(from_str("-9223372036854775808"), Ok(I64(i64::MIN)));
368     assert_eq!(from_str("9223372036854775807"), Ok(U64(i64::MAX as u64)));
369     assert_eq!(from_str("18446744073709551615"), Ok(U64(u64::MAX)));
370 }
371
372 #[test]
373 fn test_decode_numbers() {
374     let v: f64 = json::decode("3").unwrap();
375     assert_eq!(v, 3.0);
376
377     let v: f64 = json::decode("3.1").unwrap();
378     assert_eq!(v, 3.1);
379
380     let v: f64 = json::decode("-1.2").unwrap();
381     assert_eq!(v, -1.2);
382
383     let v: f64 = json::decode("0.4").unwrap();
384     assert_eq!(v, 0.4);
385
386     let v: f64 = json::decode("0.4e5").unwrap();
387     assert_eq!(v, 0.4e5);
388
389     let v: f64 = json::decode("0.4e15").unwrap();
390     assert_eq!(v, 0.4e15);
391
392     let v: f64 = json::decode("0.4e-01").unwrap();
393     assert_eq!(v, 0.4e-01);
394
395     let v: u64 = json::decode("0").unwrap();
396     assert_eq!(v, 0);
397
398     let v: u64 = json::decode("18446744073709551615").unwrap();
399     assert_eq!(v, u64::MAX);
400
401     let v: i64 = json::decode("-9223372036854775808").unwrap();
402     assert_eq!(v, i64::MIN);
403
404     let v: i64 = json::decode("9223372036854775807").unwrap();
405     assert_eq!(v, i64::MAX);
406
407     let res: DecodeResult<i64> = json::decode("765.25");
408     assert_eq!(res, Err(ExpectedError("Integer".to_string(), "765.25".to_string())));
409 }
410
411 #[test]
412 fn test_read_str() {
413     assert_eq!(from_str("\""), Err(SyntaxError(EOFWhileParsingString, 1, 2)));
414     assert_eq!(from_str("\"lol"), Err(SyntaxError(EOFWhileParsingString, 1, 5)));
415
416     assert_eq!(from_str("\"\""), Ok(String("".to_string())));
417     assert_eq!(from_str("\"foo\""), Ok(String("foo".to_string())));
418     assert_eq!(from_str("\"\\\"\""), Ok(String("\"".to_string())));
419     assert_eq!(from_str("\"\\b\""), Ok(String("\x08".to_string())));
420     assert_eq!(from_str("\"\\n\""), Ok(String("\n".to_string())));
421     assert_eq!(from_str("\"\\r\""), Ok(String("\r".to_string())));
422     assert_eq!(from_str("\"\\t\""), Ok(String("\t".to_string())));
423     assert_eq!(from_str(" \"foo\" "), Ok(String("foo".to_string())));
424     assert_eq!(from_str("\"\\u12ab\""), Ok(String("\u{12ab}".to_string())));
425     assert_eq!(from_str("\"\\uAB12\""), Ok(String("\u{AB12}".to_string())));
426 }
427
428 #[test]
429 fn test_decode_str() {
430     let s = [
431         ("\"\"", ""),
432         ("\"foo\"", "foo"),
433         ("\"\\\"\"", "\""),
434         ("\"\\b\"", "\x08"),
435         ("\"\\n\"", "\n"),
436         ("\"\\r\"", "\r"),
437         ("\"\\t\"", "\t"),
438         ("\"\\u12ab\"", "\u{12ab}"),
439         ("\"\\uAB12\"", "\u{AB12}"),
440     ];
441
442     for &(i, o) in &s {
443         let v: string::String = json::decode(i).unwrap();
444         assert_eq!(v, o);
445     }
446 }
447
448 #[test]
449 fn test_read_array() {
450     assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
451     assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
452     assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
453     assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
454     assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
455
456     assert_eq!(from_str("[]"), Ok(Array(vec![])));
457     assert_eq!(from_str("[ ]"), Ok(Array(vec![])));
458     assert_eq!(from_str("[true]"), Ok(Array(vec![Boolean(true)])));
459     assert_eq!(from_str("[ false ]"), Ok(Array(vec![Boolean(false)])));
460     assert_eq!(from_str("[null]"), Ok(Array(vec![Null])));
461     assert_eq!(from_str("[3, 1]"), Ok(Array(vec![U64(3), U64(1)])));
462     assert_eq!(from_str("\n[3, 2]\n"), Ok(Array(vec![U64(3), U64(2)])));
463     assert_eq!(from_str("[2, [4, 1]]"), Ok(Array(vec![U64(2), Array(vec![U64(4), U64(1)])])));
464 }
465
466 #[test]
467 fn test_decode_array() {
468     let v: Vec<()> = json::decode("[]").unwrap();
469     assert_eq!(v, []);
470
471     let v: Vec<()> = json::decode("[null]").unwrap();
472     assert_eq!(v, [()]);
473
474     let v: Vec<bool> = json::decode("[true]").unwrap();
475     assert_eq!(v, [true]);
476
477     let v: Vec<isize> = json::decode("[3, 1]").unwrap();
478     assert_eq!(v, [3, 1]);
479
480     let v: Vec<Vec<usize>> = json::decode("[[3], [1, 2]]").unwrap();
481     assert_eq!(v, [vec![3], vec![1, 2]]);
482 }
483
484 #[test]
485 fn test_decode_tuple() {
486     let t: (usize, usize, usize) = json::decode("[1, 2, 3]").unwrap();
487     assert_eq!(t, (1, 2, 3));
488
489     let t: (usize, string::String) = json::decode("[1, \"two\"]").unwrap();
490     assert_eq!(t, (1, "two".to_string()));
491 }
492
493 #[test]
494 fn test_decode_tuple_malformed_types() {
495     assert!(json::decode::<(usize, string::String)>("[1, 2]").is_err());
496 }
497
498 #[test]
499 fn test_decode_tuple_malformed_length() {
500     assert!(json::decode::<(usize, usize)>("[1, 2, 3]").is_err());
501 }
502
503 #[test]
504 fn test_read_object() {
505     assert_eq!(from_str("{"), Err(SyntaxError(EOFWhileParsingObject, 1, 2)));
506     assert_eq!(from_str("{ "), Err(SyntaxError(EOFWhileParsingObject, 1, 3)));
507     assert_eq!(from_str("{1"), Err(SyntaxError(KeyMustBeAString, 1, 2)));
508     assert_eq!(from_str("{ \"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
509     assert_eq!(from_str("{\"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 5)));
510     assert_eq!(from_str("{\"a\" "), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
511
512     assert_eq!(from_str("{\"a\" 1"), Err(SyntaxError(ExpectedColon, 1, 6)));
513     assert_eq!(from_str("{\"a\":"), Err(SyntaxError(EOFWhileParsingValue, 1, 6)));
514     assert_eq!(from_str("{\"a\":1"), Err(SyntaxError(EOFWhileParsingObject, 1, 7)));
515     assert_eq!(from_str("{\"a\":1 1"), Err(SyntaxError(InvalidSyntax, 1, 8)));
516     assert_eq!(from_str("{\"a\":1,"), Err(SyntaxError(EOFWhileParsingObject, 1, 8)));
517
518     assert_eq!(from_str("{}").unwrap(), mk_object(&[]));
519     assert_eq!(from_str("{\"a\": 3}").unwrap(), mk_object(&[("a".to_string(), U64(3))]));
520
521     assert_eq!(
522         from_str("{ \"a\": null, \"b\" : true }").unwrap(),
523         mk_object(&[("a".to_string(), Null), ("b".to_string(), Boolean(true))])
524     );
525     assert_eq!(
526         from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(),
527         mk_object(&[("a".to_string(), Null), ("b".to_string(), Boolean(true))])
528     );
529     assert_eq!(
530         from_str("{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(),
531         mk_object(&[("a".to_string(), F64(1.0)), ("b".to_string(), Array(vec![Boolean(true)]))])
532     );
533     assert_eq!(
534         from_str(
535             "{\
536                         \"a\": 1.0, \
537                         \"b\": [\
538                             true,\
539                             \"foo\\nbar\", \
540                             { \"c\": {\"d\": null} } \
541                         ]\
542                     }"
543         )
544         .unwrap(),
545         mk_object(&[
546             ("a".to_string(), F64(1.0)),
547             (
548                 "b".to_string(),
549                 Array(vec![
550                     Boolean(true),
551                     String("foo\nbar".to_string()),
552                     mk_object(&[("c".to_string(), mk_object(&[("d".to_string(), Null)]))])
553                 ])
554             )
555         ])
556     );
557 }
558
559 #[test]
560 fn test_decode_struct() {
561     let s = "{
562         \"inner\": [
563             { \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] }
564         ]
565     }";
566
567     let v: Outer = json::decode(s).unwrap();
568     assert_eq!(
569         v,
570         Outer { inner: vec![Inner { a: (), b: 2, c: vec!["abc".to_string(), "xyz".to_string()] }] }
571     );
572 }
573
574 #[derive(RustcDecodable)]
575 struct FloatStruct {
576     f: f64,
577     a: Vec<f64>,
578 }
579 #[test]
580 fn test_decode_struct_with_nan() {
581     let s = "{\"f\":null,\"a\":[null,123]}";
582     let obj: FloatStruct = json::decode(s).unwrap();
583     assert!(obj.f.is_nan());
584     assert!(obj.a[0].is_nan());
585     assert_eq!(obj.a[1], 123f64);
586 }
587
588 #[test]
589 fn test_decode_option() {
590     let value: Option<string::String> = json::decode("null").unwrap();
591     assert_eq!(value, None);
592
593     let value: Option<string::String> = json::decode("\"jodhpurs\"").unwrap();
594     assert_eq!(value, Some("jodhpurs".to_string()));
595 }
596
597 #[test]
598 fn test_decode_enum() {
599     let value: Animal = json::decode("\"Dog\"").unwrap();
600     assert_eq!(value, Dog);
601
602     let s = "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}";
603     let value: Animal = json::decode(s).unwrap();
604     assert_eq!(value, Frog("Henry".to_string(), 349));
605 }
606
607 #[test]
608 fn test_decode_map() {
609     let s = "{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\
610               \"fields\":[\"Henry\", 349]}}";
611     let mut map: BTreeMap<string::String, Animal> = json::decode(s).unwrap();
612
613     assert_eq!(map.remove(&"a".to_string()), Some(Dog));
614     assert_eq!(map.remove(&"b".to_string()), Some(Frog("Henry".to_string(), 349)));
615 }
616
617 #[test]
618 fn test_multiline_errors() {
619     assert_eq!(from_str("{\n  \"foo\":\n \"bar\""), Err(SyntaxError(EOFWhileParsingObject, 3, 8)));
620 }
621
622 #[derive(RustcDecodable)]
623 #[allow(dead_code)]
624 struct DecodeStruct {
625     x: f64,
626     y: bool,
627     z: string::String,
628     w: Vec<DecodeStruct>,
629 }
630 #[derive(RustcDecodable)]
631 enum DecodeEnum {
632     A(f64),
633     B(string::String),
634 }
635 fn check_err<T: Decodable>(to_parse: &'static str, expected: DecoderError) {
636     let res: DecodeResult<T> = match from_str(to_parse) {
637         Err(e) => Err(ParseError(e)),
638         Ok(json) => Decodable::decode(&mut Decoder::new(json)),
639     };
640     match res {
641         Ok(_) => panic!("`{:?}` parsed & decoded ok, expecting error `{:?}`", to_parse, expected),
642         Err(ParseError(e)) => panic!("`{:?}` is not valid json: {:?}", to_parse, e),
643         Err(e) => {
644             assert_eq!(e, expected);
645         }
646     }
647 }
648 #[test]
649 fn test_decode_errors_struct() {
650     check_err::<DecodeStruct>("[]", ExpectedError("Object".to_string(), "[]".to_string()));
651     check_err::<DecodeStruct>(
652         "{\"x\": true, \"y\": true, \"z\": \"\", \"w\": []}",
653         ExpectedError("Number".to_string(), "true".to_string()),
654     );
655     check_err::<DecodeStruct>(
656         "{\"x\": 1, \"y\": [], \"z\": \"\", \"w\": []}",
657         ExpectedError("Boolean".to_string(), "[]".to_string()),
658     );
659     check_err::<DecodeStruct>(
660         "{\"x\": 1, \"y\": true, \"z\": {}, \"w\": []}",
661         ExpectedError("String".to_string(), "{}".to_string()),
662     );
663     check_err::<DecodeStruct>(
664         "{\"x\": 1, \"y\": true, \"z\": \"\", \"w\": null}",
665         ExpectedError("Array".to_string(), "null".to_string()),
666     );
667     check_err::<DecodeStruct>(
668         "{\"x\": 1, \"y\": true, \"z\": \"\"}",
669         MissingFieldError("w".to_string()),
670     );
671 }
672 #[test]
673 fn test_decode_errors_enum() {
674     check_err::<DecodeEnum>("{}", MissingFieldError("variant".to_string()));
675     check_err::<DecodeEnum>(
676         "{\"variant\": 1}",
677         ExpectedError("String".to_string(), "1".to_string()),
678     );
679     check_err::<DecodeEnum>("{\"variant\": \"A\"}", MissingFieldError("fields".to_string()));
680     check_err::<DecodeEnum>(
681         "{\"variant\": \"A\", \"fields\": null}",
682         ExpectedError("Array".to_string(), "null".to_string()),
683     );
684     check_err::<DecodeEnum>(
685         "{\"variant\": \"C\", \"fields\": []}",
686         UnknownVariantError("C".to_string()),
687     );
688 }
689
690 #[test]
691 fn test_find() {
692     let json_value = from_str("{\"dog\" : \"cat\"}").unwrap();
693     let found_str = json_value.find("dog");
694     assert!(found_str.unwrap().as_string().unwrap() == "cat");
695 }
696
697 #[test]
698 fn test_find_path() {
699     let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
700     let found_str = json_value.find_path(&["dog", "cat", "mouse"]);
701     assert!(found_str.unwrap().as_string().unwrap() == "cheese");
702 }
703
704 #[test]
705 fn test_search() {
706     let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
707     let found_str = json_value.search("mouse").and_then(|j| j.as_string());
708     assert!(found_str.unwrap() == "cheese");
709 }
710
711 #[test]
712 fn test_index() {
713     let json_value = from_str("{\"animals\":[\"dog\",\"cat\",\"mouse\"]}").unwrap();
714     let ref array = json_value["animals"];
715     assert_eq!(array[0].as_string().unwrap(), "dog");
716     assert_eq!(array[1].as_string().unwrap(), "cat");
717     assert_eq!(array[2].as_string().unwrap(), "mouse");
718 }
719
720 #[test]
721 fn test_is_object() {
722     let json_value = from_str("{}").unwrap();
723     assert!(json_value.is_object());
724 }
725
726 #[test]
727 fn test_as_object() {
728     let json_value = from_str("{}").unwrap();
729     let json_object = json_value.as_object();
730     assert!(json_object.is_some());
731 }
732
733 #[test]
734 fn test_is_array() {
735     let json_value = from_str("[1, 2, 3]").unwrap();
736     assert!(json_value.is_array());
737 }
738
739 #[test]
740 fn test_as_array() {
741     let json_value = from_str("[1, 2, 3]").unwrap();
742     let json_array = json_value.as_array();
743     let expected_length = 3;
744     assert!(json_array.is_some() && json_array.unwrap().len() == expected_length);
745 }
746
747 #[test]
748 fn test_is_string() {
749     let json_value = from_str("\"dog\"").unwrap();
750     assert!(json_value.is_string());
751 }
752
753 #[test]
754 fn test_as_string() {
755     let json_value = from_str("\"dog\"").unwrap();
756     let json_str = json_value.as_string();
757     let expected_str = "dog";
758     assert_eq!(json_str, Some(expected_str));
759 }
760
761 #[test]
762 fn test_is_number() {
763     let json_value = from_str("12").unwrap();
764     assert!(json_value.is_number());
765 }
766
767 #[test]
768 fn test_is_i64() {
769     let json_value = from_str("-12").unwrap();
770     assert!(json_value.is_i64());
771
772     let json_value = from_str("12").unwrap();
773     assert!(!json_value.is_i64());
774
775     let json_value = from_str("12.0").unwrap();
776     assert!(!json_value.is_i64());
777 }
778
779 #[test]
780 fn test_is_u64() {
781     let json_value = from_str("12").unwrap();
782     assert!(json_value.is_u64());
783
784     let json_value = from_str("-12").unwrap();
785     assert!(!json_value.is_u64());
786
787     let json_value = from_str("12.0").unwrap();
788     assert!(!json_value.is_u64());
789 }
790
791 #[test]
792 fn test_is_f64() {
793     let json_value = from_str("12").unwrap();
794     assert!(!json_value.is_f64());
795
796     let json_value = from_str("-12").unwrap();
797     assert!(!json_value.is_f64());
798
799     let json_value = from_str("12.0").unwrap();
800     assert!(json_value.is_f64());
801
802     let json_value = from_str("-12.0").unwrap();
803     assert!(json_value.is_f64());
804 }
805
806 #[test]
807 fn test_as_i64() {
808     let json_value = from_str("-12").unwrap();
809     let json_num = json_value.as_i64();
810     assert_eq!(json_num, Some(-12));
811 }
812
813 #[test]
814 fn test_as_u64() {
815     let json_value = from_str("12").unwrap();
816     let json_num = json_value.as_u64();
817     assert_eq!(json_num, Some(12));
818 }
819
820 #[test]
821 fn test_as_f64() {
822     let json_value = from_str("12.0").unwrap();
823     let json_num = json_value.as_f64();
824     assert_eq!(json_num, Some(12f64));
825 }
826
827 #[test]
828 fn test_is_boolean() {
829     let json_value = from_str("false").unwrap();
830     assert!(json_value.is_boolean());
831 }
832
833 #[test]
834 fn test_as_boolean() {
835     let json_value = from_str("false").unwrap();
836     let json_bool = json_value.as_boolean();
837     let expected_bool = false;
838     assert!(json_bool.is_some() && json_bool.unwrap() == expected_bool);
839 }
840
841 #[test]
842 fn test_is_null() {
843     let json_value = from_str("null").unwrap();
844     assert!(json_value.is_null());
845 }
846
847 #[test]
848 fn test_as_null() {
849     let json_value = from_str("null").unwrap();
850     let json_null = json_value.as_null();
851     let expected_null = ();
852     assert!(json_null.is_some() && json_null.unwrap() == expected_null);
853 }
854
855 #[test]
856 fn test_encode_hashmap_with_numeric_key() {
857     use std::collections::HashMap;
858     use std::str::from_utf8;
859     let mut hm: HashMap<usize, bool> = HashMap::new();
860     hm.insert(1, true);
861     let mut mem_buf = Vec::new();
862     write!(&mut mem_buf, "{}", json::as_pretty_json(&hm)).unwrap();
863     let json_str = from_utf8(&mem_buf[..]).unwrap();
864     match from_str(json_str) {
865         Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
866         _ => {} // it parsed and we are good to go
867     }
868 }
869
870 #[test]
871 fn test_prettyencode_hashmap_with_numeric_key() {
872     use std::collections::HashMap;
873     use std::str::from_utf8;
874     let mut hm: HashMap<usize, bool> = HashMap::new();
875     hm.insert(1, true);
876     let mut mem_buf = Vec::new();
877     write!(&mut mem_buf, "{}", json::as_pretty_json(&hm)).unwrap();
878     let json_str = from_utf8(&mem_buf[..]).unwrap();
879     match from_str(json_str) {
880         Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
881         _ => {} // it parsed and we are good to go
882     }
883 }
884
885 #[test]
886 fn test_prettyencoder_indent_level_param() {
887     use std::collections::BTreeMap;
888     use std::str::from_utf8;
889
890     let mut tree = BTreeMap::new();
891
892     tree.insert("hello".to_string(), String("guten tag".to_string()));
893     tree.insert("goodbye".to_string(), String("sayonara".to_string()));
894
895     let json = Array(
896         // The following layout below should look a lot like
897         // the pretty-printed JSON (indent * x)
898         vec![
899             // 0x
900             String("greetings".to_string()), // 1x
901             Object(tree),                    // 1x + 2x + 2x + 1x
902         ], // 0x
903            // End JSON array (7 lines)
904     );
905
906     // Helper function for counting indents
907     fn indents(source: &str) -> usize {
908         let trimmed = source.trim_start_matches(' ');
909         source.len() - trimmed.len()
910     }
911
912     // Test up to 4 spaces of indents (more?)
913     for i in 0..4 {
914         let mut writer = Vec::new();
915         write!(&mut writer, "{}", json::as_pretty_json(&json).indent(i)).unwrap();
916
917         let printed = from_utf8(&writer[..]).unwrap();
918
919         // Check for indents at each line
920         let lines: Vec<&str> = printed.lines().collect();
921         assert_eq!(lines.len(), 7); // JSON should be 7 lines
922
923         assert_eq!(indents(lines[0]), 0 * i); // [
924         assert_eq!(indents(lines[1]), 1 * i); //   "greetings",
925         assert_eq!(indents(lines[2]), 1 * i); //   {
926         assert_eq!(indents(lines[3]), 2 * i); //     "hello": "guten tag",
927         assert_eq!(indents(lines[4]), 2 * i); //     "goodbye": "sayonara"
928         assert_eq!(indents(lines[5]), 1 * i); //   },
929         assert_eq!(indents(lines[6]), 0 * i); // ]
930
931         // Finally, test that the pretty-printed JSON is valid
932         from_str(printed).ok().expect("Pretty-printed JSON is invalid!");
933     }
934 }
935
936 #[test]
937 fn test_hashmap_with_enum_key() {
938     use std::collections::HashMap;
939     #[derive(RustcEncodable, Eq, Hash, PartialEq, RustcDecodable, Debug)]
940     enum Enum {
941         Foo,
942         #[allow(dead_code)]
943         Bar,
944     }
945     let mut map = HashMap::new();
946     map.insert(Enum::Foo, 0);
947     let result = json::encode(&map).unwrap();
948     assert_eq!(&result[..], r#"{"Foo":0}"#);
949     let decoded: HashMap<Enum, _> = json::decode(&result).unwrap();
950     assert_eq!(map, decoded);
951 }
952
953 #[test]
954 fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() {
955     use std::collections::HashMap;
956     let json_str = "{\"1\":true}";
957     let json_obj = match from_str(json_str) {
958         Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
959         Ok(o) => o,
960     };
961     let mut decoder = Decoder::new(json_obj);
962     let _hm: HashMap<usize, bool> = Decodable::decode(&mut decoder).unwrap();
963 }
964
965 #[test]
966 fn test_hashmap_with_numeric_key_will_error_with_string_keys() {
967     use std::collections::HashMap;
968     let json_str = "{\"a\":true}";
969     let json_obj = match from_str(json_str) {
970         Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
971         Ok(o) => o,
972     };
973     let mut decoder = Decoder::new(json_obj);
974     let result: Result<HashMap<usize, bool>, DecoderError> = Decodable::decode(&mut decoder);
975     assert_eq!(result, Err(ExpectedError("Number".to_string(), "a".to_string())));
976 }
977
978 fn assert_stream_equal(src: &str, expected: Vec<(JsonEvent, Vec<StackElement<'_>>)>) {
979     let mut parser = Parser::new(src.chars());
980     let mut i = 0;
981     loop {
982         let evt = match parser.next() {
983             Some(e) => e,
984             None => {
985                 break;
986             }
987         };
988         let (ref expected_evt, ref expected_stack) = expected[i];
989         if !parser.stack().is_equal_to(expected_stack) {
990             panic!("Parser stack is not equal to {:?}", expected_stack);
991         }
992         assert_eq!(&evt, expected_evt);
993         i += 1;
994     }
995 }
996 #[test]
997 fn test_streaming_parser() {
998     assert_stream_equal(
999         r#"{ "foo":"bar", "array" : [0, 1, 2, 3, 4, 5], "idents":[null,true,false]}"#,
1000         vec![
1001             (ObjectStart, vec![]),
1002             (StringValue("bar".to_string()), vec![StackElement::Key("foo")]),
1003             (ArrayStart, vec![StackElement::Key("array")]),
1004             (U64Value(0), vec![StackElement::Key("array"), StackElement::Index(0)]),
1005             (U64Value(1), vec![StackElement::Key("array"), StackElement::Index(1)]),
1006             (U64Value(2), vec![StackElement::Key("array"), StackElement::Index(2)]),
1007             (U64Value(3), vec![StackElement::Key("array"), StackElement::Index(3)]),
1008             (U64Value(4), vec![StackElement::Key("array"), StackElement::Index(4)]),
1009             (U64Value(5), vec![StackElement::Key("array"), StackElement::Index(5)]),
1010             (ArrayEnd, vec![StackElement::Key("array")]),
1011             (ArrayStart, vec![StackElement::Key("idents")]),
1012             (NullValue, vec![StackElement::Key("idents"), StackElement::Index(0)]),
1013             (BooleanValue(true), vec![StackElement::Key("idents"), StackElement::Index(1)]),
1014             (BooleanValue(false), vec![StackElement::Key("idents"), StackElement::Index(2)]),
1015             (ArrayEnd, vec![StackElement::Key("idents")]),
1016             (ObjectEnd, vec![]),
1017         ],
1018     );
1019 }
1020 fn last_event(src: &str) -> JsonEvent {
1021     let mut parser = Parser::new(src.chars());
1022     let mut evt = NullValue;
1023     loop {
1024         evt = match parser.next() {
1025             Some(e) => e,
1026             None => return evt,
1027         }
1028     }
1029 }
1030
1031 #[test]
1032 fn test_read_object_streaming() {
1033     assert_eq!(last_event("{ "), Error(SyntaxError(EOFWhileParsingObject, 1, 3)));
1034     assert_eq!(last_event("{1"), Error(SyntaxError(KeyMustBeAString, 1, 2)));
1035     assert_eq!(last_event("{ \"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
1036     assert_eq!(last_event("{\"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 5)));
1037     assert_eq!(last_event("{\"a\" "), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
1038
1039     assert_eq!(last_event("{\"a\" 1"), Error(SyntaxError(ExpectedColon, 1, 6)));
1040     assert_eq!(last_event("{\"a\":"), Error(SyntaxError(EOFWhileParsingValue, 1, 6)));
1041     assert_eq!(last_event("{\"a\":1"), Error(SyntaxError(EOFWhileParsingObject, 1, 7)));
1042     assert_eq!(last_event("{\"a\":1 1"), Error(SyntaxError(InvalidSyntax, 1, 8)));
1043     assert_eq!(last_event("{\"a\":1,"), Error(SyntaxError(EOFWhileParsingObject, 1, 8)));
1044     assert_eq!(last_event("{\"a\":1,}"), Error(SyntaxError(TrailingComma, 1, 8)));
1045
1046     assert_stream_equal("{}", vec![(ObjectStart, vec![]), (ObjectEnd, vec![])]);
1047     assert_stream_equal(
1048         "{\"a\": 3}",
1049         vec![
1050             (ObjectStart, vec![]),
1051             (U64Value(3), vec![StackElement::Key("a")]),
1052             (ObjectEnd, vec![]),
1053         ],
1054     );
1055     assert_stream_equal(
1056         "{ \"a\": null, \"b\" : true }",
1057         vec![
1058             (ObjectStart, vec![]),
1059             (NullValue, vec![StackElement::Key("a")]),
1060             (BooleanValue(true), vec![StackElement::Key("b")]),
1061             (ObjectEnd, vec![]),
1062         ],
1063     );
1064     assert_stream_equal(
1065         "{\"a\" : 1.0 ,\"b\": [ true ]}",
1066         vec![
1067             (ObjectStart, vec![]),
1068             (F64Value(1.0), vec![StackElement::Key("a")]),
1069             (ArrayStart, vec![StackElement::Key("b")]),
1070             (BooleanValue(true), vec![StackElement::Key("b"), StackElement::Index(0)]),
1071             (ArrayEnd, vec![StackElement::Key("b")]),
1072             (ObjectEnd, vec![]),
1073         ],
1074     );
1075     assert_stream_equal(
1076         r#"{
1077             "a": 1.0,
1078             "b": [
1079                 true,
1080                 "foo\nbar",
1081                 { "c": {"d": null} }
1082             ]
1083         }"#,
1084         vec![
1085             (ObjectStart, vec![]),
1086             (F64Value(1.0), vec![StackElement::Key("a")]),
1087             (ArrayStart, vec![StackElement::Key("b")]),
1088             (BooleanValue(true), vec![StackElement::Key("b"), StackElement::Index(0)]),
1089             (
1090                 StringValue("foo\nbar".to_string()),
1091                 vec![StackElement::Key("b"), StackElement::Index(1)],
1092             ),
1093             (ObjectStart, vec![StackElement::Key("b"), StackElement::Index(2)]),
1094             (
1095                 ObjectStart,
1096                 vec![StackElement::Key("b"), StackElement::Index(2), StackElement::Key("c")],
1097             ),
1098             (
1099                 NullValue,
1100                 vec![
1101                     StackElement::Key("b"),
1102                     StackElement::Index(2),
1103                     StackElement::Key("c"),
1104                     StackElement::Key("d"),
1105                 ],
1106             ),
1107             (
1108                 ObjectEnd,
1109                 vec![StackElement::Key("b"), StackElement::Index(2), StackElement::Key("c")],
1110             ),
1111             (ObjectEnd, vec![StackElement::Key("b"), StackElement::Index(2)]),
1112             (ArrayEnd, vec![StackElement::Key("b")]),
1113             (ObjectEnd, vec![]),
1114         ],
1115     );
1116 }
1117 #[test]
1118 fn test_read_array_streaming() {
1119     assert_stream_equal("[]", vec![(ArrayStart, vec![]), (ArrayEnd, vec![])]);
1120     assert_stream_equal("[ ]", vec![(ArrayStart, vec![]), (ArrayEnd, vec![])]);
1121     assert_stream_equal(
1122         "[true]",
1123         vec![
1124             (ArrayStart, vec![]),
1125             (BooleanValue(true), vec![StackElement::Index(0)]),
1126             (ArrayEnd, vec![]),
1127         ],
1128     );
1129     assert_stream_equal(
1130         "[ false ]",
1131         vec![
1132             (ArrayStart, vec![]),
1133             (BooleanValue(false), vec![StackElement::Index(0)]),
1134             (ArrayEnd, vec![]),
1135         ],
1136     );
1137     assert_stream_equal(
1138         "[null]",
1139         vec![(ArrayStart, vec![]), (NullValue, vec![StackElement::Index(0)]), (ArrayEnd, vec![])],
1140     );
1141     assert_stream_equal(
1142         "[3, 1]",
1143         vec![
1144             (ArrayStart, vec![]),
1145             (U64Value(3), vec![StackElement::Index(0)]),
1146             (U64Value(1), vec![StackElement::Index(1)]),
1147             (ArrayEnd, vec![]),
1148         ],
1149     );
1150     assert_stream_equal(
1151         "\n[3, 2]\n",
1152         vec![
1153             (ArrayStart, vec![]),
1154             (U64Value(3), vec![StackElement::Index(0)]),
1155             (U64Value(2), vec![StackElement::Index(1)]),
1156             (ArrayEnd, vec![]),
1157         ],
1158     );
1159     assert_stream_equal(
1160         "[2, [4, 1]]",
1161         vec![
1162             (ArrayStart, vec![]),
1163             (U64Value(2), vec![StackElement::Index(0)]),
1164             (ArrayStart, vec![StackElement::Index(1)]),
1165             (U64Value(4), vec![StackElement::Index(1), StackElement::Index(0)]),
1166             (U64Value(1), vec![StackElement::Index(1), StackElement::Index(1)]),
1167             (ArrayEnd, vec![StackElement::Index(1)]),
1168             (ArrayEnd, vec![]),
1169         ],
1170     );
1171
1172     assert_eq!(last_event("["), Error(SyntaxError(EOFWhileParsingValue, 1, 2)));
1173
1174     assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
1175     assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
1176     assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
1177     assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
1178     assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
1179 }
1180 #[test]
1181 fn test_trailing_characters_streaming() {
1182     assert_eq!(last_event("nulla"), Error(SyntaxError(TrailingCharacters, 1, 5)));
1183     assert_eq!(last_event("truea"), Error(SyntaxError(TrailingCharacters, 1, 5)));
1184     assert_eq!(last_event("falsea"), Error(SyntaxError(TrailingCharacters, 1, 6)));
1185     assert_eq!(last_event("1a"), Error(SyntaxError(TrailingCharacters, 1, 2)));
1186     assert_eq!(last_event("[]a"), Error(SyntaxError(TrailingCharacters, 1, 3)));
1187     assert_eq!(last_event("{}a"), Error(SyntaxError(TrailingCharacters, 1, 3)));
1188 }
1189 #[test]
1190 fn test_read_identifiers_streaming() {
1191     assert_eq!(Parser::new("null".chars()).next(), Some(NullValue));
1192     assert_eq!(Parser::new("true".chars()).next(), Some(BooleanValue(true)));
1193     assert_eq!(Parser::new("false".chars()).next(), Some(BooleanValue(false)));
1194
1195     assert_eq!(last_event("n"), Error(SyntaxError(InvalidSyntax, 1, 2)));
1196     assert_eq!(last_event("nul"), Error(SyntaxError(InvalidSyntax, 1, 4)));
1197     assert_eq!(last_event("t"), Error(SyntaxError(InvalidSyntax, 1, 2)));
1198     assert_eq!(last_event("truz"), Error(SyntaxError(InvalidSyntax, 1, 4)));
1199     assert_eq!(last_event("f"), Error(SyntaxError(InvalidSyntax, 1, 2)));
1200     assert_eq!(last_event("faz"), Error(SyntaxError(InvalidSyntax, 1, 3)));
1201 }
1202
1203 #[test]
1204 fn test_to_json() {
1205     use json::ToJson;
1206     use std::collections::{BTreeMap, HashMap};
1207
1208     let array2 = Array(vec![U64(1), U64(2)]);
1209     let array3 = Array(vec![U64(1), U64(2), U64(3)]);
1210     let object = {
1211         let mut tree_map = BTreeMap::new();
1212         tree_map.insert("a".to_string(), U64(1));
1213         tree_map.insert("b".to_string(), U64(2));
1214         Object(tree_map)
1215     };
1216
1217     assert_eq!(array2.to_json(), array2);
1218     assert_eq!(object.to_json(), object);
1219     assert_eq!(3_isize.to_json(), I64(3));
1220     assert_eq!(4_i8.to_json(), I64(4));
1221     assert_eq!(5_i16.to_json(), I64(5));
1222     assert_eq!(6_i32.to_json(), I64(6));
1223     assert_eq!(7_i64.to_json(), I64(7));
1224     assert_eq!(8_usize.to_json(), U64(8));
1225     assert_eq!(9_u8.to_json(), U64(9));
1226     assert_eq!(10_u16.to_json(), U64(10));
1227     assert_eq!(11_u32.to_json(), U64(11));
1228     assert_eq!(12_u64.to_json(), U64(12));
1229     assert_eq!(13.0_f32.to_json(), F64(13.0_f64));
1230     assert_eq!(14.0_f64.to_json(), F64(14.0_f64));
1231     assert_eq!(().to_json(), Null);
1232     assert_eq!(f32::INFINITY.to_json(), Null);
1233     assert_eq!(f64::NAN.to_json(), Null);
1234     assert_eq!(true.to_json(), Boolean(true));
1235     assert_eq!(false.to_json(), Boolean(false));
1236     assert_eq!("abc".to_json(), String("abc".to_string()));
1237     assert_eq!("abc".to_string().to_json(), String("abc".to_string()));
1238     assert_eq!((1_usize, 2_usize).to_json(), array2);
1239     assert_eq!((1_usize, 2_usize, 3_usize).to_json(), array3);
1240     assert_eq!([1_usize, 2_usize].to_json(), array2);
1241     assert_eq!((&[1_usize, 2_usize, 3_usize]).to_json(), array3);
1242     assert_eq!((vec![1_usize, 2_usize]).to_json(), array2);
1243     assert_eq!(vec![1_usize, 2_usize, 3_usize].to_json(), array3);
1244     let mut tree_map = BTreeMap::new();
1245     tree_map.insert("a".to_string(), 1 as usize);
1246     tree_map.insert("b".to_string(), 2);
1247     assert_eq!(tree_map.to_json(), object);
1248     let mut hash_map = HashMap::new();
1249     hash_map.insert("a".to_string(), 1 as usize);
1250     hash_map.insert("b".to_string(), 2);
1251     assert_eq!(hash_map.to_json(), object);
1252     assert_eq!(Some(15).to_json(), I64(15));
1253     assert_eq!(Some(15 as usize).to_json(), U64(15));
1254     assert_eq!(None::<isize>.to_json(), Null);
1255 }
1256
1257 #[test]
1258 fn test_encode_hashmap_with_arbitrary_key() {
1259     use std::collections::HashMap;
1260     #[derive(PartialEq, Eq, Hash, RustcEncodable)]
1261     struct ArbitraryType(usize);
1262     let mut hm: HashMap<ArbitraryType, bool> = HashMap::new();
1263     hm.insert(ArbitraryType(1), true);
1264     let mut mem_buf = string::String::new();
1265     let mut encoder = Encoder::new(&mut mem_buf);
1266     let result = hm.encode(&mut encoder);
1267     match result.unwrap_err() {
1268         EncoderError::BadHashmapKey => (),
1269         _ => panic!("expected bad hash map key"),
1270     }
1271 }