From 0bc39e6e6c0143a97a6d340d5d7fd8f0ba0bb406 Mon Sep 17 00:00:00 2001 From: Yoshua Wuyts Date: Mon, 9 Sep 2019 00:23:13 +0200 Subject: [PATCH 1/4] add io::cursor Signed-off-by: Yoshua Wuyts --- src/io/cursor.rs | 261 ++++++++++++++++++++++++++++++++++++++++++++++ src/io/mod.rs | 2 + src/io/prelude.rs | 8 +- 3 files changed, 267 insertions(+), 4 deletions(-) create mode 100644 src/io/cursor.rs diff --git a/src/io/cursor.rs b/src/io/cursor.rs new file mode 100644 index 000000000..c271a83e7 --- /dev/null +++ b/src/io/cursor.rs @@ -0,0 +1,261 @@ +use futures_io::{AsyncRead, AsyncSeek, AsyncWrite}; + +use std::io::{self, IoSlice, IoSliceMut, SeekFrom}; +use std::pin::Pin; +use std::task::{Context, Poll}; + +/// A `Cursor` wraps an in-memory buffer and provides it with a +/// [`Seek`] implementation. +/// +/// `Cursor`s are used with in-memory buffers, anything implementing +/// `AsRef<[u8]>`, to allow them to implement [`Read`] and/or [`Write`], +/// allowing these buffers to be used anywhere you might use a reader or writer +/// that does actual I/O. +/// +/// The standard library implements some I/O traits on various types which +/// are commonly used as a buffer, like `Cursor<`[`Vec`]`>` and +/// `Cursor<`[`&[u8]`][bytes]`>`. +/// +/// [`Seek`]: trait.Seek.html +/// [`Read`]: trait.Read.html +/// [`Write`]: trait.Write.html +/// [`Vec`]: https://doc.rust-lang.org/std/vec/struct.Vec.html +/// [bytes]: https://doc.rust-lang.org/std/primitive.slice.html +/// [`File`]: struct.File.html +#[derive(Clone, Debug, Default)] +pub struct Cursor { + inner: std::io::Cursor, +} + +impl Cursor { + /// Creates a new cursor wrapping the provided underlying in-memory buffer. + /// + /// Cursor initial position is `0` even if underlying buffer (e.g., `Vec`) + /// is not empty. So writing to cursor starts with overwriting `Vec` + /// content, not with appending to it. + /// + /// # Examples + /// + /// ``` + /// use async_std::io::Cursor; + /// + /// let buff = Cursor::new(Vec::new()); + /// # fn force_inference(_: &Cursor>) {} + /// # force_inference(&buff); + /// ``` + pub fn new(inner: T) -> Cursor { + Cursor { + inner: std::io::Cursor::new(inner), + } + } + + /// Consumes this cursor, returning the underlying value. + /// + /// # Examples + /// + /// ``` + /// use async_std::io::Cursor; + /// + /// let buff = Cursor::new(Vec::new()); + /// # fn force_inference(_: &Cursor>) {} + /// # force_inference(&buff); + /// + /// let vec = buff.into_inner(); + /// ``` + pub fn into_inner(self) -> T { + self.inner.into_inner() + } + + /// Gets a reference to the underlying value in this cursor. + /// + /// # Examples + /// + /// ``` + /// use async_std::io::Cursor; + /// + /// let buff = Cursor::new(Vec::new()); + /// # fn force_inference(_: &Cursor>) {} + /// # force_inference(&buff); + /// + /// let reference = buff.get_ref(); + /// ``` + pub fn get_ref(&self) -> &T { + self.inner.get_ref() + } + + /// Gets a mutable reference to the underlying value in this cursor. + /// + /// Care should be taken to avoid modifying the internal I/O state of the + /// underlying value as it may corrupt this cursor's position. + /// + /// # Examples + /// + /// ``` + /// use async_std::io::Cursor; + /// + /// let mut buff = Cursor::new(Vec::new()); + /// # fn force_inference(_: &Cursor>) {} + /// # force_inference(&buff); + /// + /// let reference = buff.get_mut(); + /// ``` + pub fn get_mut(&mut self) -> &mut T { + self.inner.get_mut() + } + + /// Returns the current position of this cursor. + /// + /// # Examples + /// + /// ``` + /// use async_std::io::Cursor; + /// use async_std::io::prelude::*; + /// use async_std::io::SeekFrom; + /// + /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]); + /// + /// assert_eq!(buff.position(), 0); + /// + /// buff.seek(SeekFrom::Current(2)).unwrap(); + /// assert_eq!(buff.position(), 2); + /// + /// buff.seek(SeekFrom::Current(-1)).unwrap(); + /// assert_eq!(buff.position(), 1); + /// ``` + pub fn position(&self) -> u64 { + self.inner.position() + } + + /// Sets the position of this cursor. + /// + /// # Examples + /// + /// ``` + /// use async_std::io::Cursor; + /// + /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]); + /// + /// assert_eq!(buff.position(), 0); + /// + /// buff.set_position(2); + /// assert_eq!(buff.position(), 2); + /// + /// buff.set_position(4); + /// assert_eq!(buff.position(), 4); + /// ``` + pub fn set_position(&mut self, pos: u64) { + self.inner.set_position(pos) + } +} + +impl AsyncSeek for Cursor +where + T: AsRef<[u8]> + Unpin, +{ + fn poll_seek( + mut self: Pin<&mut Self>, + _: &mut Context<'_>, + pos: SeekFrom, + ) -> Poll> { + Poll::Ready(io::Seek::seek(&mut self.inner, pos)) + } +} + +impl AsyncRead for Cursor +where + T: AsRef<[u8]> + Unpin, +{ + fn poll_read( + mut self: Pin<&mut Self>, + _cx: &mut Context<'_>, + buf: &mut [u8], + ) -> Poll> { + Poll::Ready(io::Read::read(&mut self.inner, buf)) + } + + fn poll_read_vectored( + mut self: Pin<&mut Self>, + _: &mut Context<'_>, + bufs: &mut [IoSliceMut<'_>], + ) -> Poll> { + Poll::Ready(io::Read::read_vectored(&mut self.inner, bufs)) + } +} + +// impl AsyncBufRead for Cursor +// where +// T: AsRef<[u8]> + Unpin, +// { +// fn poll_fill_buf(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { +// // let amt = cmp::min(self.position(), self.as_ref().len() as u64); +// // Poll::Ready(Ok(&self.inner.as_ref()[(amt as usize)..])) +// let res = io::BufRead::fill_buf(&mut self.inner); +// Poll::Ready(res) +// } + +// fn consume(mut self: Pin<&mut Self>, amt: usize) { +// io::BufRead::consume(&mut self.inner, amt) +// } +// } + +impl AsyncWrite for Cursor<&mut [u8]> { + fn poll_write( + mut self: Pin<&mut Self>, + _: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { + Poll::Ready(io::Write::write(&mut self.inner, buf)) + } + + fn poll_write_vectored( + mut self: Pin<&mut Self>, + _: &mut Context<'_>, + bufs: &[IoSlice<'_>], + ) -> Poll> { + Poll::Ready(io::Write::write_vectored(&mut self.inner, bufs)) + } + + fn poll_flush(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { + Poll::Ready(io::Write::flush(&mut self.inner)) + } + + fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.poll_flush(cx) + } +} + +impl AsyncWrite for Cursor<&mut Vec> { + fn poll_write( + mut self: Pin<&mut Self>, + _: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { + Poll::Ready(io::Write::write(&mut self.inner, buf)) + } + + fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.poll_flush(cx) + } + + fn poll_flush(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { + Poll::Ready(io::Write::flush(&mut self.inner)) + } +} + +impl AsyncWrite for Cursor> { + fn poll_write( + mut self: Pin<&mut Self>, + _: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { + Poll::Ready(io::Write::write(&mut self.inner, buf)) + } + + fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.poll_flush(cx) + } + + fn poll_flush(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { + Poll::Ready(io::Write::flush(&mut self.inner)) + } +} diff --git a/src/io/mod.rs b/src/io/mod.rs index 5152b0347..e0e97dd60 100644 --- a/src/io/mod.rs +++ b/src/io/mod.rs @@ -28,6 +28,7 @@ pub use std::io::{Error, ErrorKind, Result, SeekFrom}; pub use buf_read::{BufRead, Lines}; pub use buf_reader::BufReader; pub use copy::copy; +pub use cursor::Cursor; pub use empty::{empty, Empty}; pub use read::Read; pub use seek::Seek; @@ -41,6 +42,7 @@ pub use write::Write; mod buf_read; mod buf_reader; mod copy; +mod cursor; mod empty; mod read; mod seek; diff --git a/src/io/prelude.rs b/src/io/prelude.rs index 65438e13d..490be040a 100644 --- a/src/io/prelude.rs +++ b/src/io/prelude.rs @@ -9,10 +9,10 @@ //! ``` #[doc(no_inline)] -pub use super::BufRead as _; +pub use super::BufRead; #[doc(no_inline)] -pub use super::Read as _; +pub use super::Read; #[doc(no_inline)] -pub use super::Seek as _; +pub use super::Seek; #[doc(no_inline)] -pub use super::Write as _; +pub use super::Write; From a5b0acb378c0fb0702766764d02fa1f80970a1e2 Mon Sep 17 00:00:00 2001 From: Yoshua Wuyts Date: Tue, 10 Sep 2019 14:20:12 +0200 Subject: [PATCH 2/4] AsyncBufRead for Cursor Signed-off-by: Yoshua Wuyts --- src/io/cursor.rs | 27 ++++++++++++--------------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/src/io/cursor.rs b/src/io/cursor.rs index c271a83e7..33a643b79 100644 --- a/src/io/cursor.rs +++ b/src/io/cursor.rs @@ -1,4 +1,4 @@ -use futures_io::{AsyncRead, AsyncSeek, AsyncWrite}; +use futures_io::{AsyncBufRead, AsyncRead, AsyncSeek, AsyncWrite}; use std::io::{self, IoSlice, IoSliceMut, SeekFrom}; use std::pin::Pin; @@ -182,21 +182,18 @@ where } } -// impl AsyncBufRead for Cursor -// where -// T: AsRef<[u8]> + Unpin, -// { -// fn poll_fill_buf(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { -// // let amt = cmp::min(self.position(), self.as_ref().len() as u64); -// // Poll::Ready(Ok(&self.inner.as_ref()[(amt as usize)..])) -// let res = io::BufRead::fill_buf(&mut self.inner); -// Poll::Ready(res) -// } +impl AsyncBufRead for Cursor +where + T: AsRef<[u8]> + Unpin, +{ + fn poll_fill_buf(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { + Poll::Ready(io::BufRead::fill_buf(&mut self.get_mut().inner)) + } -// fn consume(mut self: Pin<&mut Self>, amt: usize) { -// io::BufRead::consume(&mut self.inner, amt) -// } -// } + fn consume(mut self: Pin<&mut Self>, amt: usize) { + io::BufRead::consume(&mut self.inner, amt) + } +} impl AsyncWrite for Cursor<&mut [u8]> { fn poll_write( From 69c9162558fed95f8b7f47b5088701f7b1c68145 Mon Sep 17 00:00:00 2001 From: Yoshua Wuyts Date: Tue, 10 Sep 2019 14:23:00 +0200 Subject: [PATCH 3/4] fix tests Signed-off-by: Yoshua Wuyts --- src/io/cursor.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/io/cursor.rs b/src/io/cursor.rs index 33a643b79..95b13ecbf 100644 --- a/src/io/cursor.rs +++ b/src/io/cursor.rs @@ -108,6 +108,8 @@ impl Cursor { /// # Examples /// /// ``` + /// # fn main() -> std::io::Result<()> { async_std::task::block_on(async { + /// # /// use async_std::io::Cursor; /// use async_std::io::prelude::*; /// use async_std::io::SeekFrom; @@ -116,11 +118,13 @@ impl Cursor { /// /// assert_eq!(buff.position(), 0); /// - /// buff.seek(SeekFrom::Current(2)).unwrap(); + /// buff.seek(SeekFrom::Current(2)).await?; /// assert_eq!(buff.position(), 2); /// - /// buff.seek(SeekFrom::Current(-1)).unwrap(); + /// buff.seek(SeekFrom::Current(-1)).await?; /// assert_eq!(buff.position(), 1); + /// # + /// # Ok(()) }) } /// ``` pub fn position(&self) -> u64 { self.inner.position() From 3b8e604acc077d49be3df35d2f8319c611d0b41a Mon Sep 17 00:00:00 2001 From: Yoshua Wuyts Date: Fri, 13 Sep 2019 20:02:31 +0200 Subject: [PATCH 4/4] mark io::cursor as unstable Signed-off-by: Yoshua Wuyts --- src/io/cursor.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/io/cursor.rs b/src/io/cursor.rs index 95b13ecbf..c890c2fc4 100644 --- a/src/io/cursor.rs +++ b/src/io/cursor.rs @@ -22,6 +22,7 @@ use std::task::{Context, Poll}; /// [`Vec`]: https://doc.rust-lang.org/std/vec/struct.Vec.html /// [bytes]: https://doc.rust-lang.org/std/primitive.slice.html /// [`File`]: struct.File.html +#[cfg_attr(feature = "docs", doc(cfg(unstable)))] #[derive(Clone, Debug, Default)] pub struct Cursor { inner: std::io::Cursor,