Skip to content

Commit

Permalink
Create BufStream from a BufReader + BufWriter (#1609)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
jonhoo authored and LucioFranco committed Sep 30, 2019
1 parent 3b8ee2d commit 5fd5329
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 7 deletions.
8 changes: 4 additions & 4 deletions tokio-io/src/io/buf_reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ use std::{cmp, fmt};
#[pin_project]
pub struct BufReader<R> {
#[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<R: AsyncRead> BufReader<R> {
Expand Down
34 changes: 34 additions & 0 deletions tokio-io/src/io/buf_stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,40 @@ impl<RW: AsyncRead + AsyncWrite> BufStream<RW> {
}
}

impl<RW> From<BufReader<BufWriter<RW>>> for BufStream<RW> {
fn from(b: BufReader<BufWriter<RW>>) -> Self {
BufStream(b)
}
}

impl<RW> From<BufWriter<BufReader<RW>>> for BufStream<RW> {
fn from(b: BufWriter<BufReader<RW>>) -> 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<RW: AsyncRead + AsyncWrite> AsyncWrite for BufStream<RW> {
fn poll_write(
self: Pin<&mut Self>,
Expand Down
6 changes: 3 additions & 3 deletions tokio-io/src/io/buf_writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ use std::task::{Context, Poll};
#[pin_project]
pub struct BufWriter<W> {
#[pin]
inner: W,
buf: Vec<u8>,
written: usize,
pub(super) inner: W,
pub(super) buf: Vec<u8>,
pub(super) written: usize,
}

impl<W: AsyncWrite> BufWriter<W> {
Expand Down

0 comments on commit 5fd5329

Please sign in to comment.