Skip to main content

tilo_render_protocol/patch/
local.rs

1//! A transport within one process: an app's instance and its window side by side, as in a
2//! capture, a test, or a browser page that runs both. The batches are the bytes any transport
3//! carries, so what is validated and applied is exactly what a socket would deliver.
4
5use std::cell::RefCell;
6use std::collections::VecDeque;
7use std::rc::Rc;
8
9use super::Transport;
10use crate::WireError;
11
12type Queue = Rc<RefCell<VecDeque<Vec<u8>>>>;
13
14/// One end of a pair: it sends to the other end and receives what the other end sent.
15pub struct End {
16    outgoing: Queue,
17    incoming: Queue,
18}
19
20/// Two ends joined to each other.
21#[must_use]
22pub fn pair() -> (End, End) {
23    let a: Queue = Rc::default();
24    let b: Queue = Rc::default();
25    (
26        End {
27            outgoing: Rc::clone(&a),
28            incoming: Rc::clone(&b),
29        },
30        End {
31            outgoing: b,
32            incoming: a,
33        },
34    )
35}
36
37impl End {
38    /// Whether the other end sent something this end has not received.
39    #[must_use]
40    pub fn has_incoming(&self) -> bool {
41        !self.incoming.borrow().is_empty()
42    }
43}
44
45impl Transport for End {
46    fn send(&mut self, batch: Vec<u8>) -> Result<(), WireError> {
47        self.outgoing.borrow_mut().push_back(batch);
48        Ok(())
49    }
50
51    fn recv(&mut self) -> Result<Option<Vec<u8>>, WireError> {
52        Ok(self.incoming.borrow_mut().pop_front())
53    }
54}
55
56#[cfg(test)]
57mod tests {
58    use super::*;
59
60    #[test]
61    fn each_end_receives_what_the_other_sent_in_order() {
62        let (mut app, mut window) = pair();
63        app.send(vec![1]).expect("sends");
64        app.send(vec![2]).expect("sends");
65        assert!(window.has_incoming());
66        assert_eq!(window.recv(), Ok(Some(vec![1])));
67        assert_eq!(window.recv(), Ok(Some(vec![2])));
68        assert_eq!(window.recv(), Ok(None));
69        window.send(vec![3]).expect("sends");
70        assert_eq!(app.recv(), Ok(Some(vec![3])));
71    }
72}