noosphere_into/transform/
stream.rs

1use async_stream::stream;
2use bytes::Bytes;
3use futures::Stream;
4use std::io::Error as IoError;
5use tokio_util::io::StreamReader;
6
7#[cfg(doc)]
8use tokio::io::AsyncRead;
9
10/// This is a helper for taking a [Stream] of strings and converting it
11/// to an [AsyncRead] suitable for writing to a file.
12pub struct TransformStream<S>(pub S)
13where
14    S: Stream<Item = String>;
15
16impl<S> TransformStream<S>
17where
18    S: Stream<Item = String>,
19{
20    /// Consume the [TransformStream] and return a [StreamReader] that yields
21    /// the stream as bytes.
22    pub fn into_reader(self) -> StreamReader<impl Stream<Item = Result<Bytes, IoError>>, Bytes> {
23        StreamReader::new(Box::pin(stream! {
24            for await part in self.0 {
25              yield Ok(Bytes::from(part));
26            }
27        }))
28    }
29}