1const TIMESTAMP_DIVIDEND: i64 = 1_000_000_000;
6
7#[cfg(not(test))]
8pub fn now() -> zx::MonotonicInstant {
9 zx::MonotonicInstant::get()
10}
11
12#[cfg(not(test))]
13pub fn inspect_format_now() -> String {
14 let timestamp = now().into_nanos();
16 let seconds = timestamp / TIMESTAMP_DIVIDEND;
17 let nanos = timestamp % TIMESTAMP_DIVIDEND;
18 format!("{seconds}.{nanos:09}")
19}
20
21#[cfg(test)]
22pub(crate) use mock::inspect_format_now;
23
24pub mod mock {
26 use super::*;
27 use std::cell::RefCell;
28
29 thread_local!(static MOCK_TIME: RefCell<zx::MonotonicInstant> = RefCell::new(zx::MonotonicInstant::get()));
30
31 pub fn now() -> zx::MonotonicInstant {
32 MOCK_TIME.with(|time| *time.borrow())
33 }
34
35 pub fn set(new_time: zx::MonotonicInstant) {
36 MOCK_TIME.with(|time| *time.borrow_mut() = new_time);
37 }
38
39 pub fn inspect_format_now() -> String {
40 let timestamp = now().into_nanos();
41 let seconds = timestamp / TIMESTAMP_DIVIDEND;
42 let nanos = timestamp % TIMESTAMP_DIVIDEND;
43 format!("{seconds}.{nanos:09}")
44 }
45}
46
47#[cfg(test)]
48mod tests {
49 use super::*;
50
51 #[fuchsia::test]
52 fn test_inspect_format() {
53 mock::set(zx::MonotonicInstant::from_nanos(0));
54 assert_eq!(String::from("0.000000000"), inspect_format_now());
55
56 mock::set(zx::MonotonicInstant::from_nanos(123));
57 assert_eq!(String::from("0.000000123"), inspect_format_now());
58
59 mock::set(zx::MonotonicInstant::from_nanos(123_000_000_000));
60 assert_eq!(String::from("123.000000000"), inspect_format_now());
61
62 mock::set(zx::MonotonicInstant::from_nanos(123_000_000_123));
63 assert_eq!(String::from("123.000000123"), inspect_format_now());
64
65 mock::set(zx::MonotonicInstant::from_nanos(123_001_230_000));
66 assert_eq!(String::from("123.001230000"), inspect_format_now());
67 }
68}