pub mod atomic_box;
pub mod rev_group;
pub mod zeroed_alloc;
pub const fn min_of_usize(a: usize, b: usize) -> usize {
if a > b {
b
} else {
a
}
}
#[cfg(feature = "nightly")]
pub use core::intrinsics::{likely, unlikely};
#[cfg(not(feature = "nightly"))]
#[inline]
#[cold]
fn cold() {}
#[cfg(not(feature = "nightly"))]
#[inline]
pub fn likely(b: bool) -> bool {
if !b {
cold();
}
b
}
#[cfg(not(feature = "nightly"))]
#[inline]
pub fn unlikely(b: bool) -> bool {
if b {
cold();
}
b
}
use std::cell::UnsafeCell;
use std::mem::MaybeUninit;
use std::sync::Once;
pub struct InitializeOnce<T: 'static> {
v: UnsafeCell<MaybeUninit<T>>,
once: Once,
}
impl<T> InitializeOnce<T> {
pub const fn new() -> Self {
InitializeOnce {
v: UnsafeCell::new(MaybeUninit::uninit()),
once: Once::new(),
}
}
pub fn initialize_once(&self, init_fn: &'static dyn Fn() -> T) {
self.once.call_once(|| {
unsafe { &mut *self.v.get() }.write(init_fn());
});
debug_assert!(self.once.is_completed());
}
pub fn get_ref(&self) -> &T {
debug_assert!(self.once.is_completed());
unsafe { (*self.v.get()).assume_init_ref() }
}
#[allow(clippy::mut_from_ref)]
pub unsafe fn get_mut(&self) -> &mut T {
debug_assert!(self.once.is_completed());
unsafe { (*self.v.get()).assume_init_mut() }
}
}
impl<T> std::ops::Deref for InitializeOnce<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.get_ref()
}
}
unsafe impl<T> Sync for InitializeOnce<T> {}
pub fn debug_process_thread_id() -> String {
let pid = unsafe { libc::getpid() };
#[cfg(target_os = "linux")]
{
let tid = unsafe { libc::gettid() };
format!("PID: {}, TID: {}", pid, tid)
}
#[cfg(not(target_os = "linux"))]
{
format!("PID: {}", pid)
}
}
#[cfg(test)]
mod initialize_once_tests {
use super::*;
#[test]
fn test_threads_compete_initialize() {
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::thread;
const N_THREADS: usize = 1000;
static I: InitializeOnce<usize> = InitializeOnce::new();
static INITIALIZE_COUNT: AtomicUsize = AtomicUsize::new(0);
fn initialize_usize() -> usize {
INITIALIZE_COUNT.fetch_add(1, Ordering::SeqCst);
42
}
let mut threads = vec![];
for _ in 1..N_THREADS {
threads.push(thread::spawn(|| {
I.initialize_once(&initialize_usize);
assert_eq!(*I, 42);
}));
}
threads.into_iter().for_each(|t| t.join().unwrap());
assert_eq!(INITIALIZE_COUNT.load(Ordering::SeqCst), 1);
}
}