Skip to main content

lib_jsl_dsp/discrete/digital_communications/
ping_pong_buffer.rs

1//! Ping-pong (double) buffer: one buffer fills with incoming samples while the other, already
2//! full, is processed, so a producer and a consumer never touch the same memory.
3//!
4//! The producer pushes samples; when the active buffer holds `block_len` samples the roles swap and
5//! that block becomes available to the consumer. If the producer fills a second block before the
6//! consumer has released the first, the new block cannot be stored: the push reports an overrun and
7//! the samples are dropped (and counted) rather than corrupting the block being read.
8//!
9//! See the book entry [DSP: synchronisation, communications, radar and controls](https://jwkunz.github.io/lib_jsl/book/comms/index.html#ping-pong-buffer).
10
11use crate::discrete::stream_operator::{StreamOperator, StreamOperatorManagement};
12use lib_jsl_core::ErrorsJSL;
13
14/// The outcome of pushing samples.
15#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
16pub struct PushOutcome {
17    /// Number of blocks completed (and made ready) by this push.
18    pub blocks_completed: usize,
19    /// Number of samples dropped because the consumer had not released the ready block.
20    pub dropped: usize,
21}
22
23/// A double buffer of two `block_len`-sample blocks.
24#[derive(Clone, Debug)]
25pub struct PingPongBuffer<T: Clone> {
26    block_len: usize,
27    /// The block being filled by the producer.
28    filling: Vec<T>,
29    /// The completed block waiting for the consumer, if any.
30    ready: Option<Vec<T>>,
31    overruns: usize,
32}
33
34impl<T: Clone> PingPongBuffer<T> {
35    /// A buffer with blocks of `block_len` samples (at least 1).
36    pub fn new(block_len: usize) -> Result<Self, ErrorsJSL> {
37        if block_len == 0 {
38            return Err(ErrorsJSL::InvalidInputRange("Block length must be at least 1"));
39        }
40        Ok(PingPongBuffer { block_len, filling: Vec::with_capacity(block_len), ready: None, overruns: 0 })
41    }
42
43    pub fn block_len(&self) -> usize {
44        self.block_len
45    }
46
47    /// Pushes samples; completed blocks swap into the ready slot. While a block is waiting, the
48    /// filling buffer can complete one more block but then further samples are dropped.
49    pub fn push(&mut self, samples: &[T]) -> PushOutcome {
50        let mut outcome = PushOutcome::default();
51        for s in samples {
52            if self.filling.len() == self.block_len {
53                // A full block is parked in the filling slot because the ready slot was occupied.
54                if self.ready.is_none() {
55                    self.ready = Some(std::mem::replace(&mut self.filling, Vec::with_capacity(self.block_len)));
56                } else {
57                    outcome.dropped += 1;
58                    continue;
59                }
60            }
61            self.filling.push(s.clone());
62            if self.filling.len() == self.block_len && self.ready.is_none() {
63                self.ready = Some(std::mem::replace(&mut self.filling, Vec::with_capacity(self.block_len)));
64                outcome.blocks_completed += 1;
65            } else if self.filling.len() == self.block_len {
66                outcome.blocks_completed += 1; // parked until the consumer frees the ready slot
67            }
68        }
69        self.overruns += outcome.dropped;
70        outcome
71    }
72
73    /// True if a completed block is waiting for the consumer.
74    pub fn is_ready(&self) -> bool {
75        self.ready.is_some()
76    }
77
78    /// The completed block, if any, without releasing it.
79    pub fn peek(&self) -> Option<&[T]> {
80        self.ready.as_deref()
81    }
82
83    /// Takes the completed block, freeing the slot (a parked full block, if any, becomes ready).
84    pub fn take(&mut self) -> Option<Vec<T>> {
85        let block = self.ready.take()?;
86        if self.filling.len() == self.block_len {
87            self.ready = Some(std::mem::replace(&mut self.filling, Vec::with_capacity(self.block_len)));
88        }
89        Some(block)
90    }
91
92    /// Number of samples currently in the filling buffer.
93    pub fn filled(&self) -> usize {
94        self.filling.len()
95    }
96
97    /// Total samples dropped over the buffer's lifetime.
98    pub fn overruns(&self) -> usize {
99        self.overruns
100    }
101
102    /// Discards all data and the overrun count.
103    pub fn clear(&mut self) {
104        self.filling.clear();
105        self.ready = None;
106        self.overruns = 0;
107    }
108}
109
110impl<T: Clone> StreamOperatorManagement for PingPongBuffer<T> {
111    fn reset(&mut self) -> Result<(), ErrorsJSL> {
112        self.clear();
113        Ok(())
114    }
115
116    fn finalize(&mut self) -> Result<(), ErrorsJSL> {
117        Ok(())
118    }
119}
120
121/// As a stream operator the buffer re-blocks a stream: it emits whole blocks as they complete (so
122/// the output is the input delayed by up to one block) and never overruns because it drains
123/// immediately. `flush` emits the final partial block as-is.
124impl<T: Clone> StreamOperator<T, T> for PingPongBuffer<T> {
125    fn process(&mut self, data_in: &[T]) -> Result<Option<Vec<T>>, ErrorsJSL> {
126        if data_in.is_empty() {
127            return Ok(None);
128        }
129        let mut out = Vec::new();
130        for chunk in data_in.chunks(self.block_len) {
131            self.push(chunk);
132            while let Some(b) = self.take() {
133                out.extend(b);
134            }
135        }
136        Ok(if out.is_empty() { None } else { Some(out) })
137    }
138
139    fn flush(&mut self) -> Result<Option<Vec<T>>, ErrorsJSL> {
140        let mut out = Vec::new();
141        while let Some(b) = self.take() {
142            out.extend(b);
143        }
144        out.append(&mut self.filling);
145        Ok(if out.is_empty() { None } else { Some(out) })
146    }
147}
148
149#[cfg(test)]
150mod tests {
151    use super::*;
152
153    #[test]
154    fn blocks_become_ready_when_full() {
155        let mut p = PingPongBuffer::new(4).unwrap();
156        assert_eq!(p.push(&[1, 2, 3]), PushOutcome { blocks_completed: 0, dropped: 0 });
157        assert!(!p.is_ready() && p.filled() == 3);
158        assert_eq!(p.push(&[4, 5]).blocks_completed, 1);
159        assert_eq!(p.peek(), Some(&[1, 2, 3, 4][..]));
160        assert_eq!(p.filled(), 1, "the overflow went into the other buffer");
161        assert_eq!(p.take(), Some(vec![1, 2, 3, 4]));
162        assert!(!p.is_ready() && p.take().is_none());
163    }
164
165    #[test]
166    fn producer_and_consumer_alternate_without_loss() {
167        let mut p = PingPongBuffer::new(3).unwrap();
168        let mut received = Vec::new();
169        for chunk in (1..=30).collect::<Vec<i32>>().chunks(2) {
170            p.push(chunk);
171            while let Some(b) = p.take() {
172                received.extend(b);
173            }
174        }
175        assert_eq!(received, (1..=30).collect::<Vec<_>>());
176        assert_eq!(p.overruns(), 0);
177    }
178
179    #[test]
180    fn overruns_are_counted_and_the_waiting_block_is_untouched() {
181        let mut p = PingPongBuffer::new(2).unwrap();
182        let o = p.push(&[1, 2, 3, 4, 5, 6]); // block A ready, block B parked, [5, 6] dropped
183        assert_eq!(o.dropped, 2);
184        assert_eq!(p.overruns(), 2);
185        assert_eq!(p.peek(), Some(&[1, 2][..]));
186        assert_eq!(p.take(), Some(vec![1, 2]));
187        assert_eq!(p.take(), Some(vec![3, 4]), "the parked block becomes ready once the slot frees");
188        assert!(p.take().is_none());
189        p.push(&[7, 8]);
190        assert_eq!(p.take(), Some(vec![7, 8]));
191    }
192
193    #[test]
194    fn stream_operator_reblocks_and_flush_emits_the_partial_block() {
195        let mut p = PingPongBuffer::new(4).unwrap();
196        assert!(p.process(&[1, 2, 3]).unwrap().is_none(), "no output until a block completes");
197        assert_eq!(p.process(&[4, 5, 6, 7, 8, 9]).unwrap().unwrap(), vec![1, 2, 3, 4, 5, 6, 7, 8]);
198        assert_eq!(p.flush().unwrap().unwrap(), vec![9]);
199        assert!(p.flush().unwrap().is_none());
200        StreamOperatorManagement::reset(&mut p).unwrap();
201        assert_eq!(p.filled(), 0);
202    }
203
204    #[test]
205    fn invalid_block_length() {
206        assert!(PingPongBuffer::<u8>::new(0).is_err());
207    }
208}