Skip to main content

dfir_rs/scheduled/handoff/
vector.rs

1use std::cell::{RefCell, RefMut};
2use std::rc::Rc;
3
4use super::{CanReceive, Handoff, HandoffMeta, Iter};
5
6/// A [Vec]-based FIFO handoff.
7pub struct VecHandoff<T>
8where
9    T: 'static,
10{
11    pub(crate) input: Rc<RefCell<Vec<T>>>,
12    pub(crate) output: Rc<RefCell<Vec<T>>>,
13}
14
15impl<T> Default for VecHandoff<T>
16where
17    T: 'static,
18{
19    fn default() -> Self {
20        Self {
21            input: Default::default(),
22            output: Default::default(),
23        }
24    }
25}
26
27impl<T> Handoff for VecHandoff<T> {
28    type Inner = Vec<T>;
29
30    fn take_inner(&self) -> Self::Inner {
31        self.input.take()
32    }
33
34    fn borrow_mut_swap(&self) -> RefMut<'_, Self::Inner> {
35        let mut input = self.input.borrow_mut();
36        let mut output = self.output.borrow_mut();
37
38        std::mem::swap(&mut *input, &mut *output);
39
40        output
41    }
42
43    fn borrow_mut_give(&self) -> RefMut<'_, Self::Inner> {
44        self.input.borrow_mut()
45    }
46}
47
48impl<T> CanReceive<Option<T>> for VecHandoff<T> {
49    fn give(&self, mut item: Option<T>) -> Option<T> {
50        if let Some(item) = item.take() {
51            (*self.input).borrow_mut().push(item)
52        }
53        None
54    }
55}
56impl<T, I> CanReceive<Iter<I>> for VecHandoff<T>
57where
58    I: Iterator<Item = T>,
59{
60    fn give(&self, mut iter: Iter<I>) -> Iter<I> {
61        (*self.input).borrow_mut().extend(&mut iter.0);
62        iter
63    }
64}
65impl<T> CanReceive<Vec<T>> for VecHandoff<T> {
66    fn give(&self, mut vec: Vec<T>) -> Vec<T> {
67        (*self.input).borrow_mut().extend(vec.drain(..));
68        vec
69    }
70}
71
72impl<T> HandoffMeta for VecHandoff<T> {
73    fn len(&self) -> usize {
74        (*self.input).borrow().len()
75    }
76}