Debian Codegraph @

third_party/rust/ron/tests/438_rusty_byte_strings.rs

raw
1 use ron::{
2 error::{Position, SpannedError},
3 Error,
4 };
5 use serde::Deserialize;
6
7 #[derive(Debug, Deserialize, PartialEq)]
8 struct BytesStruct {
9 small: Vec<u8>,
10 #[serde(with = "serde_bytes")]
11 large: Vec<u8>,
12 }
13
14 #[test]
15 fn v_9_deprecated_base64_bytes_support() {
16 #![allow(deprecated)]
17
18 // Requires padding of the base64 data
19 assert_eq!(
20 Ok(BytesStruct {
21 small: vec![1, 2],
22 large: vec![1, 2, 3, 4]
23 }),
24 ron::from_str("BytesStruct( small:[1, 2], large:\"AQIDBA==\" )"),
25 );
26
27 // Requires no padding of the base64 data
28 assert_eq!(
29 Ok(BytesStruct {
30 small: vec![1, 2],
31 large: vec![1, 2, 3, 4, 5, 6]
32 }),
33 ron::from_str("BytesStruct( small:[1, 2], large:r\"AQIDBAUG\" )"),
34 );
35
36 // Parsing an escaped byte string is also possible
37 assert_eq!(
38 Ok(BytesStruct {
39 small: vec![1, 2],
40 large: vec![1, 2, 3, 4, 5, 6]
41 }),
42 ron::from_str("BytesStruct( small:[1, 2], large:\"\\x41Q\\x49DBA\\x55G\" )"),
43 );
44
45 // Invalid base64
46 assert_eq!(
47 Err(SpannedError {
48 code: Error::Base64Error(base64::DecodeError::InvalidByte(0, b'_')),
49 position: Position { line: 1, col: 40 }
50 }),
51 ron::from_str::<BytesStruct>("BytesStruct( small:[1, 2], large:\"_+!!\" )"),
52 );
53
54 // Invalid last base64 symbol
55 assert_eq!(
56 Err(SpannedError {
57 code: Error::Base64Error(base64::DecodeError::InvalidLastSymbol(1, b'x')),
58 position: Position { line: 1, col: 40 }
59 }),
60 ron::from_str::<BytesStruct>("BytesStruct( small:[1, 2], large:\"/x==\" )"),
61 );
62
63 // Missing padding
64 assert_eq!(
65 Err(SpannedError {
66 code: Error::Base64Error(base64::DecodeError::InvalidPadding),
67 position: Position { line: 1, col: 42 }
68 }),
69 ron::from_str::<BytesStruct>("BytesStruct( small:[1, 2], large:\"AQIDBA\" )"),
70 );
71
72 // Too much padding
73 assert_eq!(
74 Err(SpannedError {
75 code: Error::Base64Error(base64::DecodeError::InvalidByte(6, b'=')),
76 position: Position { line: 1, col: 45 }
77 }),
78 ron::from_str::<BytesStruct>("BytesStruct( small:[1, 2], large:\"AQIDBA===\" )"),
79 );
80 }
81
82 #[test]
83 fn rusty_byte_string() {
84 assert_eq!(
85 Ok(BytesStruct {
86 small: vec![1, 2],
87 large: vec![1, 2, 0, 4]
88 }),
89 ron::from_str("BytesStruct( small:[1, 2], large: b\"\\x01\\u{2}\\0\\x04\" )"),
90 );
91
92 assert_eq!(
93 ron::from_str::<String>("\"Hello \\x01 \\u{2}!\"").unwrap(),
94 "Hello \x01 \u{2}!",
95 );
96 assert_eq!(
97 &*ron::from_str::<bytes::Bytes>("b\"Hello \\x01 \\u{2}!\"").unwrap(),
98 b"Hello \x01 \x02!",
99 );
100
101 rusty_byte_string_roundtrip(b"hello", "b\"hello\"", "b\"hello\"");
102 rusty_byte_string_roundtrip(b"\"", "b\"\\\"\"", "br#\"\"\"#");
103 rusty_byte_string_roundtrip(b"\"#", "b\"\\\"#\"", "br##\"\"#\"##");
104 rusty_byte_string_roundtrip(b"\n", "b\"\\n\"", "b\"\n\"");
105
106 assert_eq!(
107 ron::from_str::<bytes::Bytes>("b\"\\xf\"").unwrap_err(),
108 SpannedError {
109 code: Error::InvalidEscape("Non-hex digit found"),
110 position: Position { line: 1, col: 7 },
111 },
112 );
113 assert_eq!(
114 ron::from_str::<bytes::Bytes>("b\"\\xf🦀\"").unwrap_err(),
115 SpannedError {
116 code: Error::InvalidEscape("Non-hex digit found"),
117 position: Position { line: 1, col: 7 },
118 },
119 );
120 let err = ron::from_str::<bytes::Bytes>("br#q\"").unwrap_err();
121 assert_eq!(
122 err,
123 SpannedError {
124 code: Error::ExpectedByteString,
125 position: Position { line: 1, col: 4 },
126 },
127 );
128 assert_eq!(format!("{}", err.code), "Expected byte string",);
129 assert_eq!(
130 ron::from_str::<bytes::Bytes>("br#\"q").unwrap_err(),
131 SpannedError {
132 code: Error::ExpectedStringEnd,
133 position: Position { line: 1, col: 5 },
134 },
135 );
136 assert_eq!(
137 ron::from_str::<String>("r#q\"").unwrap_err(),
138 SpannedError {
139 code: Error::ExpectedString,
140 position: Position { line: 1, col: 3 },
141 },
142 );
143 assert_eq!(
144 ron::from_str::<String>("r#\"q").unwrap_err(),
145 SpannedError {
146 code: Error::ExpectedStringEnd,
147 position: Position { line: 1, col: 4 },
148 },
149 );
150 }
151
152 fn rusty_byte_string_roundtrip(bytes: &[u8], ron: &str, ron_raw: &str) {
153 let ser_list = ron::to_string(bytes).unwrap();
154 let de_list: Vec<u8> = ron::from_str(&ser_list).unwrap();
155 assert_eq!(de_list, bytes);
156
157 let ser = ron::to_string(&bytes::Bytes::copy_from_slice(bytes)).unwrap();
158 assert_eq!(ser, ron);
159
160 let ser_non_raw = ron::ser::to_string_pretty(
161 &bytes::Bytes::copy_from_slice(bytes),
162 ron::ser::PrettyConfig::default(),
163 )
164 .unwrap();
165 assert_eq!(ser_non_raw, ron);
166
167 let ser_raw = ron::ser::to_string_pretty(
168 &bytes::Bytes::copy_from_slice(bytes),
169 ron::ser::PrettyConfig::default().escape_strings(false),
170 )
171 .unwrap();
172 assert_eq!(ser_raw, ron_raw);
173
174 let de: bytes::Bytes = ron::from_str(&ser).unwrap();
175 assert_eq!(de, bytes);
176
177 let de_raw: bytes::Bytes = ron::from_str(&ser_raw).unwrap();
178 assert_eq!(de_raw, bytes);
179 }
180
181 #[test]
182 fn fuzzer_failures() {
183 assert_eq!(
184 ron::to_string(&bytes::Bytes::copy_from_slice(&[
185 123, 0, 0, 0, 0, 214, 214, 214, 214, 214
186 ]))
187 .unwrap(),
188 r#"b"{\x00\x00\x00\x00\xd6\xd6\xd6\xd6\xd6""#
189 );
190 // Need to fall back to escaping so no invalid UTF-8 is produced
191 assert_eq!(
192 ron::ser::to_string_pretty(
193 &bytes::Bytes::copy_from_slice(&[123, 0, 0, 0, 0, 214, 214, 214, 214, 214]),
194 ron::ser::PrettyConfig::default().escape_strings(false)
195 )
196 .unwrap(),
197 r#"b"{\x00\x00\x00\x00\xd6\xd6\xd6\xd6\xd6""#
198 );
199
200 assert_eq!(
201 ron::to_string(&bytes::Bytes::copy_from_slice(&[123, 0, 0, 0, 0])).unwrap(),
202 r#"b"{\x00\x00\x00\x00""#
203 );
204 assert_eq!(
205 ron::ser::to_string_pretty(
206 &bytes::Bytes::copy_from_slice(&[123, 0, 0, 0, 0]),
207 ron::ser::PrettyConfig::default().escape_strings(false)
208 )
209 .unwrap(),
210 "b\"{\x00\x00\x00\x00\""
211 );
212
213 // `br#` should be parsed as the start of a byte string, not the identifier `br` and a `#`
214 assert_eq!(
215 ron::from_str(r##"br#"""#"##),
216 Ok(ron::Value::Bytes(vec![34]))
217 );
218 assert_eq!(
219 ron::from_str(r##"{"error": br#"""#}"##),
220 Ok(ron::Value::Map(
221 [(
222 ron::Value::String(String::from("error")),
223 ron::Value::Bytes(vec![34])
224 )]
225 .into_iter()
226 .collect()
227 ))
228 );
229 assert_eq!(
230 ron::from_str(
231 r##"#![enable(unwrap_newtypes)]
232 #![enable(unwrap_variant_newtypes)]
233 Some({"error": br#"""#})
234 "##
235 ),
236 Ok(ron::Value::Option(Some(Box::new(ron::Value::Map(
237 [(
238 ron::Value::String(String::from("error")),
239 ron::Value::Bytes(vec![34])
240 )]
241 .into_iter()
242 .collect()
243 )))))
244 );
245
246 // `br"` should be parsed as the start of a byte string, not the identifier `br` and a `"`
247 assert_eq!(ron::from_str(r#"br"""#), Ok(ron::Value::Bytes(vec![])));
248 assert_eq!(
249 ron::from_str(r#"{"error": br""}"#),
250 Ok(ron::Value::Map(
251 [(
252 ron::Value::String(String::from("error")),
253 ron::Value::Bytes(vec![])
254 )]
255 .into_iter()
256 .collect()
257 ))
258 );
259 assert_eq!(
260 ron::from_str(
261 r#"#![enable(unwrap_newtypes)]
262 #![enable(unwrap_variant_newtypes)]
263 Some({"error": br""})
264 "#
265 ),
266 Ok(ron::Value::Option(Some(Box::new(ron::Value::Map(
267 [(
268 ron::Value::String(String::from("error")),
269 ron::Value::Bytes(vec![])
270 )]
271 .into_iter()
272 .collect()
273 )))))
274 );
275
276 // Test that the struct type check for newtype variant unwrapping does
277 // not enter inside a byte string to find a bad comment start
278 assert_eq!(
279 ron::from_str::<Option<ron::Value>>(
280 r#"#![enable(unwrap_variant_newtypes)] Some(b"\xff/not a comment")"#
281 )
282 .unwrap(),
283 Some(ron::Value::Bytes(b"\xff/not a comment".to_vec()))
284 );
285
286 // `b'` should be parsed as the start of a byte literal, not the identifier `b` and a `'`
287 assert_eq!(
288 ron::from_str(r"b'\xff'"),
289 Ok(ron::Value::Number(ron::value::Number::U8(b'\xff')))
290 );
291
292 // `b`, `br`, `bq`, and `brq` should all be parsed as identifiers
293 for id in ["b", "br", "bq", "brq"] {
294 assert_eq!(ron::from_str(id), Ok(ron::Value::Unit));
295 }
296 }
297
298 #[test]
299 fn serialize_backslash_byte_string() {
300 check_roundtrip('\\', r"'\\'", r"'\\'");
301 check_roundtrip(
302 bytes::Bytes::copy_from_slice(b"\\"),
303 r#"b"\\""#,
304 "br#\"\\\"#",
305 );
306 }
307
308 fn check_roundtrip<
309 T: PartialEq + std::fmt::Debug + serde::Serialize + serde::de::DeserializeOwned,
310 >(
311 val: T,
312 cmp: &str,
313 cmp_raw: &str,
314 ) {
315 let ron = ron::to_string(&val).unwrap();
316 assert_eq!(ron, cmp);
317
318 let ron_escaped =
319 ron::ser::to_string_pretty(&val, ron::ser::PrettyConfig::default().escape_strings(true))
320 .unwrap();
321 assert_eq!(ron_escaped, cmp);
322
323 let ron_raw = ron::ser::to_string_pretty(
324 &val,
325 ron::ser::PrettyConfig::default().escape_strings(false),
326 )
327 .unwrap();
328 assert_eq!(ron_raw, cmp_raw);
329
330 let de = ron::from_str::<T>(&ron).unwrap();
331 assert_eq!(de, val);
332
333 let de_raw = ron::from_str::<T>(&ron_raw).unwrap();
334 assert_eq!(de_raw, val);
335 }
336
337 #[test]
338 fn test_weird_escapes() {
339 assert_eq!(
340 ron::from_str::<String>(r#""\u{1F980}""#),
341 Ok(String::from("\u{1F980}"))
342 );
343 assert_eq!(
344 ron::from_str::<bytes::Bytes>(r#"b"\xf0\x9f\xa6\x80""#),
345 Ok(bytes::Bytes::copy_from_slice("\u{1F980}".as_bytes()))
346 );
347 assert_eq!(
348 ron::from_str::<String>(r#""\xf0\x9f\xa6\x80""#),
349 Ok(String::from("\u{1F980}"))
350 );
351 assert_eq!(
352 ron::from_str::<String>(r#""\xf0""#),
353 Err(SpannedError {
354 code: Error::InvalidEscape("Not a valid byte-escaped Unicode character"),
355 position: Position { line: 1, col: 6 }
356 })
357 );
358 assert_eq!(
359 ron::from_str::<String>(r#""\xf0\x9f""#),
360 Err(SpannedError {
361 code: Error::InvalidEscape("Not a valid byte-escaped Unicode character"),
362 position: Position { line: 1, col: 10 }
363 })
364 );
365 assert_eq!(
366 ron::from_str::<String>(r#""\xf0\x9f\x40""#),
367 Err(SpannedError {
368 code: Error::InvalidEscape("Not a valid byte-escaped Unicode character"),
369 position: Position { line: 1, col: 14 }
370 })
371 );
372 assert_eq!(
373 ron::from_str::<String>(r#""\xf0\x9f\xa6""#),
374 Err(SpannedError {
375 code: Error::InvalidEscape("Not a valid byte-escaped Unicode character"),
376 position: Position { line: 1, col: 14 }
377 })
378 );
379 assert_eq!(
380 ron::from_str::<String>(r#""\xff\xff\xff\xff""#),
381 Err(SpannedError {
382 code: Error::InvalidEscape("Not a valid byte-escaped Unicode character"),
383 position: Position { line: 1, col: 18 }
384 })
385 );
386
387 assert_eq!(ron::from_str::<char>(r"'\u{1F980}'"), Ok('\u{1F980}'));
388 assert_eq!(
389 ron::from_str::<char>(r"'\xf0\x9f\xa6\x80'"),
390 Err(SpannedError {
391 code: Error::InvalidEscape("Not a valid byte-escaped Unicode character"),
392 position: Position { line: 1, col: 6 }
393 })
394 );
395 }
396
397 #[test]
398 fn byte_literal() {
399 assert_eq!(
400 ron::from_str("b'\0'"),
401 Ok(ron::Value::Number(ron::value::Number::U8(0)))
402 );
403 assert_eq!(
404 ron::from_str("b'\\0'"),
405 Ok(ron::Value::Number(ron::value::Number::U8(0)))
406 );
407
408 for b in 0..=255_u8 {
409 let default = std::ascii::escape_default(b)
410 .map(char::from)
411 .collect::<String>();
412 let lower = format!(r"\x{:02x}", b);
413 let upper = format!(r"\x{:02X}", b);
414
415 assert_eq!(
416 ron::from_str(&format!("b'{}'", default)),
417 Ok(ron::Value::Number(ron::value::Number::U8(b)))
418 );
419 assert_eq!(
420 ron::from_str(&format!("b'{}'", lower)),
421 Ok(ron::Value::Number(ron::value::Number::U8(b)))
422 );
423 assert_eq!(
424 ron::from_str(&format!("b'{}'", upper)),
425 Ok(ron::Value::Number(ron::value::Number::U8(b)))
426 );
427 }
428
429 assert_eq!(
430 ron::from_str::<u8>(r#"b'\u{0}'"#),
431 Err(SpannedError {
432 code: Error::InvalidEscape("Unexpected Unicode escape in byte literal"),
433 position: Position { line: 1, col: 8 },
434 })
435 );
436
437 let err = ron::from_str::<u8>(r#"b'🦀'"#).unwrap_err();
438 assert_eq!(
439 err,
440 SpannedError {
441 code: Error::ExpectedByteLiteral,
442 position: Position { line: 1, col: 4 },
443 }
444 );
445 assert_eq!(format!("{}", err.code), "Expected byte literal");
446
447 assert_eq!(
448 ron::from_str::<u8>(r#"b'qq'"#).unwrap_err(),
449 SpannedError {
450 code: Error::ExpectedByteLiteral,
451 position: Position { line: 1, col: 4 },
452 }
453 );
454
455 assert_eq!(
456 ron::from_str::<i8>(r#"b'9'"#),
457 Err(SpannedError {
458 code: Error::InvalidValueForType {
459 expected: String::from("an 8-bit signed integer"),
460 found: String::from(r#"b'9'"#)
461 },
462 position: Position { line: 1, col: 5 },
463 })
464 );
465 }
466
467 #[test]
468 fn invalid_identifier() {
469 #[allow(dead_code)]
470 #[derive(Debug, Deserialize)] // GRCOV_EXCL_LINE
471 struct Test {
472 a: i32,
473 }
474
475 for id in ["b\"", "b'", "br#", "br\"", "r\"", "r#\"", "r##"] {
476 assert_eq!(
477 ron::from_str::<Test>(&format!("({}: 42)", id)).unwrap_err(),
478 SpannedError {
479 code: Error::ExpectedIdentifier,
480 position: Position { line: 1, col: 2 },
481 }
482 );
483 }
484 }