use crate::Scalar;
#[derive(Debug, Clone)]
pub struct Chunk<T> {
data: Vec<T>,
stamps: Vec<f64>,
channels: usize,
capacity: usize,
}
impl<T: Scalar> Chunk<T> {
pub fn new(channels: usize, capacity_samples: usize) -> Chunk<T> {
assert!(channels > 0, "a chunk needs at least one channel");
let capacity = capacity_samples.max(1);
Chunk {
data: Vec::with_capacity(channels * capacity),
stamps: Vec::with_capacity(capacity),
channels,
capacity,
}
}
pub fn len(&self) -> usize {
self.stamps.len()
}
pub fn is_empty(&self) -> bool {
self.stamps.is_empty()
}
pub fn channels(&self) -> usize {
self.channels
}
pub fn capacity_samples(&self) -> usize {
self.capacity
}
pub fn sample(&self, i: usize) -> &[T] {
&self.data[i * self.channels..(i + 1) * self.channels]
}
pub fn timestamps(&self) -> &[f64] {
&self.stamps
}
pub fn iter(&self) -> impl Iterator<Item = (f64, &[T])> + '_ {
(0..self.len()).map(move |i| (self.stamps[i], self.sample(i)))
}
pub fn channel(&self, c: usize) -> impl Iterator<Item = T> + '_ {
assert!(
c < self.channels,
"channel {c} of a chunk that has {}",
self.channels
);
self.data.iter().skip(c).step_by(self.channels).copied()
}
pub fn clear(&mut self) {
self.data.clear();
self.stamps.clear();
}
#[allow(dead_code)] pub(crate) fn push(&mut self, timestamp: f64, values: impl Iterator<Item = T>) {
let before = self.data.len();
self.data.extend(values.take(self.channels));
self.data.resize(before + self.channels, T::default());
self.stamps.push(timestamp);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn two_by_three() -> Chunk<f32> {
let mut c = Chunk::<f32>::new(2, 8);
for (i, t) in [1.0, 2.0, 3.0].into_iter().enumerate() {
c.push(t, [i as f32 * 10.0, i as f32 * 10.0 + 1.0].into_iter());
}
c
}
#[test]
fn a_channel_reads_every_value_of_that_channel() {
let c = two_by_three();
assert_eq!(c.len(), 3);
assert_eq!(c.channel(0).collect::<Vec<_>>(), vec![0.0, 10.0, 20.0]);
assert_eq!(c.channel(1).collect::<Vec<_>>(), vec![1.0, 11.0, 21.0]);
assert_eq!(c.timestamps(), &[1.0, 2.0, 3.0]);
}
#[test]
fn a_buffer_that_the_program_keeps_is_cleared_by_the_program() {
let c = two_by_three();
let mut dst = vec![99.0];
dst.extend(c.channel(0));
assert_eq!(dst, vec![99.0, 0.0, 10.0, 20.0], "extend adds");
dst.clear();
dst.extend(c.channel(0));
assert_eq!(dst, vec![0.0, 10.0, 20.0], "clear first replaces");
}
#[test]
#[should_panic(expected = "channel 2 of a chunk that has 2")]
fn a_channel_that_does_not_exist_panics() {
let _ = two_by_three().channel(2).count();
}
#[test]
#[should_panic(expected = "at least one channel")]
fn a_chunk_of_no_channel_panics() {
let _ = Chunk::<f32>::new(0, 8);
}
#[test]
fn clear_keeps_the_allocation_and_drops_the_samples() {
let mut c = two_by_three();
c.clear();
assert!(c.is_empty());
assert_eq!(c.len(), 0);
assert_eq!(c.timestamps(), &[] as &[f64]);
assert_eq!(c.channel(0).count(), 0);
}
}