Skip to content

Commit 1605205

Browse files
committed
Implement io::Seek for io::BufWriter<W> where W: io::Seek
Seeking the `BufWriter` writes out its internal buffer before seeking.
1 parent 0a380a9 commit 1605205

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

src/libstd/io/buffered.rs

+22
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,16 @@ impl<W: Write> fmt::Debug for BufWriter<W> where W: fmt::Debug {
284284
}
285285
}
286286

287+
#[unstable(feature = "buf_seek", reason = "recently added")]
288+
impl<W: Write+Seek> Seek for BufWriter<W> {
289+
/// Seek to the offset, in bytes, in the underlying writer.
290+
///
291+
/// Seeking always writes out the internal buffer before seeking.
292+
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
293+
self.flush_buf().and_then(|_| self.get_mut().seek(pos))
294+
}
295+
}
296+
287297
#[unsafe_destructor]
288298
impl<W: Write> Drop for BufWriter<W> {
289299
fn drop(&mut self) {
@@ -683,6 +693,18 @@ mod tests {
683693
assert_eq!(w, [0, 1]);
684694
}
685695

696+
#[test]
697+
fn test_buffered_writer_seek() {
698+
let mut w = BufWriter::with_capacity(3, io::Cursor::new(Vec::new()));
699+
w.write_all(&[0, 1, 2, 3, 4, 5]).unwrap();
700+
w.write_all(&[6, 7]).unwrap();
701+
assert_eq!(w.seek(SeekFrom::Current(0)).ok(), Some(8));
702+
assert_eq!(&w.get_ref().get_ref()[..], &[0, 1, 2, 3, 4, 5, 6, 7][..]);
703+
assert_eq!(w.seek(SeekFrom::Start(2)).ok(), Some(2));
704+
w.write_all(&[8, 9]).unwrap();
705+
assert_eq!(&w.into_inner().unwrap().into_inner()[..], &[0, 1, 8, 9, 4, 5, 6, 7]);
706+
}
707+
686708
// This is just here to make sure that we don't infinite loop in the
687709
// newtype struct autoderef weirdness
688710
#[test]

0 commit comments

Comments
 (0)