fuchsia_fuzzctl/
duration.rs

1// Copyright 2022 The Fuchsia 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/// This module exists to abstract away the differences between the dev host and target versions
6/// of `fuchsia_async::MonotonicDuration`.
7///
8/// In particular, on development hosts `fuchsia_async::{MonotonicDuration, MonotonicInstant}` are actually
9/// `std::time::{Duration, Instant}`.
10pub use self::platform::{deadline_after, MonotonicDuration};
11
12#[cfg(not(target_os = "fuchsia"))]
13mod platform {
14    use std::time::{Duration as OsDuration, Instant as OsTime};
15
16    #[derive(Debug)]
17    pub struct MonotonicDuration {
18        base: OsDuration,
19    }
20
21    impl MonotonicDuration {
22        pub const fn from_nanos(nanos: i64) -> Self {
23            Self { base: OsDuration::from_nanos(nanos as u64) }
24        }
25
26        pub const fn from_micros(micros: i64) -> Self {
27            Self { base: OsDuration::from_micros(micros as u64) }
28        }
29
30        pub const fn from_millis(millis: i64) -> Self {
31            Self { base: OsDuration::from_millis(millis as u64) }
32        }
33
34        pub const fn from_seconds(seconds: i64) -> Self {
35            Self { base: OsDuration::from_secs(seconds as u64) }
36        }
37
38        pub const fn into_nanos(self) -> i64 {
39            self.base.as_nanos() as i64
40        }
41
42        pub const fn into_seconds(self) -> i64 {
43            self.base.as_secs() as i64
44        }
45    }
46
47    /// Provides a deadline after `timeout` nanoseconds that a `fuchsia_async::Timer` can wait until.
48    pub fn deadline_after(timeout: Option<i64>) -> Option<fuchsia_async::MonotonicInstant> {
49        timeout.and_then(|nanos| OsTime::now().checked_add(OsDuration::from_nanos(nanos as u64)))
50    }
51}
52
53#[cfg(target_os = "fuchsia")]
54mod platform {
55    use fuchsia_async::DurationExt;
56    pub use fuchsia_async::MonotonicDuration;
57
58    /// Provides a deadline after `timeout` nanoseconds that a `fuchsia_async::Timer` can wait until.
59    pub fn deadline_after(timeout: Option<i64>) -> Option<fuchsia_async::MonotonicInstant> {
60        timeout.map(|nanos| MonotonicDuration::from_nanos(nanos).after_now())
61    }
62}