use core::sync::atomic::AtomicU32;
use core::time::Duration;
use crate::Result;
use crate::sys::time::Timespec;
use crate::sys::{errno, syscall};
const FUTEX_WAIT: u32 = 0;
const FUTEX_WAKE: u32 = 1;
const FUTEX_PRIVATE_FLAG: u32 = 128;
pub(crate) fn wait(atomic: &AtomicU32, expected: u32, timeout: Option<Duration>) -> Result<bool> {
let timeout = timeout.map(Timespec::from_duration);
let timeout = timeout
.as_ref()
.map_or(core::ptr::null(), core::ptr::from_ref);
let op = FUTEX_WAIT | FUTEX_PRIVATE_FLAG;
#[cfg(target_pointer_width = "32")]
let result = unsafe { syscall!(FUTEX_TIME64, atomic.as_ptr(), op, expected, timeout) };
#[cfg(target_pointer_width = "64")]
let result = unsafe { syscall!(FUTEX, atomic.as_ptr(), op, expected, timeout) };
match result {
Ok(_) => Ok(true),
Err(e) => match e.raw_os_error() {
errno::EAGAIN | errno::EINTR => Ok(true),
errno::ETIMEDOUT => Ok(false),
_ => Err(e),
},
}
}
pub(crate) fn wake(atomic: &AtomicU32, all: bool) {
let count = if all { i32::MAX } else { 1 };
let op = FUTEX_WAKE | FUTEX_PRIVATE_FLAG;
#[cfg(target_pointer_width = "32")]
let _ = unsafe { syscall!(FUTEX_TIME64, atomic.as_ptr(), op, count) };
#[cfg(target_pointer_width = "64")]
let _ = unsafe { syscall!(FUTEX, atomic.as_ptr(), op, count) };
}