Skip to main content

senax_common/cache/
msec.rs

1use senax_encoder::{Pack, Unpack};
2use serde::{Deserialize, Serialize};
3use std::time::{Duration, SystemTime};
4
5use super::CycleCounter;
6
7pub const MSEC_SHR: u8 = 20;
8
9#[derive(Deserialize, Serialize, Pack, Unpack, Clone, Copy, Debug, Default)]
10pub struct MSec(u64);
11
12impl MSec {
13    pub fn now() -> MSec {
14        MSec::from(
15            SystemTime::now()
16                .duration_since(SystemTime::UNIX_EPOCH)
17                .unwrap(),
18        )
19    }
20    pub fn inner(&self) -> u64 {
21        self.0
22    }
23    #[deprecated]
24    pub fn get(&self) -> u64 {
25        self.0
26    }
27    pub fn less_than_ttl(&self, time: MSec, ttl: u64) -> bool {
28        self.0.less_than(time.0.wrapping_sub(ttl))
29    }
30    pub fn add(&self, v: u64) -> MSec {
31        MSec(self.0.wrapping_add(v))
32    }
33    pub fn add_sec(&self, v: u64) -> MSec {
34        MSec(
35            self.0
36                .wrapping_add(v.saturating_mul(1_000_000_000 / (1 << MSEC_SHR))),
37        )
38    }
39    pub fn sub(&self, v: u64) -> MSec {
40        MSec(self.0.wrapping_sub(v))
41    }
42    pub fn less_than(&self, time: MSec) -> bool {
43        self.0.less_than(time.0)
44    }
45}
46impl From<Duration> for MSec {
47    fn from(time: Duration) -> Self {
48        MSec((time.as_nanos() >> MSEC_SHR) as u64)
49    }
50}
51impl From<u64> for MSec {
52    fn from(time: u64) -> Self {
53        MSec(time)
54    }
55}
56
57pub(crate) fn get_cache_time() -> (u64, MSec) {
58    let duration = SystemTime::now()
59        .duration_since(SystemTime::UNIX_EPOCH)
60        .unwrap();
61    (duration.as_secs(), duration.into())
62}