1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
use core::{time, ptr, mem};
use core::cell::Cell;
use core::sync::atomic::{AtomicPtr, Ordering};
use super::BoxFnPtr;

extern crate alloc;
use alloc::boxed::Box;

mod ffi {
    pub use core::ffi::c_void;

    type DWORD = u32;
    type BOOL = i32;

    #[repr(C)]
    pub struct FileTime {
        pub low_date_time: DWORD,
        pub high_date_time: DWORD,
    }

    pub type Callback = Option<unsafe extern "system" fn(cb_inst: *mut c_void, ctx: *mut c_void, timer: *mut c_void)>;

    extern "system" {
        pub fn CloseThreadpoolTimer(ptr: *mut c_void);
        pub fn CreateThreadpoolTimer(cb: Callback, user_data: *mut c_void, env: *mut c_void) -> *mut c_void;
        pub fn SetThreadpoolTimerEx(timer: *mut c_void, pftDueTime: *mut FileTime, msPeriod: DWORD, msWindowLength: DWORD) -> BOOL;
        pub fn IsThreadpoolTimerSet(timer: *mut c_void) -> BOOL;
        pub fn WaitForThreadpoolTimerCallbacks(timer: *mut c_void, fCancelPendingCallbacks: BOOL);
    }
}

unsafe extern "system" fn timer_callback(_: *mut ffi::c_void, data: *mut ffi::c_void, _: *mut ffi::c_void) {
    let cb: fn() -> () = mem::transmute(data);

    (cb)();
}

unsafe extern "system" fn timer_callback_unsafe(_: *mut ffi::c_void, data: *mut ffi::c_void, _: *mut ffi::c_void) {
    let cb: unsafe fn() -> () = mem::transmute(data);

    (cb)();
}

unsafe extern "system" fn timer_callback_generic<T: FnMut() -> ()>(_: *mut ffi::c_void, data: *mut ffi::c_void, _: *mut ffi::c_void) {
    let cb = &mut *(data as *mut T);

    (cb)();
}

enum CallbackVariant {
    PlainUnsafe(unsafe fn()),
    Plain(fn()),
    Closure(Box<dyn FnMut()>),
}

///Timer's callback abstraction
pub struct Callback {
    variant: CallbackVariant,
    ffi_cb: ffi::Callback,
}

impl Callback {
    ///Creates callback using plain rust function
    pub fn plain(cb: fn()) -> Self {
        Self {
            variant: CallbackVariant::Plain(cb),
            ffi_cb: Some(timer_callback),
        }
    }

    ///Creates callback using plain unsafe function
    pub fn unsafe_plain(cb: unsafe fn()) -> Self {
        Self {
            variant: CallbackVariant::PlainUnsafe(cb),
            ffi_cb: Some(timer_callback_unsafe),
        }
    }

    ///Creates callback using closure, storing it on heap.
    pub fn closure<F: 'static + FnMut()>(cb: F) -> Self {
        Self {
            variant: CallbackVariant::Closure(Box::new(cb)),
            ffi_cb: Some(timer_callback_generic::<F>),
        }
    }
}

///Windows thread pool timer
pub struct Timer {
    inner: AtomicPtr<ffi::c_void>,
    data: Cell<BoxFnPtr>,
}

impl Timer {
    #[inline]
    ///Creates new uninitialized instance.
    ///
    ///In order to use it one must call `init`.
    pub const unsafe fn uninit() -> Self {
        Self {
            inner: AtomicPtr::new(ptr::null_mut()),
            data: Cell::new(BoxFnPtr::new()),
        }
    }

    #[inline(always)]
    fn get_inner(&self) -> *mut ffi::c_void {
        let inner = self.inner.load(Ordering::Acquire);
        debug_assert!(!inner.is_null(), "Timer has not been initialized");
        inner
    }

    #[inline(always)]
    ///Returns whether timer is initialized
    pub fn is_init(&self) -> bool {
        !self.inner.load(Ordering::Acquire).is_null()
    }

    #[must_use]
    ///Performs timer initialization
    ///
    ///`cb` is variant of callback to invoke when timer expires
    ///
    ///Returns whether timer has been initialized successfully or not.
    ///
    ///If timer is already initialized does nothing, returning false.
    pub fn init(&self, cb: Callback) -> bool {
        if self.is_init() {
            return false;
        }

        let ffi_cb = cb.ffi_cb;
        let ffi_data = match cb.variant {
            CallbackVariant::Plain(cb) => cb as *mut ffi::c_void,
            CallbackVariant::PlainUnsafe(cb) => cb as *mut ffi::c_void,
            CallbackVariant::Closure(ref cb) => &*cb as *const _ as *mut ffi::c_void,
        };

        let handle = unsafe {
            ffi::CreateThreadpoolTimer(ffi_cb, ffi_data, ptr::null_mut())
        };

        match self.inner.compare_exchange(ptr::null_mut(), handle, Ordering::SeqCst, Ordering::Acquire) {
            Ok(_) => match handle.is_null() {
                true => false,
                false => {
                    match cb.variant {
                        CallbackVariant::Closure(cb) => {
                            //safe because we can never reach here once `handle.is_null() != true`
                            self.data.set(cb.into())
                        },
                        _ => (),
                    }
                    true
                },
            },
            Err(_) => {
                unsafe {
                    ffi::CloseThreadpoolTimer(handle);
                }
                false
            }
        }
    }

    ///Creates new timer, invoking provided `cb` when timer expires.
    ///
    ///On failure, returns `None`
    pub fn new(cb: Callback) -> Option<Self> {
        let ffi_cb = cb.ffi_cb;
        let ffi_data = match cb.variant {
            CallbackVariant::Plain(cb) => cb as *mut ffi::c_void,
            CallbackVariant::PlainUnsafe(cb) => cb as *mut ffi::c_void,
            CallbackVariant::Closure(ref cb) => &*cb as *const _ as *mut ffi::c_void,
        };

        let handle = unsafe {
            ffi::CreateThreadpoolTimer(ffi_cb, ffi_data, ptr::null_mut())
        };

        if handle.is_null() {
            return None;
        }

        let data = match cb.variant {
            CallbackVariant::Closure(cb) => cb.into(),
            _ => BoxFnPtr::new(),
        };

        Some(Self {
            inner: AtomicPtr::new(handle),
            data: Cell::new(data),
        })
    }

    ///Schedules timer to alarm periodically with `interval` with initial alarm of `timeout`.
    ///
    ///Note that if timer has been scheduled before, but hasn't expire yet, it shall be cancelled.
    ///To prevent that user must `cancel` timer first.
    ///
    ///# Note
    ///
    ///- `interval` is truncated by `u32::max_value()`
    ///
    ///Returns `true` if successfully set, otherwise on error returns `false`
    pub fn schedule_interval(&self, timeout: time::Duration, interval: time::Duration) -> bool {
        let mut ticks = i64::from(timeout.subsec_nanos() / 100);
        ticks += (timeout.as_secs() * 10_000_000) as i64;
        let ticks = -ticks;

        let interval = interval.as_millis() as u32;

        unsafe {
            let mut time: ffi::FileTime = mem::transmute(ticks);
            ffi::SetThreadpoolTimerEx(self.get_inner(), &mut time, interval, 0);
        }

        true
    }

    #[inline]
    ///Returns `true` if timer has been scheduled and still pending.
    ///
    ///On Win/Mac it only returns whether timer has been scheduled, as there is no way to check
    ///whether timer is ongoing
    pub fn is_scheduled(&self) -> bool {
        let handle = self.get_inner();
        unsafe {
            ffi::IsThreadpoolTimerSet(handle) != 0
        }
    }

    #[inline]
    ///Cancels ongoing timer, if it was scheduled.
    pub fn cancel(&self) {
        let handle = self.get_inner();
        unsafe {
            ffi::SetThreadpoolTimerEx(handle, ptr::null_mut(), 0, 0);
            ffi::WaitForThreadpoolTimerCallbacks(handle, 1);
        }
    }
}

impl Drop for Timer {
    fn drop(&mut self) {
        let handle = self.inner.load(Ordering::Relaxed);
        if !handle.is_null() {
            self.cancel();
            unsafe {
                ffi::CloseThreadpoolTimer(handle);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn init_plain_fn() {
        let mut timer = unsafe {
            Timer::uninit()
        };

        fn cb() {
        }

        let closure = || {
        };

        assert!(timer.init(Callback::plain(cb)));
        let ptr = timer.inner.load(Ordering::Relaxed);
        assert!(!ptr.is_null());
        assert!(timer.data.get_mut().is_null());

        assert!(!timer.init(Callback::closure(closure)));
        assert!(!ptr.is_null());
        assert_eq!(ptr, timer.inner.load(Ordering::Relaxed));
        assert!(timer.data.get_mut().is_null());
    }

    #[test]
    fn init_closure() {
        let mut timer = unsafe {
            Timer::uninit()
        };

        fn cb() {
        }

        let closure = || {
        };

        assert!(timer.init(Callback::closure(closure)));
        let ptr = timer.inner.load(Ordering::Relaxed);
        assert!(!ptr.is_null());
        assert!(!timer.data.get_mut().is_null());

        assert!(!timer.init(Callback::plain(cb)));
        assert!(!ptr.is_null());
        assert_eq!(ptr, timer.inner.load(Ordering::Relaxed));
        assert!(!timer.data.get_mut().is_null());
    }
}