Skip to main content

rill_core/buffer/
port_buffer.rs

1use core::ops::{Deref, DerefMut};
2
3/// Fixed-size audio buffer owned by a port.
4///
5/// Wraps `[T; SIZE]` with `Deref`/`DerefMut` for zero-cost slice access.
6/// The buffer is the sole owner of its data — no external references.
7#[derive(Debug, Clone)]
8pub struct Buffer<T, const SIZE: usize> {
9    data: [T; SIZE],
10}
11
12impl<T: Copy + Default, const SIZE: usize> Buffer<T, SIZE> {
13    pub fn new() -> Self {
14        Self {
15            data: [T::default(); SIZE],
16        }
17    }
18
19    pub fn from_array(data: [T; SIZE]) -> Self {
20        Self { data }
21    }
22
23    pub fn from_slice(slice: &[T]) -> Self
24    where
25        T: Copy,
26    {
27        let mut data = [T::default(); SIZE];
28        let len = slice.len().min(SIZE);
29        data[..len].copy_from_slice(&slice[..len]);
30        Self { data }
31    }
32
33    pub fn as_array(&self) -> &[T; SIZE] {
34        &self.data
35    }
36
37    pub fn as_mut_array(&mut self) -> &mut [T; SIZE] {
38        &mut self.data
39    }
40
41    pub fn as_slice(&self) -> &[T] {
42        &self.data
43    }
44
45    pub fn as_mut_slice(&mut self) -> &mut [T] {
46        &mut self.data
47    }
48
49    pub fn fill(&mut self, value: T) {
50        self.data.fill(value);
51    }
52
53    pub fn copy_from(&mut self, src: &[T; SIZE])
54    where
55        T: Copy,
56    {
57        self.data.copy_from_slice(src);
58    }
59
60    pub fn copy_from_slice(&mut self, src: &[T])
61    where
62        T: Copy,
63    {
64        let len = src.len().min(SIZE);
65        self.data[..len].copy_from_slice(&src[..len]);
66    }
67}
68
69impl<T: Copy + Default, const SIZE: usize> Default for Buffer<T, SIZE> {
70    fn default() -> Self {
71        Self::new()
72    }
73}
74
75impl<T, const SIZE: usize> Deref for Buffer<T, SIZE> {
76    type Target = [T; SIZE];
77    fn deref(&self) -> &Self::Target {
78        &self.data
79    }
80}
81
82impl<T, const SIZE: usize> DerefMut for Buffer<T, SIZE> {
83    fn deref_mut(&mut self) -> &mut Self::Target {
84        &mut self.data
85    }
86}
87
88impl<T: Copy + Default, const SIZE: usize> From<[T; SIZE]> for Buffer<T, SIZE> {
89    fn from(data: [T; SIZE]) -> Self {
90        Self::from_array(data)
91    }
92}