Skip to content

Commit

Permalink
BufferView::samples iterator
Browse files Browse the repository at this point in the history
  • Loading branch information
micahrj committed Feb 17, 2024
1 parent 3679088 commit f0768f5
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 6 deletions.
8 changes: 4 additions & 4 deletions examples/gain/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ impl Processor for GainProcessor {

fn process(&mut self, buffers: Buffers, events: Events) {
let buffer: BufferMut = buffers.try_into().unwrap();
for (mut buffer, events) in buffer.split_at_events(events) {
for (buffer, events) in buffer.split_at_events(events) {
for event in events {
match event.data {
Data::ParamChange { id, value } => {
Expand All @@ -131,10 +131,10 @@ impl Processor for GainProcessor {
}
}

for i in 0..buffer.sample_count() {
for sample in buffer.samples() {
let gain = self.params.gain.next();
for channel in 0..buffer.channel_count() {
buffer[channel][i] *= gain;
for channel in sample {
*channel *= gain;
}
}
}
Expand Down
7 changes: 6 additions & 1 deletion src/buffers/buffer_view.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::marker::PhantomData;

use super::iter::SplitAtEvents;
use super::iter::{Samples, SplitAtEvents};
use super::{Buffer, BufferMut, BufferSamples, Buffers, RawBuffer, RawBuffers, Sample, SampleMut};
use crate::events::Events;

Expand Down Expand Up @@ -33,6 +33,11 @@ pub trait BufferView: Sized {
}
}

#[inline]
fn samples(self) -> Samples<Self> {
Samples::new(self)
}

#[inline]
fn split_at_events<'e>(self, events: Events<'e>) -> SplitAtEvents<'e, Self> {
SplitAtEvents::new(self, events)
Expand Down
38 changes: 37 additions & 1 deletion src/buffers/iter.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::marker::PhantomData;

use super::{BufferView, Offset};
use super::{BufferView, Offset, SampleView};
use crate::events::Events;

pub struct SplitAtEvents<'e, B: BufferView> {
Expand Down Expand Up @@ -73,3 +73,39 @@ impl<'e, B: BufferView> Iterator for SplitAtEvents<'e, B> {
Some((buffer, events))
}
}

pub struct Samples<B: BufferView> {
raw: B::Raw,
len: usize,
_marker: PhantomData<B>,
}

impl<B: BufferView> Samples<B> {
#[inline]
pub(crate) fn new(buffer: B) -> Samples<B> {
let (raw, len) = buffer.into_raw_parts();

Samples {
raw,
len,
_marker: PhantomData,
}
}
}

impl<B: BufferView> Iterator for Samples<B> {
type Item = B::Sample;

#[inline]
fn next(&mut self) -> Option<B::Sample> {
if self.len == 0 {
return None;
}

let sample = unsafe { B::Sample::from_raw(self.raw) };
self.raw = unsafe { self.raw.offset(1) };
self.len -= 1;

Some(sample)
}
}

0 comments on commit f0768f5

Please sign in to comment.