use num_traits::Float;
use crate::Errors;
#[derive(PartialOrd, PartialEq, Debug, Copy, Clone)]
pub struct Hertz<T: Float>(T);
pub trait ToHertz<T: Float> {
fn hz(self) -> Hertz<T>;
fn khz(self) -> Hertz<T>;
fn mhz(self) -> Hertz<T>;
fn dt(self) -> Hertz<T>;
}
use num_traits::NumCast;
impl<T: Float, X: NumCast> ToHertz<T> for X {
fn hz(self) -> Hertz<T> {
Hertz::<T>::from_hz(T::from(self).unwrap()).unwrap()
}
fn khz(self) -> Hertz<T> {
Hertz::<T>::from_hz(T::from(self).unwrap() * T::from(1_000).unwrap()).unwrap()
}
fn mhz(self) -> Hertz<T> {
Hertz::<T>::from_hz(T::from(self).unwrap() * T::from(1_000_000).unwrap()).unwrap()
}
fn dt(self) -> Hertz<T> {
Hertz::<T>::from_hz(T::one() / T::from(self).unwrap()).unwrap()
}
}
impl<T: Float> Hertz<T> {
pub fn from_hz(hz: impl Into<T>) -> Result<Self, Errors> {
let hz = hz.into();
if hz > T::zero() {
Ok(Hertz(hz))
} else {
Err(Errors::NegativeFrequency)
}
}
pub fn from_dt(dt: impl Into<T>) -> Result<Self, Errors> {
let dt = dt.into();
if dt > T::zero() {
Ok(Hertz(T::one() / dt))
} else {
Err(Errors::NegativeFrequency)
}
}
pub fn hz(self) -> T {
self.0
}
}