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
use core::fmt::{Display, Formatter};
/// Represents the end of the options
pub const END_OF_OPTIONS: &str = "--";
/// Represents a command-line token.
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum Token {
/// A command
Cmd(String),
/// A prefixed option
Opt(String),
/// An argument
Arg(String),
/// End of options
EOO,
/// Option assign operator
AssignOp(char)
}
impl Token {
/// Returns `true` if the token is a command.
pub fn is_command(&self) -> bool {
matches!(self, Token::Cmd(_))
}
/// Returns `true` if the token is an option.
pub fn is_option(&self) -> bool {
matches!(self, Token::Opt(_))
}
/// Returns `true` if the token is an argument.
pub fn is_arg(&self) -> bool {
matches!(self, Token::Arg(_))
}
/// Returns `true` if the token represents an `end of options`.
pub fn is_eoo(&self) -> bool {
matches!(self, Token::EOO)
}
/// Returns `true` if the token represents an assign operator.
pub fn is_assign_op(&self) -> bool {
matches!(self, Token::AssignOp(_))
}
/// Returns a `String` representation of this `Token`.
pub fn into_string(self) -> String {
match self {
Token::Cmd(s) => s,
Token::Opt(s) => s,
Token::Arg(s) => s,
Token::EOO => String::from(END_OF_OPTIONS),
Token::AssignOp(c) => c.to_string(),
}
}
}
impl Display for Token {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Token::Cmd(name) => write!(f, "{}", name),
Token::Opt(name) => write!(f, "{}", name),
Token::Arg(name) => write!(f, "{}", name),
Token::EOO => write!(f, "{}", END_OF_OPTIONS),
Token::AssignOp(c) => write!(f, "{}", c),
}
}
}