Skip to main content

mate_rs/
environment.rs

1//
2// Copyright 2022-present theiskaa. All rights reserved.
3// Use of this source code is governed by MIT license
4// that can be found in the LICENSE file.
5//
6
7use std::collections::HashMap;
8
9/// Environment holds variable bindings for the calculator.
10/// Variables are stored as name -> value mappings.
11#[derive(Clone, Debug, Default)]
12pub struct Environment {
13    variables: HashMap<String, f64>,
14}
15
16impl Environment {
17    /// Creates a new empty environment.
18    pub fn new() -> Self {
19        Self {
20            variables: HashMap::new(),
21        }
22    }
23
24    /// Sets a variable to a value.
25    pub fn set(&mut self, name: &str, value: f64) {
26        self.variables.insert(name.to_string(), value);
27    }
28
29    /// Gets a variable's value, if it exists.
30    pub fn get(&self, name: &str) -> Option<f64> {
31        self.variables.get(name).copied()
32    }
33
34    /// Checks if a variable exists.
35    pub fn exists(&self, name: &str) -> bool {
36        self.variables.contains_key(name)
37    }
38
39    /// Returns all variable names.
40    pub fn names(&self) -> Vec<&String> {
41        self.variables.keys().collect()
42    }
43
44    /// Clears all variables.
45    pub fn clear(&mut self) {
46        self.variables.clear();
47    }
48}
49
50#[cfg(test)]
51mod tests {
52    use super::*;
53
54    #[test]
55    fn new_environment() {
56        let env = Environment::new();
57        assert!(env.variables.is_empty());
58    }
59
60    #[test]
61    fn set_and_get() {
62        let mut env = Environment::new();
63        env.set("x", 5.0);
64        assert_eq!(env.get("x"), Some(5.0));
65        assert_eq!(env.get("y"), None);
66    }
67
68    #[test]
69    fn overwrite_variable() {
70        let mut env = Environment::new();
71        env.set("x", 5.0);
72        env.set("x", 10.0);
73        assert_eq!(env.get("x"), Some(10.0));
74    }
75
76    #[test]
77    fn exists() {
78        let mut env = Environment::new();
79        env.set("x", 5.0);
80        assert!(env.exists("x"));
81        assert!(!env.exists("y"));
82    }
83
84    #[test]
85    fn clear() {
86        let mut env = Environment::new();
87        env.set("x", 5.0);
88        env.set("y", 10.0);
89        env.clear();
90        assert!(!env.exists("x"));
91        assert!(!env.exists("y"));
92    }
93}