1 #[cfg_attr(rustfmt, rustfmt_skip)]
2 static RUST_KEYWORDS: &'static [&'static str] = &[
3 "as",
4 "async",
5 "await",
6 "break",
7 "crate",
8 "dyn",
9 "else",
10 "enum",
11 "extern",
12 "false",
13 "fn",
14 "for",
15 "if",
16 "impl",
17 "in",
18 "let",
19 "loop",
20 "match",
21 "mod",
22 "move",
23 "mut",
24 "pub",
25 "ref",
26 "return",
27 "static",
28 "self",
29 "Self",
30 "struct",
31 "super",
32 "true",
33 "trait",
34 "type",
35 "unsafe",
36 "use",
37 "while",
38 "continue",
39 "box",
40 "const",
41 "where",
42 "virtual",
43 "proc",
44 "alignof",
45 "become",
46 "offsetof",
47 "priv",
48 "pure",
49 "sizeof",
50 "typeof",
51 "unsized",
52 "yield",
53 "do",
54 "abstract",
55 "final",
56 "override",
57 "macro",
58 ];
59
is_rust_keyword(ident: &str) -> bool60 pub fn is_rust_keyword(ident: &str) -> bool {
61 RUST_KEYWORDS.contains(&ident)
62 }
63
hex_digit(value: u32) -> char64 fn hex_digit(value: u32) -> char {
65 if value < 10 {
66 (b'0' + value as u8) as char
67 } else if value < 0x10 {
68 (b'a' + value as u8 - 10) as char
69 } else {
70 unreachable!()
71 }
72 }
73
quote_escape_str(s: &str) -> String74 pub fn quote_escape_str(s: &str) -> String {
75 let mut buf = String::new();
76 buf.push('"');
77 buf.extend(s.chars().flat_map(|c| c.escape_default()));
78 buf.push('"');
79 buf
80 }
81
quote_escape_bytes(bytes: &[u8]) -> String82 pub fn quote_escape_bytes(bytes: &[u8]) -> String {
83 let mut buf = String::new();
84 buf.push('b');
85 buf.push('"');
86 for &b in bytes {
87 match b {
88 b'\n' => buf.push_str(r"\n"),
89 b'\r' => buf.push_str(r"\r"),
90 b'\t' => buf.push_str(r"\t"),
91 b'"' => buf.push_str("\\\""),
92 b'\\' => buf.push_str(r"\\"),
93 b'\x20'..=b'\x7e' => buf.push(b as char),
94 _ => {
95 buf.push_str(r"\x");
96 buf.push(hex_digit((b as u32) >> 4));
97 buf.push(hex_digit((b as u32) & 0x0f));
98 }
99 }
100 }
101 buf.push('"');
102 buf
103 }
104
105 #[cfg(test)]
106 mod test {
107
108 use super::*;
109
110 #[test]
test_quote_escape_bytes()111 fn test_quote_escape_bytes() {
112 assert_eq!("b\"\"", quote_escape_bytes(b""));
113 assert_eq!("b\"xyZW\"", quote_escape_bytes(b"xyZW"));
114 assert_eq!("b\"aa\\\"bb\"", quote_escape_bytes(b"aa\"bb"));
115 assert_eq!("b\"aa\\r\\n\\tbb\"", quote_escape_bytes(b"aa\r\n\tbb"));
116 assert_eq!(
117 "b\"\\x00\\x01\\x12\\xfe\\xff\"",
118 quote_escape_bytes(b"\x00\x01\x12\xfe\xff")
119 );
120 }
121 }
122