devalang_wasm/shared/store/
mod.rs1use crate::language::syntax::ast::Value;
3use std::collections::HashMap;
4use std::sync::{Arc, RwLock};
5
6#[derive(Clone)]
8pub struct GlobalStore {
9 variables: Arc<RwLock<HashMap<String, Value>>>,
10 modules: Arc<RwLock<HashMap<String, ModuleInfo>>>,
11}
12
13#[derive(Clone, Debug)]
14pub struct ModuleInfo {
15 pub path: String,
16 pub variables: HashMap<String, Value>,
17}
18
19impl GlobalStore {
20 pub fn new() -> Self {
21 Self {
22 variables: Arc::new(RwLock::new(HashMap::new())),
23 modules: Arc::new(RwLock::new(HashMap::new())),
24 }
25 }
26
27 pub fn set_variable(&self, name: String, value: Value) {
28 if let Ok(mut vars) = self.variables.write() {
29 vars.insert(name, value);
30 }
31 }
32
33 pub fn get_variable(&self, name: &str) -> Option<Value> {
34 if let Ok(vars) = self.variables.read() {
35 vars.get(name).cloned()
36 } else {
37 None
38 }
39 }
40
41 pub fn register_module(&self, path: String, info: ModuleInfo) {
42 if let Ok(mut mods) = self.modules.write() {
43 mods.insert(path, info);
44 }
45 }
46
47 pub fn get_module(&self, path: &str) -> Option<ModuleInfo> {
48 if let Ok(mods) = self.modules.read() {
49 mods.get(path).cloned()
50 } else {
51 None
52 }
53 }
54
55 pub fn clear(&self) {
56 if let Ok(mut vars) = self.variables.write() {
57 vars.clear();
58 }
59 if let Ok(mut mods) = self.modules.write() {
60 mods.clear();
61 }
62 }
63}
64
65impl Default for GlobalStore {
66 fn default() -> Self {
67 Self::new()
68 }
69}
70
71#[cfg(test)]
72mod tests {
73 use super::*;
74
75 #[test]
76 fn test_global_store_variables() {
77 let store = GlobalStore::new();
78 store.set_variable("x".to_string(), Value::Number(42.0));
79
80 let result = store.get_variable("x");
81 assert!(matches!(result, Some(Value::Number(n)) if (n - 42.0).abs() < f32::EPSILON));
82 }
83
84 #[test]
85 fn test_global_store_modules() {
86 let store = GlobalStore::new();
87 let info = ModuleInfo {
88 path: "test".to_string(),
89 variables: HashMap::new(),
90 };
91
92 store.register_module("test".to_string(), info.clone());
93 let result = store.get_module("test");
94 assert!(result.is_some());
95 }
96}