1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
// Copyright 2016 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

//! Type-safe bindings for Zircon timer objects.

use {AsHandleRef, ClockId, HandleBased, Handle, HandleRef, Status};
use {sys, ok};
use std::ops;

#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Duration(sys::zx_duration_t);

#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Time(sys::zx_time_t);

impl ops::Add<Duration> for Time {
    type Output = Time;
    fn add(self, dur: Duration) -> Time {
        Time::from_nanos(dur.nanos() + self.nanos())
    }
}

impl ops::Add<Time> for Duration {
    type Output = Time;
    fn add(self, time: Time) -> Time {
        Time::from_nanos(self.nanos() + time.nanos())
    }
}

impl ops::Add for Duration {
    type Output = Duration;
    fn add(self, dur: Duration) -> Duration {
        Duration::from_nanos(self.nanos() + dur.nanos())
    }
}

impl ops::Sub for Duration {
    type Output = Duration;
    fn sub(self, dur: Duration) -> Duration {
        Duration::from_nanos(self.nanos() - dur.nanos())
    }
}

impl ops::Sub<Duration> for Time {
    type Output = Time;
    fn sub(self, dur: Duration) -> Time {
        Time::from_nanos(self.nanos() - dur.nanos())
    }
}

impl ops::AddAssign for Duration {
    fn add_assign(&mut self, dur: Duration) {
        self.0 += dur.nanos()
    }
}

impl ops::SubAssign for Duration {
    fn sub_assign(&mut self, dur: Duration) {
        self.0 -= dur.nanos()
    }
}

impl ops::AddAssign<Duration> for Time {
    fn add_assign(&mut self, dur: Duration) {
        self.0 += dur.nanos()
    }
}

impl ops::SubAssign<Duration> for Time {
    fn sub_assign(&mut self, dur: Duration) {
        self.0 -= dur.nanos()
    }
}

impl<T> ops::Mul<T> for Duration
    where T: Into<u64>
{
    type Output = Self;
    fn mul(self, mul: T) -> Self {
        Duration::from_nanos(self.0 * mul.into())
    }
}

impl<T> ops::Div<T> for Duration
    where T: Into<u64>
{
    type Output = Self;
    fn div(self, div: T) -> Self {
        Duration::from_nanos(self.0 / div.into())
    }
}

impl Duration {
    /// Sleep for the given amount of time.
    pub fn sleep(self) {
        Time::after(self).sleep()
    }

    pub fn nanos(self) -> u64 {
        self.0
    }

    pub fn millis(self) -> u64 {
        self.0 / 1_000_000
    }

    pub fn seconds(self) -> u64 {
        self.millis() / 1_000
    }

    pub fn minutes(self) -> u64 {
        self.seconds() / 60
    }

    pub fn hours(self) -> u64 {
        self.minutes() / 60
    }

    pub fn from_nanos(nanos: u64) -> Self {
        Duration(nanos)
    }

    pub fn from_millis(millis: u64) -> Self {
        Duration(millis * 1_000_000)
    }

    pub fn from_seconds(secs: u64) -> Self {
        Duration::from_millis(secs * 1_000)
    }

    pub fn from_minutes(min: u64) -> Self {
        Duration::from_seconds(min * 60)
    }

    pub fn from_hours(hours: u64) -> Self {
        Duration::from_minutes(hours * 60)
    }

    /// Returns a `Time` which is a `Duration` after the current time.
    /// `duration.after_now()` is equivalent to `Time::after(duration)`.
    pub fn after_now(self) -> Time {
        Time::after(self)
    }
}

pub trait DurationNum: Sized {
    fn nanos(self) -> Duration;
    fn millis(self) -> Duration;
    fn seconds(self) -> Duration;
    fn minutes(self) -> Duration;
    fn hours(self) -> Duration;

    // Singular versions to allow for `1.milli()` and `1.second()`, etc.
    fn milli(self) -> Duration { self.millis() }
    fn second(self) -> Duration { self.seconds() }
    fn minute(self) -> Duration { self.minutes() }
    fn hour(self) -> Duration { self.hours() }
}

// Note: this could be implemented for other unsized integer types, but it doesn't seem
// necessary to support the usual case.
impl DurationNum for u64 {
    fn nanos(self) -> Duration {
        Duration::from_nanos(self)
    }

    fn millis(self) -> Duration {
        Duration::from_millis(self)
    }

    fn seconds(self) -> Duration {
        Duration::from_seconds(self)
    }

    fn minutes(self) -> Duration {
        Duration::from_minutes(self)
    }

    fn hours(self) -> Duration {
        Duration::from_hours(self)
    }
}

impl Time {
    pub const INFINITE: Time = Time(sys::ZX_TIME_INFINITE);

    /// Get the current time, from the specific clock id.
    ///
    /// Wraps the
    /// [zx_time_get](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/time_get.md)
    /// syscall.
    pub fn get(clock_id: ClockId) -> Time {
        unsafe { Time(sys::zx_time_get(clock_id as u32)) }
    }

    /// Compute a deadline for the time in the future that is the given `Duration` away.
    ///
    /// Wraps the
    /// [zx_deadline_after](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/deadline_after.md)
    /// syscall.
    pub fn after(duration: Duration) -> Time {
        unsafe { Time(sys::zx_deadline_after(duration.0)) }
    }

    /// Sleep until the given time.
    ///
    /// Wraps the
    /// [zx_nanosleep](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/nanosleep.md)
    /// syscall.
    pub fn sleep(self) {
        unsafe { sys::zx_nanosleep(self.0); }
    }

    pub fn nanos(self) -> u64 {
        self.0
    }

    pub fn from_nanos(nanos: u64) -> Self {
        Time(nanos)
    }
}

/// Read the number of high-precision timer ticks since boot. These ticks may be processor cycles,
/// high speed timer, profiling timer, etc. They are not guaranteed to continue advancing when the
/// system is asleep.
///
/// Wraps the
/// [zx_ticks_get](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/ticks_get.md)
/// syscall.
pub fn ticks_get() -> u64 {
    unsafe { sys::zx_ticks_get() }
}

/// Return the number of high-precision timer ticks in a second.
///
/// Wraps the
/// [zx_ticks_per_second](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/ticks_per_second.md)
/// syscall.
pub fn ticks_per_second() -> u64 {
    unsafe { sys::zx_ticks_per_second() }
}

/// An object representing a Zircon timer, such as the one returned by
/// [zx_timer_create](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/timer_create.md).
///
/// As essentially a subtype of `Handle`, it can be freely interconverted.
#[derive(Debug, Eq, PartialEq)]
pub struct Timer(Handle);
impl_handle_based!(Timer);

impl Timer {
    /// Create a timer, an object that can signal when a specified point in time has been reached.
    /// Wraps the
    /// [zx_timer_create](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/timer_create.md)
    /// syscall.
    pub fn create(clock_id: ClockId) -> Result<Timer, Status> {
        let mut out = 0;
        let opts = 0;
        let status = unsafe { sys::zx_timer_create(opts, clock_id as u32, &mut out) };
        ok(status)?;
        unsafe {
            Ok(Self::from(Handle::from_raw(out)))
        }
    }

    /// Start a one-shot timer that will fire when `deadline` passes. Wraps the
    /// [zx_timer_set](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/timer_set.md)
    /// syscall.
    pub fn set(&self, deadline: Duration, slack: Duration) -> Result<(), Status> {
        let status = unsafe {
            sys::zx_timer_set(self.raw_handle(), deadline.nanos(), slack.nanos())
        };
        ok(status)
    }

    /// Cancels a pending timer that was started with start(). Wraps the
    /// [zx_timer_cancel](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/timer_cancel.md)
    /// syscall.
    pub fn cancel(&self) -> Result<(), Status> {
        let status = unsafe { sys::zx_timer_cancel(self.raw_handle()) };
        ok(status)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use Signals;

    #[test]
    fn create_timer_invalid_clock() {
        assert_eq!(Timer::create(ClockId::UTC).unwrap_err(), Status::INVALID_ARGS);
        assert_eq!(Timer::create(ClockId::Thread), Err(Status::INVALID_ARGS));
    }

    #[test]
    fn timer_basic() {
        let ten_ms = 10.millis();
        let twenty_ms = 20.millis();

        // Create a timer
        let timer = Timer::create(ClockId::Monotonic).unwrap();

        // Should not signal yet.
        assert_eq!(timer.wait_handle(Signals::TIMER_SIGNALED, ten_ms.after_now()), Err(Status::TIMED_OUT));

        // Set it, and soon it should signal.
        assert_eq!(timer.set(ten_ms, Duration::from_nanos(0)), Ok(()));
        assert_eq!(timer.wait_handle(Signals::TIMER_SIGNALED, twenty_ms.after_now()).unwrap(),
            Signals::TIMER_SIGNALED);

        // Cancel it, and it should stop signalling.
        assert_eq!(timer.cancel(), Ok(()));
        assert_eq!(timer.wait_handle(Signals::TIMER_SIGNALED, ten_ms.after_now()), Err(Status::TIMED_OUT));
    }
}