#![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;
pub fn submit<F: FnOnce() + Send + 'static>(f: F) {
assert!(
unsafe { submit_with_environment(core::ptr::null(), f) },
"allocation failed"
);
}
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
}
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>(
_: *mut TP_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) } != 0 {
true
} else {
drop(unsafe { Box::from_raw(context) });
false
}
}