use crate::units::{Duration, Frequency, Seconds};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[derive(Copy, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct SampleRate(Frequency);
impl SampleRate {
pub fn as_frequency(&self) -> Frequency {
self.0
}
pub fn as_u32(&self) -> u32 {
self.as_f64() as _
}
pub fn as_usize(&self) -> usize {
self.as_f64() as usize
}
pub fn as_f64(&self) -> f64 {
self.0.as_f64()
}
pub fn as_u64(&self) -> u64 {
self.as_f64() as u64
}
pub fn time_between_samples(&self) -> Duration {
Duration::from_secs_f64(1.0 / self.as_f64())
}
pub fn secs_between_samples(&self) -> Seconds {
Seconds::from(1.0 / self.as_f64())
}
}
macro_rules! impl_from_int_type {
($int_type: ty) => {
impl From<$int_type> for SampleRate {
fn from(value: $int_type) -> Self {
Self(Frequency::from(value))
}
}
};
}
impl_from_int_type!(u64);
impl_from_int_type!(u32);
impl_from_int_type!(u16);
impl_from_int_type!(u8);
impl_from_int_type!(usize);
impl_from_int_type!(i64);
impl_from_int_type!(i32);
impl_from_int_type!(i16);
impl_from_int_type!(i8);
impl_from_int_type!(isize);
macro_rules! impl_float_conversions {
($int_type: ty) => {
impl From<$int_type> for SampleRate {
fn from(value: $int_type) -> Self {
Self(Frequency::from(value))
}
}
impl From<SampleRate> for $int_type {
fn from(value: SampleRate) -> Self {
value.as_f64() as _
}
}
};
}
impl_float_conversions!(f64);
impl_float_conversions!(f32);