use prelude::*;
use math::min;
#[derive(Copy, Clone)]
#[cfg_attr(feature = "serialize-serde", derive(Deserialize, Serialize))]
pub struct Periodic<S = f32, T = S> {
interval: T,
next: S,
}
impl<S, T> Periodic<S, T>
where
S: Copy + PartialOrd + Add<T> + Sub<T> + Sub<S> +
From<<S as Add<T>>::Output> +
From<<S as Sub<T>>::Output>,
T: Copy + PartialOrd + Add<T> +
From<<S as Sub<S>>::Output>
{
pub fn new(current: S, interval: T) -> Periodic<S, T> {
Periodic {
interval: interval,
next: S::from(current + interval),
}
}
pub fn elapsed(self: &mut Self, current: S) -> bool {
if self.next <= current {
self.next = S::from(S::from(current + self.interval) - min(T::from(current - self.next), self.interval));
true
} else {
false
}
}
pub fn accumulated(self: &mut Self, current: S) -> bool {
if self.next <= current {
self.next = S::from(self.next + self.interval);
true
} else {
false
}
}
pub fn peek(self: &mut Self, current: S) -> bool {
self.next <= current
}
}
impl<S, T> Debug for Periodic<S, T> where S: Debug, T: Debug {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Periodic(interval: {:?}, next: {:?})", self.interval, self.next)
}
}