Skip to main content

atom_engine/
context.rs

1use serde_json::Value;
2use std::collections::HashMap;
3
4#[derive(Clone)]
5pub struct ContextChain {
6    layers: Vec<HashMap<String, Value>>,
7}
8
9impl ContextChain {
10    pub fn new() -> Self {
11        ContextChain {
12            layers: vec![HashMap::new()],
13        }
14    }
15
16    pub fn provide(&mut self, key: &str, value: Value) {
17        if let Some(last) = self.layers.last_mut() {
18            last.insert(key.to_string(), value);
19        }
20    }
21
22    pub fn inject(&self, key: &str) -> Option<&Value> {
23        // Search from innermost to outermost
24        for layer in self.layers.iter().rev() {
25            if let Some(value) = layer.get(key) {
26                return Some(value);
27            }
28        }
29        None
30    }
31
32    pub fn push_layer(&mut self) {
33        self.layers.push(HashMap::new());
34    }
35
36    pub fn pop_layer(&mut self) {
37        if self.layers.len() > 1 {
38            self.layers.pop();
39        }
40    }
41
42    pub fn all(&self) -> HashMap<String, Value> {
43        let mut result = HashMap::new();
44        for layer in &self.layers {
45            for (k, v) in layer {
46                result.insert(k.clone(), v.clone());
47            }
48        }
49        result
50    }
51}
52
53impl Default for ContextChain {
54    fn default() -> Self {
55        Self::new()
56    }
57}