Debian Codegraph @

third_party/rust/ron/tests/escape.rs

raw
1 use std::{char::from_u32, fmt::Debug};
2
3 use ron::{de::from_str, ser::to_string};
4 use serde::{Deserialize, Serialize};
5
6 #[test]
7 fn test_escape_basic() {
8 assert_eq!(to_string(&"\x07").unwrap(), "\"\\u{7}\"");
9
10 assert_eq!(from_str::<String>("\"\\x07\"").unwrap(), "\x07");
11 assert_eq!(from_str::<String>("\"\\u{7}\"").unwrap(), "\x07");
12
13 assert_eq!(from_str::<char>("\'\\x07\'").unwrap(), '\x07');
14 assert_eq!(from_str::<char>("\'\\u{7}\'").unwrap(), '\x07');
15
16 assert_eq!(
17 from_str::<char>("\'\\u{}\'").unwrap_err(),
18 ron::error::SpannedError {
19 code: ron::Error::InvalidEscape("Expected 1-6 digits, got 0 digits in Unicode escape"),
20 position: ron::error::Position { line: 1, col: 5 },
21 }
22 );
23
24 assert_eq!(
25 from_str::<char>("\'\\q\'").unwrap_err(),
26 ron::error::SpannedError {
27 code: ron::Error::InvalidEscape("Unknown escape character"),
28 position: ron::error::Position { line: 1, col: 4 },
29 }
30 )
31 }
32
33 fn check_same<T>(t: T)
34 where
35 T: Debug + for<'a> Deserialize<'a> + PartialEq + Serialize,
36 {
37 let s: String = to_string(&t).unwrap();
38
39 println!("Serialized: \n\n{}\n\n", s);
40
41 assert_eq!(from_str(&s), Ok(t));
42 }
43
44 #[test]
45 fn test_ascii_10() {
46 check_same("\u{10}".to_owned());
47 }
48
49 #[test]
50 fn test_ascii_chars() {
51 (1..128).flat_map(from_u32).for_each(check_same)
52 }
53
54 #[test]
55 fn test_ascii_string() {
56 let s: String = (1..128).flat_map(from_u32).collect();
57
58 check_same(s);
59 }
60
61 #[test]
62 fn test_non_ascii() {
63 assert_eq!(to_string(&"♠").unwrap(), "\"♠\"");
64 assert_eq!(to_string(&"ß").unwrap(), "\"ß\"");
65 assert_eq!(to_string(&"ä").unwrap(), "\"ä\"");
66 assert_eq!(to_string(&"ö").unwrap(), "\"ö\"");
67 assert_eq!(to_string(&"ü").unwrap(), "\"ü\"");
68 }
69
70 #[test]
71 fn test_chars() {
72 assert_eq!(to_string(&'♠').unwrap(), "'♠'");
73 assert_eq!(to_string(&'ß').unwrap(), "'ß'");
74 assert_eq!(to_string(&'ä').unwrap(), "'ä'");
75 assert_eq!(to_string(&'ö').unwrap(), "'ö'");
76 assert_eq!(to_string(&'ü').unwrap(), "'ü'");
77 assert_eq!(to_string(&'\u{715}').unwrap(), "'\u{715}'");
78 assert_eq!(
79 from_str::<char>("'\u{715}'").unwrap(),
80 from_str("'\\u{715}'").unwrap()
81 );
82 }
83
84 #[test]
85 fn test_nul_in_string() {
86 assert_eq!(
87 from_str("\"Hello\0World!\""),
88 Ok(String::from("Hello\0World!"))
89 );
90
91 check_same("Hello\0World!".to_owned());
92 check_same("Hello\x00World!".to_owned());
93 check_same("Hello\u{0}World!".to_owned());
94 }