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
use anyhow::Result;
use std::cmp;
use std::mem;
use std::ptr;
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 VectorSource<T> {
items: Vec<T>,
n_copied: usize,
}
impl<T: Send + 'static> VectorSource<T> {
pub fn new(items: Vec<T>) -> Block {
Block::new_async(
BlockMetaBuilder::new("VectorSource").build(),
StreamIoBuilder::new()
.add_output("out", mem::size_of::<T>())
.build(),
MessageIoBuilder::new().build(),
VectorSource { items, n_copied: 0 },
)
}
}
#[async_trait]
impl<T: Send + 'static> AsyncKernel for VectorSource<T> {
async fn work(
&mut self,
io: &mut WorkIo,
sio: &mut StreamIo,
_mio: &mut MessageIo<Self>,
_meta: &mut BlockMeta,
) -> Result<()> {
let out = sio.output(0).slice::<T>();
let n = cmp::min(out.len(), self.items.len() - self.n_copied);
if n > 0 {
unsafe {
let src_ptr = self.items.as_ptr().add(self.n_copied);
let dst_ptr = out.as_mut_ptr();
ptr::copy_nonoverlapping(src_ptr, dst_ptr, n)
};
self.n_copied += n;
if self.n_copied == self.items.len() {
io.finished = true;
}
sio.output(0).produce(n);
}
Ok(())
}
}
pub struct VectorSourceBuilder<T: Send> {
items: Vec<T>,
}
impl<T: Send + 'static> VectorSourceBuilder<T> {
pub fn new(items: Vec<T>) -> VectorSourceBuilder<T> {
VectorSourceBuilder { items }
}
pub fn build(self) -> Block {
VectorSource::new(self.items)
}
}