Skip to content

Commit c5e612c

Browse files
authored
Rollup merge of #85146 - ijackson:seek-rewind, r=m-ou-se
Provide io::Seek::rewind Using `Seek::seek` is slightly clumsy because of the need to write (or import) `std::io::SeekFrom` to get at `SeekStart`. C already has `rewind` (although with broken error handling); we should have it too. I'm motivated to do this because I've just found myself copy-pasting my 5-line extension trait between projects. That the example ends up using `OpenOptions` makes this look like a niche use case, but it is very common to rewind temporary files. `tempfile` isn't available for use in this example or it would have looked shorter and more natural. If this gets a positive reception I will open a tracking issue and update the feature gate.
2 parents ae8a438 + 7ae852e commit c5e612c

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

library/std/src/io/mod.rs

+37
Original file line numberDiff line numberDiff line change
@@ -1663,10 +1663,47 @@ pub trait Seek {
16631663
///
16641664
/// # Errors
16651665
///
1666+
/// Seeking can fail, for example becaue it might involve flushing a buffer.
1667+
///
16661668
/// Seeking to a negative offset is considered an error.
16671669
#[stable(feature = "rust1", since = "1.0.0")]
16681670
fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
16691671

1672+
/// Rewind to the beginning of a stream.
1673+
///
1674+
/// This is a convenience method, equivalent to `seek(SeekFrom::Start(0))`.
1675+
///
1676+
/// # Errors
1677+
///
1678+
/// Rewinding can fail, for example becaue it might involve flushing a buffer.
1679+
///
1680+
/// # Example
1681+
///
1682+
/// ```no_run
1683+
/// #![feature(seek_rewind)]
1684+
/// use std::io::{Read, Seek, Write};
1685+
/// use std::fs::OpenOptions;
1686+
///
1687+
/// let mut f = OpenOptions::new()
1688+
/// .write(true)
1689+
/// .read(true)
1690+
/// .create(true)
1691+
/// .open("foo.txt").unwrap();
1692+
///
1693+
/// let hello = "Hello!\n";
1694+
/// write!(f, "{}", hello).unwrap();
1695+
/// f.rewind().unwrap();
1696+
///
1697+
/// let mut buf = String::new();
1698+
/// f.read_to_string(&mut buf).unwrap();
1699+
/// assert_eq!(&buf, hello);
1700+
/// ```
1701+
#[unstable(feature = "seek_rewind", issue = "85149")]
1702+
fn rewind(&mut self) -> Result<()> {
1703+
self.seek(SeekFrom::Start(0))?;
1704+
Ok(())
1705+
}
1706+
16701707
/// Returns the length of this stream (in bytes).
16711708
///
16721709
/// This method is implemented using up to three seek operations. If this

0 commit comments

Comments
 (0)