use futures_util::AsyncRead;
use super::{AsyncPeekable, Buffer, DefaultBuffer};
use crate::StagingBuf;
use std::{
future::Future,
io,
pin::Pin,
task::{Context, Poll},
};
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct PeekToEnd<'a, P, B = DefaultBuffer> {
peekable: &'a mut AsyncPeekable<P, B>,
buf: &'a mut Vec<u8>,
initial_peek_len: usize,
reader_data_start: Option<usize>,
staging: StagingBuf,
}
impl<P: Unpin, B> Unpin for PeekToEnd<'_, P, B> {}
impl<'a, P: AsyncRead + Unpin, B: Buffer> PeekToEnd<'a, P, B> {
pub(super) fn new(peekable: &'a mut AsyncPeekable<P, B>, buf: &'a mut Vec<u8>) -> Self {
let initial_peek_len = peekable.buffer.len();
Self {
peekable,
buf,
initial_peek_len,
reader_data_start: None,
staging: crate::new_staging_buf(),
}
}
}
impl<A, B> Future for PeekToEnd<'_, A, B>
where
A: AsyncRead + Unpin,
B: Buffer,
{
type Output = io::Result<usize>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = &mut *self;
let inbuf = this.initial_peek_len;
let reader_start = match this.reader_data_start {
Some(pos) => pos,
None => {
this.buf.extend_from_slice(this.peekable.buffer.as_slice());
let pos = this.buf.len();
this.reader_data_start = Some(pos);
pos
}
};
loop {
match Pin::new(&mut this.peekable.reader).poll_read(cx, &mut this.staging) {
Poll::Ready(Ok(0)) => {
return Poll::Ready(Ok(inbuf + (this.buf.len() - reader_start)));
}
Poll::Ready(Ok(n)) => {
let chunk = &this.staging[..n];
if let Err(e) = this.peekable.buffer.extend_from_slice(chunk) {
this.buf.extend_from_slice(chunk);
return Poll::Ready(Err(e));
}
this.buf.extend_from_slice(chunk);
}
Poll::Ready(Err(e)) if e.kind() == io::ErrorKind::Interrupted => continue,
Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
Poll::Pending => return Poll::Pending,
}
}
}
}