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