1 mod seek; 2 3 use seek::SeekFuture; 4 5 use crate::io::SeekFrom; 6 7 extension_trait! { 8 use std::ops::{Deref, DerefMut}; 9 use std::pin::Pin; 10 11 use crate::io; 12 use crate::task::{Context, Poll}; 13 14 #[doc = r#" 15 Allows seeking through a byte stream. 16 17 This trait is a re-export of [`futures::io::AsyncSeek`] and is an async version of 18 [`std::io::Seek`]. 19 20 The [provided methods] do not really exist in the trait itself, but they become 21 available when [`SeekExt`] the [prelude] is imported: 22 23 ``` 24 # #[allow(unused_imports)] 25 use async_std::prelude::*; 26 ``` 27 28 [`std::io::Seek`]: https://doc.rust-lang.org/std/io/trait.Seek.html 29 [`futures::io::AsyncSeek`]: 30 https://docs.rs/futures/0.3/futures/io/trait.AsyncSeek.html 31 [provided methods]: #provided-methods 32 [`SeekExt`]: ../io/prelude/trait.SeekExt.html 33 [prelude]: ../prelude/index.html 34 "#] 35 pub trait Seek { 36 #[doc = r#" 37 Attempt to seek to an offset, in bytes, in a stream. 38 "#] 39 fn poll_seek( 40 self: Pin<&mut Self>, 41 cx: &mut Context<'_>, 42 pos: SeekFrom, 43 ) -> Poll<io::Result<u64>>; 44 } 45 46 #[doc = r#" 47 Extension methods for [`Seek`]. 48 49 [`Seek`]: ../trait.Seek.html 50 "#] 51 pub trait SeekExt: futures_io::AsyncSeek { 52 #[doc = r#" 53 Seeks to a new position in a byte stream. 54 55 Returns the new position in the byte stream. 56 57 A seek beyond the end of stream is allowed, but behavior is defined by the 58 implementation. 59 60 # Examples 61 62 ```no_run 63 # fn main() -> std::io::Result<()> { async_std::task::block_on(async { 64 # 65 use async_std::fs::File; 66 use async_std::io::SeekFrom; 67 use async_std::prelude::*; 68 69 let mut file = File::open("a.txt").await?; 70 71 let file_len = file.seek(SeekFrom::End(0)).await?; 72 # 73 # Ok(()) }) } 74 ``` 75 "#] 76 fn seek( 77 &mut self, 78 pos: SeekFrom, 79 ) -> impl Future<Output = io::Result<u64>> + '_ [SeekFuture<'_, Self>] 80 where 81 Self: Unpin, 82 { 83 SeekFuture { seeker: self, pos } 84 } 85 } 86 87 impl<T: Seek + Unpin + ?Sized> Seek for Box<T> { 88 fn poll_seek( 89 self: Pin<&mut Self>, 90 cx: &mut Context<'_>, 91 pos: SeekFrom, 92 ) -> Poll<io::Result<u64>> { 93 unreachable!("this impl only appears in the rendered docs") 94 } 95 } 96 97 impl<T: Seek + Unpin + ?Sized> Seek for &mut T { 98 fn poll_seek( 99 self: Pin<&mut Self>, 100 cx: &mut Context<'_>, 101 pos: SeekFrom, 102 ) -> Poll<io::Result<u64>> { 103 unreachable!("this impl only appears in the rendered docs") 104 } 105 } 106 107 impl<P> Seek for Pin<P> 108 where 109 P: DerefMut + Unpin, 110 <P as Deref>::Target: Seek, 111 { 112 fn poll_seek( 113 self: Pin<&mut Self>, 114 cx: &mut Context<'_>, 115 pos: SeekFrom, 116 ) -> Poll<io::Result<u64>> { 117 unreachable!("this impl only appears in the rendered docs") 118 } 119 } 120 } 121