1 #![allow(rustc::internal)]
3 use json::ErrorCode::*;
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;
12 use std::collections::BTreeMap;
13 use std::io::prelude::*;
17 #[derive(Eq, PartialEq, Debug)]
22 #[derive(PartialEq, Encodable, Debug)]
25 Frog(string::String, isize),
28 #[derive(PartialEq, Encodable, Debug)]
32 c: Vec<string::String>,
35 #[derive(PartialEq, Encodable, Debug)]
40 fn mk_object(items: &[(string::String, Json)]) -> Json {
41 let mut d = BTreeMap::new();
45 (ref key, ref value) => {
46 d.insert((*key).clone(), (*value).clone());
55 fn test_from_str_trait() {
57 assert!(s.parse::<Json>().unwrap() == s.parse().unwrap());
61 fn test_write_null() {
62 assert_eq!(Null.to_string(), "null");
63 assert_eq!(Null.pretty().to_string(), "null");
68 assert_eq!(U64(0).to_string(), "0");
69 assert_eq!(U64(0).pretty().to_string(), "0");
71 assert_eq!(U64(1234).to_string(), "1234");
72 assert_eq!(U64(1234).pretty().to_string(), "1234");
74 assert_eq!(I64(-5678).to_string(), "-5678");
75 assert_eq!(I64(-5678).pretty().to_string(), "-5678");
77 assert_eq!(U64(7650007200025252000).to_string(), "7650007200025252000");
78 assert_eq!(U64(7650007200025252000).pretty().to_string(), "7650007200025252000");
83 assert_eq!(F64(3.0).to_string(), "3.0");
84 assert_eq!(F64(3.0).pretty().to_string(), "3.0");
86 assert_eq!(F64(3.1).to_string(), "3.1");
87 assert_eq!(F64(3.1).pretty().to_string(), "3.1");
89 assert_eq!(F64(-1.5).to_string(), "-1.5");
90 assert_eq!(F64(-1.5).pretty().to_string(), "-1.5");
92 assert_eq!(F64(0.5).to_string(), "0.5");
93 assert_eq!(F64(0.5).pretty().to_string(), "0.5");
95 assert_eq!(F64(f64::NAN).to_string(), "null");
96 assert_eq!(F64(f64::NAN).pretty().to_string(), "null");
98 assert_eq!(F64(f64::INFINITY).to_string(), "null");
99 assert_eq!(F64(f64::INFINITY).pretty().to_string(), "null");
101 assert_eq!(F64(f64::NEG_INFINITY).to_string(), "null");
102 assert_eq!(F64(f64::NEG_INFINITY).pretty().to_string(), "null");
106 fn test_write_str() {
107 assert_eq!(String("".to_string()).to_string(), "\"\"");
108 assert_eq!(String("".to_string()).pretty().to_string(), "\"\"");
110 assert_eq!(String("homura".to_string()).to_string(), "\"homura\"");
111 assert_eq!(String("madoka".to_string()).pretty().to_string(), "\"madoka\"");
115 fn test_write_bool() {
116 assert_eq!(Boolean(true).to_string(), "true");
117 assert_eq!(Boolean(true).pretty().to_string(), "true");
119 assert_eq!(Boolean(false).to_string(), "false");
120 assert_eq!(Boolean(false).pretty().to_string(), "false");
124 fn test_write_array() {
125 assert_eq!(Array(vec![]).to_string(), "[]");
126 assert_eq!(Array(vec![]).pretty().to_string(), "[]");
128 assert_eq!(Array(vec![Boolean(true)]).to_string(), "[true]");
130 Array(vec![Boolean(true)]).pretty().to_string(),
137 let long_test_array =
138 Array(vec![Boolean(false), Null, Array(vec![String("foo\nbar".to_string()), F64(3.5)])]);
140 assert_eq!(long_test_array.to_string(), "[false,null,[\"foo\\nbar\",3.5]]");
142 long_test_array.pretty().to_string(),
156 fn test_write_object() {
157 assert_eq!(mk_object(&[]).to_string(), "{}");
158 assert_eq!(mk_object(&[]).pretty().to_string(), "{}");
160 assert_eq!(mk_object(&[("a".to_string(), Boolean(true))]).to_string(), "{\"a\":true}");
162 mk_object(&[("a".to_string(), Boolean(true))]).pretty().to_string(),
169 let complex_obj = mk_object(&[(
172 mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
173 mk_object(&[("d".to_string(), String("".to_string()))]),
178 complex_obj.to_string(),
187 complex_obj.pretty().to_string(),
192 \"c\": \"\\f\\r\"\n \
202 ("a".to_string(), Boolean(true)),
206 mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]),
207 mk_object(&[("d".to_string(), String("".to_string()))]),
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());
219 fn test_write_enum() {
221 assert_eq!(json::as_json(&animal).to_string(), "\"Dog\"");
222 assert_eq!(json::as_pretty_json(&animal).to_string(), "\"Dog\"");
224 let animal = Frog("Henry".to_string(), 349);
226 json::as_json(&animal).to_string(),
227 "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}"
230 json::as_pretty_json(&animal).to_string(),
232 \"variant\": \"Frog\",\n \
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);
246 let s = json::as_pretty_json(&$value).to_string();
247 assert_eq!(s, $expected);
252 fn test_write_some() {
253 check_encoder_for_simple!(Some("jodhpurs".to_string()), "\"jodhpurs\"");
257 fn test_write_none() {
258 check_encoder_for_simple!(None::<string::String>, "null");
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}\"");
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)));
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)));
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)));
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)));
311 assert_eq!(from_str("18446744073709551616"), Err(SyntaxError(InvalidNumber, 1, 20)));
312 assert_eq!(from_str("-9223372036854775809"), Err(SyntaxError(InvalidNumber, 1, 21)));
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)));
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)));
330 assert_eq!(from_str("\""), Err(SyntaxError(EOFWhileParsingString, 1, 2)));
331 assert_eq!(from_str("\"lol"), Err(SyntaxError(EOFWhileParsingString, 1, 5)));
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())));
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)));
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)])])));
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)));
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)));
378 assert_eq!(from_str("{}").unwrap(), mk_object(&[]));
379 assert_eq!(from_str("{\"a\": 3}").unwrap(), mk_object(&[("a".to_string(), U64(3))]));
382 from_str("{ \"a\": null, \"b\" : true }").unwrap(),
383 mk_object(&[("a".to_string(), Null), ("b".to_string(), Boolean(true))])
386 from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(),
387 mk_object(&[("a".to_string(), Null), ("b".to_string(), Boolean(true))])
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)]))])
400 { \"c\": {\"d\": null} } \
406 ("a".to_string(), F64(1.0)),
411 String("foo\nbar".to_string()),
412 mk_object(&[("c".to_string(), mk_object(&[("d".to_string(), Null)]))])
420 fn test_multiline_errors() {
421 assert_eq!(from_str("{\n \"foo\":\n \"bar\""), Err(SyntaxError(EOFWhileParsingObject, 3, 8)));
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");
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");
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");
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");
455 fn test_is_object() {
456 let json_value = from_str("{}").unwrap();
457 assert!(json_value.is_object());
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());
469 let json_value = from_str("[1, 2, 3]").unwrap();
470 assert!(json_value.is_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);
482 fn test_is_string() {
483 let json_value = from_str("\"dog\"").unwrap();
484 assert!(json_value.is_string());
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));
496 fn test_is_number() {
497 let json_value = from_str("12").unwrap();
498 assert!(json_value.is_number());
503 let json_value = from_str("-12").unwrap();
504 assert!(json_value.is_i64());
506 let json_value = from_str("12").unwrap();
507 assert!(!json_value.is_i64());
509 let json_value = from_str("12.0").unwrap();
510 assert!(!json_value.is_i64());
515 let json_value = from_str("12").unwrap();
516 assert!(json_value.is_u64());
518 let json_value = from_str("-12").unwrap();
519 assert!(!json_value.is_u64());
521 let json_value = from_str("12.0").unwrap();
522 assert!(!json_value.is_u64());
527 let json_value = from_str("12").unwrap();
528 assert!(!json_value.is_f64());
530 let json_value = from_str("-12").unwrap();
531 assert!(!json_value.is_f64());
533 let json_value = from_str("12.0").unwrap();
534 assert!(json_value.is_f64());
536 let json_value = from_str("-12.0").unwrap();
537 assert!(json_value.is_f64());
542 let json_value = from_str("-12").unwrap();
543 let json_num = json_value.as_i64();
544 assert_eq!(json_num, Some(-12));
549 let json_value = from_str("12").unwrap();
550 let json_num = json_value.as_u64();
551 assert_eq!(json_num, Some(12));
556 let json_value = from_str("12.0").unwrap();
557 let json_num = json_value.as_f64();
558 assert_eq!(json_num, Some(12f64));
562 fn test_is_boolean() {
563 let json_value = from_str("false").unwrap();
564 assert!(json_value.is_boolean());
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);
577 let json_value = from_str("null").unwrap();
578 assert!(json_value.is_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);
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();
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
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();
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
620 fn test_prettyencoder_indent_level_param() {
621 use std::collections::BTreeMap;
622 use std::str::from_utf8;
624 let mut tree = BTreeMap::new();
626 tree.insert("hello".to_string(), String("guten tag".to_string()));
627 tree.insert("goodbye".to_string(), String("sayonara".to_string()));
630 // The following layout below should look a lot like
631 // the pretty-printed JSON (indent * x)
634 String("greetings".to_string()), // 1x
635 Object(tree), // 1x + 2x + 2x + 1x
637 // End JSON array (7 lines)
640 // Helper function for counting indents
641 fn indents(source: &str) -> usize {
642 let trimmed = source.trim_start_matches(' ');
643 source.len() - trimmed.len()
646 // Test up to 4 spaces of indents (more?)
648 let mut writer = Vec::new();
649 write!(&mut writer, "{}", json::as_pretty_json(&json).indent(i)).unwrap();
651 let printed = from_utf8(&writer[..]).unwrap();
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
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); // ]
665 // Finally, test that the pretty-printed JSON is valid
666 from_str(printed).ok().expect("Pretty-printed JSON is invalid!");
671 fn test_hashmap_with_enum_key() {
672 use std::collections::HashMap;
673 #[derive(Encodable, Eq, Hash, PartialEq, Debug)]
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}"#);
685 fn assert_stream_equal(src: &str, expected: Vec<(JsonEvent, Vec<StackElement<'_>>)>) {
686 let mut parser = Parser::new(src.chars());
689 let evt = match parser.next() {
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);
699 assert_eq!(&evt, expected_evt);
704 fn test_streaming_parser() {
706 r#"{ "foo":"bar", "array" : [0, 1, 2, 3, 4, 5], "idents":[null,true,false]}"#,
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")]),
727 fn last_event(src: &str) -> JsonEvent {
728 let mut parser = Parser::new(src.chars());
729 let mut evt = NullValue;
731 evt = match parser.next() {
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)));
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)));
753 assert_stream_equal("{}", vec![(ObjectStart, vec![]), (ObjectEnd, vec![])]);
757 (ObjectStart, vec![]),
758 (U64Value(3), vec![StackElement::Key("a")]),
763 "{ \"a\": null, \"b\" : true }",
765 (ObjectStart, vec![]),
766 (NullValue, vec![StackElement::Key("a")]),
767 (BooleanValue(true), vec![StackElement::Key("b")]),
772 "{\"a\" : 1.0 ,\"b\": [ true ]}",
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")]),
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)]),
797 StringValue("foo\nbar".to_string()),
798 vec![StackElement::Key("b"), StackElement::Index(1)],
800 (ObjectStart, vec![StackElement::Key("b"), StackElement::Index(2)]),
803 vec![StackElement::Key("b"), StackElement::Index(2), StackElement::Key("c")],
808 StackElement::Key("b"),
809 StackElement::Index(2),
810 StackElement::Key("c"),
811 StackElement::Key("d"),
816 vec![StackElement::Key("b"), StackElement::Index(2), StackElement::Key("c")],
818 (ObjectEnd, vec![StackElement::Key("b"), StackElement::Index(2)]),
819 (ArrayEnd, vec![StackElement::Key("b")]),
825 fn test_read_array_streaming() {
826 assert_stream_equal("[]", vec![(ArrayStart, vec![]), (ArrayEnd, vec![])]);
827 assert_stream_equal("[ ]", vec![(ArrayStart, vec![]), (ArrayEnd, vec![])]);
831 (ArrayStart, vec![]),
832 (BooleanValue(true), vec![StackElement::Index(0)]),
839 (ArrayStart, vec![]),
840 (BooleanValue(false), vec![StackElement::Index(0)]),
846 vec![(ArrayStart, vec![]), (NullValue, vec![StackElement::Index(0)]), (ArrayEnd, vec![])],
851 (ArrayStart, vec![]),
852 (U64Value(3), vec![StackElement::Index(0)]),
853 (U64Value(1), vec![StackElement::Index(1)]),
860 (ArrayStart, vec![]),
861 (U64Value(3), vec![StackElement::Index(0)]),
862 (U64Value(2), vec![StackElement::Index(1)]),
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)]),
879 assert_eq!(last_event("["), Error(SyntaxError(EOFWhileParsingValue, 1, 2)));
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)));
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)));
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)));
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)));
913 use std::collections::{BTreeMap, HashMap};
915 let array2 = Array(vec![U64(1), U64(2)]);
916 let array3 = Array(vec![U64(1), U64(2), U64(3)]);
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));
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);
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"),