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
use core::{mem};
use crate::{
kty::{c_int, itimerspec, TFD_TIMER_ABSTIME},
syscall::{close, timerfd_settime, timerfd_gettime, read},
fd::{FdContainer},
util::retry::{retry},
time::{Time, time_to_timespec, time_from_timespec},
result::{Result},
lmem,
};
pub struct Timer {
fd: c_int,
owned: bool,
}
impl Timer {
pub fn disable(&self) -> Result {
let arg = lmem::zeroed();
rv!(timerfd_settime(self.fd, 0, &arg, None))
}
pub fn interval(&self, iv: Time) -> Result {
let arg = itimerspec {
it_interval: time_to_timespec(iv),
it_value: time_to_timespec(iv),
};
rv!(timerfd_settime(self.fd, 0, &arg, None))
}
pub fn interval_from(&self, iv: Time, start: Time) -> Result {
let arg = itimerspec {
it_interval: time_to_timespec(iv),
it_value: time_to_timespec(start),
};
rv!(timerfd_settime(self.fd, TFD_TIMER_ABSTIME, &arg, None))
}
pub fn interval_in(&self, iv: Time, when: Time) -> Result {
let arg = itimerspec {
it_interval: time_to_timespec(iv),
it_value: time_to_timespec(when),
};
rv!(timerfd_settime(self.fd, 0, &arg, None))
}
pub fn once_at(&self, when: Time) -> Result {
let arg = itimerspec {
it_interval: lmem::zeroed(),
it_value: time_to_timespec(when),
};
rv!(timerfd_settime(self.fd, TFD_TIMER_ABSTIME, &arg, None))
}
pub fn once_in(&self, when: Time) -> Result {
let arg = itimerspec {
it_interval: lmem::zeroed(),
it_value: time_to_timespec(when),
};
rv!(timerfd_settime(self.fd, 0, &arg, None))
}
pub fn status(&self) -> Result<(Time, Time)> {
let mut arg = lmem::zeroed();
rv!(timerfd_gettime(self.fd, &mut arg))?;
Ok((time_from_timespec(arg.it_interval), time_from_timespec(arg.it_value)))
}
pub fn ticks(&self) -> Result<u64> {
let mut buf = 0;
retry(|| read(self.fd, lmem::as_mut_data(&mut buf)))?;
Ok(buf)
}
}
impl Drop for Timer {
fn drop(&mut self) {
if self.owned {
close(self.fd);
}
}
}
impl From<Timer> for c_int {
fn from(timer: Timer) -> Self {
let fd = timer.fd;
mem::forget(timer);
fd
}
}
impl FdContainer for Timer {
fn is_owned(&self) -> bool {
self.owned
}
fn borrow(&self) -> c_int {
self.fd
}
fn from_owned(fd: c_int) -> Timer {
Timer { fd, owned: true }
}
fn from_borrowed(fd: c_int) -> Timer {
Timer { fd, owned: false }
}
}