use std::time::Duration;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Rate {
period: Duration,
}
impl Rate {
pub fn hz(hz: f64) -> Self {
assert!(
hz.is_finite() && hz > 0.0,
"Rate::hz requires a positive, finite value"
);
Self {
period: Duration::from_secs_f64(1.0 / hz),
}
}
pub fn every(period: Duration) -> Self {
assert!(!period.is_zero(), "Rate::every requires a non-zero period");
Self { period }
}
pub fn period(&self) -> Duration {
self.period
}
pub fn is_faster_than(&self, other: &Rate) -> bool {
self.period < other.period
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hz_converts_to_period() {
assert_eq!(Rate::hz(2.0).period(), Duration::from_millis(500));
assert_eq!(Rate::hz(10.0).period(), Duration::from_millis(100));
}
#[test]
fn every_wraps_a_duration() {
assert_eq!(
Rate::every(Duration::from_secs(3)).period(),
Duration::from_secs(3)
);
}
#[test]
fn faster_means_smaller_period() {
assert!(Rate::hz(10.0).is_faster_than(&Rate::hz(2.0)));
assert!(!Rate::hz(1.0).is_faster_than(&Rate::hz(1.0)));
}
#[test]
#[should_panic]
fn zero_hz_panics() {
let _ = Rate::hz(0.0);
}
}