nsh_core/element/
engine_context.rs1use std::{
13 any::{Any, TypeId},
14 cell::RefCell,
15 fmt,
16 marker::PhantomData,
17 rc::Rc,
18 sync::Arc,
19};
20
21use rustc_hash::FxHashMap;
22
23type Values = FxHashMap<TypeId, Arc<dyn Any + Send + Sync>>;
24
25#[derive(Clone, Default)]
28#[non_exhaustive]
29pub struct EngineContext {
30 values: Arc<Values>,
31}
32
33impl EngineContext {
34 pub fn with<T: Send + Sync + 'static>(mut self, value: T) -> Self {
36 Arc::make_mut(&mut self.values).insert(TypeId::of::<T>(), Arc::new(value));
37 self
38 }
39
40 pub fn get<T: Send + Sync + 'static>(&self) -> Option<Arc<T>> {
42 self.values
43 .get(&TypeId::of::<T>())
44 .cloned()
45 .and_then(|value| value.downcast::<T>().ok())
46 }
47
48 pub fn enter(&self) -> EngineContextGuard {
51 let previous = CURRENT.with(|current| current.replace(Some(self.clone())));
52 EngineContextGuard {
53 previous,
54 _thread: PhantomData,
55 }
56 }
57}
58
59impl fmt::Debug for EngineContext {
60 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 f.debug_struct("EngineContext")
62 .field("values", &self.values.len())
63 .finish()
64 }
65}
66
67thread_local! {
68 static CURRENT: RefCell<Option<EngineContext>> = const { RefCell::new(None) };
70}
71
72#[must_use = "the context is the thread's while the guard lives"]
77pub struct EngineContextGuard {
78 previous: Option<EngineContext>,
79 _thread: PhantomData<Rc<()>>,
82}
83
84const _: fn() = || {
88 trait AmbiguousIfSend<A> {
89 fn check() {}
90 }
91 impl<T: ?Sized> AmbiguousIfSend<()> for T {}
92 impl<T: ?Sized + Send> AmbiguousIfSend<u8> for T {}
93 let _ = EngineContextGuard::check;
94};
95
96impl Drop for EngineContextGuard {
97 fn drop(&mut self) {
98 let previous = self.previous.take();
99 let outgoing = CURRENT.with(|current| current.replace(previous));
102 drop(outgoing);
103 }
104}
105
106pub fn engine_context<T: Send + Sync + 'static>() -> Option<Arc<T>> {
110 CURRENT.with(|current| current.borrow().as_ref()?.get::<T>())
111}
112
113#[cfg(test)]
114mod tests {
115 use super::*;
116
117 #[test]
118 fn a_thread_reads_the_context_it_entered_until_the_guard_drops() {
119 let outer = EngineContext::default().with(1_u32).with("outer");
120 let inner = EngineContext::default().with(2_u32);
121 assert_eq!(engine_context::<u32>(), None);
122 {
123 let _outer = outer.enter();
124 assert_eq!(engine_context::<u32>().as_deref(), Some(&1));
125 {
126 let _inner = inner.enter();
127 assert_eq!(engine_context::<u32>().as_deref(), Some(&2));
128 assert_eq!(engine_context::<&str>(), None);
129 }
130 assert_eq!(engine_context::<&str>().as_deref(), Some(&"outer"));
131 }
132 assert_eq!(engine_context::<u32>(), None);
133 }
134
135 #[test]
136 fn releasing_context_values_allows_them_to_read_the_restored_context() {
137 use std::sync::atomic::{AtomicBool, Ordering};
138
139 struct HostState(Arc<AtomicBool>);
140 impl Drop for HostState {
141 fn drop(&mut self) {
142 assert_eq!(engine_context::<u32>().as_deref(), Some(&7));
143 self.0.store(true, Ordering::SeqCst);
144 }
145 }
146
147 let _outer = EngineContext::default().with(7_u32).enter();
148 let released = Arc::new(AtomicBool::new(false));
149 let inner = EngineContext::default()
152 .with(HostState(released.clone()))
153 .enter();
154 drop(inner);
155 assert!(released.load(Ordering::SeqCst));
156 assert_eq!(engine_context::<u32>().as_deref(), Some(&7));
157 }
158}