Skip to main content

async_nodes/
context.rs

1use std::sync::Arc;
2
3use parking_lot::{MappedRwLockReadGuard, RwLock, RwLockReadGuard};
4use typemap_rev::{TypeMap, TypeMapKey};
5
6/// Shared execution context supporting dependency injection and state mapping across AST graphs.
7#[derive(Clone, Default)]
8pub struct BspContext {
9    inner: Arc<RwLock<TypeMap>>,
10}
11
12impl BspContext {
13    /// Instantiates a new empty execution context.
14    #[must_use]
15    pub fn new() -> Self {
16        Self {
17            inner: Arc::new(RwLock::new(TypeMap::new())),
18        }
19    }
20
21    /// Injects a shared thread-safe dependency into the context store.
22    pub fn insert<K: TypeMapKey>(&self, val: K::Value) {
23        self.inner.write().insert::<K>(val);
24    }
25
26    /// Dynamically retrieves a reference-like read-guard to an injected dependency.
27    #[must_use]
28    pub fn get<K: TypeMapKey>(&self) -> Option<MappedRwLockReadGuard<'_, K::Value>> {
29        let guard = self.inner.read();
30        RwLockReadGuard::try_map(guard, typemap_rev::TypeMap::get::<K>).ok()
31    }
32}