math_engine/
context.rs

1use crate::error;
2use std::collections::HashMap;
3
4pub struct Context {
5    vars: HashMap<String, f32>,
6}
7
8impl Default for Context {
9    fn default() -> Self {
10        Self::new()
11    }
12}
13
14impl Context {
15    /// Creates a new empty context.
16    pub fn new() -> Self {
17        Self {
18            vars: HashMap::new(),
19        }
20    }
21
22    /// Adds a variable to the context, overwriting it if already existing.
23    ///
24    /// # Examples
25    /// Basic usage:
26    ///
27    /// ```
28    /// use math_engine::context::Context;
29    ///
30    /// let ctx = Context::new().with_variable("x", 32.0);
31    /// ```
32    pub fn with_variable(mut self, name: &str, val: f32) -> Self {
33        let _ = self.vars.insert(name.to_string(), val);
34        self
35    }
36
37    /// Adds a variable to the context, checking whether it has already been defined.
38    ///
39    /// # Examples
40    /// Basic usage:
41    ///
42    /// ```should_panic
43    /// use math_engine::context::Context;
44    ///
45    /// let mut ctx = Context::new();
46    /// ctx.add_variable("x", 32.0).unwrap();
47    /// ctx.add_variable("x", 31.0).unwrap(); // Panics
48    /// ```
49    pub fn add_variable(&mut self, name: &str, val: f32) -> Result<(), error::ContextError> {
50        let name = name.to_string();
51        let old_val = self.vars.insert(name.clone(), val);
52
53        match old_val {
54            Some(val) => Err(error::ContextError::VariableAlreadyDefined(name, val)),
55            None => Ok(()),
56        }
57    }
58
59    pub fn get_variable(&self, name: &String) -> Result<f32, error::ContextError> {
60        match self.vars.get(name) {
61            Some(r) => Ok(*r),
62            None => Err(error::ContextError::VariableNotFound),
63        }
64    }
65}