//! Helper for storing and retrieving context in thread-local storage. use std::{any::Any, cell::RefCell}; thread_local! { static CONTEXT: RefCell>> = RefCell::new(None); } /// Set the context value pub(crate) fn set(context: C) { CONTEXT.with(|cell| { *cell.borrow_mut() = Some(Box::new(context)); }); } /// Get the context value pub fn get() -> C { CONTEXT.with(|cell| { // Attempt to take the context from the thread-local storage let mut borrow = cell.borrow_mut(); borrow .take() .map(|context| { // Convert the context back to the original type let context = context.downcast::().expect("failed to downcast context"); *context }) .expect("no context set") }) } /// Clear the context value pub(crate) fn clear() { CONTEXT.with(|cell| { *cell.borrow_mut() = None; }); }