1 #![allow(rustc::internal)]
3 use json::ErrorCode::*;
5 use json::JsonEvent::*;
6 use json::ParserError::*;
7 use json::{from_str, Decoder, Encoder, EncoderError, Json, JsonEvent, Parser, StackElement};
8 use rustc_macros::{Decodable, Encodable};
9 use rustc_serialize::json;
10 use rustc_serialize::{Decodable, Encodable};
12 use std::collections::BTreeMap;
13 use std::io::prelude::*;
17 #[derive(Decodable, Eq, PartialEq, Debug)]
23 fn test_decode_option_none() {
25 let obj: OptionData = json::decode(s);
26 assert_eq!(obj, OptionData { opt: None });
30 fn test_decode_option_some() {
31 let s = "{ \"opt\": 10 }";
32 let obj: OptionData = json::decode(s);
33 assert_eq!(obj, OptionData { opt: Some(10) });
37 #[should_panic(expected = r#"ExpectedError("Number", "[]")"#)]
38 fn test_decode_option_malformed1() {
39 check_err::<OptionData>(r#"{ "opt": [] }"#);
43 #[should_panic(expected = r#"ExpectedError("Number", "false")"#)]
44 fn test_decode_option_malformed2() {
45 check_err::<OptionData>(r#"{ "opt": false }"#);
48 #[derive(PartialEq, Encodable, Decodable, Debug)]
51 Frog(string::String, isize),
54 #[derive(PartialEq, Encodable, Decodable, Debug)]
58 c: Vec<string::String>,
61 #[derive(PartialEq, Encodable, Decodable, Debug)]
66 fn mk_object(items: &[(string::String, Json)]) -> Json {
67 let mut d = BTreeMap::new();
71 (ref key, ref value) => {
72 d.insert((*key).clone(), (*value).clone());
81 fn test_from_str_trait() {
83 assert!(s.parse::<Json>().unwrap() == s.parse().unwrap());
87 fn test_write_null() {
88 assert_eq!(Null.to_string(), "null");
89 assert_eq!(Null.pretty().to_string(), "null");
94 assert_eq!(U64(0).to_string(), "0");
95 assert_eq!(U64(0).pretty().to_string(), "0");
97 assert_eq!(U64(1234).to_string(), "1234");
98 assert_eq!(U64(1234).pretty().to_string(), "1234");
100 assert_eq!(I64(-5678).to_string(), "-5678");
101 assert_eq!(I64(-5678).pretty().to_string(), "-5678");
103 assert_eq!(U64(7650007200025252000).to_string(), "7650007200025252000");
104 assert_eq!(U64(7650007200025252000).pretty().to_string(), "7650007200025252000");
108 fn test_write_f64() {
109 assert_eq!(F64(3.0).to_string(), "3.0");
110 assert_eq!(F64(3.0).pretty().to_string(), "3.0");
112 assert_eq!(F64(3.1).to_string(), "3.1");
113 assert_eq!(F64(3.1).pretty().to_string(), "3.1");
115 assert_eq!(F64(-1.5).to_string(), "-1.5");
116 assert_eq!(F64(-1.5).pretty().to_string(), "-1.5");
118 assert_eq!(F64(0.5).to_string(), "0.5");
119 assert_eq!(F64(0.5).pretty().to_string(), "0.5");
121 assert_eq!(F64(f64::NAN).to_string(), "null");
122 assert_eq!(F64(f64::NAN).pretty().to_string(), "null");
124 assert_eq!(F64(f64::INFINITY).to_string(), "null");
125 assert_eq!(F64(f64::INFINITY).pretty().to_string(), "null");
127 assert_eq!(F64(f64::NEG_INFINITY).to_string(), "null");
128 assert_eq!(F64(f64::NEG_INFINITY).pretty().to_string(), "null");
132 fn test_write_str() {
133 assert_eq!(String("".to_string()).to_string(), "\"\"");
134 assert_eq!(String("".to_string()).pretty().to_string(), "\"\"");
136 assert_eq!(String("homura".to_string()).to_string(), "\"homura\"");
137 assert_eq!(String("madoka".to_string()).pretty().to_string(), "\"madoka\"");
141 fn test_write_bool() {
142 assert_eq!(Boolean(true).to_string(), "true");
143 assert_eq!(Boolean(true).pretty().to_string(), "true");
145 assert_eq!(Boolean(false).to_string(), "false");
146 assert_eq!(Boolean(false).pretty().to_string(), "false");
150 fn test_write_array() {
151 assert_eq!(Array(vec![]).to_string(), "[]");
152 assert_eq!(Array(vec![]).pretty().to_string(), "[]");
154 assert_eq!(Array(vec![Boolean(true)]).to_string(), "[true]");
156 Array(vec![Boolean(true)]).pretty().to_string(),
163 let long_test_array =
164 Array(vec![Boolean(false), Null, Array(vec![String("foo\nbar".to_string()), F64(3.5)])]);
166 assert_eq!(long_test_array.to_string(), "[false,null,[\"foo\\nbar\",3.5]]");
168 long_test_array.pretty().to_string(),
182 fn test_write_object() {
183 assert_eq!(mk_object(&[]).to_string(), "{}");
184 assert_eq!(mk_object(&[]).pretty().to_string(), "{}");
186 assert_eq!(mk_object(&[("a".to_string(), Boolean(true))]).to_string(), "{\"a\":true}");
188 mk_object(&[("a".to_string(), Boolean(true))]).pretty().to_string(),
195 let complex_obj = mk_object(&[(
198 mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
199 mk_object(&[("d".to_string(), String("".to_string()))]),
204 complex_obj.to_string(),
213 complex_obj.pretty().to_string(),
218 \"c\": \"\\f\\r\"\n \
228 ("a".to_string(), Boolean(true)),
232 mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
233 mk_object(&[("d".to_string(), String("".to_string()))]),
238 // We can't compare the strings directly because the object fields be
239 // printed in a different order.
240 assert_eq!(a.clone(), a.to_string().parse().unwrap());
241 assert_eq!(a.clone(), a.pretty().to_string().parse().unwrap());
245 fn test_write_enum() {
247 assert_eq!(json::as_json(&animal).to_string(), "\"Dog\"");
248 assert_eq!(json::as_pretty_json(&animal).to_string(), "\"Dog\"");
250 let animal = Frog("Henry".to_string(), 349);
252 json::as_json(&animal).to_string(),
253 "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}"
256 json::as_pretty_json(&animal).to_string(),
258 \"variant\": \"Frog\",\n \
267 macro_rules! check_encoder_for_simple {
268 ($value:expr, $expected:expr) => {{
269 let s = json::as_json(&$value).to_string();
270 assert_eq!(s, $expected);
272 let s = json::as_pretty_json(&$value).to_string();
273 assert_eq!(s, $expected);
278 fn test_write_some() {
279 check_encoder_for_simple!(Some("jodhpurs".to_string()), "\"jodhpurs\"");
283 fn test_write_none() {
284 check_encoder_for_simple!(None::<string::String>, "null");
288 fn test_write_char() {
289 check_encoder_for_simple!('a', "\"a\"");
290 check_encoder_for_simple!('\t', "\"\\t\"");
291 check_encoder_for_simple!('\u{0000}', "\"\\u0000\"");
292 check_encoder_for_simple!('\u{001b}', "\"\\u001b\"");
293 check_encoder_for_simple!('\u{007f}', "\"\\u007f\"");
294 check_encoder_for_simple!('\u{00a0}', "\"\u{00a0}\"");
295 check_encoder_for_simple!('\u{abcd}', "\"\u{abcd}\"");
296 check_encoder_for_simple!('\u{10ffff}', "\"\u{10ffff}\"");
300 fn test_trailing_characters() {
301 assert_eq!(from_str("nulla"), Err(SyntaxError(TrailingCharacters, 1, 5)));
302 assert_eq!(from_str("truea"), Err(SyntaxError(TrailingCharacters, 1, 5)));
303 assert_eq!(from_str("falsea"), Err(SyntaxError(TrailingCharacters, 1, 6)));
304 assert_eq!(from_str("1a"), Err(SyntaxError(TrailingCharacters, 1, 2)));
305 assert_eq!(from_str("[]a"), Err(SyntaxError(TrailingCharacters, 1, 3)));
306 assert_eq!(from_str("{}a"), Err(SyntaxError(TrailingCharacters, 1, 3)));
310 fn test_read_identifiers() {
311 assert_eq!(from_str("n"), Err(SyntaxError(InvalidSyntax, 1, 2)));
312 assert_eq!(from_str("nul"), Err(SyntaxError(InvalidSyntax, 1, 4)));
313 assert_eq!(from_str("t"), Err(SyntaxError(InvalidSyntax, 1, 2)));
314 assert_eq!(from_str("truz"), Err(SyntaxError(InvalidSyntax, 1, 4)));
315 assert_eq!(from_str("f"), Err(SyntaxError(InvalidSyntax, 1, 2)));
316 assert_eq!(from_str("faz"), Err(SyntaxError(InvalidSyntax, 1, 3)));
318 assert_eq!(from_str("null"), Ok(Null));
319 assert_eq!(from_str("true"), Ok(Boolean(true)));
320 assert_eq!(from_str("false"), Ok(Boolean(false)));
321 assert_eq!(from_str(" null "), Ok(Null));
322 assert_eq!(from_str(" true "), Ok(Boolean(true)));
323 assert_eq!(from_str(" false "), Ok(Boolean(false)));
327 fn test_decode_identifiers() {
328 let v: () = json::decode("null");
331 let v: bool = json::decode("true");
334 let v: bool = json::decode("false");
335 assert_eq!(v, false);
339 fn test_read_number() {
340 assert_eq!(from_str("+"), Err(SyntaxError(InvalidSyntax, 1, 1)));
341 assert_eq!(from_str("."), Err(SyntaxError(InvalidSyntax, 1, 1)));
342 assert_eq!(from_str("NaN"), Err(SyntaxError(InvalidSyntax, 1, 1)));
343 assert_eq!(from_str("-"), Err(SyntaxError(InvalidNumber, 1, 2)));
344 assert_eq!(from_str("00"), Err(SyntaxError(InvalidNumber, 1, 2)));
345 assert_eq!(from_str("1."), Err(SyntaxError(InvalidNumber, 1, 3)));
346 assert_eq!(from_str("1e"), Err(SyntaxError(InvalidNumber, 1, 3)));
347 assert_eq!(from_str("1e+"), Err(SyntaxError(InvalidNumber, 1, 4)));
349 assert_eq!(from_str("18446744073709551616"), Err(SyntaxError(InvalidNumber, 1, 20)));
350 assert_eq!(from_str("-9223372036854775809"), Err(SyntaxError(InvalidNumber, 1, 21)));
352 assert_eq!(from_str("3"), Ok(U64(3)));
353 assert_eq!(from_str("3.1"), Ok(F64(3.1)));
354 assert_eq!(from_str("-1.2"), Ok(F64(-1.2)));
355 assert_eq!(from_str("0.4"), Ok(F64(0.4)));
356 assert_eq!(from_str("0.4e5"), Ok(F64(0.4e5)));
357 assert_eq!(from_str("0.4e+15"), Ok(F64(0.4e15)));
358 assert_eq!(from_str("0.4e-01"), Ok(F64(0.4e-01)));
359 assert_eq!(from_str(" 3 "), Ok(U64(3)));
361 assert_eq!(from_str("-9223372036854775808"), Ok(I64(i64::MIN)));
362 assert_eq!(from_str("9223372036854775807"), Ok(U64(i64::MAX as u64)));
363 assert_eq!(from_str("18446744073709551615"), Ok(U64(u64::MAX)));
367 #[should_panic(expected = r#"ExpectedError("Integer", "765.25")"#)]
368 fn test_decode_numbers() {
369 let v: f64 = json::decode("3");
372 let v: f64 = json::decode("3.1");
375 let v: f64 = json::decode("-1.2");
378 let v: f64 = json::decode("0.4");
381 let v: f64 = json::decode("0.4e5");
382 assert_eq!(v, 0.4e5);
384 let v: f64 = json::decode("0.4e15");
385 assert_eq!(v, 0.4e15);
387 let v: f64 = json::decode("0.4e-01");
388 assert_eq!(v, 0.4e-01);
390 let v: u64 = json::decode("0");
393 let v: u64 = json::decode("18446744073709551615");
394 assert_eq!(v, u64::MAX);
396 let v: i64 = json::decode("-9223372036854775808");
397 assert_eq!(v, i64::MIN);
399 let v: i64 = json::decode("9223372036854775807");
400 assert_eq!(v, i64::MAX);
402 json::decode::<i64>("765.25");
407 assert_eq!(from_str("\""), Err(SyntaxError(EOFWhileParsingString, 1, 2)));
408 assert_eq!(from_str("\"lol"), Err(SyntaxError(EOFWhileParsingString, 1, 5)));
410 assert_eq!(from_str("\"\""), Ok(String("".to_string())));
411 assert_eq!(from_str("\"foo\""), Ok(String("foo".to_string())));
412 assert_eq!(from_str("\"\\\"\""), Ok(String("\"".to_string())));
413 assert_eq!(from_str("\"\\b\""), Ok(String("\x08".to_string())));
414 assert_eq!(from_str("\"\\n\""), Ok(String("\n".to_string())));
415 assert_eq!(from_str("\"\\r\""), Ok(String("\r".to_string())));
416 assert_eq!(from_str("\"\\t\""), Ok(String("\t".to_string())));
417 assert_eq!(from_str(" \"foo\" "), Ok(String("foo".to_string())));
418 assert_eq!(from_str("\"\\u12ab\""), Ok(String("\u{12ab}".to_string())));
419 assert_eq!(from_str("\"\\uAB12\""), Ok(String("\u{AB12}".to_string())));
423 fn test_decode_str() {
432 ("\"\\u12ab\"", "\u{12ab}"),
433 ("\"\\uAB12\"", "\u{AB12}"),
437 let v: string::String = json::decode(i);
443 fn test_read_array() {
444 assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
445 assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
446 assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
447 assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
448 assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
450 assert_eq!(from_str("[]"), Ok(Array(vec![])));
451 assert_eq!(from_str("[ ]"), Ok(Array(vec![])));
452 assert_eq!(from_str("[true]"), Ok(Array(vec![Boolean(true)])));
453 assert_eq!(from_str("[ false ]"), Ok(Array(vec![Boolean(false)])));
454 assert_eq!(from_str("[null]"), Ok(Array(vec![Null])));
455 assert_eq!(from_str("[3, 1]"), Ok(Array(vec![U64(3), U64(1)])));
456 assert_eq!(from_str("\n[3, 2]\n"), Ok(Array(vec![U64(3), U64(2)])));
457 assert_eq!(from_str("[2, [4, 1]]"), Ok(Array(vec![U64(2), Array(vec![U64(4), U64(1)])])));
461 fn test_decode_array() {
462 let v: Vec<()> = json::decode("[]");
465 let v: Vec<()> = json::decode("[null]");
468 let v: Vec<bool> = json::decode("[true]");
469 assert_eq!(v, [true]);
471 let v: Vec<isize> = json::decode("[3, 1]");
472 assert_eq!(v, [3, 1]);
474 let v: Vec<Vec<usize>> = json::decode("[[3], [1, 2]]");
475 assert_eq!(v, [vec![3], vec![1, 2]]);
479 fn test_decode_tuple() {
480 let t: (usize, usize, usize) = json::decode("[1, 2, 3]");
481 assert_eq!(t, (1, 2, 3));
483 let t: (usize, string::String) = json::decode("[1, \"two\"]");
484 assert_eq!(t, (1, "two".to_string()));
489 fn test_decode_tuple_malformed_types() {
490 json::decode::<(usize, string::String)>("[1, 2]");
495 fn test_decode_tuple_malformed_length() {
496 json::decode::<(usize, usize)>("[1, 2, 3]");
500 fn test_read_object() {
501 assert_eq!(from_str("{"), Err(SyntaxError(EOFWhileParsingObject, 1, 2)));
502 assert_eq!(from_str("{ "), Err(SyntaxError(EOFWhileParsingObject, 1, 3)));
503 assert_eq!(from_str("{1"), Err(SyntaxError(KeyMustBeAString, 1, 2)));
504 assert_eq!(from_str("{ \"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
505 assert_eq!(from_str("{\"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 5)));
506 assert_eq!(from_str("{\"a\" "), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
508 assert_eq!(from_str("{\"a\" 1"), Err(SyntaxError(ExpectedColon, 1, 6)));
509 assert_eq!(from_str("{\"a\":"), Err(SyntaxError(EOFWhileParsingValue, 1, 6)));
510 assert_eq!(from_str("{\"a\":1"), Err(SyntaxError(EOFWhileParsingObject, 1, 7)));
511 assert_eq!(from_str("{\"a\":1 1"), Err(SyntaxError(InvalidSyntax, 1, 8)));
512 assert_eq!(from_str("{\"a\":1,"), Err(SyntaxError(EOFWhileParsingObject, 1, 8)));
514 assert_eq!(from_str("{}").unwrap(), mk_object(&[]));
515 assert_eq!(from_str("{\"a\": 3}").unwrap(), mk_object(&[("a".to_string(), U64(3))]));
518 from_str("{ \"a\": null, \"b\" : true }").unwrap(),
519 mk_object(&[("a".to_string(), Null), ("b".to_string(), Boolean(true))])
522 from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(),
523 mk_object(&[("a".to_string(), Null), ("b".to_string(), Boolean(true))])
526 from_str("{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(),
527 mk_object(&[("a".to_string(), F64(1.0)), ("b".to_string(), Array(vec![Boolean(true)]))])
536 { \"c\": {\"d\": null} } \
542 ("a".to_string(), F64(1.0)),
547 String("foo\nbar".to_string()),
548 mk_object(&[("c".to_string(), mk_object(&[("d".to_string(), Null)]))])
556 fn test_decode_struct() {
559 { \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] }
563 let v: Outer = json::decode(s);
566 Outer { inner: vec![Inner { a: (), b: 2, c: vec!["abc".to_string(), "xyz".to_string()] }] }
576 fn test_decode_struct_with_nan() {
577 let s = "{\"f\":null,\"a\":[null,123]}";
578 let obj: FloatStruct = json::decode(s);
579 assert!(obj.f.is_nan());
580 assert!(obj.a[0].is_nan());
581 assert_eq!(obj.a[1], 123f64);
585 fn test_decode_option() {
586 let value: Option<string::String> = json::decode("null");
587 assert_eq!(value, None);
589 let value: Option<string::String> = json::decode("\"jodhpurs\"");
590 assert_eq!(value, Some("jodhpurs".to_string()));
594 fn test_decode_enum() {
595 let value: Animal = json::decode("\"Dog\"");
596 assert_eq!(value, Dog);
598 let s = "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}";
599 let value: Animal = json::decode(s);
600 assert_eq!(value, Frog("Henry".to_string(), 349));
604 fn test_decode_map() {
605 let s = "{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\
606 \"fields\":[\"Henry\", 349]}}";
607 let mut map: BTreeMap<string::String, Animal> = json::decode(s);
609 assert_eq!(map.remove(&"a".to_string()), Some(Dog));
610 assert_eq!(map.remove(&"b".to_string()), Some(Frog("Henry".to_string(), 349)));
614 fn test_multiline_errors() {
615 assert_eq!(from_str("{\n \"foo\":\n \"bar\""), Err(SyntaxError(EOFWhileParsingObject, 3, 8)));
620 struct DecodeStruct {
624 w: Vec<DecodeStruct>,
631 fn check_err<T: Decodable<Decoder>>(to_parse: &str) {
632 let json = from_str(to_parse).unwrap();
633 let _: T = Decodable::decode(&mut Decoder::new(json));
636 #[should_panic(expected = r#"ExpectedError("Object", "[]")"#)]
637 fn test_decode_errors_struct1() {
638 check_err::<DecodeStruct>("[]");
641 #[should_panic(expected = r#"ExpectedError("Number", "true")"#)]
642 fn test_decode_errors_struct2() {
643 check_err::<DecodeStruct>(r#"{"x": true, "y": true, "z": "", "w": []}"#);
646 #[should_panic(expected = r#"ExpectedError("Boolean", "[]")"#)]
647 fn test_decode_errors_struct3() {
648 check_err::<DecodeStruct>(r#"{"x": 1, "y": [], "z": "", "w": []}"#);
651 #[should_panic(expected = r#"ExpectedError("String", "{}")"#)]
652 fn test_decode_errors_struct4() {
653 check_err::<DecodeStruct>(r#"{"x": 1, "y": true, "z": {}, "w": []}"#);
656 #[should_panic(expected = r#"ExpectedError("Array", "null")"#)]
657 fn test_decode_errors_struct5() {
658 check_err::<DecodeStruct>(r#"{"x": 1, "y": true, "z": "", "w": null}"#);
661 #[should_panic(expected = r#"ExpectedError("Array", "null")"#)]
662 fn test_decode_errors_struct6() {
663 check_err::<DecodeStruct>(r#"{"x": 1, "y": true, "z": ""}"#);
667 #[should_panic(expected = r#"MissingFieldError("variant")"#)]
668 fn test_decode_errors_enum1() {
669 check_err::<DecodeEnum>(r#"{}"#);
672 #[should_panic(expected = r#"ExpectedError("String", "1")"#)]
673 fn test_decode_errors_enum2() {
674 check_err::<DecodeEnum>(r#"{"variant": 1}"#);
677 #[should_panic(expected = r#"MissingFieldError("fields")"#)]
678 fn test_decode_errors_enum3() {
679 check_err::<DecodeEnum>(r#"{"variant": "A"}"#);
682 #[should_panic(expected = r#"ExpectedError("Array", "null")"#)]
683 fn test_decode_errors_enum4() {
684 check_err::<DecodeEnum>(r#"{"variant": "A", "fields": null}"#);
687 #[should_panic(expected = r#"UnknownVariantError("C")"#)]
688 fn test_decode_errors_enum5() {
689 check_err::<DecodeEnum>(r#"{"variant": "C", "fields": []}"#);
694 let json_value = from_str("{\"dog\" : \"cat\"}").unwrap();
695 let found_str = json_value.find("dog");
696 assert!(found_str.unwrap().as_string().unwrap() == "cat");
700 fn test_find_path() {
701 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
702 let found_str = json_value.find_path(&["dog", "cat", "mouse"]);
703 assert!(found_str.unwrap().as_string().unwrap() == "cheese");
708 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
709 let found_str = json_value.search("mouse").and_then(|j| j.as_string());
710 assert!(found_str.unwrap() == "cheese");
715 let json_value = from_str("{\"animals\":[\"dog\",\"cat\",\"mouse\"]}").unwrap();
716 let ref array = json_value["animals"];
717 assert_eq!(array[0].as_string().unwrap(), "dog");
718 assert_eq!(array[1].as_string().unwrap(), "cat");
719 assert_eq!(array[2].as_string().unwrap(), "mouse");
723 fn test_is_object() {
724 let json_value = from_str("{}").unwrap();
725 assert!(json_value.is_object());
729 fn test_as_object() {
730 let json_value = from_str("{}").unwrap();
731 let json_object = json_value.as_object();
732 assert!(json_object.is_some());
737 let json_value = from_str("[1, 2, 3]").unwrap();
738 assert!(json_value.is_array());
743 let json_value = from_str("[1, 2, 3]").unwrap();
744 let json_array = json_value.as_array();
745 let expected_length = 3;
746 assert!(json_array.is_some() && json_array.unwrap().len() == expected_length);
750 fn test_is_string() {
751 let json_value = from_str("\"dog\"").unwrap();
752 assert!(json_value.is_string());
756 fn test_as_string() {
757 let json_value = from_str("\"dog\"").unwrap();
758 let json_str = json_value.as_string();
759 let expected_str = "dog";
760 assert_eq!(json_str, Some(expected_str));
764 fn test_is_number() {
765 let json_value = from_str("12").unwrap();
766 assert!(json_value.is_number());
771 let json_value = from_str("-12").unwrap();
772 assert!(json_value.is_i64());
774 let json_value = from_str("12").unwrap();
775 assert!(!json_value.is_i64());
777 let json_value = from_str("12.0").unwrap();
778 assert!(!json_value.is_i64());
783 let json_value = from_str("12").unwrap();
784 assert!(json_value.is_u64());
786 let json_value = from_str("-12").unwrap();
787 assert!(!json_value.is_u64());
789 let json_value = from_str("12.0").unwrap();
790 assert!(!json_value.is_u64());
795 let json_value = from_str("12").unwrap();
796 assert!(!json_value.is_f64());
798 let json_value = from_str("-12").unwrap();
799 assert!(!json_value.is_f64());
801 let json_value = from_str("12.0").unwrap();
802 assert!(json_value.is_f64());
804 let json_value = from_str("-12.0").unwrap();
805 assert!(json_value.is_f64());
810 let json_value = from_str("-12").unwrap();
811 let json_num = json_value.as_i64();
812 assert_eq!(json_num, Some(-12));
817 let json_value = from_str("12").unwrap();
818 let json_num = json_value.as_u64();
819 assert_eq!(json_num, Some(12));
824 let json_value = from_str("12.0").unwrap();
825 let json_num = json_value.as_f64();
826 assert_eq!(json_num, Some(12f64));
830 fn test_is_boolean() {
831 let json_value = from_str("false").unwrap();
832 assert!(json_value.is_boolean());
836 fn test_as_boolean() {
837 let json_value = from_str("false").unwrap();
838 let json_bool = json_value.as_boolean();
839 let expected_bool = false;
840 assert!(json_bool.is_some() && json_bool.unwrap() == expected_bool);
845 let json_value = from_str("null").unwrap();
846 assert!(json_value.is_null());
851 let json_value = from_str("null").unwrap();
852 let json_null = json_value.as_null();
853 let expected_null = ();
854 assert!(json_null.is_some() && json_null.unwrap() == expected_null);
858 fn test_encode_hashmap_with_numeric_key() {
859 use std::collections::HashMap;
860 use std::str::from_utf8;
861 let mut hm: HashMap<usize, bool> = HashMap::new();
863 let mut mem_buf = Vec::new();
864 write!(&mut mem_buf, "{}", json::as_pretty_json(&hm)).unwrap();
865 let json_str = from_utf8(&mem_buf[..]).unwrap();
866 match from_str(json_str) {
867 Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
868 _ => {} // it parsed and we are good to go
873 fn test_prettyencode_hashmap_with_numeric_key() {
874 use std::collections::HashMap;
875 use std::str::from_utf8;
876 let mut hm: HashMap<usize, bool> = HashMap::new();
878 let mut mem_buf = Vec::new();
879 write!(&mut mem_buf, "{}", json::as_pretty_json(&hm)).unwrap();
880 let json_str = from_utf8(&mem_buf[..]).unwrap();
881 match from_str(json_str) {
882 Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
883 _ => {} // it parsed and we are good to go
888 fn test_prettyencoder_indent_level_param() {
889 use std::collections::BTreeMap;
890 use std::str::from_utf8;
892 let mut tree = BTreeMap::new();
894 tree.insert("hello".to_string(), String("guten tag".to_string()));
895 tree.insert("goodbye".to_string(), String("sayonara".to_string()));
898 // The following layout below should look a lot like
899 // the pretty-printed JSON (indent * x)
902 String("greetings".to_string()), // 1x
903 Object(tree), // 1x + 2x + 2x + 1x
905 // End JSON array (7 lines)
908 // Helper function for counting indents
909 fn indents(source: &str) -> usize {
910 let trimmed = source.trim_start_matches(' ');
911 source.len() - trimmed.len()
914 // Test up to 4 spaces of indents (more?)
916 let mut writer = Vec::new();
917 write!(&mut writer, "{}", json::as_pretty_json(&json).indent(i)).unwrap();
919 let printed = from_utf8(&writer[..]).unwrap();
921 // Check for indents at each line
922 let lines: Vec<&str> = printed.lines().collect();
923 assert_eq!(lines.len(), 7); // JSON should be 7 lines
925 assert_eq!(indents(lines[0]), 0 * i); // [
926 assert_eq!(indents(lines[1]), 1 * i); // "greetings",
927 assert_eq!(indents(lines[2]), 1 * i); // {
928 assert_eq!(indents(lines[3]), 2 * i); // "hello": "guten tag",
929 assert_eq!(indents(lines[4]), 2 * i); // "goodbye": "sayonara"
930 assert_eq!(indents(lines[5]), 1 * i); // },
931 assert_eq!(indents(lines[6]), 0 * i); // ]
933 // Finally, test that the pretty-printed JSON is valid
934 from_str(printed).ok().expect("Pretty-printed JSON is invalid!");
939 fn test_hashmap_with_enum_key() {
940 use std::collections::HashMap;
941 #[derive(Encodable, Eq, Hash, PartialEq, Decodable, Debug)]
947 let mut map = HashMap::new();
948 map.insert(Enum::Foo, 0);
949 let result = json::encode(&map).unwrap();
950 assert_eq!(&result[..], r#"{"Foo":0}"#);
951 let decoded: HashMap<Enum, _> = json::decode(&result);
952 assert_eq!(map, decoded);
956 fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() {
957 use std::collections::HashMap;
958 let json_str = "{\"1\":true}";
959 let json_obj = match from_str(json_str) {
960 Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
963 let mut decoder = Decoder::new(json_obj);
964 let _hm: HashMap<usize, bool> = Decodable::decode(&mut decoder);
968 #[should_panic(expected = r#"ExpectedError("Number", "a")"#)]
969 fn test_hashmap_with_numeric_key_will_error_with_string_keys() {
970 use std::collections::HashMap;
971 let json_str = "{\"a\":true}";
972 let json_obj = match from_str(json_str) {
973 Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
976 let mut decoder = Decoder::new(json_obj);
977 let _: HashMap<usize, bool> = Decodable::decode(&mut decoder);
980 fn assert_stream_equal(src: &str, expected: Vec<(JsonEvent, Vec<StackElement<'_>>)>) {
981 let mut parser = Parser::new(src.chars());
984 let evt = match parser.next() {
990 let (ref expected_evt, ref expected_stack) = expected[i];
991 if !parser.stack().is_equal_to(expected_stack) {
992 panic!("Parser stack is not equal to {:?}", expected_stack);
994 assert_eq!(&evt, expected_evt);
999 fn test_streaming_parser() {
1000 assert_stream_equal(
1001 r#"{ "foo":"bar", "array" : [0, 1, 2, 3, 4, 5], "idents":[null,true,false]}"#,
1003 (ObjectStart, vec![]),
1004 (StringValue("bar".to_string()), vec![StackElement::Key("foo")]),
1005 (ArrayStart, vec![StackElement::Key("array")]),
1006 (U64Value(0), vec![StackElement::Key("array"), StackElement::Index(0)]),
1007 (U64Value(1), vec![StackElement::Key("array"), StackElement::Index(1)]),
1008 (U64Value(2), vec![StackElement::Key("array"), StackElement::Index(2)]),
1009 (U64Value(3), vec![StackElement::Key("array"), StackElement::Index(3)]),
1010 (U64Value(4), vec![StackElement::Key("array"), StackElement::Index(4)]),
1011 (U64Value(5), vec![StackElement::Key("array"), StackElement::Index(5)]),
1012 (ArrayEnd, vec![StackElement::Key("array")]),
1013 (ArrayStart, vec![StackElement::Key("idents")]),
1014 (NullValue, vec![StackElement::Key("idents"), StackElement::Index(0)]),
1015 (BooleanValue(true), vec![StackElement::Key("idents"), StackElement::Index(1)]),
1016 (BooleanValue(false), vec![StackElement::Key("idents"), StackElement::Index(2)]),
1017 (ArrayEnd, vec![StackElement::Key("idents")]),
1018 (ObjectEnd, vec![]),
1022 fn last_event(src: &str) -> JsonEvent {
1023 let mut parser = Parser::new(src.chars());
1024 let mut evt = NullValue;
1026 evt = match parser.next() {
1034 fn test_read_object_streaming() {
1035 assert_eq!(last_event("{ "), Error(SyntaxError(EOFWhileParsingObject, 1, 3)));
1036 assert_eq!(last_event("{1"), Error(SyntaxError(KeyMustBeAString, 1, 2)));
1037 assert_eq!(last_event("{ \"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
1038 assert_eq!(last_event("{\"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 5)));
1039 assert_eq!(last_event("{\"a\" "), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
1041 assert_eq!(last_event("{\"a\" 1"), Error(SyntaxError(ExpectedColon, 1, 6)));
1042 assert_eq!(last_event("{\"a\":"), Error(SyntaxError(EOFWhileParsingValue, 1, 6)));
1043 assert_eq!(last_event("{\"a\":1"), Error(SyntaxError(EOFWhileParsingObject, 1, 7)));
1044 assert_eq!(last_event("{\"a\":1 1"), Error(SyntaxError(InvalidSyntax, 1, 8)));
1045 assert_eq!(last_event("{\"a\":1,"), Error(SyntaxError(EOFWhileParsingObject, 1, 8)));
1046 assert_eq!(last_event("{\"a\":1,}"), Error(SyntaxError(TrailingComma, 1, 8)));
1048 assert_stream_equal("{}", vec![(ObjectStart, vec![]), (ObjectEnd, vec![])]);
1049 assert_stream_equal(
1052 (ObjectStart, vec![]),
1053 (U64Value(3), vec![StackElement::Key("a")]),
1054 (ObjectEnd, vec![]),
1057 assert_stream_equal(
1058 "{ \"a\": null, \"b\" : true }",
1060 (ObjectStart, vec![]),
1061 (NullValue, vec![StackElement::Key("a")]),
1062 (BooleanValue(true), vec![StackElement::Key("b")]),
1063 (ObjectEnd, vec![]),
1066 assert_stream_equal(
1067 "{\"a\" : 1.0 ,\"b\": [ true ]}",
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![]),
1077 assert_stream_equal(
1083 { "c": {"d": null} }
1087 (ObjectStart, vec![]),
1088 (F64Value(1.0), vec![StackElement::Key("a")]),
1089 (ArrayStart, vec![StackElement::Key("b")]),
1090 (BooleanValue(true), vec![StackElement::Key("b"), StackElement::Index(0)]),
1092 StringValue("foo\nbar".to_string()),
1093 vec![StackElement::Key("b"), StackElement::Index(1)],
1095 (ObjectStart, vec![StackElement::Key("b"), StackElement::Index(2)]),
1098 vec![StackElement::Key("b"), StackElement::Index(2), StackElement::Key("c")],
1103 StackElement::Key("b"),
1104 StackElement::Index(2),
1105 StackElement::Key("c"),
1106 StackElement::Key("d"),
1111 vec![StackElement::Key("b"), StackElement::Index(2), StackElement::Key("c")],
1113 (ObjectEnd, vec![StackElement::Key("b"), StackElement::Index(2)]),
1114 (ArrayEnd, vec![StackElement::Key("b")]),
1115 (ObjectEnd, vec![]),
1120 fn test_read_array_streaming() {
1121 assert_stream_equal("[]", vec![(ArrayStart, vec![]), (ArrayEnd, vec![])]);
1122 assert_stream_equal("[ ]", vec![(ArrayStart, vec![]), (ArrayEnd, vec![])]);
1123 assert_stream_equal(
1126 (ArrayStart, vec![]),
1127 (BooleanValue(true), vec![StackElement::Index(0)]),
1131 assert_stream_equal(
1134 (ArrayStart, vec![]),
1135 (BooleanValue(false), vec![StackElement::Index(0)]),
1139 assert_stream_equal(
1141 vec![(ArrayStart, vec![]), (NullValue, vec![StackElement::Index(0)]), (ArrayEnd, vec![])],
1143 assert_stream_equal(
1146 (ArrayStart, vec![]),
1147 (U64Value(3), vec![StackElement::Index(0)]),
1148 (U64Value(1), vec![StackElement::Index(1)]),
1152 assert_stream_equal(
1155 (ArrayStart, vec![]),
1156 (U64Value(3), vec![StackElement::Index(0)]),
1157 (U64Value(2), vec![StackElement::Index(1)]),
1161 assert_stream_equal(
1164 (ArrayStart, vec![]),
1165 (U64Value(2), vec![StackElement::Index(0)]),
1166 (ArrayStart, vec![StackElement::Index(1)]),
1167 (U64Value(4), vec![StackElement::Index(1), StackElement::Index(0)]),
1168 (U64Value(1), vec![StackElement::Index(1), StackElement::Index(1)]),
1169 (ArrayEnd, vec![StackElement::Index(1)]),
1174 assert_eq!(last_event("["), Error(SyntaxError(EOFWhileParsingValue, 1, 2)));
1176 assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
1177 assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
1178 assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
1179 assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
1180 assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
1183 fn test_trailing_characters_streaming() {
1184 assert_eq!(last_event("nulla"), Error(SyntaxError(TrailingCharacters, 1, 5)));
1185 assert_eq!(last_event("truea"), Error(SyntaxError(TrailingCharacters, 1, 5)));
1186 assert_eq!(last_event("falsea"), Error(SyntaxError(TrailingCharacters, 1, 6)));
1187 assert_eq!(last_event("1a"), Error(SyntaxError(TrailingCharacters, 1, 2)));
1188 assert_eq!(last_event("[]a"), Error(SyntaxError(TrailingCharacters, 1, 3)));
1189 assert_eq!(last_event("{}a"), Error(SyntaxError(TrailingCharacters, 1, 3)));
1192 fn test_read_identifiers_streaming() {
1193 assert_eq!(Parser::new("null".chars()).next(), Some(NullValue));
1194 assert_eq!(Parser::new("true".chars()).next(), Some(BooleanValue(true)));
1195 assert_eq!(Parser::new("false".chars()).next(), Some(BooleanValue(false)));
1197 assert_eq!(last_event("n"), Error(SyntaxError(InvalidSyntax, 1, 2)));
1198 assert_eq!(last_event("nul"), Error(SyntaxError(InvalidSyntax, 1, 4)));
1199 assert_eq!(last_event("t"), Error(SyntaxError(InvalidSyntax, 1, 2)));
1200 assert_eq!(last_event("truz"), Error(SyntaxError(InvalidSyntax, 1, 4)));
1201 assert_eq!(last_event("f"), Error(SyntaxError(InvalidSyntax, 1, 2)));
1202 assert_eq!(last_event("faz"), Error(SyntaxError(InvalidSyntax, 1, 3)));
1208 use std::collections::{BTreeMap, HashMap};
1210 let array2 = Array(vec![U64(1), U64(2)]);
1211 let array3 = Array(vec![U64(1), U64(2), U64(3)]);
1213 let mut tree_map = BTreeMap::new();
1214 tree_map.insert("a".to_string(), U64(1));
1215 tree_map.insert("b".to_string(), U64(2));
1219 assert_eq!(array2.to_json(), array2);
1220 assert_eq!(object.to_json(), object);
1221 assert_eq!(3_isize.to_json(), I64(3));
1222 assert_eq!(4_i8.to_json(), I64(4));
1223 assert_eq!(5_i16.to_json(), I64(5));
1224 assert_eq!(6_i32.to_json(), I64(6));
1225 assert_eq!(7_i64.to_json(), I64(7));
1226 assert_eq!(8_usize.to_json(), U64(8));
1227 assert_eq!(9_u8.to_json(), U64(9));
1228 assert_eq!(10_u16.to_json(), U64(10));
1229 assert_eq!(11_u32.to_json(), U64(11));
1230 assert_eq!(12_u64.to_json(), U64(12));
1231 assert_eq!(13.0_f32.to_json(), F64(13.0_f64));
1232 assert_eq!(14.0_f64.to_json(), F64(14.0_f64));
1233 assert_eq!(().to_json(), Null);
1234 assert_eq!(f32::INFINITY.to_json(), Null);
1235 assert_eq!(f64::NAN.to_json(), Null);
1236 assert_eq!(true.to_json(), Boolean(true));
1237 assert_eq!(false.to_json(), Boolean(false));
1238 assert_eq!("abc".to_json(), String("abc".to_string()));
1239 assert_eq!("abc".to_string().to_json(), String("abc".to_string()));
1240 assert_eq!((1_usize, 2_usize).to_json(), array2);
1241 assert_eq!((1_usize, 2_usize, 3_usize).to_json(), array3);
1242 assert_eq!([1_usize, 2_usize].to_json(), array2);
1243 assert_eq!((&[1_usize, 2_usize, 3_usize]).to_json(), array3);
1244 assert_eq!((vec![1_usize, 2_usize]).to_json(), array2);
1245 assert_eq!(vec![1_usize, 2_usize, 3_usize].to_json(), array3);
1246 let mut tree_map = BTreeMap::new();
1247 tree_map.insert("a".to_string(), 1 as usize);
1248 tree_map.insert("b".to_string(), 2);
1249 assert_eq!(tree_map.to_json(), object);
1250 let mut hash_map = HashMap::new();
1251 hash_map.insert("a".to_string(), 1 as usize);
1252 hash_map.insert("b".to_string(), 2);
1253 assert_eq!(hash_map.to_json(), object);
1254 assert_eq!(Some(15).to_json(), I64(15));
1255 assert_eq!(Some(15 as usize).to_json(), U64(15));
1256 assert_eq!(None::<isize>.to_json(), Null);
1260 fn test_encode_hashmap_with_arbitrary_key() {
1261 use std::collections::HashMap;
1262 #[derive(PartialEq, Eq, Hash, Encodable)]
1263 struct ArbitraryType(usize);
1264 let mut hm: HashMap<ArbitraryType, bool> = HashMap::new();
1265 hm.insert(ArbitraryType(1), true);
1266 let mut mem_buf = string::String::new();
1267 let mut encoder = Encoder::new(&mut mem_buf);
1268 let result = hm.encode(&mut encoder);
1269 match result.unwrap_err() {
1270 EncoderError::BadHashmapKey => (),
1271 _ => panic!("expected bad hash map key"),