Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Switch Once to MaybeUninit #68

Merged
merged 1 commit into from
May 29, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 16 additions & 6 deletions src/once.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use core::cell::UnsafeCell;
use core::mem::MaybeUninit;
use core::sync::atomic::{AtomicUsize, Ordering, spin_loop_hint as cpu_relax};
use core::fmt;

Expand All @@ -20,7 +21,7 @@ use core::fmt;
/// ```
pub struct Once<T> {
state: AtomicUsize,
data: UnsafeCell<Option<T>>, // TODO remove option and use mem::uninitialized
data: UnsafeCell<MaybeUninit<T>>,
}

impl<T: fmt::Debug> fmt::Debug for Once<T> {
Expand Down Expand Up @@ -52,18 +53,21 @@ impl<T> Once<T> {
/// Initialization constant of `Once`.
pub const INIT: Self = Once {
state: AtomicUsize::new(INCOMPLETE),
data: UnsafeCell::new(None),
data: UnsafeCell::new(MaybeUninit::uninit()),
};

/// Creates a new `Once` value.
pub const fn new() -> Once<T> {
Self::INIT
}

/// Get a reference to the initialized instance. Must only be called once COMPLETE.
fn force_get<'a>(&'a self) -> &'a T {
match unsafe { &*self.data.get() }.as_ref() {
None => unsafe { unreachable() },
Some(p) => p,
unsafe {
// SAFETY:
// * `UnsafeCell`/inner deref: data never changes again
// * `MaybeUninit`/outer deref: data was initialized
&*(*self.data.get()).as_ptr()
}
}

Expand Down Expand Up @@ -107,7 +111,13 @@ impl<T> Once<T> {
if status == INCOMPLETE { // We init
// We use a guard (Finish) to catch panics caused by builder
let mut finish = Finish { state: &self.state, panicked: true };
unsafe { *self.data.get() = Some(builder()) };
unsafe {
// SAFETY:
// `UnsafeCell`/deref: currently the only accessor, mutably
// and immutably by cas exclusion.
// `write`: pointer comes from `MaybeUninit`.
(*self.data.get()).as_mut_ptr().write(builder())
};
finish.panicked = false;

status = COMPLETE;
Expand Down