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
use std::fmt::{self, Display, Formatter};
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct TestCommand<'a> {
pub command: &'a str,
pub options: Vec<TestOption<'a>>,
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum TestOption<'a> {
Flag(&'a str),
Value(&'a str, &'a str),
}
impl<'a> TestCommand<'a> {
pub fn new(s: &'a str) -> Self {
let mut parts = s.split_whitespace();
let cmd = parts.next().unwrap_or("");
Self {
command: cmd,
options: parts
.filter(|s| !s.is_empty())
.map(TestOption::new)
.collect(),
}
}
}
impl<'a> Display for TestCommand<'a> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}", self.command)?;
for opt in &self.options {
write!(f, " {}", opt)?;
}
writeln!(f)
}
}
impl<'a> TestOption<'a> {
pub fn new(s: &'a str) -> Self {
match s.find('=') {
None => TestOption::Flag(s),
Some(p) => TestOption::Value(&s[0..p], &s[p + 1..]),
}
}
}
impl<'a> Display for TestOption<'a> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match *self {
TestOption::Flag(s) => write!(f, "{}", s),
TestOption::Value(s, v) => write!(f, "{}={}", s, v),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_option() {
assert_eq!(TestOption::new(""), TestOption::Flag(""));
assert_eq!(TestOption::new("foo"), TestOption::Flag("foo"));
assert_eq!(TestOption::new("foo=bar"), TestOption::Value("foo", "bar"));
}
#[test]
fn parse_command() {
assert_eq!(&TestCommand::new("").to_string(), "\n");
assert_eq!(&TestCommand::new("cat").to_string(), "cat\n");
assert_eq!(&TestCommand::new("cat ").to_string(), "cat\n");
assert_eq!(&TestCommand::new("cat 1 ").to_string(), "cat 1\n");
assert_eq!(
&TestCommand::new("cat one=4 two t").to_string(),
"cat one=4 two t\n"
);
}
}