Skip to content

Commit 3e1767f

Browse files
Add a len field to track the size of the window, preventing indefinite item production in the window iterator.
1 parent d089297 commit 3e1767f

2 files changed

Lines changed: 31 additions & 0 deletions

File tree

dasp_signal/src/window/mod.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@ where
3131
{
3232
/// Yields phase stepped at a constant rate to be passed to the window function `W`.
3333
pub phase: Phase<ConstHz>,
34+
/// Size of the window
35+
pub len: usize,
3436
marker: PhantomData<(F, W)>,
3537
}
3638

@@ -87,6 +89,7 @@ where
8789
pub fn new(len: usize) -> Self {
8890
let step = crate::rate(len as f64 - 1.0).const_hz(1.0);
8991
Window {
92+
len,
9093
phase: crate::phase(step),
9194
marker: PhantomData,
9295
}
@@ -122,6 +125,12 @@ where
122125
type Item = F;
123126

124127
fn next(&mut self) -> Option<Self::Item> {
128+
// make sure we didn't produce items indefinitely
129+
if self.len == 0 {
130+
return None;
131+
}
132+
133+
self.len -= 1;
125134
let v = W::window(self.phase.next_phase());
126135
let v_f: <F::Sample as Sample>::Float = v.to_sample();
127136
Some(F::from_fn(|_| v_f.to_sample::<F::Sample>()))

dasp_signal/tests/window.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,3 +49,25 @@ fn test_window_size() {
4949
.collect();
5050
assert_eq!(windows.len(), 3);
5151
}
52+
53+
#[cfg(feature = "window-hann")]
54+
#[test]
55+
fn test_window_iterator() {
56+
let v = [1f32; 16];
57+
let windower = Windower::hann(&v, 8, 4);
58+
59+
let mut window_count = 0;
60+
let mut sample_count = 0;
61+
62+
for window in windower {
63+
window_count += 1;
64+
for sample in window {
65+
sample_count += 1
66+
}
67+
}
68+
69+
// || - first window, {} - second window, [] - third window, s - samples
70+
// | s, s, s, s, { s, s, s, s | [ s, s, s, s, } s, s, s, s, ]
71+
assert_eq!(window_count, 3);
72+
assert_eq!(sample_count, 3 * 8);
73+
}

0 commit comments

Comments
 (0)