witchcraft_metrics/clock.rs
1// Copyright 2020 Palantir Technologies, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14use once_cell::sync::Lazy;
15use std::sync::Arc;
16use std::time::Instant;
17
18pub(crate) static SYSTEM_CLOCK: Lazy<Arc<SystemClock>> = Lazy::new(|| Arc::new(SystemClock));
19
20/// A source of monotonic time.
21pub trait Clock: 'static + Sync + Send {
22 /// Returns the current time.
23 fn now(&self) -> Instant;
24}
25
26/// A `Clock` implementation which uses the system clock.
27pub struct SystemClock;
28
29impl Clock for SystemClock {
30 #[inline]
31 fn now(&self) -> Instant {
32 Instant::now()
33 }
34}
35
36#[cfg(test)]
37pub mod test {
38 use super::*;
39 use parking_lot::Mutex;
40 use std::time::Duration;
41
42 pub struct TestClock {
43 now: Mutex<Instant>,
44 }
45
46 impl TestClock {
47 #[allow(clippy::new_without_default)]
48 pub fn new() -> TestClock {
49 TestClock {
50 now: Mutex::new(Instant::now()),
51 }
52 }
53
54 pub fn advance(&self, dur: Duration) {
55 *self.now.lock() += dur;
56 }
57 }
58
59 impl Clock for TestClock {
60 fn now(&self) -> Instant {
61 *self.now.lock()
62 }
63 }
64}