zen_engine/loader/
memory.rs1use crate::loader::{DecisionLoader, LoaderError, LoaderResponse};
2use crate::model::DecisionContent;
3use ahash::HashMap;
4use std::future::Future;
5use std::sync::{Arc, RwLock};
6
7#[derive(Debug, Default)]
9pub struct MemoryLoader {
10 memory_refs: RwLock<HashMap<String, Arc<DecisionContent>>>,
11}
12
13impl MemoryLoader {
14 pub fn add<K, D>(&self, key: K, content: D)
15 where
16 K: Into<String>,
17 D: Into<DecisionContent>,
18 {
19 let mut mref = self.memory_refs.write().unwrap();
20 mref.insert(key.into(), Arc::new(content.into()));
21 }
22
23 pub fn get<K>(&self, key: K) -> Option<Arc<DecisionContent>>
24 where
25 K: AsRef<str>,
26 {
27 let mref = self.memory_refs.read().unwrap();
28 mref.get(key.as_ref()).map(|r| r.clone())
29 }
30
31 pub fn remove<K>(&self, key: K) -> bool
32 where
33 K: AsRef<str>,
34 {
35 let mut mref = self.memory_refs.write().unwrap();
36 mref.remove(key.as_ref()).is_some()
37 }
38}
39
40impl DecisionLoader for MemoryLoader {
41 fn load<'a>(&'a self, key: &'a str) -> impl Future<Output = LoaderResponse> + 'a {
42 async move {
43 self.get(&key)
44 .ok_or_else(|| LoaderError::NotFound(key.to_string()).into())
45 }
46 }
47}