1 #![allow(rustc::internal)]
3 extern crate serialize as rustc_serialize;
5 use rustc_serialize::{Encodable, Decodable};
6 use rustc_serialize::json;
8 use json::ErrorCode::*;
9 use json::ParserError::*;
10 use json::DecoderError::*;
11 use json::JsonEvent::*;
12 use json::{Json, from_str, DecodeResult, DecoderError, JsonEvent, Parser, StackElement,
13 Decoder, Encoder, EncoderError};
16 use std::{i64, u64, f32, f64};
17 use std::io::prelude::*;
18 use std::collections::BTreeMap;
21 #[derive(RustcDecodable, Eq, PartialEq, Debug)]
27 fn test_decode_option_none() {
29 let obj: OptionData = json::decode(s).unwrap();
30 assert_eq!(obj, OptionData { opt: None });
34 fn test_decode_option_some() {
35 let s = "{ \"opt\": 10 }";
36 let obj: OptionData = json::decode(s).unwrap();
37 assert_eq!(obj, OptionData { opt: Some(10) });
41 fn test_decode_option_malformed() {
42 check_err::<OptionData>("{ \"opt\": [] }",
43 ExpectedError("Number".to_string(), "[]".to_string()));
44 check_err::<OptionData>("{ \"opt\": false }",
45 ExpectedError("Number".to_string(), "false".to_string()));
48 #[derive(PartialEq, RustcEncodable, RustcDecodable, Debug)]
51 Frog(string::String, isize)
54 #[derive(PartialEq, RustcEncodable, RustcDecodable, Debug)]
58 c: Vec<string::String>,
61 #[derive(PartialEq, RustcEncodable, RustcDecodable, Debug)]
66 fn mk_object(items: &[(string::String, Json)]) -> Json {
67 let mut d = BTreeMap::new();
71 (ref key, ref value) => { d.insert((*key).clone(), (*value).clone()); },
79 fn test_from_str_trait() {
81 assert!(s.parse::<Json>().unwrap() == s.parse().unwrap());
85 fn test_write_null() {
86 assert_eq!(Null.to_string(), "null");
87 assert_eq!(Null.pretty().to_string(), "null");
92 assert_eq!(U64(0).to_string(), "0");
93 assert_eq!(U64(0).pretty().to_string(), "0");
95 assert_eq!(U64(1234).to_string(), "1234");
96 assert_eq!(U64(1234).pretty().to_string(), "1234");
98 assert_eq!(I64(-5678).to_string(), "-5678");
99 assert_eq!(I64(-5678).pretty().to_string(), "-5678");
101 assert_eq!(U64(7650007200025252000).to_string(), "7650007200025252000");
102 assert_eq!(U64(7650007200025252000).pretty().to_string(), "7650007200025252000");
106 fn test_write_f64() {
107 assert_eq!(F64(3.0).to_string(), "3.0");
108 assert_eq!(F64(3.0).pretty().to_string(), "3.0");
110 assert_eq!(F64(3.1).to_string(), "3.1");
111 assert_eq!(F64(3.1).pretty().to_string(), "3.1");
113 assert_eq!(F64(-1.5).to_string(), "-1.5");
114 assert_eq!(F64(-1.5).pretty().to_string(), "-1.5");
116 assert_eq!(F64(0.5).to_string(), "0.5");
117 assert_eq!(F64(0.5).pretty().to_string(), "0.5");
119 assert_eq!(F64(f64::NAN).to_string(), "null");
120 assert_eq!(F64(f64::NAN).pretty().to_string(), "null");
122 assert_eq!(F64(f64::INFINITY).to_string(), "null");
123 assert_eq!(F64(f64::INFINITY).pretty().to_string(), "null");
125 assert_eq!(F64(f64::NEG_INFINITY).to_string(), "null");
126 assert_eq!(F64(f64::NEG_INFINITY).pretty().to_string(), "null");
130 fn test_write_str() {
131 assert_eq!(String("".to_string()).to_string(), "\"\"");
132 assert_eq!(String("".to_string()).pretty().to_string(), "\"\"");
134 assert_eq!(String("homura".to_string()).to_string(), "\"homura\"");
135 assert_eq!(String("madoka".to_string()).pretty().to_string(), "\"madoka\"");
139 fn test_write_bool() {
140 assert_eq!(Boolean(true).to_string(), "true");
141 assert_eq!(Boolean(true).pretty().to_string(), "true");
143 assert_eq!(Boolean(false).to_string(), "false");
144 assert_eq!(Boolean(false).pretty().to_string(), "false");
148 fn test_write_array() {
149 assert_eq!(Array(vec![]).to_string(), "[]");
150 assert_eq!(Array(vec![]).pretty().to_string(), "[]");
152 assert_eq!(Array(vec![Boolean(true)]).to_string(), "[true]");
154 Array(vec![Boolean(true)]).pretty().to_string(),
161 let long_test_array = Array(vec![
164 Array(vec![String("foo\nbar".to_string()), F64(3.5)])]);
166 assert_eq!(long_test_array.to_string(),
167 "[false,null,[\"foo\\nbar\",3.5]]");
169 long_test_array.pretty().to_string(),
183 fn test_write_object() {
184 assert_eq!(mk_object(&[]).to_string(), "{}");
185 assert_eq!(mk_object(&[]).pretty().to_string(), "{}");
189 ("a".to_string(), Boolean(true))
194 mk_object(&[("a".to_string(), Boolean(true))]).pretty().to_string(),
201 let complex_obj = mk_object(&[
202 ("b".to_string(), Array(vec![
203 mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
204 mk_object(&[("d".to_string(), String("".to_string()))])
209 complex_obj.to_string(),
218 complex_obj.pretty().to_string(),
223 \"c\": \"\\f\\r\"\n \
233 ("a".to_string(), Boolean(true)),
234 ("b".to_string(), Array(vec![
235 mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
236 mk_object(&[("d".to_string(), String("".to_string()))])
240 // We can't compare the strings directly because the object fields be
241 // printed in a different order.
242 assert_eq!(a.clone(), a.to_string().parse().unwrap());
243 assert_eq!(a.clone(), a.pretty().to_string().parse().unwrap());
247 fn test_write_enum() {
250 json::as_json(&animal).to_string(),
254 json::as_pretty_json(&animal).to_string(),
258 let animal = Frog("Henry".to_string(), 349);
260 json::as_json(&animal).to_string(),
261 "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}"
264 json::as_pretty_json(&animal).to_string(),
266 \"variant\": \"Frog\",\n \
275 macro_rules! check_encoder_for_simple {
276 ($value:expr, $expected:expr) => ({
277 let s = json::as_json(&$value).to_string();
278 assert_eq!(s, $expected);
280 let s = json::as_pretty_json(&$value).to_string();
281 assert_eq!(s, $expected);
286 fn test_write_some() {
287 check_encoder_for_simple!(Some("jodhpurs".to_string()), "\"jodhpurs\"");
291 fn test_write_none() {
292 check_encoder_for_simple!(None::<string::String>, "null");
296 fn test_write_char() {
297 check_encoder_for_simple!('a', "\"a\"");
298 check_encoder_for_simple!('\t', "\"\\t\"");
299 check_encoder_for_simple!('\u{0000}', "\"\\u0000\"");
300 check_encoder_for_simple!('\u{001b}', "\"\\u001b\"");
301 check_encoder_for_simple!('\u{007f}', "\"\\u007f\"");
302 check_encoder_for_simple!('\u{00a0}', "\"\u{00a0}\"");
303 check_encoder_for_simple!('\u{abcd}', "\"\u{abcd}\"");
304 check_encoder_for_simple!('\u{10ffff}', "\"\u{10ffff}\"");
308 fn test_trailing_characters() {
309 assert_eq!(from_str("nulla"), Err(SyntaxError(TrailingCharacters, 1, 5)));
310 assert_eq!(from_str("truea"), Err(SyntaxError(TrailingCharacters, 1, 5)));
311 assert_eq!(from_str("falsea"), Err(SyntaxError(TrailingCharacters, 1, 6)));
312 assert_eq!(from_str("1a"), Err(SyntaxError(TrailingCharacters, 1, 2)));
313 assert_eq!(from_str("[]a"), Err(SyntaxError(TrailingCharacters, 1, 3)));
314 assert_eq!(from_str("{}a"), Err(SyntaxError(TrailingCharacters, 1, 3)));
318 fn test_read_identifiers() {
319 assert_eq!(from_str("n"), Err(SyntaxError(InvalidSyntax, 1, 2)));
320 assert_eq!(from_str("nul"), Err(SyntaxError(InvalidSyntax, 1, 4)));
321 assert_eq!(from_str("t"), Err(SyntaxError(InvalidSyntax, 1, 2)));
322 assert_eq!(from_str("truz"), Err(SyntaxError(InvalidSyntax, 1, 4)));
323 assert_eq!(from_str("f"), Err(SyntaxError(InvalidSyntax, 1, 2)));
324 assert_eq!(from_str("faz"), Err(SyntaxError(InvalidSyntax, 1, 3)));
326 assert_eq!(from_str("null"), Ok(Null));
327 assert_eq!(from_str("true"), Ok(Boolean(true)));
328 assert_eq!(from_str("false"), Ok(Boolean(false)));
329 assert_eq!(from_str(" null "), Ok(Null));
330 assert_eq!(from_str(" true "), Ok(Boolean(true)));
331 assert_eq!(from_str(" false "), Ok(Boolean(false)));
335 fn test_decode_identifiers() {
336 let v: () = json::decode("null").unwrap();
339 let v: bool = json::decode("true").unwrap();
342 let v: bool = json::decode("false").unwrap();
343 assert_eq!(v, false);
347 fn test_read_number() {
348 assert_eq!(from_str("+"), Err(SyntaxError(InvalidSyntax, 1, 1)));
349 assert_eq!(from_str("."), Err(SyntaxError(InvalidSyntax, 1, 1)));
350 assert_eq!(from_str("NaN"), Err(SyntaxError(InvalidSyntax, 1, 1)));
351 assert_eq!(from_str("-"), Err(SyntaxError(InvalidNumber, 1, 2)));
352 assert_eq!(from_str("00"), Err(SyntaxError(InvalidNumber, 1, 2)));
353 assert_eq!(from_str("1."), Err(SyntaxError(InvalidNumber, 1, 3)));
354 assert_eq!(from_str("1e"), Err(SyntaxError(InvalidNumber, 1, 3)));
355 assert_eq!(from_str("1e+"), Err(SyntaxError(InvalidNumber, 1, 4)));
357 assert_eq!(from_str("18446744073709551616"), Err(SyntaxError(InvalidNumber, 1, 20)));
358 assert_eq!(from_str("-9223372036854775809"), Err(SyntaxError(InvalidNumber, 1, 21)));
360 assert_eq!(from_str("3"), Ok(U64(3)));
361 assert_eq!(from_str("3.1"), Ok(F64(3.1)));
362 assert_eq!(from_str("-1.2"), Ok(F64(-1.2)));
363 assert_eq!(from_str("0.4"), Ok(F64(0.4)));
364 assert_eq!(from_str("0.4e5"), Ok(F64(0.4e5)));
365 assert_eq!(from_str("0.4e+15"), Ok(F64(0.4e15)));
366 assert_eq!(from_str("0.4e-01"), Ok(F64(0.4e-01)));
367 assert_eq!(from_str(" 3 "), Ok(U64(3)));
369 assert_eq!(from_str("-9223372036854775808"), Ok(I64(i64::MIN)));
370 assert_eq!(from_str("9223372036854775807"), Ok(U64(i64::MAX as u64)));
371 assert_eq!(from_str("18446744073709551615"), Ok(U64(u64::MAX)));
375 fn test_decode_numbers() {
376 let v: f64 = json::decode("3").unwrap();
379 let v: f64 = json::decode("3.1").unwrap();
382 let v: f64 = json::decode("-1.2").unwrap();
385 let v: f64 = json::decode("0.4").unwrap();
388 let v: f64 = json::decode("0.4e5").unwrap();
389 assert_eq!(v, 0.4e5);
391 let v: f64 = json::decode("0.4e15").unwrap();
392 assert_eq!(v, 0.4e15);
394 let v: f64 = json::decode("0.4e-01").unwrap();
395 assert_eq!(v, 0.4e-01);
397 let v: u64 = json::decode("0").unwrap();
400 let v: u64 = json::decode("18446744073709551615").unwrap();
401 assert_eq!(v, u64::MAX);
403 let v: i64 = json::decode("-9223372036854775808").unwrap();
404 assert_eq!(v, i64::MIN);
406 let v: i64 = json::decode("9223372036854775807").unwrap();
407 assert_eq!(v, i64::MAX);
409 let res: DecodeResult<i64> = json::decode("765.25");
410 assert_eq!(res, Err(ExpectedError("Integer".to_string(),
411 "765.25".to_string())));
416 assert_eq!(from_str("\""), Err(SyntaxError(EOFWhileParsingString, 1, 2)));
417 assert_eq!(from_str("\"lol"), Err(SyntaxError(EOFWhileParsingString, 1, 5)));
419 assert_eq!(from_str("\"\""), Ok(String("".to_string())));
420 assert_eq!(from_str("\"foo\""), Ok(String("foo".to_string())));
421 assert_eq!(from_str("\"\\\"\""), Ok(String("\"".to_string())));
422 assert_eq!(from_str("\"\\b\""), Ok(String("\x08".to_string())));
423 assert_eq!(from_str("\"\\n\""), Ok(String("\n".to_string())));
424 assert_eq!(from_str("\"\\r\""), Ok(String("\r".to_string())));
425 assert_eq!(from_str("\"\\t\""), Ok(String("\t".to_string())));
426 assert_eq!(from_str(" \"foo\" "), Ok(String("foo".to_string())));
427 assert_eq!(from_str("\"\\u12ab\""), Ok(String("\u{12ab}".to_string())));
428 assert_eq!(from_str("\"\\uAB12\""), Ok(String("\u{AB12}".to_string())));
432 fn test_decode_str() {
433 let s = [("\"\"", ""),
440 ("\"\\u12ab\"", "\u{12ab}"),
441 ("\"\\uAB12\"", "\u{AB12}")];
444 let v: string::String = json::decode(i).unwrap();
450 fn test_read_array() {
451 assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
452 assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
453 assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
454 assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
455 assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
457 assert_eq!(from_str("[]"), Ok(Array(vec![])));
458 assert_eq!(from_str("[ ]"), Ok(Array(vec![])));
459 assert_eq!(from_str("[true]"), Ok(Array(vec![Boolean(true)])));
460 assert_eq!(from_str("[ false ]"), Ok(Array(vec![Boolean(false)])));
461 assert_eq!(from_str("[null]"), Ok(Array(vec![Null])));
462 assert_eq!(from_str("[3, 1]"),
463 Ok(Array(vec![U64(3), U64(1)])));
464 assert_eq!(from_str("\n[3, 2]\n"),
465 Ok(Array(vec![U64(3), U64(2)])));
466 assert_eq!(from_str("[2, [4, 1]]"),
467 Ok(Array(vec![U64(2), Array(vec![U64(4), U64(1)])])));
471 fn test_decode_array() {
472 let v: Vec<()> = json::decode("[]").unwrap();
475 let v: Vec<()> = json::decode("[null]").unwrap();
478 let v: Vec<bool> = json::decode("[true]").unwrap();
479 assert_eq!(v, [true]);
481 let v: Vec<isize> = json::decode("[3, 1]").unwrap();
482 assert_eq!(v, [3, 1]);
484 let v: Vec<Vec<usize>> = json::decode("[[3], [1, 2]]").unwrap();
485 assert_eq!(v, [vec![3], vec![1, 2]]);
489 fn test_decode_tuple() {
490 let t: (usize, usize, usize) = json::decode("[1, 2, 3]").unwrap();
491 assert_eq!(t, (1, 2, 3));
493 let t: (usize, string::String) = json::decode("[1, \"two\"]").unwrap();
494 assert_eq!(t, (1, "two".to_string()));
498 fn test_decode_tuple_malformed_types() {
499 assert!(json::decode::<(usize, string::String)>("[1, 2]").is_err());
503 fn test_decode_tuple_malformed_length() {
504 assert!(json::decode::<(usize, usize)>("[1, 2, 3]").is_err());
508 fn test_read_object() {
509 assert_eq!(from_str("{"), Err(SyntaxError(EOFWhileParsingObject, 1, 2)));
510 assert_eq!(from_str("{ "), Err(SyntaxError(EOFWhileParsingObject, 1, 3)));
511 assert_eq!(from_str("{1"), Err(SyntaxError(KeyMustBeAString, 1, 2)));
512 assert_eq!(from_str("{ \"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
513 assert_eq!(from_str("{\"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 5)));
514 assert_eq!(from_str("{\"a\" "), Err(SyntaxError(EOFWhileParsingObject, 1, 6)));
516 assert_eq!(from_str("{\"a\" 1"), Err(SyntaxError(ExpectedColon, 1, 6)));
517 assert_eq!(from_str("{\"a\":"), Err(SyntaxError(EOFWhileParsingValue, 1, 6)));
518 assert_eq!(from_str("{\"a\":1"), Err(SyntaxError(EOFWhileParsingObject, 1, 7)));
519 assert_eq!(from_str("{\"a\":1 1"), Err(SyntaxError(InvalidSyntax, 1, 8)));
520 assert_eq!(from_str("{\"a\":1,"), Err(SyntaxError(EOFWhileParsingObject, 1, 8)));
522 assert_eq!(from_str("{}").unwrap(), mk_object(&[]));
523 assert_eq!(from_str("{\"a\": 3}").unwrap(),
524 mk_object(&[("a".to_string(), U64(3))]));
527 "{ \"a\": null, \"b\" : true }").unwrap(),
529 ("a".to_string(), Null),
530 ("b".to_string(), Boolean(true))]));
531 assert_eq!(from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(),
533 ("a".to_string(), Null),
534 ("b".to_string(), Boolean(true))]));
536 "{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(),
538 ("a".to_string(), F64(1.0)),
539 ("b".to_string(), Array(vec![Boolean(true)]))
547 { \"c\": {\"d\": null} } \
551 ("a".to_string(), F64(1.0)),
552 ("b".to_string(), Array(vec![
554 String("foo\nbar".to_string()),
556 ("c".to_string(), mk_object(&[("d".to_string(), Null)]))
563 fn test_decode_struct() {
566 { \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] }
570 let v: Outer = json::decode(s).unwrap();
575 Inner { a: (), b: 2, c: vec!["abc".to_string(), "xyz".to_string()] }
581 #[derive(RustcDecodable)]
587 fn test_decode_struct_with_nan() {
588 let s = "{\"f\":null,\"a\":[null,123]}";
589 let obj: FloatStruct = json::decode(s).unwrap();
590 assert!(obj.f.is_nan());
591 assert!(obj.a[0].is_nan());
592 assert_eq!(obj.a[1], 123f64);
596 fn test_decode_option() {
597 let value: Option<string::String> = json::decode("null").unwrap();
598 assert_eq!(value, None);
600 let value: Option<string::String> = json::decode("\"jodhpurs\"").unwrap();
601 assert_eq!(value, Some("jodhpurs".to_string()));
605 fn test_decode_enum() {
606 let value: Animal = json::decode("\"Dog\"").unwrap();
607 assert_eq!(value, Dog);
609 let s = "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}";
610 let value: Animal = json::decode(s).unwrap();
611 assert_eq!(value, Frog("Henry".to_string(), 349));
615 fn test_decode_map() {
616 let s = "{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\
617 \"fields\":[\"Henry\", 349]}}";
618 let mut map: BTreeMap<string::String, Animal> = json::decode(s).unwrap();
620 assert_eq!(map.remove(&"a".to_string()), Some(Dog));
621 assert_eq!(map.remove(&"b".to_string()), Some(Frog("Henry".to_string(), 349)));
625 fn test_multiline_errors() {
626 assert_eq!(from_str("{\n \"foo\":\n \"bar\""),
627 Err(SyntaxError(EOFWhileParsingObject, 3, 8)));
630 #[derive(RustcDecodable)]
632 struct DecodeStruct {
638 #[derive(RustcDecodable)]
643 fn check_err<T: Decodable>(to_parse: &'static str, expected: DecoderError) {
644 let res: DecodeResult<T> = match from_str(to_parse) {
645 Err(e) => Err(ParseError(e)),
646 Ok(json) => Decodable::decode(&mut Decoder::new(json))
649 Ok(_) => panic!("`{:?}` parsed & decoded ok, expecting error `{:?}`",
651 Err(ParseError(e)) => panic!("`{:?}` is not valid json: {:?}",
654 assert_eq!(e, expected);
659 fn test_decode_errors_struct() {
660 check_err::<DecodeStruct>("[]", ExpectedError("Object".to_string(), "[]".to_string()));
661 check_err::<DecodeStruct>("{\"x\": true, \"y\": true, \"z\": \"\", \"w\": []}",
662 ExpectedError("Number".to_string(), "true".to_string()));
663 check_err::<DecodeStruct>("{\"x\": 1, \"y\": [], \"z\": \"\", \"w\": []}",
664 ExpectedError("Boolean".to_string(), "[]".to_string()));
665 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": {}, \"w\": []}",
666 ExpectedError("String".to_string(), "{}".to_string()));
667 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\", \"w\": null}",
668 ExpectedError("Array".to_string(), "null".to_string()));
669 check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\"}",
670 MissingFieldError("w".to_string()));
673 fn test_decode_errors_enum() {
674 check_err::<DecodeEnum>("{}",
675 MissingFieldError("variant".to_string()));
676 check_err::<DecodeEnum>("{\"variant\": 1}",
677 ExpectedError("String".to_string(), "1".to_string()));
678 check_err::<DecodeEnum>("{\"variant\": \"A\"}",
679 MissingFieldError("fields".to_string()));
680 check_err::<DecodeEnum>("{\"variant\": \"A\", \"fields\": null}",
681 ExpectedError("Array".to_string(), "null".to_string()));
682 check_err::<DecodeEnum>("{\"variant\": \"C\", \"fields\": []}",
683 UnknownVariantError("C".to_string()));
688 let json_value = from_str("{\"dog\" : \"cat\"}").unwrap();
689 let found_str = json_value.find("dog");
690 assert!(found_str.unwrap().as_string().unwrap() == "cat");
695 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
696 let found_str = json_value.find_path(&["dog", "cat", "mouse"]);
697 assert!(found_str.unwrap().as_string().unwrap() == "cheese");
702 let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap();
703 let found_str = json_value.search("mouse").and_then(|j| j.as_string());
704 assert!(found_str.unwrap() == "cheese");
709 let json_value = from_str("{\"animals\":[\"dog\",\"cat\",\"mouse\"]}").unwrap();
710 let ref array = json_value["animals"];
711 assert_eq!(array[0].as_string().unwrap(), "dog");
712 assert_eq!(array[1].as_string().unwrap(), "cat");
713 assert_eq!(array[2].as_string().unwrap(), "mouse");
718 let json_value = from_str("{}").unwrap();
719 assert!(json_value.is_object());
724 let json_value = from_str("{}").unwrap();
725 let json_object = json_value.as_object();
726 assert!(json_object.is_some());
731 let json_value = from_str("[1, 2, 3]").unwrap();
732 assert!(json_value.is_array());
737 let json_value = from_str("[1, 2, 3]").unwrap();
738 let json_array = json_value.as_array();
739 let expected_length = 3;
740 assert!(json_array.is_some() && json_array.unwrap().len() == expected_length);
745 let json_value = from_str("\"dog\"").unwrap();
746 assert!(json_value.is_string());
751 let json_value = from_str("\"dog\"").unwrap();
752 let json_str = json_value.as_string();
753 let expected_str = "dog";
754 assert_eq!(json_str, Some(expected_str));
759 let json_value = from_str("12").unwrap();
760 assert!(json_value.is_number());
765 let json_value = from_str("-12").unwrap();
766 assert!(json_value.is_i64());
768 let json_value = from_str("12").unwrap();
769 assert!(!json_value.is_i64());
771 let json_value = from_str("12.0").unwrap();
772 assert!(!json_value.is_i64());
777 let json_value = from_str("12").unwrap();
778 assert!(json_value.is_u64());
780 let json_value = from_str("-12").unwrap();
781 assert!(!json_value.is_u64());
783 let json_value = from_str("12.0").unwrap();
784 assert!(!json_value.is_u64());
789 let json_value = from_str("12").unwrap();
790 assert!(!json_value.is_f64());
792 let json_value = from_str("-12").unwrap();
793 assert!(!json_value.is_f64());
795 let json_value = from_str("12.0").unwrap();
796 assert!(json_value.is_f64());
798 let json_value = from_str("-12.0").unwrap();
799 assert!(json_value.is_f64());
804 let json_value = from_str("-12").unwrap();
805 let json_num = json_value.as_i64();
806 assert_eq!(json_num, Some(-12));
811 let json_value = from_str("12").unwrap();
812 let json_num = json_value.as_u64();
813 assert_eq!(json_num, Some(12));
818 let json_value = from_str("12.0").unwrap();
819 let json_num = json_value.as_f64();
820 assert_eq!(json_num, Some(12f64));
824 fn test_is_boolean(){
825 let json_value = from_str("false").unwrap();
826 assert!(json_value.is_boolean());
830 fn test_as_boolean(){
831 let json_value = from_str("false").unwrap();
832 let json_bool = json_value.as_boolean();
833 let expected_bool = false;
834 assert!(json_bool.is_some() && json_bool.unwrap() == expected_bool);
839 let json_value = from_str("null").unwrap();
840 assert!(json_value.is_null());
845 let json_value = from_str("null").unwrap();
846 let json_null = json_value.as_null();
847 let expected_null = ();
848 assert!(json_null.is_some() && json_null.unwrap() == expected_null);
852 fn test_encode_hashmap_with_numeric_key() {
853 use std::str::from_utf8;
854 use std::collections::HashMap;
855 let mut hm: HashMap<usize, bool> = HashMap::new();
857 let mut mem_buf = Vec::new();
858 write!(&mut mem_buf, "{}", json::as_pretty_json(&hm)).unwrap();
859 let json_str = from_utf8(&mem_buf[..]).unwrap();
860 match from_str(json_str) {
861 Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
862 _ => {} // it parsed and we are good to go
867 fn test_prettyencode_hashmap_with_numeric_key() {
868 use std::str::from_utf8;
869 use std::collections::HashMap;
870 let mut hm: HashMap<usize, bool> = HashMap::new();
872 let mut mem_buf = Vec::new();
873 write!(&mut mem_buf, "{}", json::as_pretty_json(&hm)).unwrap();
874 let json_str = from_utf8(&mem_buf[..]).unwrap();
875 match from_str(json_str) {
876 Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
877 _ => {} // it parsed and we are good to go
882 fn test_prettyencoder_indent_level_param() {
883 use std::str::from_utf8;
884 use std::collections::BTreeMap;
886 let mut tree = BTreeMap::new();
888 tree.insert("hello".to_string(), String("guten tag".to_string()));
889 tree.insert("goodbye".to_string(), String("sayonara".to_string()));
892 // The following layout below should look a lot like
893 // the pretty-printed JSON (indent * x)
896 String("greetings".to_string()), // 1x
897 Object(tree), // 1x + 2x + 2x + 1x
899 // End JSON array (7 lines)
902 // Helper function for counting indents
903 fn indents(source: &str) -> usize {
904 let trimmed = source.trim_start_matches(' ');
905 source.len() - trimmed.len()
908 // Test up to 4 spaces of indents (more?)
910 let mut writer = Vec::new();
911 write!(&mut writer, "{}",
912 json::as_pretty_json(&json).indent(i)).unwrap();
914 let printed = from_utf8(&writer[..]).unwrap();
916 // Check for indents at each line
917 let lines: Vec<&str> = printed.lines().collect();
918 assert_eq!(lines.len(), 7); // JSON should be 7 lines
920 assert_eq!(indents(lines[0]), 0 * i); // [
921 assert_eq!(indents(lines[1]), 1 * i); // "greetings",
922 assert_eq!(indents(lines[2]), 1 * i); // {
923 assert_eq!(indents(lines[3]), 2 * i); // "hello": "guten tag",
924 assert_eq!(indents(lines[4]), 2 * i); // "goodbye": "sayonara"
925 assert_eq!(indents(lines[5]), 1 * i); // },
926 assert_eq!(indents(lines[6]), 0 * i); // ]
928 // Finally, test that the pretty-printed JSON is valid
929 from_str(printed).ok().expect("Pretty-printed JSON is invalid!");
934 fn test_hashmap_with_enum_key() {
935 use std::collections::HashMap;
936 #[derive(RustcEncodable, Eq, Hash, PartialEq, RustcDecodable, Debug)]
942 let mut map = HashMap::new();
943 map.insert(Enum::Foo, 0);
944 let result = json::encode(&map).unwrap();
945 assert_eq!(&result[..], r#"{"Foo":0}"#);
946 let decoded: HashMap<Enum, _> = json::decode(&result).unwrap();
947 assert_eq!(map, decoded);
951 fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() {
952 use std::collections::HashMap;
953 let json_str = "{\"1\":true}";
954 let json_obj = match from_str(json_str) {
955 Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
958 let mut decoder = Decoder::new(json_obj);
959 let _hm: HashMap<usize, bool> = Decodable::decode(&mut decoder).unwrap();
963 fn test_hashmap_with_numeric_key_will_error_with_string_keys() {
964 use std::collections::HashMap;
965 let json_str = "{\"a\":true}";
966 let json_obj = match from_str(json_str) {
967 Err(_) => panic!("Unable to parse json_str: {:?}", json_str),
970 let mut decoder = Decoder::new(json_obj);
971 let result: Result<HashMap<usize, bool>, DecoderError> = Decodable::decode(&mut decoder);
972 assert_eq!(result, Err(ExpectedError("Number".to_string(), "a".to_string())));
975 fn assert_stream_equal(src: &str,
976 expected: Vec<(JsonEvent, Vec<StackElement<'_>>)>) {
977 let mut parser = Parser::new(src.chars());
980 let evt = match parser.next() {
984 let (ref expected_evt, ref expected_stack) = expected[i];
985 if !parser.stack().is_equal_to(expected_stack) {
986 panic!("Parser stack is not equal to {:?}", expected_stack);
988 assert_eq!(&evt, expected_evt);
993 fn test_streaming_parser() {
995 r#"{ "foo":"bar", "array" : [0, 1, 2, 3, 4, 5], "idents":[null,true,false]}"#,
997 (ObjectStart, vec![]),
998 (StringValue("bar".to_string()), vec![StackElement::Key("foo")]),
999 (ArrayStart, vec![StackElement::Key("array")]),
1000 (U64Value(0), vec![StackElement::Key("array"), StackElement::Index(0)]),
1001 (U64Value(1), vec![StackElement::Key("array"), StackElement::Index(1)]),
1002 (U64Value(2), vec![StackElement::Key("array"), StackElement::Index(2)]),
1003 (U64Value(3), vec![StackElement::Key("array"), StackElement::Index(3)]),
1004 (U64Value(4), vec![StackElement::Key("array"), StackElement::Index(4)]),
1005 (U64Value(5), vec![StackElement::Key("array"), StackElement::Index(5)]),
1006 (ArrayEnd, vec![StackElement::Key("array")]),
1007 (ArrayStart, vec![StackElement::Key("idents")]),
1008 (NullValue, vec![StackElement::Key("idents"),
1009 StackElement::Index(0)]),
1010 (BooleanValue(true), vec![StackElement::Key("idents"),
1011 StackElement::Index(1)]),
1012 (BooleanValue(false), vec![StackElement::Key("idents"),
1013 StackElement::Index(2)]),
1014 (ArrayEnd, vec![StackElement::Key("idents")]),
1015 (ObjectEnd, vec![]),
1019 fn last_event(src: &str) -> JsonEvent {
1020 let mut parser = Parser::new(src.chars());
1021 let mut evt = NullValue;
1023 evt = match parser.next() {
1031 fn test_read_object_streaming() {
1032 assert_eq!(last_event("{ "), Error(SyntaxError(EOFWhileParsingObject, 1, 3)));
1033 assert_eq!(last_event("{1"), Error(SyntaxError(KeyMustBeAString, 1, 2)));
1034 assert_eq!(last_event("{ \"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
1035 assert_eq!(last_event("{\"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 5)));
1036 assert_eq!(last_event("{\"a\" "), Error(SyntaxError(EOFWhileParsingObject, 1, 6)));
1038 assert_eq!(last_event("{\"a\" 1"), Error(SyntaxError(ExpectedColon, 1, 6)));
1039 assert_eq!(last_event("{\"a\":"), Error(SyntaxError(EOFWhileParsingValue, 1, 6)));
1040 assert_eq!(last_event("{\"a\":1"), Error(SyntaxError(EOFWhileParsingObject, 1, 7)));
1041 assert_eq!(last_event("{\"a\":1 1"), Error(SyntaxError(InvalidSyntax, 1, 8)));
1042 assert_eq!(last_event("{\"a\":1,"), Error(SyntaxError(EOFWhileParsingObject, 1, 8)));
1043 assert_eq!(last_event("{\"a\":1,}"), Error(SyntaxError(TrailingComma, 1, 8)));
1045 assert_stream_equal(
1047 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"),
1091 StackElement::Index(0)]),
1092 (StringValue("foo\nbar".to_string()), vec![StackElement::Key("b"),
1093 StackElement::Index(1)]),
1094 (ObjectStart, vec![StackElement::Key("b"),
1095 StackElement::Index(2)]),
1096 (ObjectStart, vec![StackElement::Key("b"),
1097 StackElement::Index(2),
1098 StackElement::Key("c")]),
1099 (NullValue, vec![StackElement::Key("b"),
1100 StackElement::Index(2),
1101 StackElement::Key("c"),
1102 StackElement::Key("d")]),
1103 (ObjectEnd, vec![StackElement::Key("b"),
1104 StackElement::Index(2),
1105 StackElement::Key("c")]),
1106 (ObjectEnd, vec![StackElement::Key("b"),
1107 StackElement::Index(2)]),
1108 (ArrayEnd, vec![StackElement::Key("b")]),
1109 (ObjectEnd, vec![]),
1114 fn test_read_array_streaming() {
1115 assert_stream_equal(
1118 (ArrayStart, vec![]),
1122 assert_stream_equal(
1125 (ArrayStart, vec![]),
1129 assert_stream_equal(
1132 (ArrayStart, vec![]),
1133 (BooleanValue(true), vec![StackElement::Index(0)]),
1137 assert_stream_equal(
1140 (ArrayStart, vec![]),
1141 (BooleanValue(false), vec![StackElement::Index(0)]),
1145 assert_stream_equal(
1148 (ArrayStart, vec![]),
1149 (NullValue, vec![StackElement::Index(0)]),
1153 assert_stream_equal(
1156 (ArrayStart, vec![]),
1157 (U64Value(3), vec![StackElement::Index(0)]),
1158 (U64Value(1), vec![StackElement::Index(1)]),
1162 assert_stream_equal(
1165 (ArrayStart, vec![]),
1166 (U64Value(3), vec![StackElement::Index(0)]),
1167 (U64Value(2), vec![StackElement::Index(1)]),
1171 assert_stream_equal(
1174 (ArrayStart, vec![]),
1175 (U64Value(2), vec![StackElement::Index(0)]),
1176 (ArrayStart, vec![StackElement::Index(1)]),
1177 (U64Value(4), vec![StackElement::Index(1), StackElement::Index(0)]),
1178 (U64Value(1), vec![StackElement::Index(1), StackElement::Index(1)]),
1179 (ArrayEnd, vec![StackElement::Index(1)]),
1184 assert_eq!(last_event("["), Error(SyntaxError(EOFWhileParsingValue, 1, 2)));
1186 assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2)));
1187 assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3)));
1188 assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4)));
1189 assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
1190 assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4)));
1194 fn test_trailing_characters_streaming() {
1195 assert_eq!(last_event("nulla"), Error(SyntaxError(TrailingCharacters, 1, 5)));
1196 assert_eq!(last_event("truea"), Error(SyntaxError(TrailingCharacters, 1, 5)));
1197 assert_eq!(last_event("falsea"), Error(SyntaxError(TrailingCharacters, 1, 6)));
1198 assert_eq!(last_event("1a"), Error(SyntaxError(TrailingCharacters, 1, 2)));
1199 assert_eq!(last_event("[]a"), Error(SyntaxError(TrailingCharacters, 1, 3)));
1200 assert_eq!(last_event("{}a"), Error(SyntaxError(TrailingCharacters, 1, 3)));
1203 fn test_read_identifiers_streaming() {
1204 assert_eq!(Parser::new("null".chars()).next(), Some(NullValue));
1205 assert_eq!(Parser::new("true".chars()).next(), Some(BooleanValue(true)));
1206 assert_eq!(Parser::new("false".chars()).next(), Some(BooleanValue(false)));
1208 assert_eq!(last_event("n"), Error(SyntaxError(InvalidSyntax, 1, 2)));
1209 assert_eq!(last_event("nul"), Error(SyntaxError(InvalidSyntax, 1, 4)));
1210 assert_eq!(last_event("t"), Error(SyntaxError(InvalidSyntax, 1, 2)));
1211 assert_eq!(last_event("truz"), Error(SyntaxError(InvalidSyntax, 1, 4)));
1212 assert_eq!(last_event("f"), Error(SyntaxError(InvalidSyntax, 1, 2)));
1213 assert_eq!(last_event("faz"), Error(SyntaxError(InvalidSyntax, 1, 3)));
1218 use std::collections::{HashMap,BTreeMap};
1221 let array2 = Array(vec![U64(1), U64(2)]);
1222 let array3 = Array(vec![U64(1), U64(2), U64(3)]);
1224 let mut tree_map = BTreeMap::new();
1225 tree_map.insert("a".to_string(), U64(1));
1226 tree_map.insert("b".to_string(), U64(2));
1230 assert_eq!(array2.to_json(), array2);
1231 assert_eq!(object.to_json(), object);
1232 assert_eq!(3_isize.to_json(), I64(3));
1233 assert_eq!(4_i8.to_json(), I64(4));
1234 assert_eq!(5_i16.to_json(), I64(5));
1235 assert_eq!(6_i32.to_json(), I64(6));
1236 assert_eq!(7_i64.to_json(), I64(7));
1237 assert_eq!(8_usize.to_json(), U64(8));
1238 assert_eq!(9_u8.to_json(), U64(9));
1239 assert_eq!(10_u16.to_json(), U64(10));
1240 assert_eq!(11_u32.to_json(), U64(11));
1241 assert_eq!(12_u64.to_json(), U64(12));
1242 assert_eq!(13.0_f32.to_json(), F64(13.0_f64));
1243 assert_eq!(14.0_f64.to_json(), F64(14.0_f64));
1244 assert_eq!(().to_json(), Null);
1245 assert_eq!(f32::INFINITY.to_json(), Null);
1246 assert_eq!(f64::NAN.to_json(), Null);
1247 assert_eq!(true.to_json(), Boolean(true));
1248 assert_eq!(false.to_json(), Boolean(false));
1249 assert_eq!("abc".to_json(), String("abc".to_string()));
1250 assert_eq!("abc".to_string().to_json(), String("abc".to_string()));
1251 assert_eq!((1_usize, 2_usize).to_json(), array2);
1252 assert_eq!((1_usize, 2_usize, 3_usize).to_json(), array3);
1253 assert_eq!([1_usize, 2_usize].to_json(), array2);
1254 assert_eq!((&[1_usize, 2_usize, 3_usize]).to_json(), array3);
1255 assert_eq!((vec![1_usize, 2_usize]).to_json(), array2);
1256 assert_eq!(vec![1_usize, 2_usize, 3_usize].to_json(), array3);
1257 let mut tree_map = BTreeMap::new();
1258 tree_map.insert("a".to_string(), 1 as usize);
1259 tree_map.insert("b".to_string(), 2);
1260 assert_eq!(tree_map.to_json(), object);
1261 let mut hash_map = HashMap::new();
1262 hash_map.insert("a".to_string(), 1 as usize);
1263 hash_map.insert("b".to_string(), 2);
1264 assert_eq!(hash_map.to_json(), object);
1265 assert_eq!(Some(15).to_json(), I64(15));
1266 assert_eq!(Some(15 as usize).to_json(), U64(15));
1267 assert_eq!(None::<isize>.to_json(), Null);
1271 fn test_encode_hashmap_with_arbitrary_key() {
1272 use std::collections::HashMap;
1273 #[derive(PartialEq, Eq, Hash, RustcEncodable)]
1274 struct ArbitraryType(usize);
1275 let mut hm: HashMap<ArbitraryType, bool> = HashMap::new();
1276 hm.insert(ArbitraryType(1), true);
1277 let mut mem_buf = string::String::new();
1278 let mut encoder = Encoder::new(&mut mem_buf);
1279 let result = hm.encode(&mut encoder);
1280 match result.unwrap_err() {
1281 EncoderError::BadHashmapKey => (),
1282 _ => panic!("expected bad hash map key")