tokio/io/util/async_seek_ext.rs
1use crate::io::seek::{seek, Seek};
2use crate::io::AsyncSeek;
3use std::io::SeekFrom;
4
5cfg_io_util! {
6 /// An extension trait that adds utility methods to [`AsyncSeek`] types.
7 ///
8 /// # Examples
9 ///
10 /// ```
11 /// use std::io::{self, Cursor, SeekFrom};
12 /// use tokio::io::{AsyncSeekExt, AsyncReadExt};
13 ///
14 /// # #[tokio::main(flavor = "current_thread")]
15 /// # async fn main() -> io::Result<()> {
16 /// let mut cursor = Cursor::new(b"abcdefg");
17 ///
18 /// // the `seek` method is defined by this trait
19 /// cursor.seek(SeekFrom::Start(3)).await?;
20 ///
21 /// let mut buf = [0; 1];
22 /// let n = cursor.read(&mut buf).await?;
23 /// assert_eq!(n, 1);
24 /// assert_eq!(buf, [b'd']);
25 ///
26 /// Ok(())
27 /// # }
28 /// ```
29 ///
30 /// See [module][crate::io] documentation for more details.
31 ///
32 /// [`AsyncSeek`]: AsyncSeek
33 pub trait AsyncSeekExt: AsyncSeek {
34 /// Creates a future which will seek an IO object, and then yield the
35 /// new position in the object and the object itself.
36 ///
37 /// Equivalent to:
38 ///
39 /// ```ignore
40 /// async fn seek(&mut self, pos: SeekFrom) -> io::Result<u64>;
41 /// ```
42 ///
43 /// In the case of an error the buffer and the object will be discarded, with
44 /// the error yielded.
45 ///
46 /// # Examples
47 ///
48 /// ```no_run
49 /// # #[cfg(not(target_family = "wasm"))]
50 /// # {
51 /// use tokio::fs::File;
52 /// use tokio::io::{AsyncSeekExt, AsyncReadExt};
53 ///
54 /// use std::io::SeekFrom;
55 ///
56 /// # async fn dox() -> std::io::Result<()> {
57 /// let mut file = File::open("foo.txt").await?;
58 /// file.seek(SeekFrom::Start(6)).await?;
59 ///
60 /// let mut contents = vec![0u8; 10];
61 /// file.read_exact(&mut contents).await?;
62 /// # Ok(())
63 /// # }
64 /// # }
65 /// ```
66 fn seek(&mut self, pos: SeekFrom) -> Seek<'_, Self>
67 where
68 Self: Unpin,
69 {
70 seek(self, pos)
71 }
72
73 /// Creates a future which will rewind to the beginning of the stream.
74 ///
75 /// This is convenience method, equivalent to `self.seek(SeekFrom::Start(0))`.
76 fn rewind(&mut self) -> Seek<'_, Self>
77 where
78 Self: Unpin,
79 {
80 self.seek(SeekFrom::Start(0))
81 }
82
83 /// Creates a future which will return the current seek position from the
84 /// start of the stream.
85 ///
86 /// This is equivalent to `self.seek(SeekFrom::Current(0))`.
87 fn stream_position(&mut self) -> Seek<'_, Self>
88 where
89 Self: Unpin,
90 {
91 self.seek(SeekFrom::Current(0))
92 }
93 }
94}
95
96impl<S: AsyncSeek + ?Sized> AsyncSeekExt for S {}