Debian Codegraph @

src/utf8.rs

raw symbols SCIP
1 #![cfg(any(feature = "bash", feature = "fish"))]
2
3 //! Scanner for control codes, shell metacharacters, printable characters, and
4 //! UTF-8 sequences, i.e. classify each byte in a stream according to where it
5 //! appears in UTF-8.
6
7 #[derive(PartialEq)]
8 pub(crate) enum Char {
9 Bell,
10 Backspace,
11 Escape,
12 FormFeed,
13 NewLine,
14 CarriageReturn,
15 HorizontalTab,
16 VerticalTab,
17 Control(u8),
18 Backslash,
19 SingleQuote,
20 DoubleQuote,
21 Delete,
22 PrintableInert(u8),
23 Printable(u8),
24 Utf8(char),
25 }
26
27 impl Char {
28 pub fn from(ch: char) -> Self {
29 let ascii: Result<u8, _> = ch.try_into();
30 use Char::*;
31 match ascii {
32 Ok(ascii) => match ascii {
33 // ASCII control characters that frequently have dedicated backslash
34 // sequences when quoted.
35 BEL => Bell,
36 BS => Backspace,
37 ESC => Escape,
38 FF => FormFeed,
39 LF => NewLine,
40 CR => CarriageReturn,
41 TAB => HorizontalTab,
42 VT => VerticalTab,
43
44 // ASCII control characters, the rest.
45 0x00..=0x06 | 0x0E..=0x1A | 0x1C..=0x1F => Control(ascii),
46
47 // ASCII printable characters that can have dedicated backslash
48 // sequences when quoted or otherwise need some special treatment.
49 b'\\' => Backslash,
50 b'\'' => SingleQuote,
51 b'\"' => DoubleQuote,
52 DEL => Delete,
53
54 // ASCII printable letters, numbers, and "safe" punctuation.
55 b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' => PrintableInert(ascii),
56 b',' | b'.' | b'/' | b'_' | b'-' => PrintableInert(ascii),
57
58 // ASCII punctuation which can have significance in the shell.
59 b'|' | b'&' | b';' | b'(' | b')' | b'<' | b'>' => Printable(ascii),
60 b' ' | b'?' | b'[' | b']' | b'{' | b'}' | b'`' => Printable(ascii),
61 b'~' | b'!' | b'$' | b'@' | b'+' | b'=' | b'*' => Printable(ascii),
62 b'%' | b'#' | b':' | b'^' => Printable(ascii),
63
64 // UTF-8 sequences.
65 0x80..=0xff => Utf8(ch),
66 },
67 Err(_) => Utf8(ch),
68 }
69 }
70
71 #[inline]
72 pub fn is_inert(&self) -> bool {
73 matches!(self, Char::PrintableInert(_))
74 }
75 }
76
77 const BEL: u8 = 0x07; // -> \a
78 const BS: u8 = 0x08; // -> \b
79 const TAB: u8 = 0x09; // -> \t
80 const LF: u8 = 0x0A; // -> \n
81 const VT: u8 = 0x0B; // -> \v
82 const FF: u8 = 0x0C; // -> \f
83 const CR: u8 = 0x0D; // -> \r
84 const ESC: u8 = 0x1B; // -> \e
85 const DEL: u8 = 0x7F;