Function tokio_util::io::poll_read_buf

source ·
pub fn poll_read_buf<T: AsyncRead, B: BufMut>(
    io: Pin<&mut T>,
    cx: &mut Context<'_>,
    buf: &mut B
) -> Poll<Result<usize>>
Expand description

Try to read data from an AsyncRead into an implementer of the BufMut trait.

Example

use bytes::{Bytes, BytesMut};
use tokio_stream as stream;
use tokio::io::Result;
use tokio_util::io::{StreamReader, poll_read_buf};
use futures::future::poll_fn;
use std::pin::Pin;

// Create a reader from an iterator. This particular reader will always be
// ready.
let mut read = StreamReader::new(stream::iter(vec![Result::Ok(Bytes::from_static(&[0, 1, 2, 3]))]));

let mut buf = BytesMut::new();
let mut reads = 0;

loop {
    reads += 1;
    let n = poll_fn(|cx| poll_read_buf(Pin::new(&mut read), cx, &mut buf)).await?;

    if n == 0 {
        break;
    }
}

// one or more reads might be necessary.
assert!(reads >= 1);
assert_eq!(&buf[..], &[0, 1, 2, 3]);