commonware_runtime/benchmarks/
context.rs

1//! Helper for storing and retrieving context in thread-local storage.
2
3use std::{any::Any, cell::RefCell};
4
5thread_local! {
6    static CONTEXT: RefCell<Option<Box<dyn Any + Send>>> = RefCell::new(None);
7}
8
9/// Set the context value
10pub(crate) fn set<C: Send + 'static>(context: C) {
11    CONTEXT.with(|cell| {
12        *cell.borrow_mut() = Some(Box::new(context));
13    });
14}
15
16/// Get the context value
17pub fn get<C: Send + 'static>() -> C {
18    CONTEXT.with(|cell| {
19        // Attempt to take the context from the thread-local storage
20        let mut borrow = cell.borrow_mut();
21        match borrow.take() {
22            Some(context) => {
23                // Convert the context back to the original type
24                let context = context.downcast::<C>().expect("failed to downcast context");
25                *context
26            }
27            None => panic!("no context set"),
28        }
29    })
30}
31
32/// Clear the context value
33pub(crate) fn clear() {
34    CONTEXT.with(|cell| {
35        *cell.borrow_mut() = None;
36    });
37}