valence_command/parsers/
numbers.rs
1use super::Parser;
2use crate::parsers::{CommandArg, CommandArgParseError, ParseInput};
3macro_rules! impl_parser_for_number {
4 ($type:ty, $name:expr, $parser:ident) => {
5 impl CommandArg for $type {
6 fn parse_arg(input: &mut ParseInput) -> Result<Self, CommandArgParseError> {
7 input.skip_whitespace();
8 let s = input.pop_word();
9
10 let parsed = s.parse::<$type>();
11
12 parsed.map_err(|_| CommandArgParseError::InvalidArgument {
13 expected: $name.to_owned(),
14 got: s.to_owned(),
15 })
16 }
17
18 fn display() -> Parser {
19 Parser::$parser {
20 min: None,
21 max: None,
22 }
23 }
24 }
25 };
26}
27
28impl_parser_for_number!(f32, "float", Float);
29impl_parser_for_number!(f64, "double", Double);
30impl_parser_for_number!(i32, "integer", Integer);
31impl_parser_for_number!(i64, "long", Long);
32impl_parser_for_number!(u32, "unsigned integer", Integer);
33
34#[cfg(test)]
35mod tests {
36 use super::*;
37
38 #[test]
39 fn test_number() {
40 let mut input = ParseInput::new("1");
41 assert_eq!(1, i32::parse_arg(&mut input).unwrap());
42 assert!(input.is_done());
43
44 let mut input = ParseInput::new("1");
45 assert_eq!(1, i64::parse_arg(&mut input).unwrap());
46 assert!(input.is_done());
47
48 let mut input = ParseInput::new("1.0");
49 assert_eq!(1.0, f32::parse_arg(&mut input).unwrap());
50 assert!(input.is_done());
51
52 let mut input = ParseInput::new("1.0");
53 assert_eq!(1.0, f64::parse_arg(&mut input).unwrap());
54 assert!(input.is_done());
55
56 let mut input = ParseInput::new("3.40282347e+38 ");
57 assert_eq!(f32::MAX, f32::parse_arg(&mut input).unwrap());
58 assert!(!input.is_done());
59 }
60}