azalea_brigadier/arguments/
long_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 Long {
12    pub minimum: Option<i64>,
13    pub maximum: Option<i64>,
14}
15
16impl ArgumentType for Long {
17    fn parse(&self, reader: &mut StringReader) -> Result<Arc<dyn Any>, CommandSyntaxException> {
18        let start = reader.cursor;
19        let result = reader.read_long()?;
20        if let Some(minimum) = self.minimum {
21            if result < minimum {
22                reader.cursor = start;
23                return Err(BuiltInExceptions::LongTooSmall {
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::LongTooBig {
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", "123", "-123"]
45            .into_iter()
46            .map(|s| s.to_string())
47            .collect()
48    }
49}
50
51pub fn long() -> impl ArgumentType {
52    Long::default()
53}
54pub fn get_long<S>(context: &CommandContext<S>, name: &str) -> Option<i64> {
55    context
56        .argument(name)
57        .unwrap()
58        .downcast_ref::<i64>()
59        .copied()
60}