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
use std::any::Any;
use std::cell::{RefCell, RefMut};
use std::rc::Rc;

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

/// A [Vec]-based FIFO handoff.
pub struct VecHandoff<T>
where
    T: 'static,
{
    pub(crate) input: Rc<RefCell<Vec<T>>>,
    pub(crate) output: Rc<RefCell<Vec<T>>>,
}
impl<T> Default for VecHandoff<T>
where
    T: 'static,
{
    fn default() -> Self {
        Self {
            input: Default::default(),
            output: Default::default(),
        }
    }
}
impl<T> Handoff for VecHandoff<T> {
    type Inner = Vec<T>;

    fn take_inner(&self) -> Self::Inner {
        self.input.take()
    }

    fn borrow_mut_swap(&self) -> RefMut<Self::Inner> {
        let mut input = self.input.borrow_mut();
        let mut output = self.output.borrow_mut();

        std::mem::swap(&mut *input, &mut *output);

        output
    }
}

impl<T> CanReceive<Option<T>> for VecHandoff<T> {
    fn give(&self, mut item: Option<T>) -> Option<T> {
        if let Some(item) = item.take() {
            (*self.input).borrow_mut().push(item)
        }
        None
    }
}
impl<T, I> CanReceive<Iter<I>> for VecHandoff<T>
where
    I: Iterator<Item = T>,
{
    fn give(&self, mut iter: Iter<I>) -> Iter<I> {
        (*self.input).borrow_mut().extend(&mut iter.0);
        iter
    }
}
impl<T> CanReceive<Vec<T>> for VecHandoff<T> {
    fn give(&self, mut vec: Vec<T>) -> Vec<T> {
        (*self.input).borrow_mut().extend(vec.drain(..));
        vec
    }
}

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

    fn is_bottom(&self) -> bool {
        (*self.input).borrow_mut().is_empty()
    }
}

impl<H> HandoffMeta for Rc<RefCell<H>>
where
    H: HandoffMeta,
{
    fn any_ref(&self) -> &dyn Any {
        self
    }

    fn is_bottom(&self) -> bool {
        self.borrow().is_bottom()
    }
}