Debian Codegraph @

.cargo/vendor/nom/tests/json.rs

raw
1 #![cfg(feature = "alloc")]
2
3 use nom::{
4 branch::alt,
5 bytes::complete::{tag, take},
6 character::complete::{anychar, char, multispace0, none_of},
7 combinator::{map, map_opt, map_res, value, verify},
8 error::ParseError,
9 multi::{fold, separated_list0},
10 number::complete::double,
11 sequence::{delimited, preceded, separated_pair},
12 IResult, Parser,
13 };
14
15 use std::collections::HashMap;
16
17 #[derive(Debug, PartialEq, Clone)]
18 pub enum JsonValue {
19 Null,
20 Bool(bool),
21 Str(String),
22 Num(f64),
23 Array(Vec<JsonValue>),
24 Object(HashMap<String, JsonValue>),
25 }
26
27 fn boolean(input: &str) -> IResult<&str, bool> {
28 alt((value(false, tag("false")), value(true, tag("true")))).parse(input)
29 }
30
31 fn u16_hex(input: &str) -> IResult<&str, u16> {
32 map_res(take(4usize), |s| u16::from_str_radix(s, 16)).parse(input)
33 }
34
35 fn unicode_escape(input: &str) -> IResult<&str, char> {
36 map_opt(
37 alt((
38 // Not a surrogate
39 map(verify(u16_hex, |cp| !(0xD800..0xE000).contains(cp)), |cp| {
40 cp as u32
41 }),
42 // See https://en.wikipedia.org/wiki/UTF-16#Code_points_from_U+010000_to_U+10FFFF for details
43 map(
44 verify(
45 separated_pair(u16_hex, tag("\\u"), u16_hex),
46 |(high, low)| (0xD800..0xDC00).contains(high) && (0xDC00..0xE000).contains(low),
47 ),
48 |(high, low)| {
49 let high_ten = (high as u32) - 0xD800;
50 let low_ten = (low as u32) - 0xDC00;
51 (high_ten << 10) + low_ten + 0x10000
52 },
53 ),
54 )),
55 // Could be probably replaced with .unwrap() or _unchecked due to the verify checks
56 std::char::from_u32,
57 )
58 .parse(input)
59 }
60
61 fn character(input: &str) -> IResult<&str, char> {
62 let (input, c) = none_of("\"")(input)?;
63 if c == '\\' {
64 alt((
65 map_res(anychar, |c| {
66 Ok(match c {
67 '"' | '\\' | '/' => c,
68 'b' => '\x08',
69 'f' => '\x0C',
70 'n' => '\n',
71 'r' => '\r',
72 't' => '\t',
73 _ => return Err(()),
74 })
75 }),
76 preceded(char('u'), unicode_escape),
77 ))
78 .parse(input)
79 } else {
80 Ok((input, c))
81 }
82 }
83
84 fn string(input: &str) -> IResult<&str, String> {
85 delimited(
86 char('"'),
87 fold(0.., character, String::new, |mut string, c| {
88 string.push(c);
89 string
90 }),
91 char('"'),
92 )
93 .parse(input)
94 }
95
96 fn ws<'a, O, E: ParseError<&'a str>, F: Parser<&'a str, Output = O, Error = E>>(
97 f: F,
98 ) -> impl Parser<&'a str, Output = O, Error = E> {
99 delimited(multispace0, f, multispace0)
100 }
101
102 fn array(input: &str) -> IResult<&str, Vec<JsonValue>> {
103 delimited(
104 char('['),
105 ws(separated_list0(ws(char(',')), json_value)),
106 char(']'),
107 )
108 .parse(input)
109 }
110
111 fn object(input: &str) -> IResult<&str, HashMap<String, JsonValue>> {
112 map(
113 delimited(
114 char('{'),
115 ws(separated_list0(
116 ws(char(',')),
117 separated_pair(string, ws(char(':')), json_value),
118 )),
119 char('}'),
120 ),
121 |key_values| key_values.into_iter().collect(),
122 )
123 .parse(input)
124 }
125
126 fn json_value(input: &str) -> IResult<&str, JsonValue> {
127 use JsonValue::*;
128
129 alt((
130 value(Null, tag("null")),
131 map(boolean, Bool),
132 map(string, Str),
133 map(double, Num),
134 map(array, Array),
135 map(object, Object),
136 ))
137 .parse(input)
138 }
139
140 fn json(input: &str) -> IResult<&str, JsonValue> {
141 ws(json_value).parse(input)
142 }
143
144 #[test]
145 fn json_string() {
146 assert_eq!(string("\"\""), Ok(("", "".to_string())));
147 assert_eq!(string("\"abc\""), Ok(("", "abc".to_string())));
148 assert_eq!(
149 string("\"abc\\\"\\\\\\/\\b\\f\\n\\r\\t\\u0001\\u2014\u{2014}def\""),
150 Ok(("", "abc\"\\/\x08\x0C\n\r\t\x01β€”β€”def".to_string())),
151 );
152 assert_eq!(string("\"\\uD83D\\uDE10\""), Ok(("", "😐".to_string())));
153
154 assert!(string("\"").is_err());
155 assert!(string("\"abc").is_err());
156 assert!(string("\"\\\"").is_err());
157 assert!(string("\"\\u123\"").is_err());
158 assert!(string("\"\\uD800\"").is_err());
159 assert!(string("\"\\uD800\\uD800\"").is_err());
160 assert!(string("\"\\uDC00\"").is_err());
161 }
162
163 #[test]
164 fn json_object() {
165 use JsonValue::*;
166
167 let input = r#"{"a":42,"b":"x"}"#;
168
169 let expected = Object(
170 vec![
171 ("a".to_string(), Num(42.0)),
172 ("b".to_string(), Str("x".to_string())),
173 ]
174 .into_iter()
175 .collect(),
176 );
177
178 assert_eq!(json(input), Ok(("", expected)));
179 }
180
181 #[test]
182 fn json_array() {
183 use JsonValue::*;
184
185 let input = r#"[42,"x"]"#;
186
187 let expected = Array(vec![Num(42.0), Str("x".to_string())]);
188
189 assert_eq!(json(input), Ok(("", expected)));
190 }
191
192 #[test]
193 fn json_whitespace() {
194 use JsonValue::*;
195
196 let input = r#"
197 {
198 "null" : null,
199 "true" :true ,
200 "false": false ,
201 "number" : 123e4 ,
202 "string" : " abc 123 " ,
203 "array" : [ false , 1 , "two" ] ,
204 "object" : { "a" : 1.0 , "b" : "c" } ,
205 "empty_array" : [ ] ,
206 "empty_object" : { }
207 }
208 "#;
209
210 assert_eq!(
211 json(input),
212 Ok((
213 "",
214 Object(
215 vec![
216 ("null".to_string(), Null),
217 ("true".to_string(), Bool(true)),
218 ("false".to_string(), Bool(false)),
219 ("number".to_string(), Num(123e4)),
220 ("string".to_string(), Str(" abc 123 ".to_string())),
221 (
222 "array".to_string(),
223 Array(vec![Bool(false), Num(1.0), Str("two".to_string())])
224 ),
225 (
226 "object".to_string(),
227 Object(
228 vec![
229 ("a".to_string(), Num(1.0)),
230 ("b".to_string(), Str("c".to_string())),
231 ]
232 .into_iter()
233 .collect()
234 )
235 ),
236 ("empty_array".to_string(), Array(vec![]),),
237 ("empty_object".to_string(), Object(HashMap::new()),),
238 ]
239 .into_iter()
240 .collect()
241 )
242 ))
243 );
244 }