use std::any::Any;
use std::collections::HashMap;
use std::fmt::{self, Debug, Formatter};
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;
use std::sync::{Arc, Mutex};
use crate::redact::Locked;
struct KeyToken {
_non_zero_sized: u8,
}
#[derive(Clone)]
struct SlotId(Arc<KeyToken>);
impl PartialEq for SlotId {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
}
impl Eq for SlotId {}
impl Hash for SlotId {
fn hash<H: Hasher>(&self, state: &mut H) {
Arc::as_ptr(&self.0).hash(state);
}
}
pub struct Key<T> {
token: Arc<KeyToken>,
marker: PhantomData<fn(T) -> T>,
}
#[expect(
clippy::new_without_default,
reason = "ADR-006 forbids Default because every key creation must be explicit"
)]
impl<T> Key<T> {
#[must_use]
pub fn new() -> Self {
Self {
token: Arc::new(KeyToken { _non_zero_sized: 0 }),
marker: PhantomData,
}
}
fn slot_id(&self) -> SlotId {
SlotId(Arc::clone(&self.token))
}
}
impl<T> Clone for Key<T> {
fn clone(&self) -> Self {
Self {
token: Arc::clone(&self.token),
marker: PhantomData,
}
}
}
impl<T> Debug for Key<T> {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("Key")
.field("slot", &Arc::as_ptr(&self.token))
.finish()
}
}
impl<T> PartialEq for Key<T> {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.token, &other.token)
}
}
impl<T> Eq for Key<T> {}
impl<T> Hash for Key<T> {
fn hash<H: Hasher>(&self, state: &mut H) {
Arc::as_ptr(&self.token).hash(state);
}
}
type ErasedValue = Arc<dyn Any + Send + Sync>;
pub struct Store {
slots: Arc<Mutex<HashMap<SlotId, ErasedValue>>>,
_freeze: Mutex<()>,
}
impl Debug for Store {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
let mut store = formatter.debug_struct("Store");
match self.slots.try_lock() {
Ok(slots) => store.field("slots", &slots.len()),
Err(_contended_or_poisoned) => store.field("slots", &Locked),
}
.finish()
}
}
#[expect(
clippy::new_without_default,
reason = "the frozen API exposes explicit Store::new without Default"
)]
impl Store {
#[must_use]
pub fn new() -> Self {
Self {
slots: Arc::new(Mutex::new(HashMap::new())),
_freeze: Mutex::new(()),
}
}
pub(crate) fn clone_handle(&self) -> Self {
Self {
slots: Arc::clone(&self.slots),
_freeze: Mutex::new(()),
}
}
#[must_use]
pub fn load<T>(&self, key: &Key<T>) -> Option<Arc<T>>
where
T: Send + Sync + 'static,
{
let erased = self
.slots
.lock()
.expect("run-state lock poisoned")
.get(&key.slot_id())
.cloned()?;
Some(downcast(erased))
}
pub fn set<T>(&self, key: &Key<T>, value: Arc<T>) -> Option<Arc<T>>
where
T: Send + Sync + 'static,
{
self.slots
.lock()
.expect("run-state lock poisoned")
.insert(key.slot_id(), value)
.map(downcast)
}
pub fn load_or_store<T>(&self, key: &Key<T>, value: Arc<T>) -> (Arc<T>, bool)
where
T: Send + Sync + 'static,
{
let mut slots = self.slots.lock().expect("run-state lock poisoned");
if let Some(existing) = slots.get(&key.slot_id()).cloned() {
(downcast(existing), true)
} else {
slots.insert(key.slot_id(), value.clone());
(value, false)
}
}
pub fn delete<T>(&self, key: &Key<T>) -> Option<Arc<T>>
where
T: Send + Sync + 'static,
{
self.slots
.lock()
.expect("run-state lock poisoned")
.remove(&key.slot_id())
.map(downcast)
}
}
#[cfg(test)]
pub(super) fn hold_slot_lock(
store: &Store,
held: &std::sync::Barrier,
release: &std::sync::Barrier,
) {
let _guard = store.slots.lock().expect("run-state lock poisoned");
held.wait();
release.wait();
}
#[cfg(test)]
pub(super) fn corrupt<T, U>(store: &Store, key: &Key<T>, value: Arc<U>)
where
U: Send + Sync + 'static,
{
store
.slots
.lock()
.expect("run-state lock poisoned")
.insert(key.slot_id(), value);
}
fn downcast<T>(value: ErasedValue) -> Arc<T>
where
T: Send + Sync + 'static,
{
value
.downcast::<T>()
.unwrap_or_else(|_| panic!("run-state slot type invariant violated"))
}