add AsyncReaderStream
and replace AsyncIndexReader's stream implementation with that Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
This commit is contained in:
committed by
Dietmar Maurer
parent
3ddb14889a
commit
f386f512d0
@ -3,7 +3,8 @@ use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
use std::sync::mpsc::Receiver;
|
||||
|
||||
|
||||
use tokio::io::AsyncRead;
|
||||
use futures::ready;
|
||||
use futures::stream::Stream;
|
||||
|
||||
use crate::tools::runtime::block_in_place;
|
||||
@ -42,6 +43,45 @@ impl<R: Read + Unpin> Stream for WrappedReaderStream<R> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Wrapper struct to convert an AsyncReader into a Stream
|
||||
pub struct AsyncReaderStream<R: AsyncRead + Unpin> {
|
||||
reader: R,
|
||||
buffer: Vec<u8>,
|
||||
}
|
||||
|
||||
impl <R: AsyncRead + Unpin> AsyncReaderStream<R> {
|
||||
|
||||
pub fn new(reader: R) -> Self {
|
||||
let mut buffer = Vec::with_capacity(64*1024);
|
||||
unsafe { buffer.set_len(buffer.capacity()); }
|
||||
Self { reader, buffer }
|
||||
}
|
||||
|
||||
pub fn with_buffer_size(reader: R, buffer_size: usize) -> Self {
|
||||
let mut buffer = Vec::with_capacity(buffer_size);
|
||||
unsafe { buffer.set_len(buffer.capacity()); }
|
||||
Self { reader, buffer }
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: AsyncRead + Unpin> Stream for AsyncReaderStream<R> {
|
||||
type Item = Result<Vec<u8>, io::Error>;
|
||||
|
||||
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
|
||||
let this = self.get_mut();
|
||||
match ready!(Pin::new(&mut this.reader).poll_read(cx, &mut this.buffer)) {
|
||||
Ok(n) => {
|
||||
if n == 0 {
|
||||
// EOF
|
||||
Poll::Ready(None)
|
||||
} else {
|
||||
Poll::Ready(Some(Ok(this.buffer[..n].to_vec())))
|
||||
}
|
||||
}
|
||||
Err(err) => Poll::Ready(Some(Err(err))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Wrapper struct to convert a channel Receiver into a Stream
|
||||
pub struct StdChannelStream<T>(pub Receiver<T>);
|
||||
|
Reference in New Issue
Block a user