1 #![allow(dead_code)] // Only used on some platforms.
3 // This is used to wrap pthread {Mutex, Condvar, RwLock} in.
5 use crate::marker::PhantomData;
6 use crate::ops::{Deref, DerefMut};
7 use crate::ptr::null_mut;
8 use crate::sync::atomic::{
10 Ordering::{AcqRel, Acquire},
13 pub(crate) struct LazyBox<T: LazyInit> {
15 _phantom: PhantomData<T>,
18 pub(crate) trait LazyInit {
19 /// This is called before the box is allocated, to provide the value to
20 /// move into the new box.
22 /// It might be called more than once per LazyBox, as multiple threads
23 /// might race to initialize it concurrently, each constructing and initializing
24 /// their own box. All but one of them will be passed to `cancel_init` right after.
25 fn init() -> Box<Self>;
27 /// Any surplus boxes from `init()` that lost the initialization race
28 /// are passed to this function for disposal.
30 /// The default implementation calls destroy().
31 fn cancel_init(x: Box<Self>) {
35 /// This is called to destroy a used box.
37 /// The default implementation just drops it.
38 fn destroy(_: Box<Self>) {}
41 impl<T: LazyInit> LazyBox<T> {
43 pub const fn new() -> Self {
44 Self { ptr: AtomicPtr::new(null_mut()), _phantom: PhantomData }
48 fn get_pointer(&self) -> *mut T {
49 let ptr = self.ptr.load(Acquire);
50 if ptr.is_null() { self.initialize() } else { ptr }
54 fn initialize(&self) -> *mut T {
55 let new_ptr = Box::into_raw(T::init());
56 match self.ptr.compare_exchange(null_mut(), new_ptr, AcqRel, Acquire) {
59 // Lost the race to another thread.
60 // Drop the box we created, and use the one from the other thread instead.
61 T::cancel_init(unsafe { Box::from_raw(new_ptr) });
68 impl<T: LazyInit> Deref for LazyBox<T> {
71 fn deref(&self) -> &T {
72 unsafe { &*self.get_pointer() }
76 impl<T: LazyInit> DerefMut for LazyBox<T> {
78 fn deref_mut(&mut self) -> &mut T {
79 unsafe { &mut *self.get_pointer() }
83 impl<T: LazyInit> Drop for LazyBox<T> {
85 let ptr = *self.ptr.get_mut();
87 T::destroy(unsafe { Box::from_raw(ptr) });