From 200e3568f5b7b5aab5388512ddefceb813168f90 Mon Sep 17 00:00:00 2001 From: Grant Shangreaux Date: Fri, 12 Nov 2021 20:20:25 -0600 Subject: Add: phasor iterator implementation --- klangfarbrs/src/phasor.rs | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 klangfarbrs/src/phasor.rs (limited to 'klangfarbrs/src/phasor.rs') diff --git a/klangfarbrs/src/phasor.rs b/klangfarbrs/src/phasor.rs new file mode 100644 index 0000000..00372c0 --- /dev/null +++ b/klangfarbrs/src/phasor.rs @@ -0,0 +1,46 @@ +use super::{SamplesPerSecond, Hz}; + +type Phase = f32; // Phase will always be between 0.0 and 1.0. + +pub struct PhasorIter { + pub phase: Phase, + pub frequency: Hz, + sample_rate: SamplesPerSecond, +} + +impl PhasorIter { + fn new(frequency: Hz, sample_rate: SamplesPerSecond) -> Self { + Self { phase: 0.0, frequency, sample_rate } + } +} + +impl Iterator for PhasorIter { + type Item = Phase; + + fn next(&mut self) -> Option { + self.phase += (self.frequency / self.sample_rate); + + if self.phase > 1.0 { self.phase -= 1.0; } + + Some(self.phase) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn it_produces_expected_next_value() { + let mut phasor = PhasorIter::new(10.0, 100.0); + assert_eq!(phasor.next(), Some(0.1)) + } + + #[test] + fn it_produces_expected_next_values() { + let phasor = PhasorIter::new(10.0, 100.0); + let next = phasor.take(11); + assert_eq!(0.1, next.last().unwrap()) + // assert_eq!([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 0.1], next) + } +} -- cgit v1.2.3