1#![deny(missing_docs)]
2#![forbid(unsafe_op_in_unsafe_fn)]
3
4use std::io;
41use std::time::{Duration, Instant};
42
43#[cfg(all(feature = "realtime", feature = "boottime"))]
44compile_error!("features `realtime` and `boottime` are mutually exclusive");
45
46mod delay;
47mod delay_queue;
48mod interval;
49mod timer;
50
51pub use delay::Delay;
52pub use delay_queue::{DelayQueue, Expired, Key};
53pub use interval::Interval;
54
55#[cfg(any(target_os = "linux", target_os = "android"))]
56pub use timerfd::ClockId;
57
58#[cfg(any(target_os = "linux", target_os = "android"))]
59use std::io::{Error, Result};
60#[cfg(any(target_os = "linux", target_os = "android"))]
61use std::os::unix::io::{AsRawFd, RawFd};
62#[cfg(any(target_os = "linux", target_os = "android"))]
63use std::pin::Pin;
64#[cfg(any(target_os = "linux", target_os = "android"))]
65use std::task::{Context, Poll};
66
67#[cfg(any(target_os = "linux", target_os = "android"))]
68use futures_core::ready;
69#[cfg(any(target_os = "linux", target_os = "android"))]
70use timerfd::{SetTimeFlags, TimerFd as InnerTimerFd, TimerState};
71#[cfg(any(target_os = "linux", target_os = "android"))]
72use tokio::io::unix::AsyncFd;
73#[cfg(any(target_os = "linux", target_os = "android"))]
74use tokio::io::{AsyncRead, Interest, ReadBuf};
75
76#[cfg(any(target_os = "linux", target_os = "android"))]
81pub struct TimerFd(AsyncFd<InnerTimerFd>);
82
83#[cfg(any(target_os = "linux", target_os = "android"))]
84impl TimerFd {
85 pub fn new(clock: ClockId) -> io::Result<Self> {
87 let fd = InnerTimerFd::new_custom(clock, true, true)?;
88 let inner = AsyncFd::with_interest(fd, Interest::READABLE)?;
89 Ok(TimerFd(inner))
90 }
91
92 fn set_state(&mut self, state: TimerState, flags: SetTimeFlags) -> TimerState {
93 self.0.get_mut().set_state(state, flags)
94 }
95}
96
97#[cfg(any(target_os = "linux", target_os = "android"))]
98impl AsRawFd for TimerFd {
99 fn as_raw_fd(&self) -> RawFd {
100 self.0.as_raw_fd()
101 }
102}
103
104#[cfg(any(target_os = "linux", target_os = "android"))]
105fn read_u64(fd: RawFd) -> Result<u64> {
106 loop {
107 let mut buf = [0u8; 8];
108 let rv = unsafe {
109 libc::read(fd, buf.as_mut_ptr() as *mut _, buf.len())
112 };
113
114 if rv == buf.len() as isize {
115 return Ok(u64::from_ne_bytes(buf));
116 }
117 if rv < 0 {
118 let err = Error::last_os_error();
119 if err.kind() == io::ErrorKind::Interrupted {
120 continue;
121 }
122 return Err(err);
123 }
124
125 return Err(Error::new(
126 io::ErrorKind::UnexpectedEof,
127 "timerfd returned an incomplete expiration count",
128 ));
129 }
130}
131
132#[cfg(any(target_os = "linux", target_os = "android"))]
133impl AsyncRead for TimerFd {
134 fn poll_read(
135 mut self: Pin<&mut Self>,
136 cx: &mut Context<'_>,
137 buf: &mut ReadBuf<'_>,
138 ) -> Poll<Result<()>> {
139 if buf.remaining() < 8 {
140 return Poll::Ready(Err(Error::new(
141 io::ErrorKind::InvalidInput,
142 "TimerFd requires at least 8 bytes of buffer space",
143 )));
144 }
145
146 let inner = self.as_mut();
147 let fd = inner.0.as_raw_fd();
148
149 loop {
150 let mut guard = ready!(inner.0.poll_read_ready(cx))?;
151 match guard.try_io(|_| read_u64(fd)) {
152 Ok(res) => {
153 let num = res?;
154 buf.put_slice(&num.to_ne_bytes());
155 break;
156 }
157 Err(_) => continue,
158 }
159 }
160 Poll::Ready(Ok(()))
161 }
162}
163
164pub fn sleep(duration: Duration) -> Delay {
169 try_sleep(duration).expect("can't create delay")
170}
171
172pub fn try_sleep(duration: Duration) -> io::Result<Delay> {
174 let deadline = Instant::now().checked_add(duration).ok_or_else(|| {
175 io::Error::new(
176 io::ErrorKind::InvalidInput,
177 "sleep duration exceeds the supported clock range",
178 )
179 })?;
180 Delay::new(deadline)
181}
182
183#[cfg(all(test, any(target_os = "linux", target_os = "android")))]
184mod timerfd_tests {
185 use super::*;
186 use std::future::poll_fn;
187
188 #[tokio::test]
189 async fn short_read_buffer_is_rejected() {
190 let mut timer = TimerFd::new(ClockId::Monotonic).unwrap();
191 let mut buffer = [0_u8; 1];
192 let mut read_buffer = ReadBuf::new(&mut buffer);
193 let err = poll_fn(|cx| Pin::new(&mut timer).poll_read(cx, &mut read_buffer))
194 .await
195 .unwrap_err();
196 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
197 }
198}
199
200#[cfg(any(target_os = "linux", target_os = "android"))]
201#[cfg(feature = "realtime")]
202fn get_clock() -> ClockId {
203 ClockId::Realtime
204}
205
206#[cfg(any(target_os = "linux", target_os = "android"))]
207#[cfg(feature = "boottime")]
208fn get_clock() -> ClockId {
209 ClockId::Boottime
210}
211
212#[cfg(any(target_os = "linux", target_os = "android"))]
213#[cfg(not(any(feature = "boottime", feature = "realtime")))]
214fn get_clock() -> ClockId {
215 ClockId::Monotonic
216}