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