use std::{any::Any, cell::RefCell};
thread_local! {
static CONTEXT: RefCell<Option<Box<dyn Any + Send>>> = RefCell::new(None);
}
pub(crate) fn set<C: Send + 'static>(context: C) {
CONTEXT.with(|cell| {
*cell.borrow_mut() = Some(Box::new(context));
});
}
pub fn get<C: Send + 'static>() -> C {
CONTEXT.with(|cell| {
let mut borrow = cell.borrow_mut();
borrow
.take()
.map(|context| {
let context = context.downcast::<C>().expect("failed to downcast context");
*context
})
.expect("no context set")
})
}
pub(crate) fn clear() {
CONTEXT.with(|cell| {
*cell.borrow_mut() = None;
});
}