Skip to main content

axfive_matrix_dicebot/
commands.rs

1use crate::dice::ElementExpression;
2use crate::roll::Roll;
3
4pub mod parser;
5
6pub struct Execution {
7    plain: String,
8    html: String,
9}
10
11impl Execution {
12    pub fn plain(&self) -> &str {
13        &self.plain
14    }
15
16    pub fn html(&self) -> &str {
17        &self.html
18    }
19}
20
21pub struct RollCommand(ElementExpression);
22
23pub trait Command {
24    fn execute(&self) -> Execution;
25}
26
27impl Command for RollCommand {
28    fn execute(&self) -> Execution {
29        let roll = self.0.roll();
30        let plain = format!("Dice: {}\nResult: {}", self.0, roll);
31        let html = format!(
32            "<p><strong>Dice:</strong> {}</p><p><strong>Result</strong>: {}</p>",
33            self.0, roll
34        );
35        Execution { plain, html }
36    }
37}
38
39/// Parse a command string into a dynamic command execution trait object.
40/// Returns an error if a command was recognized but not parsed correctly.  Returns None if no
41/// command was recognized.
42pub fn parse_command(s: &str) -> Result<Option<Box<dyn Command>>, String> {
43    // Ignore trailing input, if any.
44    match parser::parse_command(s) {
45        Ok((_, result)) => Ok(result),
46        Err(err) => Err(err.to_string()),
47    }
48}