krush_engine/
engine.rs

1use std::collections::HashMap;
2
3use crate::{error::Error, parser};
4
5use self::command::Definition;
6
7pub mod command;
8
9/// The place where to register your commands and run them
10#[derive(Clone)]
11pub struct Engine<'a> {
12    registry: HashMap<String, Definition<'a>>
13}
14
15impl<'a> Engine<'a> {
16    /// Creates a new empty `Engine`
17    pub fn new() -> Self {
18        Self { registry: HashMap::new() }
19    }
20
21    /// Adds a new command to the `Engine` registry with given name and [`Definition`]
22    pub fn register_command(&mut self, name: &'static str, definition: Definition<'a>) {
23        self.registry.insert(name.to_string(), definition);
24    }
25
26    /// Receives a command and call the respective callback if the command was registered in [`Definition::register_command`]
27    pub fn evaluate(&mut self, command: String) -> Result<Option<String>, Error> {
28        let mut command = command;
29        let name = &parser::get_name(&mut command);
30
31        
32        match self.registry.get_mut(name) {
33            Some(definition) => {
34                let args = parser::parse_args(definition.args(), &mut command)?;
35
36                Ok((definition.callback().lock().unwrap())(args))
37            },
38            None => Err(Error(format!("Unknown command: {}", name))),
39        }
40    }
41}