hex_digit(value: u32) -> char1 fn hex_digit(value: u32) -> char {
2 if value < 10 {
3 (b'0' + value as u8) as char
4 } else if value < 0x10 {
5 (b'a' + value as u8 - 10) as char
6 } else {
7 unreachable!()
8 }
9 }
10
quote_escape_str(s: &str) -> String11 pub fn quote_escape_str(s: &str) -> String {
12 let mut buf = String::new();
13 buf.push('"');
14 buf.extend(s.chars().flat_map(|c| c.escape_default()));
15 buf.push('"');
16 buf
17 }
18
quote_escape_bytes(bytes: &[u8]) -> String19 pub fn quote_escape_bytes(bytes: &[u8]) -> String {
20 let mut buf = String::new();
21 buf.push('b');
22 buf.push('"');
23 for &b in bytes {
24 match b {
25 b'\n' => buf.push_str(r"\n"),
26 b'\r' => buf.push_str(r"\r"),
27 b'\t' => buf.push_str(r"\t"),
28 b'"' => buf.push_str("\\\""),
29 b'\\' => buf.push_str(r"\\"),
30 b'\x20'..=b'\x7e' => buf.push(b as char),
31 _ => {
32 buf.push_str(r"\x");
33 buf.push(hex_digit((b as u32) >> 4));
34 buf.push(hex_digit((b as u32) & 0x0f));
35 }
36 }
37 }
38 buf.push('"');
39 buf
40 }
41
42 #[cfg(test)]
43 mod test {
44
45 use super::*;
46
47 #[test]
test_quote_escape_bytes()48 fn test_quote_escape_bytes() {
49 assert_eq!("b\"\"", quote_escape_bytes(b""));
50 assert_eq!("b\"xyZW\"", quote_escape_bytes(b"xyZW"));
51 assert_eq!("b\"aa\\\"bb\"", quote_escape_bytes(b"aa\"bb"));
52 assert_eq!("b\"aa\\r\\n\\tbb\"", quote_escape_bytes(b"aa\r\n\tbb"));
53 assert_eq!(
54 "b\"\\x00\\x01\\x12\\xfe\\xff\"",
55 quote_escape_bytes(b"\x00\x01\x12\xfe\xff")
56 );
57 }
58 }
59