1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
use logos::{Lexer, Logos};
#[derive(Logos, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Escape {
#[token(r#"\b"#)]
Backspace,
#[token(r#"\t"#)]
Tab,
#[regex(r#"\\\s+\n"#)]
Newline,
#[token(r#"\n"#)]
LineFeed,
#[token(r#"\f"#)]
FormFeed,
#[token(r#"\r"#)]
CarriageReturn,
#[token(r#"\""#)]
Quote,
#[token(r#"\\"#)]
Backslash,
#[regex(r#"\\u[0-9A-Fa-f_][0-9A-Fa-f_][0-9A-Fa-f_][0-9A-Fa-f_]"#)]
Unicode,
#[regex(r#"\\U[0-9A-Fa-f_][0-9A-Fa-f_][0-9A-Fa-f_][0-9A-Fa-f_][0-9A-Fa-f_][0-9A-Fa-f_][0-9A-Fa-f_][0-9A-Fa-f_]"#)]
UnicodeLarge,
#[regex(r#"\\."#)]
Unknown,
#[error]
UnEscaped,
}
use Escape::*;
pub fn unescape(s: &str) -> Result<String, usize> {
let mut new_s = String::with_capacity(s.len());
let mut lexer: Lexer<Escape> = Lexer::new(s);
while let Some(t) = lexer.next() {
match t {
Backspace => new_s += "\u{0008}",
Tab => new_s += "\u{0009}",
LineFeed => new_s += "\u{000A}",
FormFeed => new_s += "\u{000C}",
CarriageReturn => new_s += "\u{000D}",
Quote => new_s += "\u{0022}",
Backslash => new_s += "\u{005C}",
Newline => {}
Unicode => {
new_s += &std::char::from_u32(
u32::from_str_radix(&lexer.slice()[2..], 16).map_err(|_| lexer.span().start)?,
)
.ok_or(lexer.span().start)?
.to_string();
}
UnicodeLarge => {
new_s += &std::char::from_u32(
u32::from_str_radix(&lexer.slice()[2..], 16).map_err(|_| lexer.span().start)?,
)
.ok_or(lexer.span().start)?
.to_string();
}
Unknown => return Err(lexer.span().end),
UnEscaped => {
new_s += lexer.slice();
}
}
}
Ok(new_s + lexer.remainder())
}
pub fn check_escape(s: &str) -> Result<(), Vec<usize>> {
let mut lexer: Lexer<Escape> = Lexer::new(s);
let mut invalid = Vec::new();
while let Some(t) = lexer.next() {
match t {
Backspace => {}
Tab => {}
LineFeed => {}
FormFeed => {}
CarriageReturn => {}
Quote => {}
Backslash => {}
Newline => {}
Unicode => {
let char_val = match u32::from_str_radix(&lexer.slice()[2..], 16) {
Ok(v) => v,
Err(_) => {
invalid.push(lexer.span().start);
continue;
}
};
match std::char::from_u32(char_val) {
None => {
invalid.push(lexer.span().start);
}
Some(_) => {}
};
}
UnicodeLarge => {
let char_val = match u32::from_str_radix(&lexer.slice()[2..], 16) {
Ok(v) => v,
Err(_) => {
invalid.push(lexer.span().start);
continue;
}
};
match std::char::from_u32(char_val) {
None => {
invalid.push(lexer.span().start);
}
Some(_) => {}
};
}
Unknown => invalid.push(lexer.span().start),
UnEscaped => {}
}
}
if invalid.is_empty() {
Ok(())
} else {
Err(invalid)
}
}