peekable 0.6.0

Buffered peek for `Read` and async readers (tokio, futures): inspect incoming bytes without consuming them. Useful for protocol detection, length-prefixed framing, and header inspection.
Documentation
use ::tokio::io::AsyncRead;
use pin_project_lite::pin_project;

use std::{
  future::Future,
  io,
  marker::PhantomPinned,
  pin::Pin,
  task::{Context, Poll},
};

use super::{AsyncPeekable, Buffer, DefaultBuffer};
use crate::StagingBuf;

pin_project! {
  /// Peek to end
  #[derive(Debug)]
  #[must_use = "futures do nothing unless you `.await` or poll them"]
  pub struct PeekToEnd<'a, R, B = DefaultBuffer> {
    peekable: &'a mut AsyncPeekable<R, B>,
    buf: &'a mut Vec<u8>,
    initial_peek_len: usize,
    reader_data_start: Option<usize>,
    staging: StagingBuf,
    #[pin]
    _pin: PhantomPinned,
  }
}

pub(crate) fn peek_to_end<'a, R, B>(
  peekable: &'a mut AsyncPeekable<R, B>,
  buffer: &'a mut Vec<u8>,
) -> PeekToEnd<'a, R, B>
where
  R: AsyncRead + Unpin,
  B: Buffer,
{
  let initial_peek_len = peekable.buffer.len();
  PeekToEnd {
    peekable,
    buf: buffer,
    initial_peek_len,
    reader_data_start: None,
    staging: crate::new_staging_buf(),
    _pin: PhantomPinned,
  }
}

impl<A, B> Future for PeekToEnd<'_, A, B>
where
  A: AsyncRead + Unpin,
  B: Buffer,
{
  type Output = io::Result<usize>;

  fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
    let me = self.project();
    let inbuf = *me.initial_peek_len;

    let reader_start = match *me.reader_data_start {
      Some(pos) => pos,
      None => {
        me.buf.extend_from_slice(me.peekable.buffer.as_slice());
        let pos = me.buf.len();
        *me.reader_data_start = Some(pos);
        pos
      }
    };

    loop {
      let mut read_buf = tokio::io::ReadBuf::new(me.staging);
      match Pin::new(&mut me.peekable.reader).poll_read(cx, &mut read_buf) {
        Poll::Ready(Ok(())) => {
          let filled = read_buf.filled();
          let n = filled.len();
          if n == 0 {
            return Poll::Ready(Ok(inbuf + (me.buf.len() - reader_start)));
          }
          // TODO(al8n): if extend_from_slice fails, the peek buffer
          // won't have these bytes — see future/peek_to_end.rs.
          // At least give the caller the data in buf (matching
          // read_to_end's partial-data-on-error contract).
          if let Err(e) = me.peekable.buffer.extend_from_slice(filled) {
            me.buf.extend_from_slice(filled);
            return Poll::Ready(Err(e));
          }
          me.buf.extend_from_slice(filled);
        }
        Poll::Ready(Err(e)) if e.kind() == io::ErrorKind::Interrupted => continue,
        // Leave partial data in buf — matches std/tokio's
        // read_to_end contract.
        Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
        Poll::Pending => return Poll::Pending,
      }
    }
  }
}