azalea_brigadier/arguments/
float_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 Float {
12    pub minimum: Option<f32>,
13    pub maximum: Option<f32>,
14}
15
16impl ArgumentType for Float {
17    fn parse(&self, reader: &mut StringReader) -> Result<Arc<dyn Any>, CommandSyntaxException> {
18        let start = reader.cursor;
19        let result = reader.read_float()?;
20        if let Some(minimum) = self.minimum {
21            if result < minimum {
22                reader.cursor = start;
23                return Err(BuiltInExceptions::FloatTooSmall {
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::FloatTooBig {
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 float() -> impl ArgumentType {
52    Float::default()
53}
54pub fn get_float<S>(context: &CommandContext<S>, name: &str) -> Option<f32> {
55    context
56        .argument(name)
57        .unwrap()
58        .downcast_ref::<f32>()
59        .copied()
60}