audio_core/buf/
tail.rs

1use crate::{Buf, BufMut, Channel, ChannelMut, ExactSizeBuf, ReadBuf};
2
3/// The tail of a buffer.
4///
5/// See [Buf::tail].
6pub struct Tail<B> {
7    buf: B,
8    n: usize,
9}
10
11impl<B> Tail<B> {
12    /// Construct a new buffer tail.
13    pub(crate) fn new(buf: B, n: usize) -> Self {
14        Self { buf, n }
15    }
16}
17
18impl<B> Buf for Tail<B>
19where
20    B: Buf,
21{
22    type Sample = B::Sample;
23
24    type Channel<'this>
25        = B::Channel<'this>
26    where
27        Self: 'this;
28
29    type IterChannels<'this>
30        = IterChannels<B::IterChannels<'this>>
31    where
32        Self: 'this;
33
34    fn frames_hint(&self) -> Option<usize> {
35        let frames = self.buf.frames_hint()?;
36        Some(usize::min(frames, self.n))
37    }
38
39    fn channels(&self) -> usize {
40        self.buf.channels()
41    }
42
43    fn get_channel(&self, channel: usize) -> Option<Self::Channel<'_>> {
44        Some(self.buf.get_channel(channel)?.tail(self.n))
45    }
46
47    fn iter_channels(&self) -> Self::IterChannels<'_> {
48        IterChannels {
49            iter: self.buf.iter_channels(),
50            n: self.n,
51        }
52    }
53}
54
55impl<B> BufMut for Tail<B>
56where
57    B: BufMut,
58{
59    type ChannelMut<'a>
60        = B::ChannelMut<'a>
61    where
62        Self: 'a;
63
64    type IterChannelsMut<'a>
65        = IterChannelsMut<B::IterChannelsMut<'a>>
66    where
67        Self: 'a;
68
69    fn get_channel_mut(&mut self, channel: usize) -> Option<Self::ChannelMut<'_>> {
70        Some(self.buf.get_channel_mut(channel)?.tail(self.n))
71    }
72
73    fn copy_channel(&mut self, from: usize, to: usize)
74    where
75        Self::Sample: Copy,
76    {
77        self.buf.copy_channel(from, to);
78    }
79
80    fn iter_channels_mut(&mut self) -> Self::IterChannelsMut<'_> {
81        IterChannelsMut {
82            iter: self.buf.iter_channels_mut(),
83            n: self.n,
84        }
85    }
86}
87
88/// [Tail] adjusts the implementation of [ExactSizeBuf].
89///
90/// ```
91/// use audio::{Buf, ExactSizeBuf};
92///
93/// let buf = audio::interleaved![[0; 4]; 2];
94///
95/// assert_eq!((&buf).tail(0).frames(), 0);
96/// assert_eq!((&buf).tail(1).frames(), 1);
97/// assert_eq!((&buf).tail(5).frames(), 4);
98/// ```
99impl<B> ExactSizeBuf for Tail<B>
100where
101    B: ExactSizeBuf,
102{
103    fn frames(&self) -> usize {
104        usize::min(self.buf.frames(), self.n)
105    }
106}
107
108impl<B> ReadBuf for Tail<B>
109where
110    B: ReadBuf,
111{
112    fn remaining(&self) -> usize {
113        usize::min(self.buf.remaining(), self.n)
114    }
115
116    fn advance(&mut self, n: usize) {
117        let n = self
118            .buf
119            .remaining()
120            .saturating_sub(self.n)
121            .saturating_add(n);
122
123        self.buf.advance(n);
124    }
125}
126
127iterators!(n: usize => self.tail(n));