use std::cell::UnsafeCell;
use std::error::Error;
use std::fmt;
use std::sync::atomic::{AtomicU32, Ordering};
use crate::task::TaskLocalsWrapper;
#[derive(Debug)]
pub struct LocalKey<T: Send + 'static> {
#[doc(hidden)]
pub __init: fn() -> T,
#[doc(hidden)]
pub __key: AtomicU32,
}
impl<T: Send + 'static> LocalKey<T> {
pub fn with<F, R>(&'static self, f: F) -> R
where
F: FnOnce(&T) -> R,
{
self.try_with(f)
.expect("`LocalKey::with` called outside the context of a task")
}
pub fn try_with<F, R>(&'static self, f: F) -> Result<R, AccessError>
where
F: FnOnce(&T) -> R,
{
TaskLocalsWrapper::get_current(|task| unsafe {
let key = self.key();
let init = || Box::new((self.__init)()) as Box<dyn Send>;
let value: *const dyn Send = task.locals().get_or_insert(key, init);
f(&*(value as *const T))
})
.ok_or(AccessError { _private: () })
}
#[inline]
fn key(&self) -> u32 {
#[cold]
fn init(key: &AtomicU32) -> u32 {
static COUNTER: AtomicU32 = AtomicU32::new(1);
let counter = COUNTER.fetch_add(1, Ordering::Relaxed);
if counter > u32::max_value() / 2 {
std::process::abort();
}
match key.compare_exchange(0, counter, Ordering::AcqRel, Ordering::Acquire) {
Ok(_) => counter,
Err(k) => k,
}
}
match self.__key.load(Ordering::Acquire) {
0 => init(&self.__key),
k => k,
}
}
}
#[derive(Clone, Copy, Eq, PartialEq)]
pub struct AccessError {
_private: (),
}
impl fmt::Debug for AccessError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("AccessError").finish()
}
}
impl fmt::Display for AccessError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
"already destroyed or called outside the context of a task".fmt(f)
}
}
impl Error for AccessError {}
struct Entry {
key: u32,
value: Box<dyn Send>,
}
pub(crate) struct LocalsMap {
entries: UnsafeCell<Option<Vec<Entry>>>,
}
impl LocalsMap {
pub fn new() -> LocalsMap {
LocalsMap {
entries: UnsafeCell::new(Some(Vec::new())),
}
}
#[inline]
pub fn get_or_insert(&self, key: u32, init: impl FnOnce() -> Box<dyn Send>) -> &dyn Send {
match unsafe { (*self.entries.get()).as_mut() } {
None => panic!("can't access task-locals while the task is being dropped"),
Some(entries) => {
let index = match entries.binary_search_by_key(&key, |e| e.key) {
Ok(i) => i,
Err(i) => {
let value = init();
entries.insert(i, Entry { key, value });
i
}
};
&*entries[index].value
}
}
}
pub unsafe fn clear(&self) {
let entries = (*self.entries.get()).take();
drop(entries);
}
}