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;
14use core::time::Duration;
15
16pub fn submit<F: FnOnce() + Send + 'static>(f: F) {
22 assert!(
24 unsafe { submit_with_environment(core::ptr::null(), f) },
25 "allocation failed"
26 );
27}
28
29#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
34pub enum Priority {
35 High,
37 #[default]
39 Normal,
40 Low,
42}
43
44impl Priority {
45 fn to_raw(self) -> TP_CALLBACK_PRIORITY {
46 match self {
47 Self::High => TP_CALLBACK_PRIORITY_HIGH,
48 Self::Normal => TP_CALLBACK_PRIORITY_NORMAL,
49 Self::Low => TP_CALLBACK_PRIORITY_LOW,
50 }
51 }
52}
53
54pub fn submit_with_priority<F: FnOnce() + Send + 'static>(priority: Priority, f: F) {
58 let environment = environment(core::ptr::null_mut(), core::ptr::null_mut(), priority);
59
60 assert!(
62 unsafe { submit_with_environment(&environment, f) },
63 "allocation failed"
64 );
65}
66
67pub fn submit_after<F: FnOnce() + Send + 'static>(delay: Duration, f: F) {
73 struct Delayed<F> {
74 deadline: Option<i64>,
75 f: F,
76 }
77
78 unsafe extern "system" fn callback<F: FnOnce() + Send>(
82 _: PTP_CALLBACK_INSTANCE,
83 context: *mut c_void,
84 timer: PTP_TIMER,
85 ) {
86 let delayed = context as *mut Delayed<F>;
87 let remaining = match unsafe { (*delayed).deadline } {
88 Some(deadline) => ticks_to_duration(deadline.saturating_sub(counter())),
89 None => Duration::MAX,
90 };
91
92 if remaining.is_zero() {
93 unsafe {
94 CloseThreadpoolTimer(timer);
95 (Box::from_raw(delayed).f)();
96 }
97 } else {
98 set_timer(timer, remaining);
99 }
100 }
101
102 let context = Box::into_raw(Box::new(Delayed {
103 deadline: duration_to_ticks(delay).and_then(|ticks| counter().checked_add(ticks)),
104 f,
105 }));
106 let timer =
107 unsafe { CreateThreadpoolTimer(Some(callback::<F>), context as _, core::ptr::null_mut()) };
108
109 if timer.is_null() {
110 drop(unsafe { Box::from_raw(context) });
112 panic!("allocation failed");
113 }
114
115 set_timer(timer, delay);
116}
117
118fn set_timer(timer: PTP_TIMER, delay: Duration) {
119 let ticks = delay.as_nanos().div_ceil(100).min(i64::MAX as u128) as i64;
121 let due = (-ticks) as u64;
122 let mut due = FILETIME {
123 dwLowDateTime: due as u32,
124 dwHighDateTime: (due >> 32) as u32,
125 };
126
127 unsafe { SetThreadpoolTimer(timer, &mut due, 0, 0) };
128}
129
130fn counter() -> i64 {
132 let mut value = LARGE_INTEGER::default();
133 unsafe {
134 QueryPerformanceCounter(&mut value);
135 value.QuadPart
136 }
137}
138
139fn frequency() -> u128 {
140 let mut value = LARGE_INTEGER::default();
141 unsafe {
142 QueryPerformanceFrequency(&mut value);
143 value.QuadPart as u128
144 }
145}
146
147fn duration_to_ticks(duration: Duration) -> Option<i64> {
149 i64::try_from((duration.as_nanos() * frequency()).div_ceil(1_000_000_000)).ok()
150}
151
152fn ticks_to_duration(ticks: i64) -> Duration {
153 let nanos = (ticks.max(0) as u128 * 1_000_000_000).div_ceil(frequency());
154 Duration::from_nanos(nanos.min(u64::MAX as u128) as u64)
155}
156
157pub fn for_each<I, F, T>(i: I, f: F)
161where
162 I: Iterator<Item = T>,
163 F: Fn(T) + Sync,
164 T: Send,
165{
166 Pool::with_scope(|pool| {
167 for item in i {
168 pool.submit(|| f(item));
169 }
170 });
171}
172
173pub fn thread_id() -> u32 {
175 unsafe { GetCurrentThreadId() }
176}
177
178pub fn sleep(milliseconds: u32) {
180 unsafe {
181 Sleep(milliseconds);
182 }
183}
184
185fn check<D: Default + PartialEq>(result: D) -> D {
187 assert!(result != D::default(), "allocation failed");
188
189 result
190}
191
192fn check_ptr<T>(result: *mut T) -> *mut T {
194 assert!(!result.is_null(), "allocation failed");
195
196 result
197}
198
199fn environment(
200 pool: PTP_POOL,
201 cleanup_group: PTP_CLEANUP_GROUP,
202 priority: Priority,
203) -> TP_CALLBACK_ENVIRON_V3 {
204 TP_CALLBACK_ENVIRON_V3 {
205 Version: 3,
206 Pool: pool,
207 CleanupGroup: cleanup_group,
208 CallbackPriority: priority.to_raw(),
209 Size: size_of::<TP_CALLBACK_ENVIRON_V3>() as u32,
210 ..Default::default()
211 }
212}
213
214unsafe fn submit_with_environment<F: FnOnce() + Send>(
217 environment: *const TP_CALLBACK_ENVIRON_V3,
218 f: F,
219) -> bool {
220 unsafe extern "system" fn callback<F: FnOnce() + Send>(
221 _: PTP_CALLBACK_INSTANCE,
222 callback: *mut c_void,
223 ) {
224 unsafe {
225 Box::from_raw(callback as *mut F)();
226 }
227 }
228
229 let context = Box::into_raw(Box::new(f));
230 if unsafe {
231 TrySubmitThreadpoolCallback(Some(callback::<F>), context as _, environment.cast_mut())
232 } != 0
233 {
234 true
235 } else {
236 drop(unsafe { Box::from_raw(context) });
238 false
239 }
240}