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
use crate::NativeTimerWrapper;
#[cfg(target_os = "windows")]
use winapi::um::winnt::PVOID;
#[cfg(target_os = "linux")]
use libc::{c_int, c_void, siginfo_t};
#[cfg(target_os = "macos")]
use libc::c_void;
pub struct Timer<F>
where
F: Fn(),
{
native_timer: NativeTimerWrapper,
cb: F,
}
impl<F> Timer<F>
where
F: Fn(),
{
pub fn new(cb: F) -> Self {
Self {
native_timer: NativeTimerWrapper::new(),
cb,
}
}
pub fn start(&mut self, period_ns: u32) {
let ptr = self as *mut Self;
self.native_timer
.start(Some(Self::rt_thread), period_ns, ptr);
}
pub fn close(&mut self) {
self.native_timer.close();
}
#[cfg(target_os = "windows")]
unsafe extern "system" fn rt_thread(lp_param: PVOID, _t: u8) {
let ptr = lp_param as *mut Self;
((*ptr).cb)();
}
#[cfg(target_os = "linux")]
unsafe extern "C" fn rt_thread(_sig: c_int, _si: *mut siginfo_t, uc: *mut c_void) {
let ptr = uc as *mut Self;
((*ptr).cb)();
}
#[cfg(target_os = "macos")]
unsafe extern "C" fn rt_thread(ptr: *const c_void) {
let ptr = ptr as *mut Self;
((*ptr).cb)();
}
}