Skip to content

Commit ad156b1

Browse files
committed
feat: Add BufWriter::into_inner flush
1 parent 30b5ca5 commit ad156b1

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

src/io/buf_writer.rs

+26-2
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use std::pin::Pin;
44
use futures_core::ready;
55

66
use crate::io::{self, Seek, SeekFrom, Write};
7+
use crate::io::write::WriteExt;
78
use crate::task::{Context, Poll};
89

910
const DEFAULT_CAPACITY: usize = 8 * 1024;
@@ -83,6 +84,9 @@ pub struct BufWriter<W> {
8384
written: usize,
8485
}
8586

87+
#[derive(Debug)]
88+
pub struct IntoInnerError<W>(W, std::io::Error);
89+
8690
impl<W: Write> BufWriter<W> {
8791
pin_utils::unsafe_pinned!(inner: W);
8892
pin_utils::unsafe_unpinned!(buf: Vec<u8>);
@@ -180,8 +184,28 @@ impl<W: Write> BufWriter<W> {
180184
/// For method that will attempt to write before returning the writer see [`poll_into_inner`]
181185
///
182186
/// [`poll_into_inner`]: #method.poll_into_inner
183-
pub fn into_inner(self) -> W {
184-
self.inner
187+
/// # Examples
188+
///
189+
/// ```no_run
190+
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
191+
/// use async_std::io::BufWriter;
192+
/// use async_std::net::TcpStream;
193+
///
194+
/// let buf_writer = BufWriter::new(TcpStream::connect("127.0.0.1:34251").await?);
195+
///
196+
/// // unwrap the TcpStream and flush the buffer
197+
/// let stream = buf_writer.into_inner().await.unwrap();
198+
/// #
199+
/// # Ok(()) }) }
200+
/// ```
201+
pub async fn into_inner(mut self) -> Result<W, IntoInnerError<BufWriter<W>>>
202+
where
203+
Self: Unpin
204+
{
205+
match self.flush().await {
206+
Err(e) => Err(IntoInnerError(self, e)),
207+
Ok(()) => Ok(self.inner),
208+
}
185209
}
186210

187211
/// Returns a reference to the internally buffered data.

tests/buf_writer.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ fn test_buffered_writer_inner_into_inner_does_not_flush() {
5353
let mut w = BufWriter::with_capacity(3, Vec::new());
5454
w.write(&[0, 1]).await.unwrap();
5555
assert_eq!(*w.get_ref(), []);
56-
let w = w.into_inner();
56+
let w = w.into_inner().await.unwrap();
5757
assert_eq!(w, []);
5858
})
5959
}

0 commit comments

Comments
 (0)