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