1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#![allow(dead_code)] use crate::marker::PhantomData;
use crate::ops::{Deref, DerefMut};
use crate::ptr::null_mut;
use crate::sync::atomic::{
AtomicPtr,
Ordering::{AcqRel, Acquire},
};
pub(crate) struct LazyBox<T: LazyInit> {
ptr: AtomicPtr<T>,
_phantom: PhantomData<T>,
}
pub(crate) trait LazyInit {
fn init() -> Box<Self>;
fn cancel_init(x: Box<Self>) {
Self::destroy(x);
}
fn destroy(_: Box<Self>) {}
}
impl<T: LazyInit> LazyBox<T> {
#[inline]
pub const fn new() -> Self {
Self { ptr: AtomicPtr::new(null_mut()), _phantom: PhantomData }
}
#[inline]
fn get_pointer(&self) -> *mut T {
let ptr = self.ptr.load(Acquire);
if ptr.is_null() { self.initialize() } else { ptr }
}
#[cold]
fn initialize(&self) -> *mut T {
let new_ptr = Box::into_raw(T::init());
match self.ptr.compare_exchange(null_mut(), new_ptr, AcqRel, Acquire) {
Ok(_) => new_ptr,
Err(ptr) => {
T::cancel_init(unsafe { Box::from_raw(new_ptr) });
ptr
}
}
}
}
impl<T: LazyInit> Deref for LazyBox<T> {
type Target = T;
#[inline]
fn deref(&self) -> &T {
unsafe { &*self.get_pointer() }
}
}
impl<T: LazyInit> DerefMut for LazyBox<T> {
#[inline]
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.get_pointer() }
}
}
impl<T: LazyInit> Drop for LazyBox<T> {
fn drop(&mut self) {
let ptr = *self.ptr.get_mut();
if !ptr.is_null() {
T::destroy(unsafe { Box::from_raw(ptr) });
}
}
}