broker_tokio/io/util/
async_seek_ext.rs

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