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 destroyed right after.)
25 fn init() -> Box<Self>;
28 impl<T: LazyInit> LazyBox<T> {
30 pub const fn new() -> Self {
31 Self { ptr: AtomicPtr::new(null_mut()), _phantom: PhantomData }
35 fn get_pointer(&self) -> *mut T {
36 let ptr = self.ptr.load(Acquire);
37 if ptr.is_null() { self.initialize() } else { ptr }
41 fn initialize(&self) -> *mut T {
42 let new_ptr = Box::into_raw(T::init());
43 match self.ptr.compare_exchange(null_mut(), new_ptr, AcqRel, Acquire) {
46 // Lost the race to another thread.
47 // Drop the box we created, and use the one from the other thread instead.
48 drop(unsafe { Box::from_raw(new_ptr) });
55 impl<T: LazyInit> Deref for LazyBox<T> {
58 fn deref(&self) -> &T {
59 unsafe { &*self.get_pointer() }
63 impl<T: LazyInit> DerefMut for LazyBox<T> {
65 fn deref_mut(&mut self) -> &mut T {
66 unsafe { &mut *self.get_pointer() }
70 impl<T: LazyInit> Drop for LazyBox<T> {
72 let ptr = *self.ptr.get_mut();
74 drop(unsafe { Box::from_raw(ptr) });