krush_engine/engine/
command.rs

1use std::sync::{Mutex, Arc};
2
3use crate::error::Error;
4
5pub type Callback<'a> = Arc<Mutex<dyn FnMut(Vec<Value>) -> Option<String> + 'a + Send>>;
6
7/// Used to describe the type of each argument in a [`Definition`]
8#[derive(Clone, Copy)]
9pub enum Type {
10    Str,
11    Int,
12    Float,
13    Bool,
14    List
15}
16
17/// The values obtained from parsing a command arguments following its [`Definition`]
18pub enum Value {
19    Str(String),
20    Int(i32),
21    Float(f64),
22    Bool(bool),
23    List(Vec<String>)
24}
25
26/// Structure where to set the arguments using [`Type`] and the callback function to be called on the command evaluation by [`Engine::evaluate`] [`crate::Value::unwrap_str()`]
27#[derive(Clone)]
28pub struct Definition<'a> {
29    args: Vec<Type>,
30    callback: Callback<'a>
31}
32
33impl<'a> Definition<'a> {
34    pub fn build(args: &[Type], callback: Callback<'a>) -> Self {
35        Self::new(args.to_vec(), callback)
36    }
37    
38    pub fn new(args: Vec<Type>, callback: Callback<'a>) -> Self {
39        Self { args, callback }
40    }
41
42    pub fn args(&self) -> &Vec<Type> {
43        &self.args
44    }
45
46    pub fn callback(&mut self) -> &mut Callback<'a> {
47        &mut self.callback
48    }
49}
50
51impl Value {
52    pub fn unwrap_str(&self) -> Result<String, Error> {
53        match self {
54            Value::Str(s) => Ok(s.to_owned()),
55            _ => Err(Error("[VALUE UNWRAP] This isn't a string".to_string()))
56        }
57    }
58
59    pub fn unwrap_i32(&self) -> Result<i32, Error> {
60        match self {
61            Value::Int(i) => Ok(*i),
62            _ => Err(Error("[VALUE UNWRAP] This isn't an i32".to_string()))
63        }
64    }
65
66    
67    pub fn unwrap_f64(&self) -> Result<f64, Error> {
68        match self {
69            Value::Float(f) => Ok(*f),
70            _ => Err(Error("[VALUE UNWRAP] This isn't a f64".to_string()))
71        }
72    }
73
74    
75    pub fn unwrap_bool(&self) -> Result<bool, Error> {
76        match self {
77            Value::Bool(b) => Ok(*b),
78            _ => Err(Error("[VALUE UNWRAP] This isn't a bool".to_string()))
79        }
80    }
81
82    
83    pub fn unwrap_list(&self) -> Result<Vec<String>, Error> {
84        match self {
85            Value::List(l) => Ok(l.to_owned()),
86            _ => Err(Error("[VALUE UNWRAP] This isn't a list".to_string()))
87        }
88    }
89}