Skip to content

Commit

Permalink
clock: new module, system and fixed time options
Browse files Browse the repository at this point in the history
  • Loading branch information
da2ce7 committed Sep 9, 2022
1 parent e622c13 commit 0b96540
Show file tree
Hide file tree
Showing 2 changed files with 102 additions and 0 deletions.
101 changes: 101 additions & 0 deletions src/protocol/clock.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
use std::{
cell::RefCell,
convert::TryInto,
ops::Div,
time::{Duration, SystemTime},
};

pub trait Time: Sized + Div + Into<u64> + TryInto<u32> {
fn now() -> Self;
fn after(period: &Duration) -> Self;

fn after_sec(period: u64) -> Self {
Self::after(&Duration::new(period, 0))
}
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct UnixTime<const T: usize>(pub Duration);

pub enum ClockType {
SystemTime,
FixedTime,
}

#[cfg(not(test))]
pub type DefaultTime = UnixTime<{ ClockType::SystemTime as usize }>;

#[cfg(test)]
pub type DefaultTime = UnixTime<{ ClockType::FixedTime as usize }>;

pub type CurrentTime = UnixTime<{ ClockType::SystemTime as usize }>;

impl Time for UnixTime<{ ClockType::SystemTime as usize }> {
fn now() -> Self {
Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap())
}

fn after(period: &Duration) -> Self {
Self(
SystemTime::now()
.checked_add(*period)
.unwrap()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap(),
)
}
}

thread_local!(static FIXED_TIME: RefCell<Duration> = RefCell::new(Duration::ZERO));

impl Time for UnixTime<{ ClockType::FixedTime as usize }> {
fn now() -> Self {
let mut now: Duration = Duration::default();
FIXED_TIME.with(|time| {
now = *time.borrow();
});

Self(now)
}

fn after(period: &Duration) -> Self {
let mut now: Duration = Duration::default();
FIXED_TIME.with(|time| {
now = *time.borrow();
});

Self(now.checked_add(*period).unwrap())
}
}

impl UnixTime<{ ClockType::FixedTime as usize }> {
pub fn set_time(new_time: &Duration) {
FIXED_TIME.with(|time| {
*time.borrow_mut() = *new_time;
});
}
pub fn reset_time() {
Self::set_time(&Duration::ZERO)
}
}

impl<const T: usize> Div for UnixTime<{ T }> {
type Output = u128;
fn div(self, rhs: Self) -> Self::Output {
self.0.as_nanos() / rhs.0.as_nanos()
}
}

impl<const T: usize> Into<u64> for UnixTime<{ T }> {
fn into(self) -> u64 {
self.0.as_secs()
}
}

impl<const T: usize> TryInto<u32> for UnixTime<{ T }> {
type Error = <u32 as TryFrom<u64>>::Error;

fn try_into(self) -> Result<u32, Self::Error> {
self.0.as_secs().try_into()
}
}
1 change: 1 addition & 0 deletions src/protocol/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
pub mod clock;
pub mod common;
pub mod utils;

0 comments on commit 0b96540

Please sign in to comment.