audio_core/resizable_buf.rs
1/// Trait implemented for buffers that can be resized.
2pub trait ResizableBuf {
3 /// Ensure that the audio buffer has space for at least the given `capacity`
4 /// of contiguous memory. The `capacity` is specified in number of
5 /// [Samples][crate::Buf::Sample].
6 ///
7 /// This is a no-op unless the underlying buffer is contiguous in memory
8 /// which can be ensured by requiring traits such as
9 /// [InterleavedBufMut][crate::InterleavedBufMut].
10 ///
11 /// This returns a boolean indicating if we could successfully reserve the
12 /// given amount of memory. The caller can only assume that a buffer is
13 /// present up to the given number of samples if it returns `true`. This is
14 /// important to observe if the code you're working on has safety
15 /// implications.
16 ///
17 /// A typical approach in case a reservation fails is to either panic or
18 /// return an error indicating that the provided buffer is not supported.
19 fn try_reserve(&mut self, capacity: usize) -> bool;
20
21 /// Resize the number of per-channel frames in the buffer.
22 ///
23 /// # Examples
24 ///
25 /// ```
26 /// use audio::{Buf, ExactSizeBuf, ResizableBuf};
27 ///
28 /// fn test(mut buffer: impl ResizableBuf) {
29 /// buffer.resize_frames(4);
30 /// }
31 ///
32 /// let mut buf = audio::interleaved![[0; 0]; 2];
33 ///
34 /// assert_eq!(buf.channels(), 2);
35 /// assert_eq!(buf.frames(), 0);
36 ///
37 /// test(&mut buf);
38 ///
39 /// assert_eq!(buf.channels(), 2);
40 /// assert_eq!(buf.frames(), 4);
41 /// ```
42 fn resize_frames(&mut self, frames: usize);
43
44 /// Resize the buffer to match the given topology.
45 ///
46 /// # Examples
47 ///
48 /// ```
49 /// use audio::ResizableBuf;
50 ///
51 /// fn test(mut buf: impl ResizableBuf) {
52 /// buf.resize_topology(2, 4);
53 /// }
54 ///
55 /// let mut buf = audio::interleaved![[0; 0]; 4];
56 ///
57 /// test(&mut buf);
58 ///
59 /// assert_eq!(buf.channels(), 2);
60 /// assert_eq!(buf.frames(), 4);
61 /// ```
62 fn resize_topology(&mut self, channels: usize, frames: usize);
63}
64
65impl<B> ResizableBuf for &mut B
66where
67 B: ?Sized + ResizableBuf,
68{
69 fn try_reserve(&mut self, capacity: usize) -> bool {
70 (**self).try_reserve(capacity)
71 }
72
73 fn resize_frames(&mut self, frames: usize) {
74 (**self).resize_frames(frames);
75 }
76
77 fn resize_topology(&mut self, channels: usize, frames: usize) {
78 (**self).resize_topology(channels, frames);
79 }
80}