]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_serialize/tests/json.rs
Remove support for JSON deserialization to Rust
[rust.git] / compiler / rustc_serialize / tests / json.rs
1 #![allow(rustc::internal)]
2
3 use json::ErrorCode::*;
4 use json::Json::*;
5 use json::JsonEvent::*;
6 use json::ParserError::*;
7 use json::{from_str, Encoder, EncoderError, Json, JsonEvent, Parser, StackElement};
8 use rustc_macros::Encodable;
9 use rustc_serialize::json;
10 use rustc_serialize::Encodable;
11
12 use std::collections::BTreeMap;
13 use std::io::prelude::*;
14 use std::string;
15 use Animal::*;
16
17 #[derive(Eq, PartialEq, Debug)]
18 struct OptionData {
19     opt: Option<usize>,
20 }
21
22 #[derive(PartialEq, Encodable, Debug)]
23 enum Animal {
24     Dog,
25     Frog(string::String, isize),
26 }
27
28 #[derive(PartialEq, Encodable, Debug)]
29 struct Inner {
30     a: (),
31     b: usize,
32     c: Vec<string::String>,
33 }
34
35 #[derive(PartialEq, Encodable, Debug)]
36 struct Outer {
37     inner: Vec<Inner>,
38 }
39
40 fn mk_object(items: &[(string::String, Json)]) -> Json {
41     let mut d = BTreeMap::new();
42
43     for item in items {
44         match *item {
45             (ref key, ref value) => {
46                 d.insert((*key).clone(), (*value).clone());
47             }
48         }
49     }
50
51     Object(d)
52 }
53
54 #[test]
55 fn test_from_str_trait() {
56     let s = "null";
57     assert!(s.parse::<Json>().unwrap() == s.parse().unwrap());
58 }
59
60 #[test]
61 fn test_write_null() {
62     assert_eq!(Null.to_string(), "null");
63     assert_eq!(Null.pretty().to_string(), "null");
64 }
65
66 #[test]
67 fn test_write_i64() {
68     assert_eq!(U64(0).to_string(), "0");
69     assert_eq!(U64(0).pretty().to_string(), "0");
70
71     assert_eq!(U64(1234).to_string(), "1234");
72     assert_eq!(U64(1234).pretty().to_string(), "1234");
73
74     assert_eq!(I64(-5678).to_string(), "-5678");
75     assert_eq!(I64(-5678).pretty().to_string(), "-5678");
76
77     assert_eq!(U64(7650007200025252000).to_string(), "7650007200025252000");
78     assert_eq!(U64(7650007200025252000).pretty().to_string(), "7650007200025252000");
79 }
80
81 #[test]
82 fn test_write_f64() {
83     assert_eq!(F64(3.0).to_string(), "3.0");
84     assert_eq!(F64(3.0).pretty().to_string(), "3.0");
85
86     assert_eq!(F64(3.1).to_string(), "3.1");
87     assert_eq!(F64(3.1).pretty().to_string(), "3.1");
88
89     assert_eq!(F64(-1.5).to_string(), "-1.5");
90     assert_eq!(F64(-1.5).pretty().to_string(), "-1.5");
91
92     assert_eq!(F64(0.5).to_string(), "0.5");
93     assert_eq!(F64(0.5).pretty().to_string(), "0.5");
94
95     assert_eq!(F64(f64::NAN).to_string(), "null");
96     assert_eq!(F64(f64::NAN).pretty().to_string(), "null");
97
98     assert_eq!(F64(f64::INFINITY).to_string(), "null");
99     assert_eq!(F64(f64::INFINITY).pretty().to_string(), "null");
100
101     assert_eq!(F64(f64::NEG_INFINITY).to_string(), "null");
102     assert_eq!(F64(f64::NEG_INFINITY).pretty().to_string(), "null");
103 }
104
105 #[test]
106 fn test_write_str() {
107     assert_eq!(String("".to_string()).to_string(), "\"\"");
108     assert_eq!(String("".to_string()).pretty().to_string(), "\"\"");
109
110     assert_eq!(String("homura".to_string()).to_string(), "\"homura\"");
111     assert_eq!(String("madoka".to_string()).pretty().to_string(), "\"madoka\"");
112 }
113
114 #[test]
115 fn test_write_bool() {
116     assert_eq!(Boolean(true).to_string(), "true");
117     assert_eq!(Boolean(true).pretty().to_string(), "true");
118
119     assert_eq!(Boolean(false).to_string(), "false");
120     assert_eq!(Boolean(false).pretty().to_string(), "false");
121 }
122
123 #[test]
124 fn test_write_array() {
125     assert_eq!(Array(vec![]).to_string(), "[]");
126     assert_eq!(Array(vec![]).pretty().to_string(), "[]");
127
128     assert_eq!(Array(vec![Boolean(true)]).to_string(), "[true]");
129     assert_eq!(
130         Array(vec![Boolean(true)]).pretty().to_string(),
131         "\
132         [\n  \
133             true\n\
134         ]"
135     );
136
137     let long_test_array =
138         Array(vec![Boolean(false), Null, Array(vec![String("foo\nbar".to_string()), F64(3.5)])]);
139
140     assert_eq!(long_test_array.to_string(), "[false,null,[\"foo\\nbar\",3.5]]");
141     assert_eq!(
142         long_test_array.pretty().to_string(),
143         "\
144         [\n  \
145             false,\n  \
146             null,\n  \
147             [\n    \
148                 \"foo\\nbar\",\n    \
149                 3.5\n  \
150             ]\n\
151         ]"
152     );
153 }
154
155 #[test]
156 fn test_write_object() {
157     assert_eq!(mk_object(&[]).to_string(), "{}");
158     assert_eq!(mk_object(&[]).pretty().to_string(), "{}");
159
160     assert_eq!(mk_object(&[("a".to_string(), Boolean(true))]).to_string(), "{\"a\":true}");
161     assert_eq!(
162         mk_object(&[("a".to_string(), Boolean(true))]).pretty().to_string(),
163         "\
164         {\n  \
165             \"a\": true\n\
166         }"
167     );
168
169     let complex_obj = mk_object(&[(
170         "b".to_string(),
171         Array(vec![
172             mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
173             mk_object(&[("d".to_string(), String("".to_string()))]),
174         ]),
175     )]);
176
177     assert_eq!(
178         complex_obj.to_string(),
179         "{\
180             \"b\":[\
181                 {\"c\":\"\\f\\r\"},\
182                 {\"d\":\"\"}\
183             ]\
184         }"
185     );
186     assert_eq!(
187         complex_obj.pretty().to_string(),
188         "\
189         {\n  \
190             \"b\": [\n    \
191                 {\n      \
192                     \"c\": \"\\f\\r\"\n    \
193                 },\n    \
194                 {\n      \
195                     \"d\": \"\"\n    \
196                 }\n  \
197             ]\n\
198         }"
199     );
200
201     let a = mk_object(&[
202         ("a".to_string(), Boolean(true)),
203         (
204             "b".to_string(),
205             Array(vec![
206                 mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
207                 mk_object(&[("d".to_string(), String("".to_string()))]),
208             ]),
209         ),
210     ]);
211
212     // We can't compare the strings directly because the object fields be
213     // printed in a different order.
214     assert_eq!(a.clone(), a.to_string().parse().unwrap());
215     assert_eq!(a.clone(), a.pretty().to_string().parse().unwrap());
216 }
217
218 #[test]
219 fn test_write_enum() {
220     let animal = Dog;
221     assert_eq!(json::as_json(&animal).to_string(), "\"Dog\"");
222     assert_eq!(json::as_pretty_json(&animal).to_string(), "\"Dog\"");
223
224     let animal = Frog("Henry".to_string(), 349);
225     assert_eq!(
226         json::as_json(&animal).to_string(),
227         "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}"
228     );
229     assert_eq!(
230         json::as_pretty_json(&animal).to_string(),
231         "{\n  \
232            \"variant\": \"Frog\",\n  \
233            \"fields\": [\n    \
234              \"Henry\",\n    \
235              349\n  \
236            ]\n\
237          }"
238     );
239 }
240
241 macro_rules! check_encoder_for_simple {
242     ($value:expr, $expected:expr) => {{
243         let s = json::as_json(&$value).to_string();
244         assert_eq!(s, $expected);
245
246         let s = json::as_pretty_json(&$value).to_string();
247         assert_eq!(s, $expected);
248     }};
249 }
250
251 #[test]
252 fn test_write_some() {
253     check_encoder_for_simple!(Some("jodhpurs".to_string()), "\"jodhpurs\"");
254 }
255
256 #[test]
257 fn test_write_none() {
258     check_encoder_for_simple!(None::<string::String>, "null");
259 }
260
261 #[test]
262 fn test_write_char() {
263     check_encoder_for_simple!('a', "\"a\"");
264     check_encoder_for_simple!('\t', "\"\\t\"");
265     check_encoder_for_simple!('\u{0000}', "\"\\u0000\"");
266     check_encoder_for_simple!('\u{001b}', "\"\\u001b\"");
267     check_encoder_for_simple!('\u{007f}', "\"\\u007f\"");
268     check_encoder_for_simple!('\u{00a0}', "\"\u{00a0}\"");
269     check_encoder_for_simple!('\u{abcd}', "\"\u{abcd}\"");
270     check_encoder_for_simple!('\u{10ffff}', "\"\u{10ffff}\"");
271 }
272
273 #[test]
274 fn test_trailing_characters() {
275     assert_eq!(from_str("nulla"), Err(SyntaxError(TrailingCharacters, 1, 5)));
276     assert_eq!(from_str("truea"), Err(SyntaxError(TrailingCharacters, 1, 5)));
277     assert_eq!(from_str("falsea"), Err(SyntaxError(TrailingCharacters, 1, 6)));
278     assert_eq!(from_str("1a"), Err(SyntaxError(TrailingCharacters, 1, 2)));
279     assert_eq!(from_str("[]a"), Err(SyntaxError(TrailingCharacters, 1, 3)));
280     assert_eq!(from_str("{}a"), Err(SyntaxError(TrailingCharacters, 1, 3)));
281 }
282
283 #[test]
284 fn test_read_identifiers() {
285     assert_eq!(from_str("n"), Err(SyntaxError(InvalidSyntax, 1, 2)));
286     assert_eq!(from_str("nul"), Err(SyntaxError(InvalidSyntax, 1, 4)));
287     assert_eq!(from_str("t"), Err(SyntaxError(InvalidSyntax, 1, 2)));
288     assert_eq!(from_str("truz"), Err(SyntaxError(InvalidSyntax, 1, 4)));
289     assert_eq!(from_str("f"), Err(SyntaxError(InvalidSyntax, 1, 2)));
290     assert_eq!(from_str("faz"), Err(SyntaxError(InvalidSyntax, 1, 3)));
291
292     assert_eq!(from_str("null"), Ok(Null));
293     assert_eq!(from_str("true"), Ok(Boolean(true)));
294     assert_eq!(from_str("false"), Ok(Boolean(false)));
295     assert_eq!(from_str(" null "), Ok(Null));
296     assert_eq!(from_str(" true "), Ok(Boolean(true)));
297     assert_eq!(from_str(" false "), Ok(Boolean(false)));
298 }
299
300 #[test]
301 fn test_read_number() {
302     assert_eq!(from_str("+"), Err(SyntaxError(InvalidSyntax, 1, 1)));
303     assert_eq!(from_str("."), Err(SyntaxError(InvalidSyntax, 1, 1)));
304     assert_eq!(from_str("NaN"), Err(SyntaxError(InvalidSyntax, 1, 1)));
305     assert_eq!(from_str("-"), Err(SyntaxError(InvalidNumber, 1, 2)));
306     assert_eq!(from_str("00"), Err(SyntaxError(InvalidNumber, 1, 2)));
307     assert_eq!(from_str("1."), Err(SyntaxError(InvalidNumber, 1, 3)));
308     assert_eq!(from_str("1e"), Err(SyntaxError(InvalidNumber, 1, 3)));
309     assert_eq!(from_str("1e+"), Err(SyntaxError(InvalidNumber, 1, 4)));
310
311     assert_eq!(from_str("18446744073709551616"), Err(SyntaxError(InvalidNumber, 1, 20)));
312     assert_eq!(from_str("-9223372036854775809"), Err(SyntaxError(InvalidNumber, 1, 21)));
313
314     assert_eq!(from_str("3"), Ok(U64(3)));
315     assert_eq!(from_str("3.1"), Ok(F64(3.1)));
316     assert_eq!(from_str("-1.2"), Ok(F64(-1.2)));
317     assert_eq!(from_str("0.4"), Ok(F64(0.4)));
318     assert_eq!(from_str("0.4e5"), Ok(F64(0.4e5)));
319     assert_eq!(from_str("0.4e+15"), Ok(F64(0.4e15)));
320     assert_eq!(from_str("0.4e-01"), Ok(F64(0.4e-01)));
321     assert_eq!(from_str(" 3 "), Ok(U64(3)));
322
323     assert_eq!(from_str("-9223372036854775808"), Ok(I64(i64::MIN)));
324     assert_eq!(from_str("9223372036854775807"), Ok(U64(i64::MAX as u64)));
325     assert_eq!(from_str("18446744073709551615"), Ok(U64(u64::MAX)));
326 }
327
328 #[test]
329 fn test_read_str() {
330     assert_eq!(from_str("\""), Err(SyntaxError(EOFWhileParsingString, 1, 2)));
331     assert_eq!(from_str("\"lol"), Err(SyntaxError(EOFWhileParsingString, 1, 5)));
332
333     assert_eq!(from_str("\"\""), Ok(String("".to_string())));
334     assert_eq!(from_str("\"foo\""), Ok(String("foo".to_string())));
335     assert_eq!(from_str("\"\\\"\""), Ok(String("\"".to_string())));
336     assert_eq!(from_str("\"\\b\""), Ok(String("\x08".to_string())));
337     assert_eq!(from_str("\"\\n\""), Ok(String("\n".to_string())));
338     assert_eq!(from_str("\"\\r\""), Ok(String("\r".to_string())));
339     assert_eq!(from_str("\"\\t\""), Ok(String("\t".to_string())));
340     assert_eq!(from_str(" \"foo\" "), Ok(String("foo".to_string())));
341     assert_eq!(from_str("\"\\u12ab\""), Ok(String("\u{12ab}".to_string())));
342     assert_eq!(from_str("\"\\uAB12\""), Ok(String("\u{AB12}".to_string())));
343 }
344
345 #[test]
346 fn test_read_array() {
347     assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
348     assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
349     assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
350     assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
351     assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
352
353     assert_eq!(from_str("[]"), Ok(Array(vec![])));
354     assert_eq!(from_str("[ ]"), Ok(Array(vec![])));
355     assert_eq!(from_str("[true]"), Ok(Array(vec![Boolean(true)])));
356     assert_eq!(from_str("[ false ]"), Ok(Array(vec![Boolean(false)])));
357     assert_eq!(from_str("[null]"), Ok(Array(vec![Null])));
358     assert_eq!(from_str("[3, 1]"), Ok(Array(vec![U64(3), U64(1)])));
359     assert_eq!(from_str("\n[3, 2]\n"), Ok(Array(vec![U64(3), U64(2)])));
360     assert_eq!(from_str("[2, [4, 1]]"), Ok(Array(vec![U64(2), Array(vec![U64(4), U64(1)])])));
361 }
362
363 #[test]
364 fn test_read_object() {
365     assert_eq!(from_str("{"), Err(SyntaxError(EOFWhileParsingObject, 1, 2)));
366     assert_eq!(from_str("{ "), Err(SyntaxError(EOFWhileParsingObject, 1, 3)));
367     assert_eq!(from_str("{1"), Err(SyntaxError(KeyMustBeAString, 1, 2)));
368     assert_eq!(from_str("{ \"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
369     assert_eq!(from_str("{\"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 5)));
370     assert_eq!(from_str("{\"a\" "), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
371
372     assert_eq!(from_str("{\"a\" 1"), Err(SyntaxError(ExpectedColon, 1, 6)));
373     assert_eq!(from_str("{\"a\":"), Err(SyntaxError(EOFWhileParsingValue, 1, 6)));
374     assert_eq!(from_str("{\"a\":1"), Err(SyntaxError(EOFWhileParsingObject, 1, 7)));
375     assert_eq!(from_str("{\"a\":1 1"), Err(SyntaxError(InvalidSyntax, 1, 8)));
376     assert_eq!(from_str("{\"a\":1,"), Err(SyntaxError(EOFWhileParsingObject, 1, 8)));
377
378     assert_eq!(from_str("{}").unwrap(), mk_object(&[]));
379     assert_eq!(from_str("{\"a\": 3}").unwrap(), mk_object(&[("a".to_string(), U64(3))]));
380
381     assert_eq!(
382         from_str("{ \"a\": null, \"b\" : true }").unwrap(),
383         mk_object(&[("a".to_string(), Null), ("b".to_string(), Boolean(true))])
384     );
385     assert_eq!(
386         from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(),
387         mk_object(&[("a".to_string(), Null), ("b".to_string(), Boolean(true))])
388     );
389     assert_eq!(
390         from_str("{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(),
391         mk_object(&[("a".to_string(), F64(1.0)), ("b".to_string(), Array(vec![Boolean(true)]))])
392     );
393     assert_eq!(
394         from_str(
395             "{\
396                         \"a\": 1.0, \
397                         \"b\": [\
398                             true,\
399                             \"foo\\nbar\", \
400                             { \"c\": {\"d\": null} } \
401                         ]\
402                     }"
403         )
404         .unwrap(),
405         mk_object(&[
406             ("a".to_string(), F64(1.0)),
407             (
408                 "b".to_string(),
409                 Array(vec![
410                     Boolean(true),
411                     String("foo\nbar".to_string()),
412                     mk_object(&[("c".to_string(), mk_object(&[("d".to_string(), Null)]))])
413                 ])
414             )
415         ])
416     );
417 }
418
419 #[test]
420 fn test_multiline_errors() {
421     assert_eq!(from_str("{\n  \"foo\":\n \"bar\""), Err(SyntaxError(EOFWhileParsingObject, 3, 8)));
422 }
423
424 #[test]
425 fn test_find() {
426     let json_value = from_str("{\"dog\" : \"cat\"}").unwrap();
427     let found_str = json_value.find("dog");
428     assert!(found_str.unwrap().as_string().unwrap() == "cat");
429 }
430
431 #[test]
432 fn test_find_path() {
433     let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
434     let found_str = json_value.find_path(&["dog", "cat", "mouse"]);
435     assert!(found_str.unwrap().as_string().unwrap() == "cheese");
436 }
437
438 #[test]
439 fn test_search() {
440     let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
441     let found_str = json_value.search("mouse").and_then(|j| j.as_string());
442     assert!(found_str.unwrap() == "cheese");
443 }
444
445 #[test]
446 fn test_index() {
447     let json_value = from_str("{\"animals\":[\"dog\",\"cat\",\"mouse\"]}").unwrap();
448     let ref array = json_value["animals"];
449     assert_eq!(array[0].as_string().unwrap(), "dog");
450     assert_eq!(array[1].as_string().unwrap(), "cat");
451     assert_eq!(array[2].as_string().unwrap(), "mouse");
452 }
453
454 #[test]
455 fn test_is_object() {
456     let json_value = from_str("{}").unwrap();
457     assert!(json_value.is_object());
458 }
459
460 #[test]
461 fn test_as_object() {
462     let json_value = from_str("{}").unwrap();
463     let json_object = json_value.as_object();
464     assert!(json_object.is_some());
465 }
466
467 #[test]
468 fn test_is_array() {
469     let json_value = from_str("[1, 2, 3]").unwrap();
470     assert!(json_value.is_array());
471 }
472
473 #[test]
474 fn test_as_array() {
475     let json_value = from_str("[1, 2, 3]").unwrap();
476     let json_array = json_value.as_array();
477     let expected_length = 3;
478     assert!(json_array.is_some() && json_array.unwrap().len() == expected_length);
479 }
480
481 #[test]
482 fn test_is_string() {
483     let json_value = from_str("\"dog\"").unwrap();
484     assert!(json_value.is_string());
485 }
486
487 #[test]
488 fn test_as_string() {
489     let json_value = from_str("\"dog\"").unwrap();
490     let json_str = json_value.as_string();
491     let expected_str = "dog";
492     assert_eq!(json_str, Some(expected_str));
493 }
494
495 #[test]
496 fn test_is_number() {
497     let json_value = from_str("12").unwrap();
498     assert!(json_value.is_number());
499 }
500
501 #[test]
502 fn test_is_i64() {
503     let json_value = from_str("-12").unwrap();
504     assert!(json_value.is_i64());
505
506     let json_value = from_str("12").unwrap();
507     assert!(!json_value.is_i64());
508
509     let json_value = from_str("12.0").unwrap();
510     assert!(!json_value.is_i64());
511 }
512
513 #[test]
514 fn test_is_u64() {
515     let json_value = from_str("12").unwrap();
516     assert!(json_value.is_u64());
517
518     let json_value = from_str("-12").unwrap();
519     assert!(!json_value.is_u64());
520
521     let json_value = from_str("12.0").unwrap();
522     assert!(!json_value.is_u64());
523 }
524
525 #[test]
526 fn test_is_f64() {
527     let json_value = from_str("12").unwrap();
528     assert!(!json_value.is_f64());
529
530     let json_value = from_str("-12").unwrap();
531     assert!(!json_value.is_f64());
532
533     let json_value = from_str("12.0").unwrap();
534     assert!(json_value.is_f64());
535
536     let json_value = from_str("-12.0").unwrap();
537     assert!(json_value.is_f64());
538 }
539
540 #[test]
541 fn test_as_i64() {
542     let json_value = from_str("-12").unwrap();
543     let json_num = json_value.as_i64();
544     assert_eq!(json_num, Some(-12));
545 }
546
547 #[test]
548 fn test_as_u64() {
549     let json_value = from_str("12").unwrap();
550     let json_num = json_value.as_u64();
551     assert_eq!(json_num, Some(12));
552 }
553
554 #[test]
555 fn test_as_f64() {
556     let json_value = from_str("12.0").unwrap();
557     let json_num = json_value.as_f64();
558     assert_eq!(json_num, Some(12f64));
559 }
560
561 #[test]
562 fn test_is_boolean() {
563     let json_value = from_str("false").unwrap();
564     assert!(json_value.is_boolean());
565 }
566
567 #[test]
568 fn test_as_boolean() {
569     let json_value = from_str("false").unwrap();
570     let json_bool = json_value.as_boolean();
571     let expected_bool = false;
572     assert!(json_bool.is_some() && json_bool.unwrap() == expected_bool);
573 }
574
575 #[test]
576 fn test_is_null() {
577     let json_value = from_str("null").unwrap();
578     assert!(json_value.is_null());
579 }
580
581 #[test]
582 fn test_as_null() {
583     let json_value = from_str("null").unwrap();
584     let json_null = json_value.as_null();
585     let expected_null = ();
586     assert!(json_null.is_some() && json_null.unwrap() == expected_null);
587 }
588
589 #[test]
590 fn test_encode_hashmap_with_numeric_key() {
591     use std::collections::HashMap;
592     use std::str::from_utf8;
593     let mut hm: HashMap<usize, bool> = HashMap::new();
594     hm.insert(1, true);
595     let mut mem_buf = Vec::new();
596     write!(&mut mem_buf, "{}", json::as_pretty_json(&hm)).unwrap();
597     let json_str = from_utf8(&mem_buf[..]).unwrap();
598     match from_str(json_str) {
599         Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
600         _ => {} // it parsed and we are good to go
601     }
602 }
603
604 #[test]
605 fn test_prettyencode_hashmap_with_numeric_key() {
606     use std::collections::HashMap;
607     use std::str::from_utf8;
608     let mut hm: HashMap<usize, bool> = HashMap::new();
609     hm.insert(1, true);
610     let mut mem_buf = Vec::new();
611     write!(&mut mem_buf, "{}", json::as_pretty_json(&hm)).unwrap();
612     let json_str = from_utf8(&mem_buf[..]).unwrap();
613     match from_str(json_str) {
614         Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
615         _ => {} // it parsed and we are good to go
616     }
617 }
618
619 #[test]
620 fn test_prettyencoder_indent_level_param() {
621     use std::collections::BTreeMap;
622     use std::str::from_utf8;
623
624     let mut tree = BTreeMap::new();
625
626     tree.insert("hello".to_string(), String("guten tag".to_string()));
627     tree.insert("goodbye".to_string(), String("sayonara".to_string()));
628
629     let json = Array(
630         // The following layout below should look a lot like
631         // the pretty-printed JSON (indent * x)
632         vec![
633             // 0x
634             String("greetings".to_string()), // 1x
635             Object(tree),                    // 1x + 2x + 2x + 1x
636         ], // 0x
637            // End JSON array (7 lines)
638     );
639
640     // Helper function for counting indents
641     fn indents(source: &str) -> usize {
642         let trimmed = source.trim_start_matches(' ');
643         source.len() - trimmed.len()
644     }
645
646     // Test up to 4 spaces of indents (more?)
647     for i in 0..4 {
648         let mut writer = Vec::new();
649         write!(&mut writer, "{}", json::as_pretty_json(&json).indent(i)).unwrap();
650
651         let printed = from_utf8(&writer[..]).unwrap();
652
653         // Check for indents at each line
654         let lines: Vec<&str> = printed.lines().collect();
655         assert_eq!(lines.len(), 7); // JSON should be 7 lines
656
657         assert_eq!(indents(lines[0]), 0 * i); // [
658         assert_eq!(indents(lines[1]), 1 * i); //   "greetings",
659         assert_eq!(indents(lines[2]), 1 * i); //   {
660         assert_eq!(indents(lines[3]), 2 * i); //     "hello": "guten tag",
661         assert_eq!(indents(lines[4]), 2 * i); //     "goodbye": "sayonara"
662         assert_eq!(indents(lines[5]), 1 * i); //   },
663         assert_eq!(indents(lines[6]), 0 * i); // ]
664
665         // Finally, test that the pretty-printed JSON is valid
666         from_str(printed).ok().expect("Pretty-printed JSON is invalid!");
667     }
668 }
669
670 #[test]
671 fn test_hashmap_with_enum_key() {
672     use std::collections::HashMap;
673     #[derive(Encodable, Eq, Hash, PartialEq, Debug)]
674     enum Enum {
675         Foo,
676         #[allow(dead_code)]
677         Bar,
678     }
679     let mut map = HashMap::new();
680     map.insert(Enum::Foo, 0);
681     let result = json::encode(&map).unwrap();
682     assert_eq!(&result[..], r#"{"Foo":0}"#);
683 }
684
685 fn assert_stream_equal(src: &str, expected: Vec<(JsonEvent, Vec<StackElement<'_>>)>) {
686     let mut parser = Parser::new(src.chars());
687     let mut i = 0;
688     loop {
689         let evt = match parser.next() {
690             Some(e) => e,
691             None => {
692                 break;
693             }
694         };
695         let (ref expected_evt, ref expected_stack) = expected[i];
696         if !parser.stack().is_equal_to(expected_stack) {
697             panic!("Parser stack is not equal to {:?}", expected_stack);
698         }
699         assert_eq!(&evt, expected_evt);
700         i += 1;
701     }
702 }
703 #[test]
704 fn test_streaming_parser() {
705     assert_stream_equal(
706         r#"{ "foo":"bar", "array" : [0, 1, 2, 3, 4, 5], "idents":[null,true,false]}"#,
707         vec![
708             (ObjectStart, vec![]),
709             (StringValue("bar".to_string()), vec![StackElement::Key("foo")]),
710             (ArrayStart, vec![StackElement::Key("array")]),
711             (U64Value(0), vec![StackElement::Key("array"), StackElement::Index(0)]),
712             (U64Value(1), vec![StackElement::Key("array"), StackElement::Index(1)]),
713             (U64Value(2), vec![StackElement::Key("array"), StackElement::Index(2)]),
714             (U64Value(3), vec![StackElement::Key("array"), StackElement::Index(3)]),
715             (U64Value(4), vec![StackElement::Key("array"), StackElement::Index(4)]),
716             (U64Value(5), vec![StackElement::Key("array"), StackElement::Index(5)]),
717             (ArrayEnd, vec![StackElement::Key("array")]),
718             (ArrayStart, vec![StackElement::Key("idents")]),
719             (NullValue, vec![StackElement::Key("idents"), StackElement::Index(0)]),
720             (BooleanValue(true), vec![StackElement::Key("idents"), StackElement::Index(1)]),
721             (BooleanValue(false), vec![StackElement::Key("idents"), StackElement::Index(2)]),
722             (ArrayEnd, vec![StackElement::Key("idents")]),
723             (ObjectEnd, vec![]),
724         ],
725     );
726 }
727 fn last_event(src: &str) -> JsonEvent {
728     let mut parser = Parser::new(src.chars());
729     let mut evt = NullValue;
730     loop {
731         evt = match parser.next() {
732             Some(e) => e,
733             None => return evt,
734         }
735     }
736 }
737
738 #[test]
739 fn test_read_object_streaming() {
740     assert_eq!(last_event("{ "), Error(SyntaxError(EOFWhileParsingObject, 1, 3)));
741     assert_eq!(last_event("{1"), Error(SyntaxError(KeyMustBeAString, 1, 2)));
742     assert_eq!(last_event("{ \"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
743     assert_eq!(last_event("{\"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 5)));
744     assert_eq!(last_event("{\"a\" "), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
745
746     assert_eq!(last_event("{\"a\" 1"), Error(SyntaxError(ExpectedColon, 1, 6)));
747     assert_eq!(last_event("{\"a\":"), Error(SyntaxError(EOFWhileParsingValue, 1, 6)));
748     assert_eq!(last_event("{\"a\":1"), Error(SyntaxError(EOFWhileParsingObject, 1, 7)));
749     assert_eq!(last_event("{\"a\":1 1"), Error(SyntaxError(InvalidSyntax, 1, 8)));
750     assert_eq!(last_event("{\"a\":1,"), Error(SyntaxError(EOFWhileParsingObject, 1, 8)));
751     assert_eq!(last_event("{\"a\":1,}"), Error(SyntaxError(TrailingComma, 1, 8)));
752
753     assert_stream_equal("{}", vec![(ObjectStart, vec![]), (ObjectEnd, vec![])]);
754     assert_stream_equal(
755         "{\"a\": 3}",
756         vec![
757             (ObjectStart, vec![]),
758             (U64Value(3), vec![StackElement::Key("a")]),
759             (ObjectEnd, vec![]),
760         ],
761     );
762     assert_stream_equal(
763         "{ \"a\": null, \"b\" : true }",
764         vec![
765             (ObjectStart, vec![]),
766             (NullValue, vec![StackElement::Key("a")]),
767             (BooleanValue(true), vec![StackElement::Key("b")]),
768             (ObjectEnd, vec![]),
769         ],
770     );
771     assert_stream_equal(
772         "{\"a\" : 1.0 ,\"b\": [ true ]}",
773         vec![
774             (ObjectStart, vec![]),
775             (F64Value(1.0), vec![StackElement::Key("a")]),
776             (ArrayStart, vec![StackElement::Key("b")]),
777             (BooleanValue(true), vec![StackElement::Key("b"), StackElement::Index(0)]),
778             (ArrayEnd, vec![StackElement::Key("b")]),
779             (ObjectEnd, vec![]),
780         ],
781     );
782     assert_stream_equal(
783         r#"{
784             "a": 1.0,
785             "b": [
786                 true,
787                 "foo\nbar",
788                 { "c": {"d": null} }
789             ]
790         }"#,
791         vec![
792             (ObjectStart, vec![]),
793             (F64Value(1.0), vec![StackElement::Key("a")]),
794             (ArrayStart, vec![StackElement::Key("b")]),
795             (BooleanValue(true), vec![StackElement::Key("b"), StackElement::Index(0)]),
796             (
797                 StringValue("foo\nbar".to_string()),
798                 vec![StackElement::Key("b"), StackElement::Index(1)],
799             ),
800             (ObjectStart, vec![StackElement::Key("b"), StackElement::Index(2)]),
801             (
802                 ObjectStart,
803                 vec![StackElement::Key("b"), StackElement::Index(2), StackElement::Key("c")],
804             ),
805             (
806                 NullValue,
807                 vec![
808                     StackElement::Key("b"),
809                     StackElement::Index(2),
810                     StackElement::Key("c"),
811                     StackElement::Key("d"),
812                 ],
813             ),
814             (
815                 ObjectEnd,
816                 vec![StackElement::Key("b"), StackElement::Index(2), StackElement::Key("c")],
817             ),
818             (ObjectEnd, vec![StackElement::Key("b"), StackElement::Index(2)]),
819             (ArrayEnd, vec![StackElement::Key("b")]),
820             (ObjectEnd, vec![]),
821         ],
822     );
823 }
824 #[test]
825 fn test_read_array_streaming() {
826     assert_stream_equal("[]", vec![(ArrayStart, vec![]), (ArrayEnd, vec![])]);
827     assert_stream_equal("[ ]", vec![(ArrayStart, vec![]), (ArrayEnd, vec![])]);
828     assert_stream_equal(
829         "[true]",
830         vec![
831             (ArrayStart, vec![]),
832             (BooleanValue(true), vec![StackElement::Index(0)]),
833             (ArrayEnd, vec![]),
834         ],
835     );
836     assert_stream_equal(
837         "[ false ]",
838         vec![
839             (ArrayStart, vec![]),
840             (BooleanValue(false), vec![StackElement::Index(0)]),
841             (ArrayEnd, vec![]),
842         ],
843     );
844     assert_stream_equal(
845         "[null]",
846         vec![(ArrayStart, vec![]), (NullValue, vec![StackElement::Index(0)]), (ArrayEnd, vec![])],
847     );
848     assert_stream_equal(
849         "[3, 1]",
850         vec![
851             (ArrayStart, vec![]),
852             (U64Value(3), vec![StackElement::Index(0)]),
853             (U64Value(1), vec![StackElement::Index(1)]),
854             (ArrayEnd, vec![]),
855         ],
856     );
857     assert_stream_equal(
858         "\n[3, 2]\n",
859         vec![
860             (ArrayStart, vec![]),
861             (U64Value(3), vec![StackElement::Index(0)]),
862             (U64Value(2), vec![StackElement::Index(1)]),
863             (ArrayEnd, vec![]),
864         ],
865     );
866     assert_stream_equal(
867         "[2, [4, 1]]",
868         vec![
869             (ArrayStart, vec![]),
870             (U64Value(2), vec![StackElement::Index(0)]),
871             (ArrayStart, vec![StackElement::Index(1)]),
872             (U64Value(4), vec![StackElement::Index(1), StackElement::Index(0)]),
873             (U64Value(1), vec![StackElement::Index(1), StackElement::Index(1)]),
874             (ArrayEnd, vec![StackElement::Index(1)]),
875             (ArrayEnd, vec![]),
876         ],
877     );
878
879     assert_eq!(last_event("["), Error(SyntaxError(EOFWhileParsingValue, 1, 2)));
880
881     assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
882     assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
883     assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
884     assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
885     assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
886 }
887 #[test]
888 fn test_trailing_characters_streaming() {
889     assert_eq!(last_event("nulla"), Error(SyntaxError(TrailingCharacters, 1, 5)));
890     assert_eq!(last_event("truea"), Error(SyntaxError(TrailingCharacters, 1, 5)));
891     assert_eq!(last_event("falsea"), Error(SyntaxError(TrailingCharacters, 1, 6)));
892     assert_eq!(last_event("1a"), Error(SyntaxError(TrailingCharacters, 1, 2)));
893     assert_eq!(last_event("[]a"), Error(SyntaxError(TrailingCharacters, 1, 3)));
894     assert_eq!(last_event("{}a"), Error(SyntaxError(TrailingCharacters, 1, 3)));
895 }
896 #[test]
897 fn test_read_identifiers_streaming() {
898     assert_eq!(Parser::new("null".chars()).next(), Some(NullValue));
899     assert_eq!(Parser::new("true".chars()).next(), Some(BooleanValue(true)));
900     assert_eq!(Parser::new("false".chars()).next(), Some(BooleanValue(false)));
901
902     assert_eq!(last_event("n"), Error(SyntaxError(InvalidSyntax, 1, 2)));
903     assert_eq!(last_event("nul"), Error(SyntaxError(InvalidSyntax, 1, 4)));
904     assert_eq!(last_event("t"), Error(SyntaxError(InvalidSyntax, 1, 2)));
905     assert_eq!(last_event("truz"), Error(SyntaxError(InvalidSyntax, 1, 4)));
906     assert_eq!(last_event("f"), Error(SyntaxError(InvalidSyntax, 1, 2)));
907     assert_eq!(last_event("faz"), Error(SyntaxError(InvalidSyntax, 1, 3)));
908 }
909
910 #[test]
911 fn test_to_json() {
912     use json::ToJson;
913     use std::collections::{BTreeMap, HashMap};
914
915     let array2 = Array(vec![U64(1), U64(2)]);
916     let array3 = Array(vec![U64(1), U64(2), U64(3)]);
917     let object = {
918         let mut tree_map = BTreeMap::new();
919         tree_map.insert("a".to_string(), U64(1));
920         tree_map.insert("b".to_string(), U64(2));
921         Object(tree_map)
922     };
923
924     assert_eq!(array2.to_json(), array2);
925     assert_eq!(object.to_json(), object);
926     assert_eq!(3_isize.to_json(), I64(3));
927     assert_eq!(4_i8.to_json(), I64(4));
928     assert_eq!(5_i16.to_json(), I64(5));
929     assert_eq!(6_i32.to_json(), I64(6));
930     assert_eq!(7_i64.to_json(), I64(7));
931     assert_eq!(8_usize.to_json(), U64(8));
932     assert_eq!(9_u8.to_json(), U64(9));
933     assert_eq!(10_u16.to_json(), U64(10));
934     assert_eq!(11_u32.to_json(), U64(11));
935     assert_eq!(12_u64.to_json(), U64(12));
936     assert_eq!(13.0_f32.to_json(), F64(13.0_f64));
937     assert_eq!(14.0_f64.to_json(), F64(14.0_f64));
938     assert_eq!(().to_json(), Null);
939     assert_eq!(f32::INFINITY.to_json(), Null);
940     assert_eq!(f64::NAN.to_json(), Null);
941     assert_eq!(true.to_json(), Boolean(true));
942     assert_eq!(false.to_json(), Boolean(false));
943     assert_eq!("abc".to_json(), String("abc".to_string()));
944     assert_eq!("abc".to_string().to_json(), String("abc".to_string()));
945     assert_eq!((1_usize, 2_usize).to_json(), array2);
946     assert_eq!((1_usize, 2_usize, 3_usize).to_json(), array3);
947     assert_eq!([1_usize, 2_usize].to_json(), array2);
948     assert_eq!((&[1_usize, 2_usize, 3_usize]).to_json(), array3);
949     assert_eq!((vec![1_usize, 2_usize]).to_json(), array2);
950     assert_eq!(vec![1_usize, 2_usize, 3_usize].to_json(), array3);
951     let mut tree_map = BTreeMap::new();
952     tree_map.insert("a".to_string(), 1 as usize);
953     tree_map.insert("b".to_string(), 2);
954     assert_eq!(tree_map.to_json(), object);
955     let mut hash_map = HashMap::new();
956     hash_map.insert("a".to_string(), 1 as usize);
957     hash_map.insert("b".to_string(), 2);
958     assert_eq!(hash_map.to_json(), object);
959     assert_eq!(Some(15).to_json(), I64(15));
960     assert_eq!(Some(15 as usize).to_json(), U64(15));
961     assert_eq!(None::<isize>.to_json(), Null);
962 }
963
964 #[test]
965 fn test_encode_hashmap_with_arbitrary_key() {
966     use std::collections::HashMap;
967     #[derive(PartialEq, Eq, Hash, Encodable)]
968     struct ArbitraryType(usize);
969     let mut hm: HashMap<ArbitraryType, bool> = HashMap::new();
970     hm.insert(ArbitraryType(1), true);
971     let mut mem_buf = string::String::new();
972     let mut encoder = Encoder::new(&mut mem_buf);
973     let result = hm.encode(&mut encoder);
974     match result.unwrap_err() {
975         EncoderError::BadHashmapKey => (),
976         _ => panic!("expected bad hash map key"),
977     }
978 }