Skip to content

Commit 3817631

Browse files
committed
BufWriter: Provide into_raw_parts
If something goes wrong, one might want to unpeel the layers of nested Writers to perform recovery actions on the underlying writer, or reuse its resources. `into_inner` can be used for this when the inner writer is still working. But when the inner writer is broken, and returning errors, `into_inner` simply gives you the error from flush, and the same `Bufwriter` back again. Here I provide the necessary function, which I have chosen to call `into_raw_parts`. I had to do something with `panicked`. Returning it to the caller as a boolean seemed rather bare. Throwing the buffered data away in this situation also seems unfriendly: maybe the programmer knows something about the underlying writer and can recover somehow. So I went for a custom Error. This may be overkill, but it does have the nice property that a caller who actually wants to look at the buffered data, rather than simply extracting the inner writer, will be told by the type system if they forget to handle the panicked case. If a caller doesn't need the buffer, it can just be discarded. That WriterPanicked is a newtype around Vec<u8> means that hopefully the layouts of the Ok and Err variants can be very similar, with just a boolean discriminant. So this custom error type should compile down to nearly no code. Signed-off-by: Ian Jackson <[email protected]>
1 parent c4926d0 commit 3817631

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

Diff for: library/std/src/io/buffered/bufwriter.rs

+73
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1+
use crate::error;
12
use crate::fmt;
23
use crate::io::{
34
self, Error, ErrorKind, IntoInnerError, IoSlice, Seek, SeekFrom, Write, DEFAULT_BUF_SIZE,
45
};
6+
use crate::mem;
57

68
/// Wraps a writer and buffers its output.
79
///
@@ -287,6 +289,77 @@ impl<W: Write> BufWriter<W> {
287289
Ok(()) => Ok(self.inner.take().unwrap()),
288290
}
289291
}
292+
293+
/// Disassembles this `BufWriter<W>`, returning the underlying writer, and any buffered but
294+
/// unwritten data.
295+
///
296+
/// If the underlying writer panicked, it is not known what portion of the data was written.
297+
/// In this case, we return `WriterPanicked` for the buffered data (from which the buffer
298+
/// contents can still be recovered).
299+
///
300+
/// `into_raw_parts` makes no attempt to flush data and cannot fail.
301+
///
302+
/// # Examples
303+
///
304+
/// ```
305+
/// #![feature(bufwriter_into_raw_parts)]
306+
/// use std::io::{BufWriter, Write};
307+
///
308+
/// let mut buffer = [0u8; 10];
309+
/// let mut stream = BufWriter::new(buffer.as_mut());
310+
/// write!(stream, "too much data").unwrap();
311+
/// stream.flush().expect_err("it doesn't fit");
312+
/// let (recovered_writer, buffered_data) = stream.into_raw_parts();
313+
/// assert_eq!(recovered_writer.len(), 0);
314+
/// assert_eq!(&buffered_data.unwrap(), b"ata");
315+
/// ```
316+
#[unstable(feature = "bufwriter_into_raw_parts", issue = "none")]
317+
pub fn into_raw_parts(mut self) -> (W, Result<Vec<u8>, WriterPanicked>) {
318+
let buf = mem::take(&mut self.buf);
319+
let buf = if !self.panicked { Ok(buf) } else { Err(WriterPanicked { buf }) };
320+
(self.inner.take().unwrap(), buf)
321+
}
322+
}
323+
324+
#[unstable(feature = "bufwriter_into_raw_parts", issue = "none")]
325+
/// Error returned for the buffered data from `BufWriter::into_raw_parts`, when the underlying
326+
/// writer has previously panicked. Contains the (possibly partly written) buffered data.
327+
pub struct WriterPanicked {
328+
buf: Vec<u8>,
329+
}
330+
331+
impl WriterPanicked {
332+
/// Returns the perhaps-unwritten data. Some of this data may have been written by the
333+
/// panicking call(s) to the underlying writer, so simply writing it again is not a good idea.
334+
#[unstable(feature = "bufwriter_into_raw_parts", issue = "none")]
335+
pub fn into_inner(self) -> Vec<u8> {
336+
self.buf
337+
}
338+
339+
const DESCRIPTION: &'static str =
340+
"BufWriter inner writer panicked, what data remains unwritten is not known";
341+
}
342+
343+
#[unstable(feature = "bufwriter_into_raw_parts", issue = "none")]
344+
impl error::Error for WriterPanicked {
345+
#[allow(deprecated, deprecated_in_future)]
346+
fn description(&self) -> &str {
347+
Self::DESCRIPTION
348+
}
349+
}
350+
351+
#[unstable(feature = "bufwriter_into_raw_parts", issue = "none")]
352+
impl fmt::Display for WriterPanicked {
353+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
354+
write!(f, "{}", Self::DESCRIPTION)
355+
}
356+
}
357+
358+
#[unstable(feature = "bufwriter_into_raw_parts", issue = "none")]
359+
impl fmt::Debug for WriterPanicked {
360+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
361+
write!(f, "WriterPanicked{{..buf.len={}..}}", self.buf.len())
362+
}
290363
}
291364

292365
#[stable(feature = "rust1", since = "1.0.0")]

0 commit comments

Comments
 (0)