sl4f_lib/time/
facade.rs

1// Copyright 2020 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
5use anyhow::Error;
6use std::time::SystemTime;
7
8const NANOS_IN_MILLIS: u64 = 1000000;
9
10/// Facade providing access to system time.
11#[derive(Debug)]
12pub struct TimeFacade {}
13
14impl TimeFacade {
15    pub fn new() -> Self {
16        TimeFacade {}
17    }
18
19    /// Returns the system's reported UTC time in millis since the Unix epoch retrieved
20    /// through standard language libraries.
21    pub fn system_time_millis() -> Result<u64, Error> {
22        let time_millis = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis();
23        // Zircon stores time as 64 bits so truncating from u128 should not fail.
24        Ok(time_millis.try_into()?)
25    }
26
27    /// Returns the system's reported UTC time in millis since the Unix epoch, retrieved by
28    /// explicitly using the clock handle provided to the runtime.
29    pub fn userspace_time_millis() -> Result<u64, Error> {
30        let clock = fuchsia_runtime::duplicate_utc_clock_handle(zx::Rights::READ)?;
31        Ok(clock.read()?.into_nanos() as u64 / NANOS_IN_MILLIS)
32    }
33
34    /// Returns true iff system time has been synchronized with some source.
35    pub async fn is_synchronized() -> Result<bool, Error> {
36        let clock = fuchsia_runtime::duplicate_utc_clock_handle(zx::Rights::WAIT)?;
37        match clock.wait_one(zx::Signals::CLOCK_STARTED, zx::MonotonicInstant::ZERO).to_result() {
38            Ok(_) => Ok(true),
39            Err(zx::Status::TIMED_OUT) => Ok(false),
40            Err(e) => Err(e.into()),
41        }
42    }
43}