use std::fs::File;
use std::mem;
use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
use std::ptr;
use std::time::Duration;
use std::sync::Arc;
use sync::Mutex;
use libc::{self, timerfd_create, timerfd_gettime, timerfd_settime, CLOCK_MONOTONIC, TFD_CLOEXEC};
use {errno_result, Result, FakeClock, EventFd};
pub struct TimerFd(File);
impl TimerFd {
pub fn new() -> Result<TimerFd> {
let ret = unsafe { timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC) };
if ret < 0 {
return errno_result();
}
Ok(TimerFd(unsafe { File::from_raw_fd(ret) }))
}
pub fn reset(&mut self, dur: Duration, interval: Option<Duration>) -> Result<()> {
let mut spec: libc::itimerspec = unsafe { mem::zeroed() };
spec.it_value.tv_sec = dur.as_secs() as libc::time_t;
spec.it_value.tv_nsec = dur.subsec_nanos() as libc::c_long;
if let Some(int) = interval {
spec.it_interval.tv_sec = int.as_secs() as libc::time_t;
spec.it_interval.tv_nsec = int.subsec_nanos() as libc::c_long;
}
let ret = unsafe { timerfd_settime(self.as_raw_fd(), 0, &spec, ptr::null_mut()) };
if ret < 0 {
return errno_result();
}
Ok(())
}
pub fn wait(&mut self) -> Result<u64> {
let mut count = 0u64;
let ret = unsafe {
libc::read(
self.as_raw_fd(),
&mut count as *mut _ as *mut libc::c_void,
mem::size_of_val(&count),
)
};
if ret < 0 {
return errno_result();
}
Ok(count)
}
pub fn is_armed(&self) -> Result<bool> {
let mut spec: libc::itimerspec = unsafe { mem::zeroed() };
let ret = unsafe { timerfd_gettime(self.as_raw_fd(), &mut spec) };
if ret < 0 {
return errno_result();
}
Ok(spec.it_value.tv_sec != 0 || spec.it_value.tv_nsec != 0)
}
pub fn clear(&mut self) -> Result<()> {
let spec: libc::itimerspec = unsafe { mem::zeroed() };
let ret = unsafe { timerfd_settime(self.as_raw_fd(), 0, &spec, ptr::null_mut()) };
if ret < 0 {
return errno_result();
}
Ok(())
}
}
impl AsRawFd for TimerFd {
fn as_raw_fd(&self) -> RawFd {
self.0.as_raw_fd()
}
}
impl FromRawFd for TimerFd {
unsafe fn from_raw_fd(fd: RawFd) -> Self {
TimerFd(File::from_raw_fd(fd))
}
}
impl IntoRawFd for TimerFd {
fn into_raw_fd(self) -> RawFd {
self.0.into_raw_fd()
}
}
pub struct FakeTimerFd {
clock: Arc<Mutex<FakeClock>>,
deadline_ns: Option<u64>,
interval: Option<Duration>,
fd: EventFd,
}
impl FakeTimerFd {
pub fn new(clock: Arc<Mutex<FakeClock>>) -> Self {
FakeTimerFd {
clock,
deadline_ns: None,
interval: None,
fd: EventFd::new().unwrap(),
}
}
fn duration_to_nanos(d: Duration) -> u64 {
d.as_secs() * 1_000_000_000 + u64::from(d.subsec_nanos())
}
pub fn reset(&mut self, dur: Duration, interval: Option<Duration>) -> Result<()> {
let mut guard = self.clock.lock();
let deadline = guard.nanos() + FakeTimerFd::duration_to_nanos(dur);
self.deadline_ns = Some(deadline);
self.interval = interval;
guard.add_event_fd(deadline, self.fd.try_clone()?);
Ok(())
}
pub fn wait(&mut self) -> Result<u64> {
loop {
self.fd.read()?;
if let Some(ref mut deadline_ns) = self.deadline_ns {
let mut guard = self.clock.lock();
let now = guard.nanos();
if now >= *deadline_ns {
let mut expirys = 0;
if let Some(interval) = self.interval {
let interval_ns = FakeTimerFd::duration_to_nanos(interval);
if interval_ns > 0 {
expirys += (now - *deadline_ns) / interval_ns;
*deadline_ns += (expirys + 1) * interval_ns;
guard.add_event_fd(*deadline_ns, self.fd.try_clone()?);
}
}
return Ok(expirys + 1);
}
}
}
}
pub fn is_armed(&self) -> Result<bool> {
Ok(self.deadline_ns.is_some())
}
pub fn clear(&mut self) -> Result<()> {
self.deadline_ns = None;
self.interval = None;
Ok(())
}
}
impl AsRawFd for FakeTimerFd {
fn as_raw_fd(&self) -> RawFd {
self.fd.as_raw_fd()
}
}
impl IntoRawFd for FakeTimerFd {
fn into_raw_fd(self) -> RawFd {
self.fd.into_raw_fd()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::thread::sleep;
use std::time::{Duration, Instant};
#[test]
fn one_shot() {
let mut tfd = TimerFd::new().expect("failed to create timerfd");
assert_eq!(tfd.is_armed().unwrap(), false);
let dur = Duration::from_millis(200);
let now = Instant::now();
tfd.reset(dur.clone(), None).expect("failed to arm timer");
assert_eq!(tfd.is_armed().unwrap(), true);
let count = tfd.wait().expect("unable to wait for timer");
assert_eq!(count, 1);
assert!(now.elapsed() >= dur);
}
#[test]
fn repeating() {
let mut tfd = TimerFd::new().expect("failed to create timerfd");
let dur = Duration::from_millis(200);
let interval = Duration::from_millis(100);
tfd.reset(dur.clone(), Some(interval))
.expect("failed to arm timer");
sleep(dur * 3);
let count = tfd.wait().expect("unable to wait for timer");
assert!(count >= 5, "count = {}", count);
}
#[test]
fn fake_one_shot() {
let clock = Arc::new(Mutex::new(FakeClock::new()));
let mut tfd = FakeTimerFd::new(clock.clone());
assert_eq!(tfd.is_armed().unwrap(), false);
let dur = Duration::from_nanos(200);
tfd.reset(dur.clone(), None).expect("failed to arm timer");
assert_eq!(tfd.is_armed().unwrap(), true);
clock.lock().add_ns(200);
let count = tfd.wait().expect("unable to wait for timer");
assert_eq!(count, 1);
}
#[test]
fn fake_repeating() {
let clock = Arc::new(Mutex::new(FakeClock::new()));
let mut tfd = FakeTimerFd::new(clock.clone());
let dur = Duration::from_nanos(200);
let interval = Duration::from_nanos(100);
tfd.reset(dur.clone(), Some(interval)).expect("failed to arm timer");
clock.lock().add_ns(300);
let mut count = tfd.wait().expect("unable to wait for timer");
assert_eq!(count, 2);
clock.lock().add_ns(300);
count = tfd.wait().expect("unable to wait for timer");
assert_eq!(count, 3);
}
}