• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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::descriptor::{AsRawDescriptor, FromRawDescriptor, IntoRawDescriptor};
6 use crate::{FakeClock, RawDescriptor, Result};
7 
8 use crate::platform::{FakeTimerFd, TimerFd};
9 use std::{
10     os::unix::io::{AsRawFd, FromRawFd, IntoRawFd},
11     sync::Arc,
12     time::Duration,
13 };
14 use sync::Mutex;
15 
16 /// See [TimerFd](crate::platform::TimerFd) for struct- and method-level
17 /// documentation.
18 pub struct Timer(pub TimerFd);
19 impl Timer {
new() -> Result<Timer>20     pub fn new() -> Result<Timer> {
21         TimerFd::new().map(Timer)
22     }
23 }
24 
25 /// See [FakeTimerFd](crate::platform::FakeTimerFd) for struct- and method-level
26 /// documentation.
27 pub struct FakeTimer(FakeTimerFd);
28 impl FakeTimer {
new(clock: Arc<Mutex<FakeClock>>) -> Self29     pub fn new(clock: Arc<Mutex<FakeClock>>) -> Self {
30         FakeTimer(FakeTimerFd::new(clock))
31     }
32 }
33 
34 macro_rules! build_timer {
35     ($timer:ident, $inner:ident) => {
36         impl $timer {
37             pub fn reset(&mut self, dur: Duration, interval: Option<Duration>) -> Result<()> {
38                 self.0.reset(dur, interval)
39             }
40 
41             pub fn wait(&mut self) -> Result<()> {
42                 self.0.wait().map(|_| ())
43             }
44 
45             pub fn clear(&mut self) -> Result<()> {
46                 self.0.clear()
47             }
48 
49             pub fn resolution() -> Result<Duration> {
50                 $inner::resolution()
51             }
52         }
53 
54         impl AsRawDescriptor for $timer {
55             fn as_raw_descriptor(&self) -> RawDescriptor {
56                 self.0.as_raw_fd()
57             }
58         }
59 
60         impl IntoRawDescriptor for $timer {
61             fn into_raw_descriptor(self) -> RawDescriptor {
62                 self.0.into_raw_fd()
63             }
64         }
65     };
66 }
67 
68 build_timer!(Timer, TimerFd);
69 build_timer!(FakeTimer, FakeTimerFd);
70 
71 impl FromRawDescriptor for Timer {
from_raw_descriptor(descriptor: RawDescriptor) -> Self72     unsafe fn from_raw_descriptor(descriptor: RawDescriptor) -> Self {
73         Timer(TimerFd::from_raw_fd(descriptor))
74     }
75 }
76