use crate::lifecycle::{Reclaimable, ReclaimableKey};
use std::thread::LocalKey;
#[doc(hidden)]
pub trait RootKey<T: 'static> {
fn install(&'static self, app: T);
fn with<R>(&'static self, f: impl FnOnce(&T) -> R) -> R;
fn clear(&'static self);
fn is_empty(&'static self) -> bool;
}
impl<T: 'static> RootKey<T> for LocalKey<Reclaimable<Option<T>>> {
fn install(&'static self, app: T) {
self.with_borrow_mut(|slot| {
assert!(slot.is_none(), "root already bound");
*slot = Some(app);
});
}
fn with<R>(&'static self, f: impl FnOnce(&T) -> R) -> R {
self.with_borrow(|slot| f(slot.as_ref().expect("root missing")))
}
fn clear(&'static self) {
drop(self.take());
}
fn is_empty(&'static self) -> bool {
self.inspect(|slot| slot.is_none_or(Option::is_none))
}
}
#[doc(hidden)]
pub struct HotRoot<T>(std::marker::PhantomData<fn(T) -> T>);
#[cfg(target_family = "wasm")]
impl<T: 'static> HotRoot<T> {
pub const unsafe fn new() -> Self {
Self(std::marker::PhantomData)
}
fn storage(&self) -> &'static storage::Storage<T, PAYLOAD_BYTES> {
unsafe { &*(cdk_rsx_platform::profile::HOT_ROOT_BASE as *const _) }
}
}
#[cfg(target_family = "wasm")]
const PAYLOAD_BYTES: usize = cdk_rsx_platform::profile::HOT_ROOT_BYTES - storage::HEADER_BYTES;
#[cfg(target_family = "wasm")]
const _: () = {
use cdk_rsx_platform::profile;
use std::mem::{align_of, size_of};
assert!(size_of::<storage::Storage<(), PAYLOAD_BYTES>>() <= profile::HOT_ROOT_BYTES);
assert!(align_of::<storage::Storage<(), PAYLOAD_BYTES>>() <= profile::HOT_CONTROL_ALIGNMENT);
assert!(
profile::HOT_ROOT_BASE.is_multiple_of(align_of::<storage::Storage<(), PAYLOAD_BYTES>>())
);
};
#[cfg(target_family = "wasm")]
impl<T: 'static> RootKey<T> for HotRoot<T> {
fn install(&'static self, app: T) {
self.storage().install(app);
}
fn with<R>(&'static self, f: impl FnOnce(&T) -> R) -> R {
self.storage().with(f)
}
fn clear(&'static self) {
self.storage().clear();
}
fn is_empty(&'static self) -> bool {
self.storage().is_empty()
}
}
#[cfg(any(target_family = "wasm", test))]
mod storage {
use std::{
cell::{Cell, RefCell, UnsafeCell},
marker::PhantomData,
mem::{MaybeUninit, align_of, size_of},
};
#[repr(C, align(16))]
struct Bytes<const N: usize>(UnsafeCell<MaybeUninit<[u8; N]>>);
#[repr(C)]
pub(super) struct Storage<T, const N: usize> {
initialized: Cell<bool>,
bytes: Bytes<N>,
ty: PhantomData<fn(T) -> T>,
}
pub(super) const HEADER_BYTES: usize = size_of::<Storage<(), 0>>();
enum Backing<'a, T> {
Inline(&'a RefCell<Option<T>>),
Boxed(&'a RefCell<Option<Box<T>>>),
}
impl<T, const N: usize> Storage<T, N> {
pub(super) const INLINE: bool = size_of::<RefCell<Option<T>>>() <= N
&& align_of::<RefCell<Option<T>>>() <= align_of::<Bytes<N>>();
#[cfg(test)]
pub(super) const fn new() -> Self {
Self {
initialized: Cell::new(false),
bytes: Bytes(UnsafeCell::new(MaybeUninit::uninit())),
ty: PhantomData,
}
}
unsafe fn cell<S>(&self) -> &RefCell<Option<S>> {
let pointer = self.bytes.0.get().cast::<RefCell<Option<S>>>();
if !self.initialized.get() {
unsafe { pointer.write(RefCell::new(None)) };
self.initialized.set(true);
}
unsafe { &*pointer }
}
fn backing(&self) -> Backing<'_, T> {
const {
assert!(size_of::<RefCell<Option<Box<T>>>>() <= N);
assert!(align_of::<RefCell<Option<Box<T>>>>() <= align_of::<Bytes<N>>());
}
if Self::INLINE {
Backing::Inline(unsafe { self.cell::<T>() })
} else {
Backing::Boxed(unsafe { self.cell::<Box<T>>() })
}
}
pub(super) fn install(&self, app: T) {
match self.backing() {
Backing::Inline(cell) => {
let mut slot = cell.borrow_mut();
assert!(slot.is_none(), "root already bound");
*slot = Some(app);
}
Backing::Boxed(cell) => {
let mut slot = cell.borrow_mut();
assert!(slot.is_none(), "root already bound");
*slot = Some(Box::new(app));
}
}
}
pub(super) fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
match self.backing() {
Backing::Inline(cell) => f(cell.borrow().as_ref().expect("root missing")),
Backing::Boxed(cell) => f(cell.borrow().as_deref().expect("root missing")),
}
}
pub(super) fn is_empty(&self) -> bool {
if !self.initialized.get() {
return true;
}
match self.backing() {
Backing::Inline(cell) => cell.borrow().is_none(),
Backing::Boxed(cell) => cell.borrow().is_none(),
}
}
pub(super) fn clear(&self) {
if !self.initialized.get() {
return;
}
match self.backing() {
Backing::Inline(cell) => {
let value = cell.borrow_mut().take();
drop(value);
}
Backing::Boxed(cell) => {
let value = cell.borrow_mut().take();
drop(value);
}
}
}
}
impl<T, const N: usize> Drop for Storage<T, N> {
fn drop(&mut self) {
self.clear();
}
}
}
#[cfg(test)]
mod tests {
use super::{RootKey, storage::Storage};
use crate::lifecycle::Reclaimable;
use std::{cell::Cell, rc::Rc};
fn aliases_and_unwind<const N: usize>() {
let root = Storage::<String, N>::new();
assert!(root.is_empty());
root.install("root".to_owned());
root.with(|a| root.with(|b| assert!(std::ptr::eq(a, b))));
for mutate in [false, true] {
let failed = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
root.with(|_| {
if mutate {
root.install("duplicate".to_owned());
} else {
root.clear();
}
});
}));
assert!(failed.is_err());
root.with(|value| assert_eq!(value, "root"));
}
assert!(
std::panic::catch_unwind(std::panic::AssertUnwindSafe(
|| root.with(|_| panic!("body"))
))
.is_err()
);
assert!(
std::panic::catch_unwind(std::panic::AssertUnwindSafe(
|| root.install("duplicate".to_owned())
))
.is_err()
);
root.clear();
assert!(root.is_empty());
root.install("rebound".to_owned());
root.with(|value| assert_eq!(value, "rebound"));
}
#[test]
fn inline_and_boxed_headers_preserve_loans_unwind_and_rebinding() {
assert!(Storage::<String, 128>::INLINE);
assert!(!Storage::<String, 16>::INLINE);
aliases_and_unwind::<128>();
aliases_and_unwind::<16>();
}
#[test]
fn large_and_overaligned_apps_use_the_ordinary_box_fallback() {
struct Large {
value: [u8; 8192],
drops: Rc<Cell<u32>>,
}
impl Drop for Large {
fn drop(&mut self) {
self.drops.set(self.drops.get() + 1);
}
}
#[repr(align(64))]
struct Aligned([u8; 3]);
let drops = Rc::new(Cell::new(0));
let large = Storage::<Large, 128>::new();
let aligned = Storage::<Aligned, 128>::new();
assert!(!Storage::<Large, 128>::INLINE);
assert_eq!(
std::mem::size_of_val(&large),
super::storage::HEADER_BYTES + 128
);
assert!(!Storage::<Aligned, 128>::INLINE);
large.install(Large {
value: [7; 8192],
drops: drops.clone(),
});
aligned.install(Aligned([3, 4, 5]));
large.with(|value| assert!(value.value.iter().all(|byte| *byte == 7)));
large.clear();
assert_eq!(drops.get(), 1);
aligned.with(|value| {
assert!((value as *const Aligned as usize).is_multiple_of(64));
assert_eq!(value.0, [3, 4, 5]);
});
}
thread_local! {
static DROPS: Storage<Probe, 128> = const { Storage::new() };
static NATIVE: Reclaimable<Option<u64>> = const { Reclaimable::new() };
}
struct Probe {
count: Rc<Cell<u32>>,
recreate: bool,
fail: bool,
}
impl Drop for Probe {
fn drop(&mut self) {
self.count.set(self.count.get() + 1);
DROPS.with(|root| {
assert!(
root.is_empty(),
"drop must run after detaching and releasing the loan"
);
if self.recreate {
root.install(Probe {
count: self.count.clone(),
recreate: false,
fail: false,
});
}
});
assert!(!self.fail, "destructor failure");
}
}
#[test]
fn clearing_drops_outside_the_loan_and_leaves_recreation_visible() {
let count = Rc::new(Cell::new(0));
DROPS.with(|root| {
root.install(Probe {
count: count.clone(),
recreate: true,
fail: false,
});
root.clear();
assert!(!root.is_empty());
root.clear();
assert_eq!(count.get(), 2);
root.install(Probe {
count: count.clone(),
recreate: false,
fail: true,
});
assert!(
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| root.clear())).is_err()
);
assert!(root.is_empty());
assert_eq!(count.get(), 3);
});
}
#[test]
fn native_generated_key_retains_thread_local_reclamation() {
assert!(RootKey::is_empty(&NATIVE));
RootKey::install(&NATIVE, 17);
RootKey::with(&NATIVE, |a| {
RootKey::with(&NATIVE, |b| assert_eq!((*a, *b), (17, 17)))
});
assert!(
std::panic::catch_unwind(|| RootKey::with(&NATIVE, |_| RootKey::clear(&NATIVE)))
.is_err()
);
RootKey::clear(&NATIVE);
assert!(RootKey::is_empty(&NATIVE));
std::thread::spawn(|| assert!(RootKey::is_empty(&NATIVE)))
.join()
.unwrap();
}
}