use core::{
cell::UnsafeCell,
mem::{ManuallyDrop, MaybeUninit},
sync::atomic::{AtomicUsize, Ordering},
fmt,
};
pub struct Once<T> {
state: AtomicUsize,
data: UnsafeCell<MaybeUninit<T>>,
}
impl<T: fmt::Debug> fmt::Debug for Once<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.get() {
Some(s) => write!(f, "Once {{ data: ")
.and_then(|()| s.fmt(f))
.and_then(|()| write!(f, "}}")),
None => write!(f, "Once {{ <uninitialized> }}")
}
}
}
unsafe impl<T: Send + Sync> Sync for Once<T> {}
unsafe impl<T: Send> Send for Once<T> {}
const INCOMPLETE: usize = 0x0;
const RUNNING: usize = 0x1;
const COMPLETE: usize = 0x2;
const PANICKED: usize = 0x3;
use core::hint::unreachable_unchecked as unreachable;
impl<T> Once<T> {
#[allow(clippy::declare_interior_mutable_const)]
pub const INIT: Self = Self {
state: AtomicUsize::new(INCOMPLETE),
data: UnsafeCell::new(MaybeUninit::uninit()),
};
pub const fn new() -> Once<T> {
Self::INIT
}
pub const fn initialized(data: T) -> Once<T> {
Self {
state: AtomicUsize::new(COMPLETE),
data: UnsafeCell::new(MaybeUninit::new(data)),
}
}
unsafe fn force_get(&self) -> &T {
&*(*self.data.get()).as_ptr()
}
unsafe fn force_get_mut(&mut self) -> &mut T {
&mut *(*self.data.get()).as_mut_ptr()
}
unsafe fn force_into_inner(self) -> T {
let mut this = ManuallyDrop::new(self);
this.data.get_mut().assume_init_read()
}
pub fn call_once<F: FnOnce() -> T>(&self, f: F) -> &T {
let mut status = self.state.load(Ordering::SeqCst);
if status == INCOMPLETE {
status = self.state.compare_and_swap(
INCOMPLETE,
RUNNING,
Ordering::SeqCst,
);
if status == INCOMPLETE { let mut finish = Finish { state: &self.state, panicked: true };
unsafe {
(*self.data.get()).as_mut_ptr().write(f())
};
finish.panicked = false;
status = COMPLETE;
self.state.store(status, Ordering::SeqCst);
return unsafe { self.force_get() };
}
}
self
.poll()
.unwrap_or_else(|| unreachable!("Encountered INCOMPLETE when polling Once"))
}
pub fn get(&self) -> Option<&T> {
match self.state.load(Ordering::SeqCst) {
COMPLETE => Some(unsafe { self.force_get() }),
_ => None,
}
}
pub fn get_mut(&mut self) -> Option<&mut T> {
match *self.state.get_mut() {
COMPLETE => Some(unsafe { self.force_get_mut() }),
_ => None,
}
}
pub fn try_into_inner(mut self) -> Option<T> {
match *self.state.get_mut() {
COMPLETE => Some(unsafe { self.force_into_inner() }),
_ => None,
}
}
pub fn is_completed(&self) -> bool {
self.state.load(Ordering::SeqCst) == COMPLETE
}
pub fn wait(&self) -> &T {
loop {
match self.poll() {
Some(x) => break x,
None => crate::relax(),
}
}
}
pub fn poll(&self) -> Option<&T> {
loop {
match self.state.load(Ordering::SeqCst) {
INCOMPLETE => return None,
RUNNING => crate::relax(), COMPLETE => return Some(unsafe { self.force_get() }),
PANICKED => panic!("Once previously poisoned by a panicked"),
_ => unsafe { unreachable() },
}
}
}
}
impl<T> From<T> for Once<T> {
fn from(data: T) -> Self {
Self::initialized(data)
}
}
impl<T> Drop for Once<T> {
fn drop(&mut self) {
if self.state.load(Ordering::SeqCst) == COMPLETE {
unsafe {
core::ptr::drop_in_place((*self.data.get()).as_mut_ptr());
}
}
}
}
struct Finish<'a> {
state: &'a AtomicUsize,
panicked: bool,
}
impl<'a> Drop for Finish<'a> {
fn drop(&mut self) {
if self.panicked {
self.state.store(PANICKED, Ordering::SeqCst);
}
}
}
#[cfg(test)]
mod tests {
use std::prelude::v1::*;
use std::sync::mpsc::channel;
use std::thread;
use super::Once;
#[test]
fn smoke_once() {
static O: Once<()> = Once::new();
let mut a = 0;
O.call_once(|| a += 1);
assert_eq!(a, 1);
O.call_once(|| a += 1);
assert_eq!(a, 1);
}
#[test]
fn smoke_once_value() {
static O: Once<usize> = Once::new();
let a = O.call_once(|| 1);
assert_eq!(*a, 1);
let b = O.call_once(|| 2);
assert_eq!(*b, 1);
}
#[test]
fn stampede_once() {
static O: Once<()> = Once::new();
static mut RUN: bool = false;
let (tx, rx) = channel();
for _ in 0..10 {
let tx = tx.clone();
thread::spawn(move|| {
for _ in 0..4 { thread::yield_now() }
unsafe {
O.call_once(|| {
assert!(!RUN);
RUN = true;
});
assert!(RUN);
}
tx.send(()).unwrap();
});
}
unsafe {
O.call_once(|| {
assert!(!RUN);
RUN = true;
});
assert!(RUN);
}
for _ in 0..10 {
rx.recv().unwrap();
}
}
#[test]
fn get() {
static INIT: Once<usize> = Once::new();
assert!(INIT.get().is_none());
INIT.call_once(|| 2);
assert_eq!(INIT.get().map(|r| *r), Some(2));
}
#[test]
fn get_no_wait() {
static INIT: Once<usize> = Once::new();
assert!(INIT.get().is_none());
thread::spawn(move|| {
INIT.call_once(|| loop { });
});
assert!(INIT.get().is_none());
}
#[test]
fn poll() {
static INIT: Once<usize> = Once::new();
assert!(INIT.poll().is_none());
INIT.call_once(|| 3);
assert_eq!(INIT.poll().map(|r| *r), Some(3));
}
#[test]
fn wait() {
static INIT: Once<usize> = Once::new();
std::thread::spawn(|| {
assert_eq!(*INIT.wait(), 3);
assert!(INIT.is_completed());
});
for _ in 0..4 { thread::yield_now() }
assert!(INIT.poll().is_none());
INIT.call_once(|| 3);
}
#[test]
fn panic() {
use ::std::panic;
static INIT: Once<()> = Once::new();
let t = panic::catch_unwind(|| {
INIT.call_once(|| panic!());
});
assert!(t.is_err());
let t = panic::catch_unwind(|| {
INIT.call_once(|| {});
});
assert!(t.is_err());
}
#[test]
fn init_constant() {
static O: Once<()> = Once::INIT;
let mut a = 0;
O.call_once(|| a += 1);
assert_eq!(a, 1);
O.call_once(|| a += 1);
assert_eq!(a, 1);
}
static mut CALLED: bool = false;
struct DropTest {}
impl Drop for DropTest {
fn drop(&mut self) {
unsafe {
CALLED = true;
}
}
}
#[test]
fn drop() {
unsafe {
CALLED = false;
}
{
let once = Once::new();
once.call_once(|| DropTest {});
}
assert!(unsafe {
CALLED
});
}
#[test]
fn skip_uninit_drop() {
unsafe {
CALLED = false;
}
{
let once = Once::<DropTest>::new();
}
assert!(unsafe {
!CALLED
});
}
#[test]
fn drop_boxed() {
let boxed = Box::new(5);
let once = Once::<_, Spin>::initialized(boxed);
let boxed = once.try_into_inner().unwrap();
println!("{}", boxed);
}
}