Skip to content

core: replace Once::data inner type to MaybeUninit #3206

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
14 changes: 7 additions & 7 deletions tracing-core/src/spin/once.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ use core::cell::UnsafeCell;
use core::fmt;
use core::hint::spin_loop;
use core::sync::atomic::{AtomicUsize, Ordering};
use core::mem::MaybeUninit;

/// A synchronization primitive which can be used to run a one-time global
/// initialization. Unlike its std equivalent, this is generalized so that the
/// closure returns a value and it is stored. Once therefore acts something like
/// a future, too.
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 @@ -41,7 +42,7 @@ 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.
Expand All @@ -50,10 +51,7 @@ impl<T> Once<T> {
}

fn force_get<'a>(&'a self) -> &'a T {
match unsafe { &*self.data.get() }.as_ref() {
None => unsafe { unreachable() },
Some(p) => p,
}
unsafe { (*self.data.get()).assume_init_ref() }
}

/// Performs an initialization routine once and only once. The given closure
Expand Down Expand Up @@ -91,7 +89,9 @@ impl<T> Once<T> {
state: &self.state,
panicked: true,
};
unsafe { *self.data.get() = Some(builder()) };
unsafe {
*self.data.get() = MaybeUninit::new(builder());
};
finish.panicked = false;

self.state.store(COMPLETE, Ordering::SeqCst);
Expand Down