Skip to content

Commit a1e1b5c

Browse files
committed
rework LineWriter example
The original example didn't check the return value of `write()`, didn't flush the writer, and didn't properly demonstrate the buffering. Fixes rust-lang#51621.
1 parent 0c0315c commit a1e1b5c

File tree

1 file changed

+24
-10
lines changed

1 file changed

+24
-10
lines changed

src/libstd/io/buffered.rs

+24-10
Original file line numberDiff line numberDiff line change
@@ -738,7 +738,7 @@ impl<W> fmt::Display for IntoInnerError<W> {
738738
/// reducing the number of actual writes to the file.
739739
///
740740
/// ```no_run
741-
/// use std::fs::File;
741+
/// use std::fs::{self, File};
742742
/// use std::io::prelude::*;
743743
/// use std::io::LineWriter;
744744
///
@@ -752,17 +752,31 @@ impl<W> fmt::Display for IntoInnerError<W> {
752752
/// let file = File::create("poem.txt")?;
753753
/// let mut file = LineWriter::new(file);
754754
///
755-
/// for &byte in road_not_taken.iter() {
756-
/// file.write(&[byte]).unwrap();
757-
/// }
755+
/// file.write_all(b"I shall be telling this with a sigh")?;
756+
///
757+
/// // No bytes are written until a newline is encountered (or
758+
/// // the internal buffer is filled).
759+
/// assert_eq!(fs::read_to_string("poem.txt")?.as_bytes(), b"");
760+
/// file.write_all(b"\n")?;
761+
/// assert_eq!(
762+
/// fs::read_to_string("poem.txt")?.as_bytes(),
763+
/// &b"I shall be telling this with a sigh\n"[..],
764+
/// );
758765
///
759-
/// // let's check we did the right thing.
760-
/// let mut file = File::open("poem.txt")?;
761-
/// let mut contents = String::new();
766+
/// // Write the rest of the poem.
767+
/// file.write_all(b"Somewhere ages and ages hence:
768+
/// Two roads diverged in a wood, and I -
769+
/// I took the one less traveled by,
770+
/// And that has made all the difference.")?;
762771
///
763-
/// file.read_to_string(&mut contents)?;
772+
/// // The last line of the poem doesn't end in a newline, so
773+
/// // we have to flush or drop the `LineWriter` to finish
774+
/// // writing.
775+
/// file.flush()?;
764776
///
765-
/// assert_eq!(contents.as_bytes(), &road_not_taken[..]);
777+
/// // Confirm the whole poem was written.
778+
/// let mut poem = fs::read_to_string("poem.txt")?;
779+
/// assert_eq!(poem.as_bytes(), &road_not_taken[..]);
766780
/// Ok(())
767781
/// }
768782
/// ```
@@ -862,7 +876,7 @@ impl<W: Write> LineWriter<W> {
862876
///
863877
/// The internal buffer is written out before returning the writer.
864878
///
865-
// # Errors
879+
/// # Errors
866880
///
867881
/// An `Err` will be returned if an error occurs while flushing the buffer.
868882
///

0 commit comments

Comments
 (0)