io: implement AsyncWrite for Vec<u8> (#1409)

This commit is contained in:
tmiasko 2019-08-09 05:55:27 +02:00 committed by Carl Lerche
parent 790d649dc5
commit eba8bf2b4b
2 changed files with 22 additions and 27 deletions

View File

@ -190,3 +190,22 @@ where
self.get_mut().as_mut().poll_shutdown(cx)
}
}
impl AsyncWrite for Vec<u8> {
fn poll_write(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
self.get_mut().extend_from_slice(buf);
Poll::Ready(Ok(buf.len()))
}
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Poll::Ready(Ok(()))
}
fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Poll::Ready(Ok(()))
}
}

View File

@ -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<io::Result<usize>> {
self.0.extend(buf);
Ok(buf.len()).into()
}
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Ok(()).into()
}
fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
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");
}