valence_command/parsers/
time.rs
1use super::Parser;
2use crate::parsers::{CommandArg, CommandArgParseError, ParseInput};
3
4#[derive(Debug, Clone, Copy, PartialEq)]
5pub enum Time {
6 Ticks(f32),
7 Seconds(f32),
8 Days(f32),
9}
10
11impl CommandArg for Time {
12 fn parse_arg(input: &mut ParseInput) -> Result<Self, CommandArgParseError> {
13 input.skip_whitespace();
14 let mut number_str = String::new();
15 while let Some(c) = input.pop() {
16 match c {
17 't' => {
18 return Ok(Time::Ticks(number_str.parse::<f32>().map_err(|_| {
19 CommandArgParseError::InvalidArgument {
20 expected: "time".to_owned(),
21 got: "not a valid time".to_owned(),
22 }
23 })?));
24 }
25 's' => {
26 return Ok(Time::Seconds(number_str.parse::<f32>().map_err(|_| {
27 CommandArgParseError::InvalidArgument {
28 expected: "time".to_owned(),
29 got: "not a valid time".to_owned(),
30 }
31 })?));
32 }
33 'd' => {
34 return Ok(Time::Days(number_str.parse::<f32>().map_err(|_| {
35 CommandArgParseError::InvalidArgument {
36 expected: "time".to_owned(),
37 got: "not a valid time".to_owned(),
38 }
39 })?));
40 }
41 _ => {
42 number_str.push(c);
43 }
44 }
45 }
46 if !number_str.is_empty() {
47 return Ok(Time::Ticks(number_str.parse::<f32>().map_err(|_| {
48 CommandArgParseError::InvalidArgument {
49 expected: "time".to_owned(),
50 got: "not a valid time".to_owned(),
51 }
52 })?));
53 }
54
55 Err(CommandArgParseError::InvalidArgument {
56 expected: "time".to_owned(),
57 got: "not a valid time".to_owned(),
58 })
59 }
60
61 fn display() -> Parser {
62 Parser::Time
63 }
64}
65
66#[cfg(test)]
67mod tests {
68 use super::*;
69
70 #[test]
71 fn test_time() {
72 let mut input = ParseInput::new("42.31t");
73 let time = Time::parse_arg(&mut input).unwrap();
74 assert_eq!(time, Time::Ticks(42.31));
75
76 let mut input = ParseInput::new("42.31");
77 let time = Time::parse_arg(&mut input).unwrap();
78 assert_eq!(time, Time::Ticks(42.31));
79
80 let mut input = ParseInput::new("1239.72s");
81 let time = Time::parse_arg(&mut input).unwrap();
82 assert_eq!(time, Time::Seconds(1239.72));
83
84 let mut input = ParseInput::new("133.1d");
85 let time = Time::parse_arg(&mut input).unwrap();
86 assert_eq!(time, Time::Days(133.1));
87 }
88}