std/sys/thread_local/native/
lazy.rs1use crate::cell::UnsafeCell;
2use crate::hint::unreachable_unchecked;
3use crate::ptr;
4use crate::sys::thread_local::{abort_on_dtor_unwind, destructors};
5
6pub unsafe trait DestroyedState: Sized {
7 fn register_dtor<T>(s: &Storage<T, Self>);
8}
9
10unsafe impl DestroyedState for ! {
11 fn register_dtor<T>(_: &Storage<T, !>) {}
12}
13
14unsafe impl DestroyedState for () {
15 fn register_dtor<T>(s: &Storage<T, ()>) {
16 unsafe {
17 destructors::register(ptr::from_ref(s).cast_mut().cast(), destroy::<T>);
18 }
19 }
20}
21
22enum State<T, D> {
23 Initial,
24 Alive(T),
25 Destroyed(D),
26}
27
28#[allow(missing_debug_implementations)]
29pub struct Storage<T, D> {
30 state: UnsafeCell<State<T, D>>,
31}
32
33impl<T, D> Storage<T, D>
34where
35 D: DestroyedState,
36{
37 pub const fn new() -> Storage<T, D> {
38 Storage { state: UnsafeCell::new(State::Initial) }
39 }
40
41 #[inline]
51 pub unsafe fn get_or_init(&self, i: Option<&mut Option<T>>, f: impl FnOnce() -> T) -> *const T {
52 let state = unsafe { &*self.state.get() };
53 match state {
54 State::Alive(v) => v,
55 State::Destroyed(_) => ptr::null(),
56 State::Initial => unsafe { self.initialize(i, f) },
57 }
58 }
59
60 #[cold]
61 unsafe fn initialize(&self, i: Option<&mut Option<T>>, f: impl FnOnce() -> T) -> *const T {
62 let v = i.and_then(Option::take).unwrap_or_else(f);
65
66 let old = unsafe { self.state.get().replace(State::Alive(v)) };
67 match old {
68 State::Initial => D::register_dtor(self),
72 val => drop(val),
74 }
75
76 unsafe {
78 let State::Alive(v) = &*self.state.get() else { unreachable_unchecked() };
79 v
80 }
81 }
82}
83
84unsafe extern "C" fn destroy<T>(ptr: *mut u8) {
92 abort_on_dtor_unwind(|| {
94 let storage = unsafe { &*(ptr as *const Storage<T, ()>) };
95 let val = unsafe { storage.state.get().replace(State::Destroyed(())) };
98 drop(val);
99 })
100}