use std::any::Any;
use std::cell::{Cell, RefCell};
use std::fmt;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread::LocalKey;
thread_local! {
static CURRENT: Cell<Option<&'static State>> = const { Cell::new(None) };
}
static NEXT_INDEX: AtomicUsize = AtomicUsize::new(0);
pub fn set_current(state: Option<&'static State>) -> Option<&'static State> {
CURRENT.replace(state)
}
pub struct State {
values: RefCell<Vec<Option<&'static dyn Any>>>,
}
impl State {
pub fn new() -> &'static Self {
Box::leak(Box::new(Self {
values: RefCell::new(Vec::new()),
}))
}
fn value<T: 'static>(&self, key: &StateKey<T>) -> &'static T {
let index = key.index();
let made = self.values.borrow().get(index).copied().flatten();
let value = made.unwrap_or_else(|| {
let fresh: &'static dyn Any = Box::leak(Box::new((key.init)()));
let mut values = self.values.borrow_mut();
if values.len() <= index {
values.resize(index + 1, None);
}
*values[index].get_or_insert(fresh)
});
value
.downcast_ref()
.expect("a state keeps a variable's value at its key's index")
}
}
impl fmt::Debug for State {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let reached = self.values.borrow().iter().flatten().count();
f.debug_struct("State").field("reached", &reached).finish()
}
}
#[doc(hidden)]
pub type LastLookup<T> = Cell<Option<(&'static State, &'static T)>>;
pub struct StateKey<T: 'static> {
own: &'static LocalKey<T>,
last: &'static LocalKey<LastLookup<T>>,
init: fn() -> T,
index: OnceLock<usize>,
}
impl<T: 'static> StateKey<T> {
#[doc(hidden)]
pub const fn new(
own: &'static LocalKey<T>,
last: &'static LocalKey<LastLookup<T>>,
init: fn() -> T,
) -> Self {
Self {
own,
last,
init,
index: OnceLock::new(),
}
}
fn index(&self) -> usize {
*self
.index
.get_or_init(|| NEXT_INDEX.fetch_add(1, Ordering::Relaxed))
}
pub fn with<R>(&'static self, f: impl FnOnce(&T) -> R) -> R {
let Some(state) = CURRENT.get() else {
return self.own.with(f);
};
let value = match self.last.get() {
Some((last, value)) if std::ptr::eq(last, state) => value,
_ => {
let value = state.value(self);
self.last.set(Some((state, value)));
value
}
};
f(value)
}
}
impl<T: 'static> StateKey<RefCell<T>> {
pub fn with_borrow<R>(&'static self, f: impl FnOnce(&T) -> R) -> R {
self.with(|cell| f(&cell.borrow()))
}
pub fn with_borrow_mut<R>(&'static self, f: impl FnOnce(&mut T) -> R) -> R {
self.with(|cell| f(&mut cell.borrow_mut()))
}
pub fn replace(&'static self, value: T) -> T {
self.with(|cell| cell.replace(value))
}
pub fn set(&'static self, value: T) {
drop(self.replace(value));
}
pub fn take(&'static self) -> T
where
T: Default,
{
self.replace(T::default())
}
}
impl<T: Copy + 'static> StateKey<Cell<T>> {
pub fn get(&'static self) -> T {
self.with(Cell::get)
}
pub fn set(&'static self, value: T) {
self.with(|cell| cell.set(value));
}
pub fn replace(&'static self, value: T) -> T {
self.with(|cell| cell.replace(value))
}
}
impl<T: 'static> fmt::Debug for StateKey<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("StateKey").finish_non_exhaustive()
}
}
#[macro_export]
macro_rules! thread_state {
() => {};
($(#[$attr:meta])* $vis:vis static $name:ident: $ty:ty = const { $init:expr }; $($rest:tt)*) => {
$(#[$attr])*
$vis static $name: $crate::state::StateKey<$ty> = {
::std::thread_local! {
static OWN: $ty = const { $init };
static LAST: $crate::state::LastLookup<$ty> = const { ::std::cell::Cell::new(None) };
}
fn init() -> $ty {
$init
}
$crate::state::StateKey::new(&OWN, &LAST, init)
};
$crate::thread_state!($($rest)*);
};
($(#[$attr:meta])* $vis:vis static $name:ident: $ty:ty = $init:expr; $($rest:tt)*) => {
$(#[$attr])*
$vis static $name: $crate::state::StateKey<$ty> = {
::std::thread_local! {
static OWN: $ty = $init;
static LAST: $crate::state::LastLookup<$ty> = const { ::std::cell::Cell::new(None) };
}
fn init() -> $ty {
$init
}
$crate::state::StateKey::new(&OWN, &LAST, init)
};
$crate::thread_state!($($rest)*);
};
}
#[cfg(test)]
mod tests {
use std::rc::Rc;
use super::*;
crate::thread_state! {
static COUNT: Cell<u32> = const { Cell::new(0) };
static NAMES: RefCell<Vec<String>> = RefCell::new(vec!["first".to_owned()]);
static DOUBLED: u32 = COUNT.get() * 2;
}
fn working_with<R>(state: &'static State, f: impl FnOnce() -> R) -> R {
let own = set_current(Some(state));
let result = f();
set_current(own);
result
}
#[test]
fn threads_work_with_their_own_values() {
COUNT.set(5);
let elsewhere = std::thread::spawn(|| COUNT.get()).join().expect("joins");
assert_eq!((COUNT.get(), elsewhere), (5, 0));
}
#[test]
fn a_state_keeps_values_apart_from_the_thread() {
NAMES.with_borrow_mut(|names| names.push("own".to_owned()));
let state = State::new();
working_with(state, || {
assert_eq!(NAMES.with_borrow(Vec::len), 1, "made afresh");
NAMES.with_borrow_mut(|names| names.push("shared".to_owned()));
});
assert_eq!(NAMES.take(), ["first", "own"]);
let shared = working_with(state, || NAMES.replace(Vec::new()));
assert_eq!(shared, ["first", "shared"], "kept by the state");
}
#[test]
fn each_state_keeps_its_own_values() {
let (one, two) = (State::new(), State::new());
working_with(one, || COUNT.set(1));
working_with(two, || COUNT.set(2));
let seen = [one, two, one].map(|state| working_with(state, || COUNT.get()));
assert_eq!(seen, [1, 2, 1]);
}
#[test]
fn values_made_in_a_state_may_reach_other_variables() {
let state = State::new();
let doubled = working_with(state, || {
COUNT.set(21);
DOUBLED.with(|value| *value)
});
assert_eq!(doubled, 42);
assert!(format!("{state:?}").contains("reached: 2"), "{state:?}");
}
#[test]
fn states_hold_values_that_are_not_send() {
crate::thread_state! {
static SHARED: RefCell<Option<Rc<str>>> = const { RefCell::new(None) };
}
let state = State::new();
working_with(state, || SHARED.set(Some(Rc::from("kept"))));
let kept = working_with(state, || SHARED.with_borrow(Clone::clone));
assert_eq!(kept.as_deref(), Some("kept"));
assert!(SHARED.with_borrow(Option::is_none), "not the thread's own");
}
}