From 7af0f327513d468c685776789c6fe0f68f6ed102 Mon Sep 17 00:00:00 2001 From: Thibeau Vercruyssen <74682871+tvercruyssen@users.noreply.github.com> Date: Tue, 14 Sep 2021 16:05:01 +0200 Subject: [PATCH] io: add convenience method `AsyncSeekExt::rewind`. (#4107) --- tokio/src/io/util/async_seek_ext.rs | 10 ++++++++++ tokio/tests/fs_file.rs | 20 ++++++++++++++++---- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/tokio/src/io/util/async_seek_ext.rs b/tokio/src/io/util/async_seek_ext.rs index 297a4a61a..46b3e6c0d 100644 --- a/tokio/src/io/util/async_seek_ext.rs +++ b/tokio/src/io/util/async_seek_ext.rs @@ -67,6 +67,16 @@ cfg_io_util! { seek(self, pos) } + /// Creates a future which will rewind to the beginning of the stream. + /// + /// This is convenience method, equivalent to to `self.seek(SeekFrom::Start(0))`. + fn rewind(&mut self) -> Seek<'_, Self> + where + Self: Unpin, + { + self.seek(SeekFrom::Start(0)) + } + /// Creates a future which will return the current seek position from the /// start of the stream. /// diff --git a/tokio/tests/fs_file.rs b/tokio/tests/fs_file.rs index bf2f1d7b5..f645e61ae 100644 --- a/tokio/tests/fs_file.rs +++ b/tokio/tests/fs_file.rs @@ -1,12 +1,11 @@ #![warn(rust_2018_idioms)] #![cfg(feature = "full")] -use tokio::fs::File; -use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt}; -use tokio_test::task; - use std::io::prelude::*; use tempfile::NamedTempFile; +use tokio::fs::File; +use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt, SeekFrom}; +use tokio_test::task; const HELLO: &[u8] = b"hello world..."; @@ -50,6 +49,19 @@ async fn basic_write_and_shutdown() { assert_eq!(file, HELLO); } +#[tokio::test] +async fn rewind_seek_position() { + let tempfile = tempfile(); + + let mut file = File::create(tempfile.path()).await.unwrap(); + + file.seek(SeekFrom::Current(10)).await.unwrap(); + + file.rewind().await.unwrap(); + + assert_eq!(file.stream_position().await.unwrap(), 0); +} + #[tokio::test] async fn coop() { let mut tempfile = tempfile();