m5stack_core/io/
console_tap.rs1use core::cell::Cell;
5
6use embassy_sync::blocking_mutex::{Mutex, raw::RawMutex};
7
8pub trait Tap: Sync {
14 fn bytes(&self, data: &[u8]);
15}
16
17pub(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 pub(crate) fn set(&self, tap: &'static dyn Tap) {
27 self.0.lock(|slot| slot.set(Some(tap)));
28 }
29
30 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}