Skip to content

Add BufWriter::into_inner flush #315

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

Merged
merged 2 commits into from
Oct 13, 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 26 additions & 2 deletions src/io/buf_writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::pin::Pin;

use futures_core::ready;

use crate::io::write::WriteExt;
use crate::io::{self, Seek, SeekFrom, Write};
use crate::task::{Context, Poll};

Expand Down Expand Up @@ -83,6 +84,9 @@ pub struct BufWriter<W> {
written: usize,
}

#[derive(Debug)]
pub struct IntoInnerError<W>(W, std::io::Error);

impl<W: Write> BufWriter<W> {
pin_utils::unsafe_pinned!(inner: W);
pin_utils::unsafe_unpinned!(buf: Vec<u8>);
Expand Down Expand Up @@ -180,8 +184,28 @@ impl<W: Write> BufWriter<W> {
/// For method that will attempt to write before returning the writer see [`poll_into_inner`]
///
/// [`poll_into_inner`]: #method.poll_into_inner
pub fn into_inner(self) -> W {
self.inner
/// # Examples
///
/// ```no_run
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// use async_std::io::BufWriter;
/// use async_std::net::TcpStream;
///
/// let buf_writer = BufWriter::new(TcpStream::connect("127.0.0.1:34251").await?);
///
/// // unwrap the TcpStream and flush the buffer
/// let stream = buf_writer.into_inner().await.unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub async fn into_inner(mut self) -> Result<W, IntoInnerError<BufWriter<W>>>
where
Self: Unpin,
{
match self.flush().await {
Err(e) => Err(IntoInnerError(self, e)),
Ok(()) => Ok(self.inner),
}
}

/// Returns a reference to the internally buffered data.
Expand Down
2 changes: 1 addition & 1 deletion tests/buf_writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ fn test_buffered_writer_inner_into_inner_does_not_flush() {
let mut w = BufWriter::with_capacity(3, Vec::new());
w.write(&[0, 1]).await.unwrap();
assert_eq!(*w.get_ref(), []);
let w = w.into_inner();
let w = w.into_inner().await.unwrap();
assert_eq!(w, []);
})
}
Expand Down