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