Skip to content

Commit 09458e2

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 e0f2991 commit 09458e2

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

src/libstd/io/buffered.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -283,6 +283,15 @@ impl<W: Write> fmt::Debug for BufWriter<W> where W: fmt::Debug {
283283
}
284284
}
285285

286+
impl<W: Write+Seek> Seek for BufWriter<W> {
287+
/// Seek to the offset, in bytes, in the underlying writer.
288+
///
289+
/// Seeking always writes out the internal buffer before seeking.
290+
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
291+
self.flush_buf().and_then(|_| self.get_mut().seek(pos))
292+
}
293+
}
294+
286295
#[unsafe_destructor]
287296
impl<W: Write> Drop for BufWriter<W> {
288297
fn drop(&mut self) {
@@ -682,6 +691,18 @@ mod tests {
682691
assert_eq!(w, [0, 1]);
683692
}
684693

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

0 commit comments

Comments
 (0)