rocketmq_common/utils/
time_utils.rs

1/*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements.  See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18#[inline]
19pub fn get_current_millis() -> u64 {
20    std::time::SystemTime::now()
21        .duration_since(std::time::UNIX_EPOCH)
22        .unwrap()
23        .as_millis() as u64
24}
25
26#[inline]
27pub fn get_current_nano() -> u64 {
28    std::time::SystemTime::now()
29        .duration_since(std::time::UNIX_EPOCH)
30        .unwrap()
31        .as_nanos() as u64
32}
33
34#[cfg(test)]
35mod tests {
36    use std::time::Duration;
37    use std::time::SystemTime;
38    use std::time::UNIX_EPOCH;
39
40    use super::*;
41
42    #[test]
43    fn get_current_millis_returns_correct_value() {
44        let before = SystemTime::now()
45            .duration_since(UNIX_EPOCH)
46            .unwrap()
47            .as_millis() as u64;
48        let current = get_current_millis();
49        let after = SystemTime::now()
50            .duration_since(UNIX_EPOCH)
51            .unwrap()
52            .as_millis() as u64;
53        assert!(current >= before && current <= after);
54    }
55
56    #[test]
57    fn get_current_nano_returns_correct_value() {
58        let before = SystemTime::now()
59            .duration_since(UNIX_EPOCH)
60            .unwrap()
61            .as_nanos() as u64;
62        let current = get_current_nano();
63        let after = SystemTime::now()
64            .duration_since(UNIX_EPOCH)
65            .unwrap()
66            .as_nanos() as u64;
67        assert!(current >= before && current <= after);
68    }
69}