rocketmq_runtime/common/system_clock.rs
1// Copyright 2023 The RocketMQ Rust Authors
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.
14
15use std::time::SystemTime;
16use std::time::UNIX_EPOCH;
17
18/// Represents system clock.
19pub struct SystemClock;
20
21impl SystemClock {
22 /// Executes now.
23 pub fn now() -> u128 {
24 millis_since_epoch(SystemTime::now())
25 }
26}
27
28fn millis_since_epoch(now: SystemTime) -> u128 {
29 now.duration_since(UNIX_EPOCH)
30 .map(|duration| duration.as_millis())
31 .unwrap_or_default()
32}
33
34#[cfg(test)]
35mod tests {
36 use std::time::Duration;
37
38 use super::*;
39
40 #[test]
41 fn millis_since_epoch_saturates_when_clock_is_before_epoch() {
42 assert_eq!(millis_since_epoch(UNIX_EPOCH - Duration::from_millis(1)), 0);
43 }
44}