azalea_brigadier/arguments/
string_argument_type.rs

1use std::{any::Any, sync::Arc};
2
3use super::ArgumentType;
4use crate::{
5    context::CommandContext, exceptions::CommandSyntaxException, string_reader::StringReader,
6};
7
8pub enum StringArgument {
9    /// Match up until the next space.
10    SingleWord,
11    /// Same as single word unless the argument is wrapped in quotes, in which
12    /// case it can contain spaces.
13    QuotablePhrase,
14    /// Match the rest of the input.
15    GreedyPhrase,
16}
17
18impl ArgumentType for StringArgument {
19    fn parse(&self, reader: &mut StringReader) -> Result<Arc<dyn Any>, CommandSyntaxException> {
20        let result = match self {
21            StringArgument::SingleWord => reader.read_unquoted_string().to_string(),
22            StringArgument::QuotablePhrase => reader.read_string()?,
23            StringArgument::GreedyPhrase => {
24                let text = reader.remaining().to_string();
25                reader.cursor = reader.total_length();
26                text
27            }
28        };
29        Ok(Arc::new(result))
30    }
31
32    fn examples(&self) -> Vec<String> {
33        match self {
34            StringArgument::SingleWord => vec!["word", "words_with_underscores"],
35            StringArgument::QuotablePhrase => vec!["\"quoted phrase\"", "word", "\"\""],
36            StringArgument::GreedyPhrase => vec!["word", "words with spaces", "\"and symbols\""],
37        }
38        .into_iter()
39        .map(|s| s.to_string())
40        .collect()
41    }
42}
43
44/// Match up until the next space.
45pub fn word() -> impl ArgumentType {
46    StringArgument::SingleWord
47}
48/// Same as single word unless the argument is wrapped in quotes, in which case
49/// it can contain spaces.
50pub fn string() -> impl ArgumentType {
51    StringArgument::QuotablePhrase
52}
53/// Match the rest of the input.
54pub fn greedy_string() -> impl ArgumentType {
55    StringArgument::GreedyPhrase
56}
57pub fn get_string<S>(context: &CommandContext<S>, name: &str) -> Option<String> {
58    context
59        .argument(name)
60        .unwrap()
61        .downcast_ref::<String>()
62        .cloned()
63}