mirror of
https://git.proxmox.com/git/proxmox
synced 2025-05-01 03:17:54 +00:00
49 lines
1.4 KiB
Rust
49 lines
1.4 KiB
Rust
//! Wrappers between async readers and streams.
|
|
|
|
use std::io;
|
|
use std::pin::Pin;
|
|
use std::task::{Context, Poll};
|
|
|
|
use futures::ready;
|
|
use futures::stream::Stream;
|
|
use tokio::io::{AsyncRead, ReadBuf};
|
|
|
|
use proxmox_io::vec;
|
|
|
|
/// Wrapper struct to convert an [AsyncRead] 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 {
|
|
Self::with_buffer_size(reader, 64 * 1024)
|
|
}
|
|
|
|
pub fn with_buffer_size(reader: R, buffer_size: usize) -> Self {
|
|
Self { reader, buffer: vec::undefined(buffer_size) }
|
|
}
|
|
}
|
|
|
|
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();
|
|
let mut read_buf = ReadBuf::new(&mut this.buffer);
|
|
match ready!(Pin::new(&mut this.reader).poll_read(cx, &mut read_buf)) {
|
|
Ok(()) => {
|
|
let n = read_buf.filled().len();
|
|
if n == 0 {
|
|
// EOF
|
|
Poll::Ready(None)
|
|
} else {
|
|
Poll::Ready(Some(Ok(this.buffer[..n].to_vec())))
|
|
}
|
|
}
|
|
Err(err) => Poll::Ready(Some(Err(err))),
|
|
}
|
|
}
|
|
}
|