1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
//! Module for teeing handoffs, not currently used much.
#![allow(missing_docs)]

use std::any::Any;
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;

use super::{CanReceive, Handoff, HandoffMeta};

struct ReaderHandoff<T> {
    contents: VecDeque<Vec<T>>,
}

impl<T> Default for ReaderHandoff<T> {
    fn default() -> Self {
        Self {
            contents: Default::default(),
        }
    }
}

struct TeeingHandoffInternal<T> {
    readers: Vec<ReaderHandoff<T>>,
}

// A [Handoff] which is part of a "family" of handoffs. Writing to this handoff
// will write to every reader. New readers can be created by calling `tee`.
#[derive(Clone)]
pub struct TeeingHandoff<T>
where
    T: 'static,
{
    read_from: usize,
    internal: Rc<RefCell<TeeingHandoffInternal<T>>>,
}

impl<T> Default for TeeingHandoff<T> {
    fn default() -> Self {
        TeeingHandoff {
            read_from: 0,
            internal: Rc::new(RefCell::new(TeeingHandoffInternal {
                readers: vec![Default::default()],
            })),
        }
    }
}

impl<T> TeeingHandoff<T>
where
    T: Clone,
{
    #[must_use]
    pub fn tee(&self) -> Self {
        let id = (*self.internal).borrow().readers.len();
        (*self.internal)
            .borrow_mut()
            .readers
            .push(ReaderHandoff::default());
        Self {
            read_from: id,
            internal: self.internal.clone(),
        }
    }
}

impl<T> HandoffMeta for TeeingHandoff<T> {
    fn any_ref(&self) -> &dyn Any {
        self
    }

    fn is_bottom(&self) -> bool {
        true
    }
}

impl<T> Handoff for TeeingHandoff<T> {
    type Inner = VecDeque<Vec<T>>;

    fn take_inner(&self) -> Self::Inner {
        std::mem::take(&mut (*self.internal).borrow_mut().readers[self.read_from].contents)
    }

    fn borrow_mut_swap(&self) -> std::cell::RefMut<Self::Inner> {
        todo!()
    }
}

impl<T> CanReceive<Vec<T>> for TeeingHandoff<T>
where
    T: Clone,
{
    fn give(&self, vec: Vec<T>) -> Vec<T> {
        let readers = &mut (*self.internal).borrow_mut().readers;
        for i in 0..(readers.len() - 1) {
            readers[i].contents.push_back(vec.clone());
        }
        let last = readers.len() - 1;
        readers[last].contents.push_back(vec);
        Vec::new()
    }
}