Skip to content

Commit

Permalink
Add OnceBox::get_or_create.
Browse files Browse the repository at this point in the history
  • Loading branch information
partim committed Oct 11, 2024
1 parent a4b6351 commit 8b03c61
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/local_array/oncebox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,29 @@ impl<T> OnceBox<T> {
};
unsafe { &*res }
}

pub fn get_or_create(&self, create: impl FnOnce() -> Box<T>) -> &T {
if let Some(res) = self.get() {
return res
}
let ptr = Box::leak(create());
let res = match self.ptr.compare_exchange(
null_mut(), ptr, Ordering::SeqCst, Ordering::Acquire
) {
Ok(current) => {
// We set the new value, return it.
assert!(current.is_null());
ptr as *const _
}
Err(current) => {
// `current` is the real value we need to drop our value.
assert!(!current.is_null());
let _ = unsafe { Box::from_raw(ptr) };
current as *const _
}
};
unsafe { &*res }
}
}

impl<T> Drop for OnceBox<T> {
Expand Down

0 comments on commit 8b03c61

Please sign in to comment.