#![doc = include_str!("../readme.md")]
#![no_std]
#![expect(non_snake_case, non_camel_case_types, clippy::upper_case_acronyms)]
mod bindings;
use bindings::*;
mod pool;
pub use pool::*;
extern crate alloc;
use alloc::boxed::Box;
use core::ffi::c_void;
use core::time::Duration;
pub fn submit<F: FnOnce() + Send + 'static>(f: F) {
assert!(
unsafe { submit_with_environment(core::ptr::null(), f) },
"allocation failed"
);
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Priority {
High,
#[default]
Normal,
Low,
}
impl Priority {
fn to_raw(self) -> TP_CALLBACK_PRIORITY {
match self {
Self::High => TP_CALLBACK_PRIORITY_HIGH,
Self::Normal => TP_CALLBACK_PRIORITY_NORMAL,
Self::Low => TP_CALLBACK_PRIORITY_LOW,
}
}
}
pub fn submit_with_priority<F: FnOnce() + Send + 'static>(priority: Priority, f: F) {
let environment = environment(core::ptr::null_mut(), core::ptr::null_mut(), priority);
assert!(
unsafe { submit_with_environment(&environment, f) },
"allocation failed"
);
}
pub fn submit_after<F: FnOnce() + Send + 'static>(delay: Duration, f: F) {
struct Delayed<F> {
deadline: Option<i64>,
f: F,
}
unsafe extern "system" fn callback<F: FnOnce() + Send>(
_: PTP_CALLBACK_INSTANCE,
context: *mut c_void,
timer: PTP_TIMER,
) {
let delayed = context as *mut Delayed<F>;
let remaining = match unsafe { (*delayed).deadline } {
Some(deadline) => ticks_to_duration(deadline.saturating_sub(counter())),
None => Duration::MAX,
};
if remaining.is_zero() {
unsafe {
CloseThreadpoolTimer(timer);
(Box::from_raw(delayed).f)();
}
} else {
set_timer(timer, remaining);
}
}
let context = Box::into_raw(Box::new(Delayed {
deadline: duration_to_ticks(delay).and_then(|ticks| counter().checked_add(ticks)),
f,
}));
let timer =
unsafe { CreateThreadpoolTimer(Some(callback::<F>), context as _, core::ptr::null_mut()) };
if timer.is_null() {
drop(unsafe { Box::from_raw(context) });
panic!("allocation failed");
}
set_timer(timer, delay);
}
fn set_timer(timer: PTP_TIMER, delay: Duration) {
let ticks = delay.as_nanos().div_ceil(100).min(i64::MAX as u128) as i64;
let due = (-ticks) as u64;
let mut due = FILETIME {
dwLowDateTime: due as u32,
dwHighDateTime: (due >> 32) as u32,
};
unsafe { SetThreadpoolTimer(timer, &mut due, 0, 0) };
}
fn counter() -> i64 {
let mut value = LARGE_INTEGER::default();
unsafe {
QueryPerformanceCounter(&mut value);
value.QuadPart
}
}
fn frequency() -> u128 {
let mut value = LARGE_INTEGER::default();
unsafe {
QueryPerformanceFrequency(&mut value);
value.QuadPart as u128
}
}
fn duration_to_ticks(duration: Duration) -> Option<i64> {
i64::try_from((duration.as_nanos() * frequency()).div_ceil(1_000_000_000)).ok()
}
fn ticks_to_duration(ticks: i64) -> Duration {
let nanos = (ticks.max(0) as u128 * 1_000_000_000).div_ceil(frequency());
Duration::from_nanos(nanos.min(u64::MAX as u128) as u64)
}
pub fn for_each<I, F, T>(i: I, f: F)
where
I: Iterator<Item = T>,
F: Fn(T) + Sync,
T: Send,
{
Pool::with_scope(|pool| {
for item in i {
pool.submit(|| f(item));
}
});
}
pub fn thread_id() -> u32 {
unsafe { GetCurrentThreadId() }
}
pub fn sleep(milliseconds: u32) {
unsafe {
Sleep(milliseconds);
}
}
fn check<D: Default + PartialEq>(result: D) -> D {
assert!(result != D::default(), "allocation failed");
result
}
fn check_ptr<T>(result: *mut T) -> *mut T {
assert!(!result.is_null(), "allocation failed");
result
}
fn environment(
pool: PTP_POOL,
cleanup_group: PTP_CLEANUP_GROUP,
priority: Priority,
) -> TP_CALLBACK_ENVIRON_V3 {
TP_CALLBACK_ENVIRON_V3 {
Version: 3,
Pool: pool,
CleanupGroup: cleanup_group,
CallbackPriority: priority.to_raw(),
Size: size_of::<TP_CALLBACK_ENVIRON_V3>() as u32,
..Default::default()
}
}
unsafe fn submit_with_environment<F: FnOnce() + Send>(
environment: *const TP_CALLBACK_ENVIRON_V3,
f: F,
) -> bool {
unsafe extern "system" fn callback<F: FnOnce() + Send>(
_: PTP_CALLBACK_INSTANCE,
callback: *mut c_void,
) {
unsafe {
Box::from_raw(callback as *mut F)();
}
}
let context = Box::into_raw(Box::new(f));
if unsafe {
TrySubmitThreadpoolCallback(Some(callback::<F>), context as _, environment.cast_mut())
} != 0
{
true
} else {
drop(unsafe { Box::from_raw(context) });
false
}
}