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
use crate::{Error, Result};
use std::borrow::Cow;
use std::str::Chars;
pub fn dedent(s: &str) -> Cow<str> {
if s.is_empty() {
return Cow::Borrowed(s);
}
let mut leading_ws = usize::MAX;
let mut non_empty_lines = 0;
for line in s.lines().filter(|line| !line.is_empty()) {
let line_leading_ws = line.chars().take_while(|ch| ch.is_whitespace()).count();
if line_leading_ws == 0 {
return Cow::Borrowed(s);
}
leading_ws = leading_ws.min(line_leading_ws);
non_empty_lines += 1;
}
let mut dedented = String::with_capacity(s.len() - leading_ws * non_empty_lines);
for line in s.lines() {
if !line.is_empty() {
dedented.extend(line.chars().skip(leading_ws));
}
dedented.push('\n');
}
if dedented.ends_with('\n') && !s.ends_with('\n') {
let new_len = dedented.len() - 1;
dedented.truncate(new_len);
}
Cow::Owned(dedented)
}
pub fn unescape(s: &str) -> Result<Cow<str>> {
for (idx, ch) in s.chars().enumerate() {
if ch == '\\' {
return unescape_owned(s, idx).map(Cow::Owned);
}
}
Ok(Cow::Borrowed(s))
}
fn unescape_owned(s: &str, idx: usize) -> Result<String> {
let mut buf = String::with_capacity(s.len());
buf.push_str(&s[..idx]);
let mut chars = s[idx..].chars();
let mut scratch = String::new();
while let Some(ch) = chars.next() {
if ch != '\\' {
buf.push(ch);
continue;
}
let ch = match chars.next() {
Some('\n') => continue,
Some('b') => '\u{0008}',
Some('f') => '\u{000C}',
Some('n') => '\n',
Some('r') => '\r',
Some('t') => '\t',
Some('\'') => '\'',
Some('\"') => '\"',
Some('\\') => '\\',
Some('u') => match unescape_unicode(&mut chars, &mut scratch) {
Some(ch) => ch,
None => return Err(Error::InvalidUnicodeCodePoint(scratch)),
},
Some(ch) => return Err(Error::InvalidEscape(ch)),
None => return Err(Error::Eof),
};
buf.push(ch);
}
Ok(buf)
}
fn unescape_unicode(chars: &mut Chars<'_>, scratch: &mut String) -> Option<char> {
scratch.clear();
for _ in 0..4 {
scratch.push(chars.next()?);
}
char::from_u32(u32::from_str_radix(scratch, 16).ok()?)
}
pub fn try_unescape(s: &str) -> Cow<str> {
match unescape(s) {
Ok(s) => s,
Err(_) => Cow::Borrowed(s),
}
}