Skip to main content

m5stack_core/io/
console_ring.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! The console's byte ring, hardware-free so it is tested on the host.
3
4/// Ring capacity. ~50 lines × 80 B = ~4 KB — same memory budget as the prior
5/// `Channel<Line, 12>` (~4.2 KB), and large enough to hold a message-only
6/// panic plus the immediate pre-failure context. Bump if `esp-backtrace` is
7/// ever wired up (a trace would add several KB).
8pub(crate) const RING_SIZE: usize = 4096;
9
10/// Shed gaps the drain has not reached yet. Beyond this a new gap merges into
11/// the last one, so its marker then sits at the earlier position.
12const MAX_GAPS: usize = 4;
13
14/// Bytes shed at one stream position: the reader reports them when it gets
15/// there, not when it happens to read the counter.
16#[derive(Clone, Copy)]
17struct Gap {
18    at: u32,
19    bytes: u32,
20}
21
22/// Byte ring with overwrite-on-full. Single struct held inside the mutex.
23pub(crate) struct Ring {
24    buf: [u8; RING_SIZE],
25    head: usize, // write position (next byte to be written)
26    tail: usize, // read position (next byte to be read)
27    full: bool,  // disambiguates empty vs full when head == tail
28    /// Stream positions: bytes ever written and ever read, wrapping.
29    written: u32,
30    read: u32,
31    /// Whole log lines refused because they did not fit, by where they would
32    /// have gone. Distinct from `dropped`: nothing queued was harmed, the
33    /// console shed load. Kept separate so a gate cannot confuse the two —
34    /// `dropped` outside a panic means a real overrun.
35    gaps: heapless::Deque<Gap, MAX_GAPS>,
36    /// Bytes silently overwritten (oldest discarded) since the last drain read.
37    /// The drain turns this into a VISIBLE `[CONSOLE-DROP …]` marker so a
38    /// ring overrun never looks like a clean gap (which previously made
39    /// `log_interval`'s read-back fail mysteriously). Saturates.
40    dropped: u32,
41}
42
43impl Ring {
44    pub(crate) const fn new() -> Self {
45        Self {
46            buf: [0; RING_SIZE],
47            head: 0,
48            tail: 0,
49            full: false,
50            written: 0,
51            read: 0,
52            gaps: heapless::Deque::new(),
53            dropped: 0,
54        }
55    }
56
57    /// Append `bytes`; on full, the **oldest** bytes are overwritten. Always
58    /// succeeds — no return value, no error path, no waiting. Each overwritten
59    /// byte bumps `dropped` so the drain can flag the loss.
60    ///
61    /// Overwriting cuts whichever line the tail is in half, so this is reserved
62    /// for the panic path, where getting the message out outranks whatever was
63    /// queued. Ordinary logging goes through [`Ring::write_line`].
64    pub(crate) fn write(&mut self, bytes: &[u8]) {
65        if bytes.len() <= self.free() {
66            self.append(bytes);
67            return;
68        }
69        for &b in bytes {
70            self.buf[self.head] = b;
71            self.head = (self.head + 1) % RING_SIZE;
72            self.written = self.written.wrapping_add(1);
73            if self.full {
74                self.read = self.read.wrapping_add(1);
75                // Overwrote the tail byte — advance tail to track it, and
76                // record the drop so it surfaces downstream.
77                self.tail = (self.tail + 1) % RING_SIZE;
78                self.dropped = self.dropped.saturating_add(1);
79            } else if self.head == self.tail {
80                self.full = true;
81            }
82        }
83    }
84
85    /// Copy `bytes`, which fit, in at most two slices: the lock is held for this.
86    fn append(&mut self, bytes: &[u8]) {
87        if bytes.is_empty() {
88            return;
89        }
90        let first = bytes.len().min(RING_SIZE - self.head);
91        self.buf[self.head..self.head + first].copy_from_slice(&bytes[..first]);
92        self.buf[..bytes.len() - first].copy_from_slice(&bytes[first..]);
93        self.head = (self.head + bytes.len()) % RING_SIZE;
94        self.written = self.written.wrapping_add(bytes.len() as u32);
95        self.full = self.head == self.tail;
96    }
97
98    /// Append `bytes` only if the whole slice fits; otherwise drop it and count
99    /// the loss. Never blocks, so the hot log path keeps its guarantee to
100    /// time-critical producers, and never overwrites — which is what makes
101    /// `send_line`'s reservation hold: bytes already queued cannot be cut in
102    /// half by a later log line. Dropping the incoming line rather than the
103    /// oldest also keeps the ring whole-lines-only, so a reader never sees a
104    /// truncated record.
105    ///
106    /// Note what this inverts: under sustained overflow the surviving lines are
107    /// the OLD end, not the recent one, so "read the last lines before it died"
108    /// gets the opposite of what it expects. `[CONSOLE-SHED …]` is what says the
109    /// tail is missing; a panic is unaffected, since it overwrites.
110    pub(crate) fn write_line(&mut self, bytes: &[u8]) -> bool {
111        if self.free() < bytes.len() {
112            self.shed_here(bytes.len() as u32);
113            return false;
114        }
115        self.write(bytes);
116        true
117    }
118
119    /// Read + reset the overwritten-byte counter (drain-side).
120    #[cfg(any(test, feature = "console-serial"))]
121    pub(crate) fn take_dropped(&mut self) -> u32 {
122        core::mem::take(&mut self.dropped)
123    }
124
125    /// Record `bytes` shed at the current write position. Consecutive sheds
126    /// share one gap, so a flood is one marker however many lines it loses.
127    fn shed_here(&mut self, bytes: u32) {
128        let (at, full) = (self.written, self.gaps.is_full());
129        match self.gaps.back_mut() {
130            Some(g) if g.at == at || full => g.bytes = g.bytes.saturating_add(bytes),
131            _ => {
132                let _fits = self.gaps.push_back(Gap { at, bytes });
133            }
134        }
135    }
136
137    /// Bytes until the next gap: 0 once the reader has reached it, or passed it
138    /// because a panic overwrite moved the tail over it.
139    #[cfg(any(test, feature = "console-serial"))]
140    fn to_next_gap(&self) -> Option<usize> {
141        let g = self.gaps.front()?;
142        let d = g.at.wrapping_sub(self.read) as usize;
143        Some(if d > self.used() { 0 } else { d })
144    }
145
146    /// The bytes shed where the reader now stands, once (drain-side). Taken
147    /// before reading on, so the marker goes out exactly at the discontinuity.
148    #[cfg(any(test, feature = "console-serial"))]
149    pub(crate) fn take_shed(&mut self) -> u32 {
150        let mut bytes = 0u32;
151        while self.to_next_gap() == Some(0) {
152            bytes = bytes.saturating_add(self.gaps.pop_front().map_or(0, |g| g.bytes));
153        }
154        bytes
155    }
156
157    #[cfg(any(test, feature = "console-serial"))]
158    pub(crate) fn is_empty(&self) -> bool {
159        !self.full && self.head == self.tail
160    }
161
162    /// Bytes currently queued (unread).
163    pub(crate) fn used(&self) -> usize {
164        if self.full {
165            RING_SIZE
166        } else if self.head >= self.tail {
167            self.head - self.tail
168        } else {
169            RING_SIZE - self.tail + self.head
170        }
171    }
172
173    /// Free bytes available before overwrite-on-full would discard data.
174    pub(crate) fn free(&self) -> usize {
175        RING_SIZE - self.used()
176    }
177
178    /// Copy up to `dst.len()` readable bytes into `dst` and advance `tail`.
179    /// Bytes are taken from a single contiguous slice — if the ring wraps,
180    /// the caller will get the rest on the next call — and never across a
181    /// pending gap, which [`Ring::take_shed`] must report first. Returns bytes
182    /// copied.
183    #[cfg(any(test, feature = "console-serial"))]
184    pub(crate) fn read_and_consume(&mut self, dst: &mut [u8]) -> usize {
185        if self.is_empty() {
186            return 0;
187        }
188        // Length of the next contiguous readable slice.
189        let n_contig = if self.head > self.tail {
190            self.head - self.tail
191        } else {
192            RING_SIZE - self.tail
193        };
194        let n = n_contig
195            .min(dst.len())
196            .min(self.to_next_gap().unwrap_or(usize::MAX));
197        let end = self.tail + n;
198        dst[..n].copy_from_slice(&self.buf[self.tail..end]);
199        self.tail = end % RING_SIZE;
200        self.read = self.read.wrapping_add(n as u32);
201        if n > 0 {
202            self.full = false;
203        }
204        n
205    }
206}
207
208#[cfg(test)]
209mod tests {
210    use super::*;
211
212    fn drain(r: &mut Ring) -> Vec<u8> {
213        let mut out = Vec::new();
214        let mut chunk = [0u8; 64];
215        loop {
216            let n = r.read_and_consume(&mut chunk);
217            if n == 0 {
218                return out;
219            }
220            out.extend_from_slice(&chunk[..n]);
221        }
222    }
223
224    #[test]
225    fn a_write_that_wraps_reads_back_in_order() {
226        let mut r = Ring::new();
227        let pad = vec![b'x'; RING_SIZE - 3];
228        r.write(&pad);
229        assert_eq!(drain(&mut r), pad);
230        r.write(b"abcdef");
231        assert_eq!(r.used(), 6);
232        assert_eq!(drain(&mut r), b"abcdef");
233    }
234
235    #[test]
236    fn an_exact_fill_is_full_not_empty() {
237        let mut r = Ring::new();
238        r.write(&vec![b'y'; RING_SIZE]);
239        assert_eq!(r.free(), 0);
240        assert!(!r.is_empty());
241        assert_eq!(r.take_dropped(), 0);
242    }
243
244    #[test]
245    fn overflow_overwrites_the_oldest_and_counts_it() {
246        let mut r = Ring::new();
247        r.write(&vec![b'a'; RING_SIZE - 2]);
248        r.write(b"bcde");
249        assert_eq!(r.take_dropped(), 2);
250        let out = drain(&mut r);
251        assert_eq!(out.len(), RING_SIZE);
252        assert_eq!(&out[out.len() - 4..], b"bcde");
253    }
254
255    #[test]
256    fn a_shed_is_reported_where_it_happened_not_before() {
257        let mut r = Ring::new();
258        r.write(b"old\n");
259        r.write(&vec![b'f'; RING_SIZE - 8]);
260        assert!(!r.write_line(b"lost line\n"));
261        assert!(!r.write_line(b"lost too\n"));
262        assert_eq!(r.take_shed(), 0, "bytes queued before the loss come first");
263        let before = drain(&mut r);
264        assert_eq!(before.len(), RING_SIZE - 4);
265        assert_eq!(r.take_shed(), 19, "both sheds are one gap, reported at it");
266        assert!(r.write_line(b"after\n"));
267        assert_eq!(drain(&mut r), b"after\n");
268        assert_eq!(r.take_shed(), 0, "reported once");
269    }
270
271    #[test]
272    fn separate_losses_are_separate_gaps_in_order() {
273        let mut r = Ring::new();
274        r.write(&vec![b'a'; RING_SIZE]);
275        assert!(!r.write_line(b"x\n"));
276        let mut chunk = [0u8; 100];
277        assert_eq!(r.read_and_consume(&mut chunk), 100);
278        assert!(r.write_line(b"kept\n"));
279        r.write(&vec![b'b'; r.free()]);
280        assert!(!r.write_line(b"yz\n"));
281        assert_eq!(
282            drain(&mut r).len(),
283            RING_SIZE - 100,
284            "stops at the first gap"
285        );
286        assert_eq!(r.take_shed(), 2);
287        let between = drain(&mut r);
288        assert!(between.starts_with(b"kept\n"));
289        assert_eq!(r.take_shed(), 3);
290    }
291
292    #[test]
293    fn write_line_sheds_what_does_not_fit_whole() {
294        let mut r = Ring::new();
295        r.write(&vec![b'a'; RING_SIZE - 3]);
296        assert!(!r.write_line(b"four"));
297        assert!(r.write_line(b"two"));
298        assert_eq!(r.free(), 0);
299        assert_eq!(drain(&mut r).len(), RING_SIZE - 3);
300        assert_eq!(r.take_shed(), 4);
301        assert_eq!(drain(&mut r), b"two");
302    }
303}