diff --git a/tokio-util/CHANGELOG.md b/tokio-util/CHANGELOG.md index 64228895200..48dfe778e26 100644 --- a/tokio-util/CHANGELOG.md +++ b/tokio-util/CHANGELOG.md @@ -1,11 +1,11 @@ +### Added +- io: `poll_read_buf` util fn (#2972). + # 0.5.0 (October 30, 2020) ### Changed - io: update `bytes` to 0.6 (#3071). -### Added -- io: `poll_read_buf` util fn (#2972). - # 0.4.0 (October 15, 2020) ### Added diff --git a/tokio-util/src/io/mod.rs b/tokio-util/src/io/mod.rs index 6f181ab1703..ceb3ac27185 100644 --- a/tokio-util/src/io/mod.rs +++ b/tokio-util/src/io/mod.rs @@ -10,6 +10,7 @@ mod read_buf; mod reader_stream; mod stream_reader; +pub use crate::util::poll_read_buf; pub use self::read_buf::read_buf; pub use self::reader_stream::ReaderStream; pub use self::stream_reader::StreamReader; diff --git a/tokio-util/src/lib.rs b/tokio-util/src/lib.rs index 253f4437aac..7c0b0aad092 100644 --- a/tokio-util/src/lib.rs +++ b/tokio-util/src/lib.rs @@ -69,7 +69,45 @@ mod util { use std::pin::Pin; use std::task::{Context, Poll}; - pub(crate) fn poll_read_buf( + /// Try to read data from an `AsyncRead` into an implementer of the [`Buf`] trait. + /// + /// [`Buf`]: bytes::Buf + /// + /// # Example + /// + /// ``` + /// use bytes::{Bytes, BytesMut}; + /// use tokio::stream; + /// use tokio::io::Result; + /// use tokio_util::io::{StreamReader, poll_read_buf}; + /// use futures::future::poll_fn; + /// use std::pin::Pin; + /// # #[tokio::main] + /// # async fn main() -> std::io::Result<()> { + /// + /// // 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(cx, Pin::new(&mut read), &mut buf)).await?; + /// + /// if n == 0 { + /// break; + /// } + /// } + /// + /// // one or more reads might be necessary. + /// assert!(reads >= 1); + /// assert_eq!(&buf[..], &[0, 1, 2, 3]); + /// # Ok(()) + /// # } + /// ``` + pub fn poll_read_buf( cx: &mut Context<'_>, io: Pin<&mut T>, buf: &mut impl BufMut,