Skip to main content

rdf_reader/
stream_iter.rs

1// This is free and unencumbered software released into the public domain.
2
3use alloc::boxed::Box;
4use core::pin::Pin;
5use futures::{Stream, StreamExt};
6use tokio::runtime::Handle;
7
8/// An iterator that blocks on a `Stream` using a Tokio runtime `Handle`.
9///
10/// This stores the stream as a pinned boxed trait object so the underlying
11/// stream implementation doesn't need to implement `Unpin`.
12pub struct StreamIter<I> {
13    stream: Pin<Box<dyn Stream<Item = I> + Send>>,
14    handle: Handle,
15}
16
17impl<I> StreamIter<I> {
18    pub fn new<S>(stream: S, handle: Handle) -> Self
19    where
20        S: Stream<Item = I> + Send + 'static,
21    {
22        Self {
23            stream: Box::pin(stream),
24            handle,
25        }
26    }
27}
28
29impl<I> Iterator for StreamIter<I> {
30    type Item = I;
31
32    fn next(&mut self) -> Option<Self::Item> {
33        self.handle.block_on(self.stream.next())
34    }
35}