From 5fd5329497ca7982a376d8997bc1a8a41cd2db1c Mon Sep 17 00:00:00 2001 From: Jon Gjengset Date: Mon, 30 Sep 2019 14:22:59 -0400 Subject: [PATCH] Create BufStream from a BufReader + BufWriter (#1609) This is handy if developers want to construct the inner buffers with a particular capacity, and still end up with a `BufStream` at the end. --- tokio-io/src/io/buf_reader.rs | 8 ++++---- tokio-io/src/io/buf_stream.rs | 34 ++++++++++++++++++++++++++++++++++ tokio-io/src/io/buf_writer.rs | 6 +++--- 3 files changed, 41 insertions(+), 7 deletions(-) diff --git a/tokio-io/src/io/buf_reader.rs b/tokio-io/src/io/buf_reader.rs index a6afd7b3741..971332bc90e 100644 --- a/tokio-io/src/io/buf_reader.rs +++ b/tokio-io/src/io/buf_reader.rs @@ -26,10 +26,10 @@ use std::{cmp, fmt}; #[pin_project] pub struct BufReader { #[pin] - inner: R, - buf: Box<[u8]>, - pos: usize, - cap: usize, + pub(super) inner: R, + pub(super) buf: Box<[u8]>, + pub(super) pos: usize, + pub(super) cap: usize, } impl BufReader { diff --git a/tokio-io/src/io/buf_stream.rs b/tokio-io/src/io/buf_stream.rs index 6ec03effb7c..4daa4088a33 100644 --- a/tokio-io/src/io/buf_stream.rs +++ b/tokio-io/src/io/buf_stream.rs @@ -55,6 +55,40 @@ impl BufStream { } } +impl From>> for BufStream { + fn from(b: BufReader>) -> Self { + BufStream(b) + } +} + +impl From>> for BufStream { + fn from(b: BufWriter>) -> Self { + // we need to "invert" the reader and writer + let BufWriter { + inner: + BufReader { + inner, + buf: rbuf, + pos, + cap, + }, + buf: wbuf, + written, + } = b; + + BufStream(BufReader { + inner: BufWriter { + inner, + buf: wbuf, + written, + }, + buf: rbuf, + pos, + cap, + }) + } +} + impl AsyncWrite for BufStream { fn poll_write( self: Pin<&mut Self>, diff --git a/tokio-io/src/io/buf_writer.rs b/tokio-io/src/io/buf_writer.rs index 5059d3d74ed..67c825d2f69 100644 --- a/tokio-io/src/io/buf_writer.rs +++ b/tokio-io/src/io/buf_writer.rs @@ -31,9 +31,9 @@ use std::task::{Context, Poll}; #[pin_project] pub struct BufWriter { #[pin] - inner: W, - buf: Vec, - written: usize, + pub(super) inner: W, + pub(super) buf: Vec, + pub(super) written: usize, } impl BufWriter {