pingap_core/
util.rs

1// Copyright 2024-2025 Tree xie.
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 once_cell::sync::Lazy;
16use std::time::{Duration, SystemTime, UNIX_EPOCH};
17
18// 2022-05-07: 1651852800
19// const SUPER_TIMESTAMP: u64 = 1651852800;
20static SUPER_TIMESTAMP: Lazy<SystemTime> = Lazy::new(|| {
21    UNIX_EPOCH
22        .checked_add(Duration::from_secs(1651852800))
23        .unwrap_or(SystemTime::now())
24});
25
26/// Returns the number of seconds elapsed since SUPER_TIMESTAMP
27/// Returns 0 if the current time is before SUPER_TIMESTAMP
28#[inline]
29pub fn get_super_ts() -> u32 {
30    match SystemTime::now().duration_since(*SUPER_TIMESTAMP) {
31        Ok(duration) => duration.as_secs() as u32,
32        Err(_) => 0,
33    }
34}
35
36static HOST_NAME: Lazy<String> = Lazy::new(|| {
37    hostname::get()
38        .unwrap_or_default()
39        .to_str()
40        .unwrap_or_default()
41        .to_string()
42});
43
44/// Returns the system hostname.
45///
46/// Returns:
47/// * `&'static str` - The system's hostname as a string slice
48pub fn get_hostname() -> &'static str {
49    HOST_NAME.as_str()
50}
51
52#[inline]
53pub(crate) fn now_ms() -> u64 {
54    SystemTime::now()
55        .duration_since(UNIX_EPOCH)
56        .unwrap_or_default()
57        .as_millis() as u64
58}