1 use crate::io::seek::{seek, Seek};
2 use crate::io::AsyncSeek;
3 use std::io::SeekFrom;
4 
5 /// An extension trait which adds utility methods to [`AsyncSeek`] types.
6 ///
7 /// As a convenience, this trait may be imported using the [`prelude`]:
8 ///
9 /// # Examples
10 ///
11 /// ```
12 /// use std::io::{Cursor, SeekFrom};
13 /// use tokio::prelude::*;
14 ///
15 /// #[tokio::main]
16 /// async fn main() -> io::Result<()> {
17 ///     let mut cursor = Cursor::new(b"abcdefg");
18 ///
19 ///     // the `seek` method is defined by this trait
20 ///     cursor.seek(SeekFrom::Start(3)).await?;
21 ///
22 ///     let mut buf = [0; 1];
23 ///     let n = cursor.read(&mut buf).await?;
24 ///     assert_eq!(n, 1);
25 ///     assert_eq!(buf, [b'd']);
26 ///
27 ///     Ok(())
28 /// }
29 /// ```
30 ///
31 /// See [module][crate::io] documentation for more details.
32 ///
33 /// [`AsyncSeek`]: AsyncSeek
34 /// [`prelude`]: crate::prelude
35 pub trait AsyncSeekExt: AsyncSeek {
36     /// Creates a future which will seek an IO object, and then yield the
37     /// new position in the object and the object itself.
38     ///
39     /// In the case of an error the buffer and the object will be discarded, with
40     /// the error yielded.
41     ///
42     /// # Examples
43     ///
44     /// ```no_run
45     /// use tokio::fs::File;
46     /// use tokio::prelude::*;
47     ///
48     /// use std::io::SeekFrom;
49     ///
50     /// # async fn dox() -> std::io::Result<()> {
51     /// let mut file = File::open("foo.txt").await?;
52     /// file.seek(SeekFrom::Start(6)).await?;
53     ///
54     /// let mut contents = vec![0u8; 10];
55     /// file.read_exact(&mut contents).await?;
56     /// # Ok(())
57     /// # }
58     /// ```
seek(&mut self, pos: SeekFrom) -> Seek<'_, Self> where Self: Unpin,59     fn seek(&mut self, pos: SeekFrom) -> Seek<'_, Self>
60     where
61         Self: Unpin,
62     {
63         seek(self, pos)
64     }
65 }
66 
67 impl<S: AsyncSeek + ?Sized> AsyncSeekExt for S {}
68