1 // Copyright 2020 The Chromium OS Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 use crate::{ 6 AsRawDescriptor, FakeClock, FromRawDescriptor, IntoRawDescriptor, RawDescriptor, Result, 7 }; 8 9 use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd}; 10 use std::sync::Arc; 11 use std::time::Duration; 12 use sync::Mutex; 13 use sys_util::{FakeTimerFd, TimerFd}; 14 15 /// See [TimerFd](sys_util::TimerFd) for struct- and method-level 16 /// documentation. 17 pub struct Timer(pub TimerFd); 18 impl Timer { new() -> Result<Timer>19 pub fn new() -> Result<Timer> { 20 TimerFd::new().map(Timer) 21 } 22 } 23 24 /// See [FakeTimerFd](sys_util::FakeTimerFd) for struct- and method-level 25 /// documentation. 26 pub struct FakeTimer(FakeTimerFd); 27 impl FakeTimer { new(clock: Arc<Mutex<FakeClock>>) -> Self28 pub fn new(clock: Arc<Mutex<FakeClock>>) -> Self { 29 FakeTimer(FakeTimerFd::new(clock)) 30 } 31 } 32 33 macro_rules! build_timer { 34 ($timer:ident, $inner:ident) => { 35 impl $timer { 36 pub fn reset(&mut self, dur: Duration, interval: Option<Duration>) -> Result<()> { 37 self.0.reset(dur, interval) 38 } 39 40 pub fn wait(&mut self) -> Result<()> { 41 self.0.wait().map(|_| ()) 42 } 43 44 pub fn is_armed(&self) -> Result<bool> { 45 self.0.is_armed() 46 } 47 48 pub fn clear(&mut self) -> Result<()> { 49 self.0.clear() 50 } 51 52 pub fn resolution() -> Result<Duration> { 53 $inner::resolution() 54 } 55 } 56 57 impl AsRawDescriptor for $timer { 58 fn as_raw_descriptor(&self) -> RawDescriptor { 59 self.0.as_raw_fd() 60 } 61 } 62 63 impl IntoRawDescriptor for $timer { 64 fn into_raw_descriptor(self) -> RawDescriptor { 65 self.0.into_raw_fd() 66 } 67 } 68 }; 69 } 70 71 build_timer!(Timer, TimerFd); 72 build_timer!(FakeTimer, FakeTimerFd); 73 74 impl FromRawDescriptor for Timer { from_raw_descriptor(descriptor: RawDescriptor) -> Self75 unsafe fn from_raw_descriptor(descriptor: RawDescriptor) -> Self { 76 Timer(TimerFd::from_raw_fd(descriptor)) 77 } 78 } 79