Skip to content

Commit

Permalink
Generic add/sub
Browse files Browse the repository at this point in the history
  • Loading branch information
korken89 committed May 23, 2021
1 parent f437645 commit 95ff29b
Showing 1 changed file with 67 additions and 2 deletions.
69 changes: 67 additions & 2 deletions src/instant.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
//! An instant of time
use crate::{
duration::{self, Duration},
duration::{self, Duration, Generic},
fixed_point::FixedPoint,
time_int::TimeInt,
};
use core::{
cmp::Ordering,
convert::TryFrom,
convert::{TryFrom, TryInto},
hash::{Hash, Hasher},
ops,
};
Expand Down Expand Up @@ -189,6 +190,23 @@ impl<Clock: crate::Clock> Instant<Clock> {
}
}

/// `Generic` version of `checked_add`.
pub fn checked_add_generic<T: TimeInt>(self, duration: Generic<T>) -> Option<Self>
where
Clock::T: core::ops::Div<Output = Clock::T>,
Generic<Clock::T>: TryFrom<Generic<T>>,
{
let clock_dur: Generic<Clock::T> = duration.try_into().ok()?;
let add_ticks: Clock::T = *clock_dur.integer();
if add_ticks <= (<Clock::T as num::Bounded>::max_value() / 2.into()) {
Some(Self {
ticks: self.ticks.wrapping_add(&add_ticks),
})
} else {
None
}
}

/// This `Instant` - [`Duration`] = earlier `Instant`
///
/// Returns [`None`] if the [`Duration`] is too large
Expand Down Expand Up @@ -226,6 +244,23 @@ impl<Clock: crate::Clock> Instant<Clock> {
None
}
}

/// `Generic` version of `checked_sub`.
pub fn checked_sub_generic<T: TimeInt>(self, duration: Generic<T>) -> Option<Self>
where
Clock::T: core::ops::Div<Output = Clock::T>,
Generic<Clock::T>: TryFrom<Generic<T>>,
{
let clock_dur: Generic<Clock::T> = duration.try_into().ok()?;
let sub_ticks: Clock::T = *clock_dur.integer();
if sub_ticks <= (<Clock::T as num::Bounded>::max_value() / 2.into()) {
Some(Self {
ticks: self.ticks.wrapping_sub(&sub_ticks),
})
} else {
None
}
}
}

impl<Clock: crate::Clock> Copy for Instant<Clock> {}
Expand Down Expand Up @@ -342,6 +377,21 @@ where
}
}

impl<Clock: crate::Clock, T: TimeInt> ops::Add<Generic<T>> for Instant<Clock>
where
Generic<Clock::T>: TryFrom<Generic<T>>,
{
type Output = Self;

fn add(self, rhs: Generic<T>) -> Self::Output {
if let Some(v) = self.checked_add_generic(rhs) {
v
} else {
panic!("Add failed")
}
}
}

impl<Clock: crate::Clock, Dur: Duration> ops::Sub<Dur> for Instant<Clock>
where
Clock::T: TryFrom<Dur::T>,
Expand Down Expand Up @@ -404,6 +454,21 @@ where
}
}

impl<Clock: crate::Clock, T: TimeInt> ops::Sub<Generic<T>> for Instant<Clock>
where
Generic<Clock::T>: TryFrom<Generic<T>>,
{
type Output = Self;

fn sub(self, rhs: Generic<T>) -> Self::Output {
if let Some(v) = self.checked_sub_generic(rhs) {
v
} else {
panic!("Sub failed")
}
}
}

impl<Clock: crate::Clock> ops::Sub<Instant<Clock>> for Instant<Clock> {
type Output = duration::Generic<Clock::T>;

Expand Down

0 comments on commit 95ff29b

Please sign in to comment.