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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
use std::borrow::Cow;
pub struct Shlex<'a> {
in_iter: std::str::Bytes<'a>,
pub line_no: usize,
pub had_error: bool,
}
impl<'a> Shlex<'a> {
pub fn new(in_str: &'a str) -> Self {
Shlex {
in_iter: in_str.bytes(),
line_no: 1,
had_error: false,
}
}
fn parse_word(&mut self, mut ch: u8) -> Option<String> {
let mut result: Vec<u8> = Vec::new();
loop {
match ch as char {
'"' => if let Err(()) = self.parse_double(&mut result) {
self.had_error = true;
return None;
},
'\'' => if let Err(()) = self.parse_single(&mut result) {
self.had_error = true;
return None;
},
'\\' => if let Some(ch2) = self.next_char() {
if ch2 != '\n' as u8 { result.push(ch2); }
} else {
self.had_error = true;
return None;
},
' ' | '\t' | '\n' => { break; },
_ => { result.push(ch as u8); },
}
if let Some(ch2) = self.next_char() { ch = ch2; } else { break; }
}
unsafe { Some(String::from_utf8_unchecked(result)) }
}
fn parse_double(&mut self, result: &mut Vec<u8>) -> Result<(), ()> {
loop {
if let Some(ch2) = self.next_char() {
match ch2 as char {
'\\' => {
if let Some(ch3) = self.next_char() {
match ch3 as char {
'$' | '`' | '"' | '\\' => { result.push(ch3); },
'\n' => {},
_ => { result.push('\\' as u8); result.push(ch3); }
}
} else {
return Err(());
}
},
'"' => { return Ok(()); },
_ => { result.push(ch2); },
}
} else {
return Err(());
}
}
}
fn parse_single(&mut self, result: &mut Vec<u8>) -> Result<(), ()> {
loop {
if let Some(ch2) = self.next_char() {
match ch2 as char {
'\\' => {
if let Some(ch3) = self.next_char() {
match ch3 as char {
'\'' | '\\' => { result.push(ch3); },
_ => { result.push('\\' as u8); result.push(ch3); }
}
} else {
return Err(());
}
},
'\'' => { return Ok(()); },
_ => { result.push(ch2); },
}
} else {
return Err(());
}
}
}
fn next_char(&mut self) -> Option<u8> {
let res = self.in_iter.next();
if res == Some('\n' as u8) { self.line_no += 1; }
res
}
}
impl<'a> Iterator for Shlex<'a> {
type Item = String;
fn next(&mut self) -> Option<String> {
if let Some(mut ch) = self.next_char() {
loop {
match ch as char {
' ' | '\t' | '\n' => {},
'#' => {
while let Some(ch2) = self.next_char() {
if ch2 as char == '\n' { break; }
}
},
_ => { break; }
}
if let Some(ch2) = self.next_char() { ch = ch2; } else { return None; }
}
self.parse_word(ch)
} else {
None
}
}
}
pub fn split(in_str: &str) -> Option<Vec<String>> {
let mut shl = Shlex::new(in_str);
let res = shl.by_ref().collect();
if shl.had_error { None } else { Some(res) }
}
pub fn quote(in_str: &str) -> Cow<str> {
if in_str.len() == 0 {
"\"\"".into()
} else if in_str.bytes().any(|c| match c as char {
'|' | '&' | ';' | '<' | '>' | '(' | ')' | '$' | '`' | '\\' | '"' | '\'' | ' ' | '\t' |
'\r' | '\n' | '*' | '?' | '[' | '#' | '~' | '=' | '%' => true,
_ => false
}) {
let mut out: Vec<u8> = Vec::new();
out.push('"' as u8);
for c in in_str.bytes() {
match c as char {
'$' | '`' | '"' | '\\' => out.push('\\' as u8),
_ => ()
}
out.push(c);
}
out.push('"' as u8);
unsafe { String::from_utf8_unchecked(out) }.into()
} else {
in_str.into()
}
}
#[cfg(test)]
static SPLIT_TEST_ITEMS: &'static [(&'static str, Option<&'static [&'static str]>)] = &[
("foo$baz", Some(&["foo$baz"])),
("foo baz", Some(&["foo", "baz"])),
("foo\"bar\"baz", Some(&["foobarbaz"])),
("foo \"bar\"baz", Some(&["foo", "barbaz"])),
(" foo \nbar", Some(&["foo", "bar"])),
("foo\\\nbar", Some(&["foobar"])),
("\"foo\\\nbar\"", Some(&["foobar"])),
("'baz\\$b'", Some(&["baz\\$b"])),
("'baz\\\''", Some(&["baz\'"])),
("\\", None),
("\"\\", None),
("'\\", None),
("\"", None),
("'", None),
("foo #bar\nbaz", Some(&["foo", "baz"])),
("foo #bar", Some(&["foo"])),
("foo#bar", Some(&["foo#bar"])),
("foo\"#bar", None),
];
#[test]
fn test_split() {
for &(input, output) in SPLIT_TEST_ITEMS {
assert_eq!(split(input), output.map(|o| o.iter().map(|&x| x.to_owned()).collect()));
}
}
#[test]
fn test_lineno() {
let mut sh = Shlex::new("\nfoo\nbar");
while let Some(word) = sh.next() {
if word == "bar" {
assert_eq!(sh.line_no, 3);
}
}
}
#[test]
fn test_quote() {
assert_eq!(quote("foobar"), "foobar");
assert_eq!(quote("foo bar"), "\"foo bar\"");
assert_eq!(quote("\""), "\"\\\"\"");
assert_eq!(quote(""), "\"\"");
}