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
use crate::UltrarouteError;
use std::convert::TryFrom;
use std::hash::{Hash, Hasher};
static PREFIXES: [char; 2] = ['!', '/'];
#[inline(always)]
fn unprefix_and_lowercase(mut input: String) -> String {
if input
.chars()
.next()
.map(|chr| PREFIXES.contains(&chr))
.unwrap_or(false)
{
input.remove(0);
input.to_lowercase()
} else {
input.to_lowercase()
}
}
#[derive(Debug, Clone)]
pub struct Command {
pub cmd: String,
pub args: Vec<String>,
pub args_count: u8,
}
impl Command {
#[inline]
pub fn new(initial: String) -> Result<Self, UltrarouteError> {
let initial = unprefix_and_lowercase(initial);
let mut parts: Vec<String> = initial
.trim()
.split_ascii_whitespace()
.map(|s| s.to_string())
.collect();
if parts.len() < 1 {
return Err(UltrarouteError::StringIsEmpty);
}
let cmd = parts.remove(0);
let args_count = parts.len() as u8;
Ok(Self {
cmd,
args: parts,
args_count,
})
}
}
impl TryFrom<String> for Command {
type Error = UltrarouteError;
fn try_from(string: String) -> Result<Self, UltrarouteError> {
Self::new(string)
}
}
impl TryFrom<&str> for Command {
type Error = UltrarouteError;
fn try_from(string: &str) -> Result<Self, UltrarouteError> {
Self::new(string.to_string())
}
}
#[macro_export]
macro_rules! create_command {
($command:expr) => {{
use std::convert::TryFrom;
match Command::try_from($command) {
Ok(ok) => ok,
Err(e) => panic!("{}", e),
}
}};
}
impl PartialEq for Command {
fn eq(&self, other: &Self) -> bool {
self.cmd == other.cmd && self.args_count == other.args_count
}
}
impl Eq for Command {}
impl Hash for Command {
fn hash<H: Hasher>(&self, state: &mut H) {
self.cmd.hash(state);
self.args_count.hash(state);
}
}