Skip to main content

m5stack_core/io/
console_tap.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! The console's tap, hardware-free so it is tested on the host.
3
4use core::cell::Cell;
5
6use embassy_sync::blocking_mutex::{Mutex, raw::RawMutex};
7
8/// A second reader of the console's output. The drain hands it every slice it
9/// writes to the transmitter, markers included, in order and without gaps.
10///
11/// Called from the drain task before the transmitter write, outside the ring's
12/// lock. It must not block: the drain waits for it.
13pub trait Tap: Sync {
14    fn bytes(&self, data: &[u8]);
15}
16
17/// The one registered tap, if any.
18pub(crate) struct TapSlot<M: RawMutex>(Mutex<M, Cell<Option<&'static dyn Tap>>>);
19
20impl<M: RawMutex> TapSlot<M> {
21    pub(crate) const fn new() -> Self {
22        Self(Mutex::new(Cell::new(None)))
23    }
24
25    /// Replaces the registered tap.
26    pub(crate) fn set(&self, tap: &'static dyn Tap) {
27        self.0.lock(|slot| slot.set(Some(tap)));
28    }
29
30    /// Hands `data` to the registered tap; nothing without one.
31    pub(crate) fn feed(&self, data: &[u8]) {
32        if let Some(tap) = self.0.lock(Cell::get) {
33            tap.bytes(data);
34        }
35    }
36}
37
38#[cfg(test)]
39mod tests {
40    extern crate std;
41
42    use embassy_sync::blocking_mutex::raw::NoopRawMutex;
43    use std::sync::Mutex as StdMutex;
44    use std::vec::Vec;
45
46    use super::*;
47
48    struct Collect(StdMutex<Vec<u8>>);
49
50    impl Tap for Collect {
51        fn bytes(&self, data: &[u8]) {
52            self.0.lock().unwrap().extend_from_slice(data);
53        }
54    }
55
56    #[test]
57    fn feed_without_a_tap_is_a_no_op() {
58        let slot = TapSlot::<NoopRawMutex>::new();
59        slot.feed(b"lost");
60    }
61
62    #[test]
63    fn the_tap_sees_every_slice_in_order() {
64        static SEEN: Collect = Collect(StdMutex::new(Vec::new()));
65        let slot = TapSlot::<NoopRawMutex>::new();
66        slot.set(&SEEN);
67        slot.feed(b"ab");
68        slot.feed(b"cd");
69        assert_eq!(SEEN.0.lock().unwrap().as_slice(), b"abcd");
70    }
71}