From eba8bf2b4b082d7a9daab8fd3aecf7a95e9466e2 Mon Sep 17 00:00:00 2001 From: tmiasko Date: Fri, 9 Aug 2019 05:55:27 +0200 Subject: [PATCH] io: implement AsyncWrite for Vec (#1409) --- tokio-io/src/async_write.rs | 19 +++++++++++++++++++ tokio-io/tests/copy.rs | 30 +++--------------------------- 2 files changed, 22 insertions(+), 27 deletions(-) diff --git a/tokio-io/src/async_write.rs b/tokio-io/src/async_write.rs index 62155112b..dc8b852f7 100644 --- a/tokio-io/src/async_write.rs +++ b/tokio-io/src/async_write.rs @@ -190,3 +190,22 @@ where self.get_mut().as_mut().poll_shutdown(cx) } } + +impl AsyncWrite for Vec { + fn poll_write( + self: Pin<&mut Self>, + _cx: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { + self.get_mut().extend_from_slice(buf); + Poll::Ready(Ok(buf.len())) + } + + fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + + fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } +} diff --git a/tokio-io/tests/copy.rs b/tokio-io/tests/copy.rs index f9e3fee26..8173084f8 100644 --- a/tokio-io/tests/copy.rs +++ b/tokio-io/tests/copy.rs @@ -1,10 +1,9 @@ #![deny(warnings, rust_2018_idioms)] #![feature(async_await)] -use tokio_io::{AsyncRead, AsyncReadExt, AsyncWrite}; +use tokio_io::{AsyncRead, AsyncReadExt}; use tokio_test::assert_ok; -use bytes::BytesMut; use std::io; use std::pin::Pin; use std::task::{Context, Poll}; @@ -29,33 +28,10 @@ async fn copy() { } } - struct Wr(BytesMut); - - impl Unpin for Wr {} - impl AsyncWrite for Wr { - fn poll_write( - mut self: Pin<&mut Self>, - _cx: &mut Context<'_>, - buf: &[u8], - ) -> Poll> { - self.0.extend(buf); - Ok(buf.len()).into() - } - - fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { - Ok(()).into() - } - - fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { - Ok(()).into() - } - } - - let buf = BytesMut::with_capacity(64); let mut rd = Rd(true); - let mut wr = Wr(buf); + let mut wr = Vec::new(); let n = assert_ok!(rd.copy(&mut wr).await); assert_eq!(n, 11); - assert_eq!(wr.0[..], b"hello world"[..]); + assert_eq!(wr, b"hello world"); }