Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use our own io::Cursor #1943

Merged
merged 1 commit into from Nov 4, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
38 changes: 0 additions & 38 deletions futures-io/src/lib.rs
Expand Up @@ -385,10 +385,6 @@ mod if_std {
delegate_async_read_to_stdio!();
}

impl<T: AsRef<[u8]> + Unpin> AsyncRead for io::Cursor<T> {
delegate_async_read_to_stdio!();
}

macro_rules! deref_async_write {
() => {
fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8])
Expand Down Expand Up @@ -471,22 +467,6 @@ mod if_std {
}
}

impl AsyncWrite for io::Cursor<&mut [u8]> {
delegate_async_write_to_stdio!();
}

impl AsyncWrite for io::Cursor<&mut Vec<u8>> {
delegate_async_write_to_stdio!();
}

impl AsyncWrite for io::Cursor<Vec<u8>> {
delegate_async_write_to_stdio!();
}

impl AsyncWrite for io::Cursor<Box<[u8]>> {
delegate_async_write_to_stdio!();
}

impl AsyncWrite for Vec<u8> {
delegate_async_write_to_stdio!();
}
Expand Down Expand Up @@ -521,20 +501,6 @@ mod if_std {
}
}

macro_rules! delegate_async_seek_to_stdio {
() => {
fn poll_seek(mut self: Pin<&mut Self>, _: &mut Context<'_>, pos: SeekFrom)
-> Poll<Result<u64>>
{
Poll::Ready(io::Seek::seek(&mut *self, pos))
}
}
}

impl<T: AsRef<[u8]> + Unpin> AsyncSeek for io::Cursor<T> {
delegate_async_seek_to_stdio!();
}

macro_rules! deref_async_buf_read {
() => {
fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>)
Expand Down Expand Up @@ -590,10 +556,6 @@ mod if_std {
impl AsyncBufRead for &[u8] {
delegate_async_buf_read_to_stdio!();
}

impl<T: AsRef<[u8]> + Unpin> AsyncBufRead for io::Cursor<T> {
delegate_async_buf_read_to_stdio!();
}
}

#[cfg(feature = "std")]
Expand Down
12 changes: 6 additions & 6 deletions futures-test/src/io/read/mod.rs
Expand Up @@ -14,12 +14,12 @@ pub trait AsyncReadTestExt: AsyncRead {
///
/// ```
/// use futures::task::Poll;
/// use futures::io::AsyncRead;
/// use futures::io::{AsyncRead, Cursor};
/// use futures_test::task::noop_context;
/// use futures_test::io::AsyncReadTestExt;
/// use futures::pin_mut;
///
/// let reader = std::io::Cursor::new(&[1, 2, 3]).interleave_pending();
/// let reader = Cursor::new(&[1, 2, 3]).interleave_pending();
/// pin_mut!(reader);
///
/// let mut cx = noop_context();
Expand All @@ -44,12 +44,12 @@ pub trait AsyncReadTestExt: AsyncRead {
///
/// ```
/// use futures::task::Poll;
/// use futures::io::AsyncBufRead;
/// use futures::io::{AsyncBufRead, Cursor};
/// use futures_test::task::noop_context;
/// use futures_test::io::AsyncReadTestExt;
/// use futures::pin_mut;
///
/// let reader = std::io::Cursor::new(&[1, 2, 3]).interleave_pending();
/// let reader = Cursor::new(&[1, 2, 3]).interleave_pending();
/// pin_mut!(reader);
///
/// let mut cx = noop_context();
Expand Down Expand Up @@ -78,12 +78,12 @@ pub trait AsyncReadTestExt: AsyncRead {
///
/// ```
/// use futures::task::Poll;
/// use futures::io::AsyncRead;
/// use futures::io::{AsyncRead, Cursor};
/// use futures_test::task::noop_context;
/// use futures_test::io::AsyncReadTestExt;
/// use futures::pin_mut;
///
/// let reader = std::io::Cursor::new(&[1, 2, 3, 4, 5]).limited(2);
/// let reader = Cursor::new(&[1, 2, 3, 4, 5]).limited(2);
/// pin_mut!(reader);
///
/// let mut cx = noop_context();
Expand Down
8 changes: 4 additions & 4 deletions futures-test/src/io/write/mod.rs
Expand Up @@ -14,12 +14,12 @@ pub trait AsyncWriteTestExt: AsyncWrite {
///
/// ```
/// use futures::task::Poll;
/// use futures::io::AsyncWrite;
/// use futures::io::{AsyncWrite, Cursor};
/// use futures_test::task::noop_context;
/// use futures_test::io::AsyncWriteTestExt;
/// use futures::pin_mut;
///
/// let writer = std::io::Cursor::new(vec![0u8; 4].into_boxed_slice()).interleave_pending_write();
/// let writer = Cursor::new(vec![0u8; 4].into_boxed_slice()).interleave_pending_write();
/// pin_mut!(writer);
///
/// let mut cx = noop_context();
Expand Down Expand Up @@ -54,12 +54,12 @@ pub trait AsyncWriteTestExt: AsyncWrite {
///
/// ```
/// use futures::task::Poll;
/// use futures::io::AsyncWrite;
/// use futures::io::{AsyncWrite, Cursor};
/// use futures_test::task::noop_context;
/// use futures_test::io::AsyncWriteTestExt;
/// use futures::pin_mut;
///
/// let writer = std::io::Cursor::new(vec![0u8; 4].into_boxed_slice()).limited_write(2);
/// let writer = Cursor::new(vec![0u8; 4].into_boxed_slice()).limited_write(2);
/// pin_mut!(writer);
///
/// let mut cx = noop_context();
Expand Down
238 changes: 238 additions & 0 deletions futures-util/src/io/cursor.rs
@@ -0,0 +1,238 @@
use futures_core::task::{Context, Poll};
#[cfg(feature = "read_initializer")]
use futures_io::Initializer;
use futures_io::{AsyncBufRead, AsyncRead, AsyncSeek, AsyncWrite, IoSlice, IoSliceMut, SeekFrom};
use std::io;
use std::pin::Pin;

/// A `Cursor` wraps an in-memory buffer and provides it with a
/// [`AsyncSeek`] implementation.
///
/// `Cursor`s are used with in-memory buffers, anything implementing
/// `AsRef<[u8]>`, to allow them to implement [`AsyncRead`] and/or [`AsyncWrite`],
/// 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`]`<u8>>` and
/// `Cursor<`[`&[u8]`][bytes]`>`.
///
/// [`AsyncSeek`]: trait.AsyncSeek.html
/// [`AsyncRead`]: trait.AsyncRead.html
/// [`AsyncWrite`]: trait.AsyncWrite.html
/// [bytes]: https://doc.rust-lang.org/std/primitive.slice.html
#[derive(Clone, Debug, Default)]
pub struct Cursor<T> {
inner: io::Cursor<T>,
Copy link
Member Author

@taiki-e taiki-e Nov 4, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As there is not enough time, it is implemented as a newtype, but it can be optimized later.

}

impl<T> Cursor<T> {
/// 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 futures::io::Cursor;
///
/// let buff = Cursor::new(Vec::new());
/// # fn force_inference(_: &Cursor<Vec<u8>>) {}
/// # force_inference(&buff);
/// ```
pub fn new(inner: T) -> Cursor<T> {
Cursor {
inner: io::Cursor::new(inner),
}
}

/// Consumes this cursor, returning the underlying value.
///
/// # Examples
///
/// ```
/// use futures::io::Cursor;
///
/// let buff = Cursor::new(Vec::new());
/// # fn force_inference(_: &Cursor<Vec<u8>>) {}
/// # 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 futures::io::Cursor;
///
/// let buff = Cursor::new(Vec::new());
/// # fn force_inference(_: &Cursor<Vec<u8>>) {}
/// # 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 futures::io::Cursor;
///
/// let mut buff = Cursor::new(Vec::new());
/// # fn force_inference(_: &Cursor<Vec<u8>>) {}
/// # 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
///
/// ```
/// # futures::executor::block_on(async {
/// use futures::io::{AsyncSeekExt, Cursor, SeekFrom};
///
/// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]);
///
/// assert_eq!(buff.position(), 0);
///
/// buff.seek(SeekFrom::Current(2)).await?;
/// assert_eq!(buff.position(), 2);
///
/// buff.seek(SeekFrom::Current(-1)).await?;
/// assert_eq!(buff.position(), 1);
/// # Ok::<(), Box<dyn std::error::Error>>(()) }).unwrap();
/// ```
pub fn position(&self) -> u64 {
self.inner.position()
}

/// Sets the position of this cursor.
///
/// # Examples
///
/// ```
/// use futures::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<T> AsyncSeek for Cursor<T>
where
T: AsRef<[u8]> + Unpin,
{
fn poll_seek(
mut self: Pin<&mut Self>,
_: &mut Context<'_>,
pos: SeekFrom,
) -> Poll<io::Result<u64>> {
Poll::Ready(io::Seek::seek(&mut self.inner, pos))
}
}

impl<T: AsRef<[u8]> + Unpin> AsyncRead for Cursor<T> {
#[cfg(feature = "read_initializer")]
#[inline]
unsafe fn initializer(&self) -> Initializer {
io::Read::initializer(&self.inner)
}

fn poll_read(
mut self: Pin<&mut Self>,
_cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
Poll::Ready(io::Read::read(&mut self.inner, buf))
}

fn poll_read_vectored(
mut self: Pin<&mut Self>,
_: &mut Context<'_>,
bufs: &mut [IoSliceMut<'_>],
) -> Poll<io::Result<usize>> {
Poll::Ready(io::Read::read_vectored(&mut self.inner, bufs))
}
}

impl<T> AsyncBufRead for Cursor<T>
where
T: AsRef<[u8]> + Unpin,
{
fn poll_fill_buf(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
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)
}
}

macro_rules! delegate_async_write_to_stdio {
() => {
fn poll_write(mut self: Pin<&mut Self>, _: &mut Context<'_>, buf: &[u8])
-> Poll<io::Result<usize>>
{
Poll::Ready(io::Write::write(&mut self.inner, buf))
}

fn poll_write_vectored(mut self: Pin<&mut Self>, _: &mut Context<'_>, bufs: &[IoSlice<'_>])
-> Poll<io::Result<usize>>
{
Poll::Ready(io::Write::write_vectored(&mut self.inner, bufs))
}

fn poll_flush(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
Poll::Ready(io::Write::flush(&mut self.inner))
}

fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
self.poll_flush(cx)
}
}
}

impl AsyncWrite for Cursor<&mut [u8]> {
delegate_async_write_to_stdio!();
}

impl AsyncWrite for Cursor<&mut Vec<u8>> {
delegate_async_write_to_stdio!();
}

impl AsyncWrite for Cursor<Vec<u8>> {
delegate_async_write_to_stdio!();
}

impl AsyncWrite for Cursor<Box<[u8]>> {
delegate_async_write_to_stdio!();
}