azalea_brigadier/arguments/
string_argument_type.rs

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