use core::ffi::c_void;
use core::time::Duration;
use crate::sys::{cvt, dll, last_error};
use crate::time::{Clock, Timestamp};
use crate::{ErrorKind, Result};
const EPOCH_DIFFERENCE: i64 = 11_644_473_600;
const UNITS_PER_SEC: u64 = 10_000_000;
const MAX_TIMER_UNITS: u64 = i64::MAX as u64 / 2;
const CREATE_WAITABLE_TIMER_HIGH_RESOLUTION: u32 = 2;
const TIMER_ALL_ACCESS: u32 = 0x1F0003;
const INFINITE: u32 = u32::MAX;
const WAIT_OBJECT_0: u32 = 0;
#[repr(C)]
#[derive(Clone, Copy, Default)]
struct FileTime {
low: u32,
high: u32,
}
impl FileTime {
fn units(self) -> u64 {
(self.high as u64) << 32 | self.low as u64
}
}
dll!("kernel32.dll" {
fn GetSystemTimePreciseAsFileTime(time: *mut FileTime);
fn GetCurrentProcess() -> *mut c_void;
fn GetCurrentThread() -> *mut c_void;
fn GetProcessTimes(
process: *mut c_void,
creation: *mut FileTime,
exit: *mut FileTime,
kernel: *mut FileTime,
user: *mut FileTime,
) -> i32;
fn GetThreadTimes(
thread: *mut c_void,
creation: *mut FileTime,
exit: *mut FileTime,
kernel: *mut FileTime,
user: *mut FileTime,
) -> i32;
fn GetSystemTimeAdjustment(
adjustment: *mut u32,
increment: *mut u32,
disabled: *mut i32,
) -> i32;
fn QueryPerformanceFrequency(frequency: *mut i64) -> i32;
fn CreateWaitableTimerExW(
attributes: *const c_void,
name: *const u16,
flags: u32,
access: u32,
) -> *mut c_void;
fn SetWaitableTimer(
timer: *mut c_void,
due: *const i64,
period: i32,
routine: *const c_void,
argument: *const c_void,
resume: i32,
) -> i32;
fn WaitForSingleObject(handle: *mut c_void, milliseconds: u32) -> u32;
fn CloseHandle(handle: *mut c_void) -> i32;
fn Sleep(milliseconds: u32);
});
dll!("api-ms-win-core-realtime-l1-1-1.dll" {
fn QueryInterruptTimePrecise(time: *mut u64);
fn QueryUnbiasedInterruptTimePrecise(time: *mut u64);
});
fn from_units(units: u64) -> Duration {
Duration::new(units / UNITS_PER_SEC, (units % UNITS_PER_SEC) as u32 * 100)
}
pub(crate) fn now() -> Result<Timestamp> {
let mut time = FileTime::default();
unsafe { GetSystemTimePreciseAsFileTime(&raw mut time) };
let units = time.units();
Ok(Timestamp {
secs: (units / UNITS_PER_SEC) as i64 - EPOCH_DIFFERENCE,
nanos: (units % UNITS_PER_SEC) as u32 * 100,
})
}
pub(crate) fn unbiased() -> u64 {
let mut units = 0;
unsafe { QueryUnbiasedInterruptTimePrecise(&raw mut units) };
units
}
pub(crate) fn clock(clock: Clock) -> Result<Duration> {
let units = match clock {
Clock::Monotonic => unbiased(),
Clock::Boottime => {
let mut units = 0;
unsafe { QueryInterruptTimePrecise(&raw mut units) };
units
}
Clock::ProcessCpu | Clock::ThreadCpu => {
let mut times = [FileTime::default(); 4];
let [creation, exit, kernel, user] = &mut times;
cvt(unsafe {
if clock == Clock::ProcessCpu {
GetProcessTimes(GetCurrentProcess(), creation, exit, kernel, user)
} else {
GetThreadTimes(GetCurrentThread(), creation, exit, kernel, user)
}
})?;
times[2].units().saturating_add(times[3].units())
}
};
Ok(from_units(units))
}
pub(crate) fn resolution(clock: Clock) -> Result<Duration> {
match clock {
Clock::Monotonic | Clock::Boottime => {
let mut frequency = 0;
cvt(unsafe { QueryPerformanceFrequency(&raw mut frequency) })?;
if frequency <= 0 {
return Err(ErrorKind::Other.into());
}
let nanos = 1_000_000_000u64.div_ceil(frequency as u64);
Ok(Duration::from_nanos(nanos.max(100)))
}
Clock::ProcessCpu | Clock::ThreadCpu => {
let (mut adjustment, mut increment, mut disabled) = (0, 0, 0);
cvt(unsafe {
GetSystemTimeAdjustment(&raw mut adjustment, &raw mut increment, &raw mut disabled)
})?;
Ok(from_units(increment.into()))
}
}
}
fn timer_sleep(units: u64) -> Result<()> {
let timer = unsafe {
CreateWaitableTimerExW(
core::ptr::null(),
core::ptr::null(),
CREATE_WAITABLE_TIMER_HIGH_RESOLUTION,
TIMER_ALL_ACCESS,
)
};
if timer.is_null() {
return Err(last_error());
}
let due = -i64::try_from(units).unwrap_or(i64::MAX);
let set = cvt(unsafe {
SetWaitableTimer(
timer,
&raw const due,
0,
core::ptr::null(),
core::ptr::null(),
0,
)
});
let waited = set.and_then(|()| {
match unsafe { WaitForSingleObject(timer, INFINITE) } {
WAIT_OBJECT_0 => Ok(()),
_ => Err(last_error()),
}
});
unsafe { CloseHandle(timer) };
waited
}
fn sleep_until_units(deadline: u64) -> Result<()> {
let mut high_resolution = true;
loop {
let now = unbiased();
if now >= deadline {
return Ok(());
}
let left = (deadline - now).min(MAX_TIMER_UNITS);
if high_resolution && timer_sleep(left).is_err() {
high_resolution = false;
}
if !high_resolution {
let milliseconds = left.div_ceil(10_000).min((INFINITE - 1).into()) as u32;
unsafe { Sleep(milliseconds) };
}
}
}
pub(crate) fn to_units(duration: Duration) -> u64 {
duration.as_nanos().div_ceil(100).min(i64::MAX as u128) as u64
}
pub(crate) fn sleep(duration: Duration) -> Result<()> {
sleep_until_units(unbiased().saturating_add(to_units(duration)))
}
pub(crate) fn sleep_until(deadline: Duration) -> Result<()> {
sleep_until_units(to_units(deadline))
}