tokio_util/io/read_buf.rs
1use bytes::BufMut;
2use std::future::poll_fn;
3use std::io;
4use std::pin::Pin;
5use tokio::io::AsyncRead;
6
7/// Read data from an `AsyncRead` into an implementer of the [`BufMut`] trait.
8///
9/// [`BufMut`]: bytes::BufMut
10///
11/// # Example
12///
13/// ```
14/// use bytes::{Bytes, BytesMut};
15/// use tokio_stream as stream;
16/// use tokio::io::Result;
17/// use tokio_util::io::{StreamReader, read_buf};
18/// # #[tokio::main(flavor = "current_thread")]
19/// # async fn main() -> std::io::Result<()> {
20///
21/// // Create a reader from an iterator. This particular reader will always be
22/// // ready.
23/// let mut read = StreamReader::new(stream::iter(vec![Result::Ok(Bytes::from_static(&[0, 1, 2, 3]))]));
24///
25/// let mut buf = BytesMut::new();
26/// let mut reads = 0;
27///
28/// loop {
29/// reads += 1;
30/// let n = read_buf(&mut read, &mut buf).await?;
31///
32/// if n == 0 {
33/// break;
34/// }
35/// }
36///
37/// // one or more reads might be necessary.
38/// assert!(reads >= 1);
39/// assert_eq!(&buf[..], &[0, 1, 2, 3]);
40/// # Ok(())
41/// # }
42/// ```
43pub async fn read_buf<R, B>(read: &mut R, buf: &mut B) -> io::Result<usize>
44where
45 R: AsyncRead + Unpin,
46 B: BufMut,
47{
48 poll_fn(|cx| crate::util::poll_read_buf(Pin::new(read), cx, buf)).await
49}