1#![doc = include_str!("../readme.md")]
2#![no_std]
3#![expect(non_snake_case, non_camel_case_types, clippy::upper_case_acronyms)]
4
5mod bindings;
6use bindings::*;
7
8mod pool;
9pub use pool::*;
10
11extern crate alloc;
12use alloc::boxed::Box;
13use core::ffi::c_void;
14
15pub fn submit<F: FnOnce() + Send + 'static>(f: F) {
21 assert!(
23 unsafe { submit_with_environment(core::ptr::null(), f) },
24 "allocation failed"
25 );
26}
27
28pub fn for_each<I, F, T>(i: I, f: F)
32where
33 I: Iterator<Item = T>,
34 F: Fn(T) + Sync,
35 T: Send,
36{
37 Pool::with_scope(|pool| {
38 for item in i {
39 pool.submit(|| f(item));
40 }
41 });
42}
43
44pub fn thread_id() -> u32 {
46 unsafe { GetCurrentThreadId() }
47}
48
49pub fn sleep(milliseconds: u32) {
51 unsafe {
52 Sleep(milliseconds);
53 }
54}
55
56fn check<D: Default + PartialEq>(result: D) -> D {
58 assert!(result != D::default(), "allocation failed");
59
60 result
61}
62
63fn check_ptr<T>(result: *mut T) -> *mut T {
65 assert!(!result.is_null(), "allocation failed");
66
67 result
68}
69
70unsafe fn submit_with_environment<F: FnOnce() + Send>(
73 environment: *const TP_CALLBACK_ENVIRON_V3,
74 f: F,
75) -> bool {
76 unsafe extern "system" fn callback<F: FnOnce() + Send>(
77 _: *mut TP_CALLBACK_INSTANCE,
78 callback: *mut c_void,
79 ) {
80 unsafe {
81 Box::from_raw(callback as *mut F)();
82 }
83 }
84
85 let context = Box::into_raw(Box::new(f));
86 if unsafe { TrySubmitThreadpoolCallback(Some(callback::<F>), context as _, environment) } != 0 {
87 true
88 } else {
89 drop(unsafe { Box::from_raw(context) });
91 false
92 }
93}