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
use std::marker::PhantomData;
use std::mem;

use crate::anyhow::Result;
use crate::runtime::AsyncKernel;
use crate::runtime::Block;
use crate::runtime::BlockMeta;
use crate::runtime::BlockMetaBuilder;
use crate::runtime::MessageIo;
use crate::runtime::MessageIoBuilder;
use crate::runtime::StreamIo;
use crate::runtime::StreamIoBuilder;
use crate::runtime::WorkIo;

pub struct VectorSink<T> {
    items: Vec<T>,
}

impl<T: Clone + std::fmt::Debug + Send + Sync + 'static> VectorSink<T> {
    pub fn new(capacity: usize) -> Block {
        Block::new_async(
            BlockMetaBuilder::new("VectorSink").build(),
            StreamIoBuilder::new()
                .add_input("in", mem::size_of::<T>())
                .build(),
            MessageIoBuilder::<Self>::new().build(),
            VectorSink {
                items: Vec::<T>::with_capacity(capacity),
            },
        )
    }

    pub fn items(&self) -> &Vec<T> {
        &self.items
    }
}

#[async_trait]
impl<T: Clone + std::fmt::Debug + Send + Sync + 'static> AsyncKernel for VectorSink<T> {
    async fn work(
        &mut self,
        io: &mut WorkIo,
        sio: &mut StreamIo,
        _mio: &mut MessageIo<Self>,
        _meta: &mut BlockMeta,
    ) -> Result<()> {
        loop {
            let i = sio.input(0).slice::<T>();
            if i.is_empty() {
                break;
            }

            self.items.extend_from_slice(i);

            sio.input(0).consume(i.len());
        }

        if sio.input(0).finished() {
            io.finished = true;
        }

        Ok(())
    }
}

pub struct VectorSinkBuilder<T> {
    capacity: usize,
    _foo: PhantomData<T>,
}

impl<T: Clone + std::fmt::Debug + Send + Sync + 'static> VectorSinkBuilder<T> {
    pub fn new() -> VectorSinkBuilder<T> {
        VectorSinkBuilder {
            capacity: 8192,
            _foo: PhantomData,
        }
    }

    pub fn init_capacity(mut self, n: usize) -> VectorSinkBuilder<T> {
        self.capacity = n;
        self
    }

    pub fn build(self) -> Block {
        VectorSink::<T>::new(self.capacity)
    }
}

impl<T: Clone + std::fmt::Debug + Send + Sync + 'static> Default for VectorSinkBuilder<T> {
    fn default() -> Self {
        Self::new()
    }
}