#![allow(clippy::declare_interior_mutable_const)]
use crate::Extensions;
use std::cell::RefCell;
use std::future::Future;
tokio::task_local! {
static EXTENSIONS: RefCell<Extensions>;
}
pub async fn with_extensions<T>(
extensions: Extensions,
fut: impl Future<Output = T>,
) -> (Extensions, T) {
EXTENSIONS
.scope(RefCell::new(extensions), async move {
let response = fut.await;
let mut extensions = Extensions::new();
EXTENSIONS.with(|ext| std::mem::swap(&mut *ext.borrow_mut(), &mut extensions));
(extensions, response)
})
.await
}
pub async fn get_local_item<T: Send + Sync + Clone + 'static>() -> Option<T> {
EXTENSIONS
.try_with(|e| e.borrow().get::<T>().cloned())
.ok()
.flatten()
}
pub async fn set_local_item<T: Send + Sync + 'static>(item: T) {
EXTENSIONS
.try_with(|e| e.borrow_mut().insert(item))
.expect("Failed to set local item.");
}