#![deny(missing_docs)]
#![forbid(unsafe_op_in_unsafe_fn)]
use std::io;
use std::time::{Duration, Instant};
#[cfg(all(feature = "realtime", feature = "boottime"))]
compile_error!("features `realtime` and `boottime` are mutually exclusive");
mod delay;
mod delay_queue;
mod interval;
mod timer;
pub use delay::Delay;
pub use delay_queue::{DelayQueue, Expired, Key};
pub use interval::Interval;
#[cfg(any(target_os = "linux", target_os = "android"))]
pub use timerfd::ClockId;
#[cfg(any(target_os = "linux", target_os = "android"))]
use std::io::{Error, Result};
#[cfg(any(target_os = "linux", target_os = "android"))]
use std::os::unix::io::{AsRawFd, RawFd};
#[cfg(any(target_os = "linux", target_os = "android"))]
use std::pin::Pin;
#[cfg(any(target_os = "linux", target_os = "android"))]
use std::task::{Context, Poll};
#[cfg(any(target_os = "linux", target_os = "android"))]
use futures_core::ready;
#[cfg(any(target_os = "linux", target_os = "android"))]
use timerfd::{SetTimeFlags, TimerFd as InnerTimerFd, TimerState};
#[cfg(any(target_os = "linux", target_os = "android"))]
use tokio::io::unix::AsyncFd;
#[cfg(any(target_os = "linux", target_os = "android"))]
use tokio::io::{AsyncRead, Interest, ReadBuf};
#[cfg(any(target_os = "linux", target_os = "android"))]
pub struct TimerFd(AsyncFd<InnerTimerFd>);
#[cfg(any(target_os = "linux", target_os = "android"))]
impl TimerFd {
pub fn new(clock: ClockId) -> io::Result<Self> {
let fd = InnerTimerFd::new_custom(clock, true, true)?;
let inner = AsyncFd::with_interest(fd, Interest::READABLE)?;
Ok(TimerFd(inner))
}
fn set_state(&mut self, state: TimerState, flags: SetTimeFlags) -> TimerState {
self.0.get_mut().set_state(state, flags)
}
}
#[cfg(any(target_os = "linux", target_os = "android"))]
impl AsRawFd for TimerFd {
fn as_raw_fd(&self) -> RawFd {
self.0.as_raw_fd()
}
}
#[cfg(any(target_os = "linux", target_os = "android"))]
fn read_u64(fd: RawFd) -> Result<u64> {
loop {
let mut buf = [0u8; 8];
let rv = unsafe {
libc::read(fd, buf.as_mut_ptr() as *mut _, buf.len())
};
if rv == buf.len() as isize {
return Ok(u64::from_ne_bytes(buf));
}
if rv < 0 {
let err = Error::last_os_error();
if err.kind() == io::ErrorKind::Interrupted {
continue;
}
return Err(err);
}
return Err(Error::new(
io::ErrorKind::UnexpectedEof,
"timerfd returned an incomplete expiration count",
));
}
}
#[cfg(any(target_os = "linux", target_os = "android"))]
impl AsyncRead for TimerFd {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<Result<()>> {
if buf.remaining() < 8 {
return Poll::Ready(Err(Error::new(
io::ErrorKind::InvalidInput,
"TimerFd requires at least 8 bytes of buffer space",
)));
}
let inner = self.as_mut();
let fd = inner.0.as_raw_fd();
loop {
let mut guard = ready!(inner.0.poll_read_ready(cx))?;
match guard.try_io(|_| read_u64(fd)) {
Ok(res) => {
let num = res?;
buf.put_slice(&num.to_ne_bytes());
break;
}
Err(_) => continue,
}
}
Poll::Ready(Ok(()))
}
}
pub fn sleep(duration: Duration) -> Delay {
try_sleep(duration).expect("can't create delay")
}
pub fn try_sleep(duration: Duration) -> io::Result<Delay> {
let deadline = Instant::now().checked_add(duration).ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
"sleep duration exceeds the supported clock range",
)
})?;
Delay::new(deadline)
}
#[cfg(all(test, any(target_os = "linux", target_os = "android")))]
mod timerfd_tests {
use super::*;
use std::future::poll_fn;
#[tokio::test]
async fn short_read_buffer_is_rejected() {
let mut timer = TimerFd::new(ClockId::Monotonic).unwrap();
let mut buffer = [0_u8; 1];
let mut read_buffer = ReadBuf::new(&mut buffer);
let err = poll_fn(|cx| Pin::new(&mut timer).poll_read(cx, &mut read_buffer))
.await
.unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
}
}
#[cfg(any(target_os = "linux", target_os = "android"))]
#[cfg(feature = "realtime")]
fn get_clock() -> ClockId {
ClockId::Realtime
}
#[cfg(any(target_os = "linux", target_os = "android"))]
#[cfg(feature = "boottime")]
fn get_clock() -> ClockId {
ClockId::Boottime
}
#[cfg(any(target_os = "linux", target_os = "android"))]
#[cfg(not(any(feature = "boottime", feature = "realtime")))]
fn get_clock() -> ClockId {
ClockId::Monotonic
}