nrpc/
stream_utils.rs

1use futures::Stream;
2
3use core::{pin::Pin, task::{Context, Poll}};
4use core::marker::{PhantomData, Unpin};
5
6#[derive(Default, Clone, Copy)]
7pub struct EmptyStream<T> {
8    _idc: PhantomData<T>,
9}
10
11impl <T> Stream for EmptyStream<T> {
12    type Item = T;
13
14    fn poll_next(
15        self: Pin<&mut Self>,
16        _cx: &mut Context<'_>
17    ) -> Poll<Option<Self::Item>> {
18        Poll::Ready(None)
19    }
20
21    fn size_hint(&self) -> (usize, Option<usize>) {
22        (0, Some(0))
23    }
24}
25
26#[derive(Clone)]
27pub struct OnceStream<T: Unpin> {
28    item: Option<T>,
29}
30
31impl <T: Unpin> OnceStream<T> {
32    pub fn once(item: T) -> Self {
33        Self { item: Some(item) }
34    }
35}
36
37impl <T: Unpin> Stream for OnceStream<T> {
38    type Item = T;
39
40    fn poll_next(
41        mut self: Pin<&mut Self>,
42        _cx: &mut Context<'_>
43    ) -> Poll<Option<Self::Item>> {
44        Poll::Ready(self.item.take())
45    }
46
47    fn size_hint(&self) -> (usize, Option<usize>) {
48        if self.item.is_some() {
49            (1, Some(1))
50        } else {
51            (0, Some(0))
52        }
53    }
54}
55
56#[derive(Clone)]
57pub struct VecStream<T: Unpin> {
58    items: std::collections::VecDeque<T>,
59}
60
61impl <T: Unpin> VecStream<T> {
62    pub fn from_iter(iter: impl Iterator<Item=T>) -> Self {
63        Self { items: iter.collect() }
64    }
65}
66
67impl <T: Unpin> Stream for VecStream<T> {
68    type Item = T;
69
70    fn poll_next(
71        mut self: Pin<&mut Self>,
72        _cx: &mut Context<'_>
73    ) -> Poll<Option<Self::Item>> {
74        Poll::Ready(self.items.pop_front())
75    }
76
77    fn size_hint(&self) -> (usize, Option<usize>) {
78        (self.items.len(), Some(self.items.len()))
79    }
80}