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