1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
use crate::error::Error;

pub type Callback<'a> = Box<dyn FnMut(Vec<Value>) -> Option<String> + 'a>;

/// Used to describe the type of each argument in a [`Definition`]
#[derive(Clone, Copy)]
pub enum Type {
    Str,
    Int,
    Float,
    Bool,
    List
}

/// The values obtained from parsing a command arguments following its [`Definition`]
pub enum Value {
    Str(String),
    Int(i32),
    Float(f64),
    Bool(bool),
    List(Vec<String>)
}

/// 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()`]
pub struct Definition<'a> {
    args: Vec<Type>,
    callback: Callback<'a>
}

impl<'a> Definition<'a> {
    pub fn build(args: &[Type], callback: Callback<'a>) -> Self {
        Self::new(args.to_vec(), Box::new(callback))
    }
    
    pub fn new(args: Vec<Type>, callback: Callback<'a>) -> Self {
        Self { args, callback }
    }

    pub fn args(&self) -> &Vec<Type> {
        &self.args
    }

    pub fn callback(&mut self) -> &mut Callback<'a> {
        &mut self.callback
    }
}

impl Value {
    pub fn unwrap_str(&self) -> Result<String, Error> {
        match self {
            Value::Str(s) => Ok(s.to_owned()),
            _ => Err(Error("[VALUE UNWRAP] This isn't a string".to_string()))
        }
    }

    pub fn unwrap_i32(&self) -> Result<i32, Error> {
        match self {
            Value::Int(i) => Ok(*i),
            _ => Err(Error("[VALUE UNWRAP] This isn't an i32".to_string()))
        }
    }

    
    pub fn unwrap_f64(&self) -> Result<f64, Error> {
        match self {
            Value::Float(f) => Ok(*f),
            _ => Err(Error("[VALUE UNWRAP] This isn't a f64".to_string()))
        }
    }

    
    pub fn unwrap_bool(&self) -> Result<bool, Error> {
        match self {
            Value::Bool(b) => Ok(*b),
            _ => Err(Error("[VALUE UNWRAP] This isn't a bool".to_string()))
        }
    }

    
    pub fn unwrap_list(&self) -> Result<Vec<String>, Error> {
        match self {
            Value::List(l) => Ok(l.to_owned()),
            _ => Err(Error("[VALUE UNWRAP] This isn't a list".to_string()))
        }
    }
}