azalea_brigadier/arguments/
double_argument_type.rs

1use std::{any::Any, sync::Arc};
2
3use super::ArgumentType;
4use crate::{
5    context::CommandContext,
6    exceptions::{BuiltInExceptions, CommandSyntaxException},
7    string_reader::StringReader,
8};
9
10#[derive(Default)]
11struct Double {
12    pub minimum: Option<f64>,
13    pub maximum: Option<f64>,
14}
15
16impl ArgumentType for Double {
17    fn parse(&self, reader: &mut StringReader) -> Result<Arc<dyn Any>, CommandSyntaxException> {
18        let start = reader.cursor;
19        let result = reader.read_double()?;
20        if let Some(minimum) = self.minimum {
21            if result < minimum {
22                reader.cursor = start;
23                return Err(BuiltInExceptions::DoubleTooSmall {
24                    found: result,
25                    min: minimum,
26                }
27                .create_with_context(reader));
28            }
29        }
30        if let Some(maximum) = self.maximum {
31            if result > maximum {
32                reader.cursor = start;
33                return Err(BuiltInExceptions::DoubleTooBig {
34                    found: result,
35                    max: maximum,
36                }
37                .create_with_context(reader));
38            }
39        }
40        Ok(Arc::new(result))
41    }
42
43    fn examples(&self) -> Vec<String> {
44        vec!["0", "1.2", ".5", "-1", "-.5", "-1234.56"]
45            .into_iter()
46            .map(|s| s.to_string())
47            .collect()
48    }
49}
50
51pub fn double() -> impl ArgumentType {
52    Double::default()
53}
54pub fn get_double<S>(context: &CommandContext<S>, name: &str) -> Option<f64> {
55    context
56        .argument(name)
57        .unwrap()
58        .downcast_ref::<f64>()
59        .copied()
60}