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
use std::collections::HashMap;
pub fn parse_hashmap(input: Vec<String>, unescape: bool) -> HashMap<String, String> {
let mut map: HashMap<String, String> = HashMap::new();
input.into_iter().for_each(|s| {
s.split_whitespace().for_each(|e| {
let mut entries = e.split('=');
if let (Some(k), Some(v)) = (entries.next(), entries.next()) {
let v = if unescape {
unescape_val(v)
} else {
v.to_string()
};
map.insert(k.to_string(), v);
}
});
});
map
}
pub fn escape_arg(input: &str) -> String {
let res: Vec<u8> = Escape::new(input.bytes()).collect();
String::from_utf8(res).unwrap()
}
pub fn unescape_val(it: &str) -> String {
let mut res: Vec<u8> = Vec::new();
let mut escaped = false;
for n in it.as_bytes().iter() {
if !escaped && *n == b'\\' {
escaped = true;
} else if escaped {
let ch = match n {
b's' => b' ',
b'p' => b'|',
b'a' => 7,
b'b' => 8,
b'f' => 12,
b'n' => b'\n',
b'r' => b'\r',
b't' => b'\t',
b'v' => 11,
_ => *n,
};
res.push(ch);
escaped = false;
} else {
res.push(*n);
}
}
unsafe {
String::from_utf8_unchecked(res)
}
}
const LONGEST_ESCAPE: usize = 2;
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
struct Escape<I: Iterator<Item = u8>> {
inner: I,
buffer: u8,
}
impl<I: Iterator<Item = u8>> Escape<I> {
pub fn new(i: I) -> Escape<I> {
Escape {
inner: i,
buffer: 0,
}
}
}
impl<I: Iterator<Item = u8>> Iterator for Escape<I> {
type Item = u8;
fn next(&mut self) -> Option<u8> {
if self.buffer != 0 {
let ret = Some(self.buffer as u8);
self.buffer = 0;
ret
} else if let Some(ch) = self.inner.next() {
match ch {
b'\\' | b'/' => {
self.buffer = ch;
Some(b'\\')
}
b' ' => {
self.buffer = b's';
Some(b'\\')
}
b'|' => {
self.buffer = b'p';
Some(b'\\')
}
7 => {
self.buffer = b'a';
Some(b'\\')
}
8 => {
self.buffer = b'b';
Some(b'\\')
}
12 => {
self.buffer = b'f';
Some(b'\\')
}
b'\n' => {
self.buffer = b'n';
Some(b'\\')
}
b'\r' => {
self.buffer = b'r';
Some(b'\\')
}
b'\t' => {
self.buffer = b't';
Some(b'\\')
}
11 => {
self.buffer = b'v';
Some(b'\\')
}
_ => Some(ch),
}
} else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let (l, u) = self.inner.size_hint();
(
l,
if let Some(u_) = u {
u_.checked_mul(LONGEST_ESCAPE)
} else {
None
},
)
}
}