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.
This commit is contained in:
commit
c5e612ce6b
1 changed files with 37 additions and 0 deletions
|
@ -1663,10 +1663,47 @@ pub trait Seek {
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
///
|
///
|
||||||
|
/// Seeking can fail, for example becaue it might involve flushing a buffer.
|
||||||
|
///
|
||||||
/// Seeking to a negative offset is considered an error.
|
/// Seeking to a negative offset is considered an error.
|
||||||
#[stable(feature = "rust1", since = "1.0.0")]
|
#[stable(feature = "rust1", since = "1.0.0")]
|
||||||
fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
|
fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
|
||||||
|
|
||||||
|
/// Rewind to the beginning of a stream.
|
||||||
|
///
|
||||||
|
/// This is a convenience method, equivalent to `seek(SeekFrom::Start(0))`.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// Rewinding can fail, for example becaue it might involve flushing a buffer.
|
||||||
|
///
|
||||||
|
/// # Example
|
||||||
|
///
|
||||||
|
/// ```no_run
|
||||||
|
/// #![feature(seek_rewind)]
|
||||||
|
/// use std::io::{Read, Seek, Write};
|
||||||
|
/// use std::fs::OpenOptions;
|
||||||
|
///
|
||||||
|
/// let mut f = OpenOptions::new()
|
||||||
|
/// .write(true)
|
||||||
|
/// .read(true)
|
||||||
|
/// .create(true)
|
||||||
|
/// .open("foo.txt").unwrap();
|
||||||
|
///
|
||||||
|
/// let hello = "Hello!\n";
|
||||||
|
/// write!(f, "{}", hello).unwrap();
|
||||||
|
/// f.rewind().unwrap();
|
||||||
|
///
|
||||||
|
/// let mut buf = String::new();
|
||||||
|
/// f.read_to_string(&mut buf).unwrap();
|
||||||
|
/// assert_eq!(&buf, hello);
|
||||||
|
/// ```
|
||||||
|
#[unstable(feature = "seek_rewind", issue = "85149")]
|
||||||
|
fn rewind(&mut self) -> Result<()> {
|
||||||
|
self.seek(SeekFrom::Start(0))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// Returns the length of this stream (in bytes).
|
/// Returns the length of this stream (in bytes).
|
||||||
///
|
///
|
||||||
/// This method is implemented using up to three seek operations. If this
|
/// This method is implemented using up to three seek operations. If this
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue