async_std/io/read/
mod.rs

1mod bytes;
2mod chain;
3mod read;
4mod read_exact;
5mod read_to_end;
6mod read_to_string;
7mod read_vectored;
8mod take;
9
10use read::ReadFuture;
11use read_exact::ReadExactFuture;
12use read_to_end::{read_to_end_internal, ReadToEndFuture};
13use read_to_string::ReadToStringFuture;
14use read_vectored::ReadVectoredFuture;
15
16use std::mem;
17
18use crate::io::IoSliceMut;
19
20pub use take::Take;
21pub use bytes::Bytes;
22pub use chain::Chain;
23
24extension_trait! {
25    use std::pin::Pin;
26    use std::ops::{Deref, DerefMut};
27
28    use crate::io;
29    use crate::task::{Context, Poll};
30
31    #[doc = r#"
32        Allows reading from a byte stream.
33
34        This trait is a re-export of [`futures::io::AsyncRead`] and is an async version of
35        [`std::io::Read`].
36
37        Methods other than [`poll_read`] and [`poll_read_vectored`] do not really exist in the
38        trait itself, but they become available when [`ReadExt`] from the [prelude] is imported:
39
40        ```
41        # #[allow(unused_imports)]
42        use async_std::prelude::*;
43        ```
44
45        [`std::io::Read`]: https://doc.rust-lang.org/std/io/trait.Read.html
46        [`futures::io::AsyncRead`]:
47        https://docs.rs/futures/0.3/futures/io/trait.AsyncRead.html
48        [`poll_read`]: #tymethod.poll_read
49        [`poll_read_vectored`]: #method.poll_read_vectored
50        [`ReadExt`]: ../io/prelude/trait.ReadExt.html
51        [prelude]: ../prelude/index.html
52    "#]
53    pub trait Read {
54        #[doc = r#"
55            Attempt to read from the `AsyncRead` into `buf`.
56        "#]
57        fn poll_read(
58            self: Pin<&mut Self>,
59            cx: &mut Context<'_>,
60            buf: &mut [u8],
61        ) -> Poll<io::Result<usize>>;
62
63        #[doc = r#"
64            Attempt to read from the `AsyncRead` into `bufs` using vectored IO operations.
65        "#]
66        fn poll_read_vectored(
67            self: Pin<&mut Self>,
68            cx: &mut Context<'_>,
69            bufs: &mut [IoSliceMut<'_>],
70        ) -> Poll<io::Result<usize>> {
71            unreachable!("this impl only appears in the rendered docs")
72        }
73    }
74
75    #[doc = r#"
76        Extension methods for [`Read`].
77
78        [`Read`]: ../trait.Read.html
79    "#]
80    pub trait ReadExt: futures_io::AsyncRead {
81        #[doc = r#"
82            Reads some bytes from the byte stream.
83
84            Returns the number of bytes read from the start of the buffer.
85
86            If the return value is `Ok(n)`, then it must be guaranteed that
87            `0 <= n <= buf.len()`. A nonzero `n` value indicates that the buffer has been
88            filled in with `n` bytes of data. If `n` is `0`, then it can indicate one of two
89            scenarios:
90
91            1. This reader has reached its "end of file" and will likely no longer be able to
92               produce bytes. Note that this does not mean that the reader will always no
93               longer be able to produce bytes.
94            2. The buffer specified was 0 bytes in length.
95
96            # Examples
97
98            ```no_run
99            # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
100            #
101            use async_std::fs::File;
102            use async_std::prelude::*;
103
104            let mut file = File::open("a.txt").await?;
105
106            let mut buf = vec![0; 1024];
107            let n = file.read(&mut buf).await?;
108            #
109            # Ok(()) }) }
110            ```
111        "#]
112        fn read<'a>(
113            &'a mut self,
114            buf: &'a mut [u8],
115        ) -> impl Future<Output = io::Result<usize>> + 'a [ReadFuture<'a, Self>]
116        where
117            Self: Unpin
118        {
119            ReadFuture { reader: self, buf }
120        }
121
122        #[doc = r#"
123            Like [`read`], except that it reads into a slice of buffers.
124
125            Data is copied to fill each buffer in order, with the final buffer written to
126            possibly being only partially filled. This method must behave as a single call to
127            [`read`] with the buffers concatenated would.
128
129            The default implementation calls [`read`] with either the first nonempty buffer
130            provided, or an empty one if none exists.
131
132            [`read`]: #tymethod.read
133        "#]
134        fn read_vectored<'a>(
135            &'a mut self,
136            bufs: &'a mut [IoSliceMut<'a>],
137        ) -> impl Future<Output = io::Result<usize>> + 'a [ReadVectoredFuture<'a, Self>]
138        where
139            Self: Unpin,
140        {
141            ReadVectoredFuture { reader: self, bufs }
142        }
143
144        #[doc = r#"
145            Reads all bytes from the byte stream.
146
147            All bytes read from this stream will be appended to the specified buffer `buf`.
148            This function will continuously call [`read`] to append more data to `buf` until
149            [`read`] returns either `Ok(0)` or an error.
150
151            If successful, this function will return the total number of bytes read.
152
153            [`read`]: #tymethod.read
154
155            # Examples
156
157            ```no_run
158            # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
159            #
160            use async_std::fs::File;
161            use async_std::prelude::*;
162
163            let mut file = File::open("a.txt").await?;
164
165            let mut buf = Vec::new();
166            file.read_to_end(&mut buf).await?;
167            #
168            # Ok(()) }) }
169            ```
170        "#]
171        fn read_to_end<'a>(
172            &'a mut self,
173            buf: &'a mut Vec<u8>,
174        ) -> impl Future<Output = io::Result<usize>> + 'a [ReadToEndFuture<'a, Self>]
175        where
176            Self: Unpin,
177        {
178            let start_len = buf.len();
179            ReadToEndFuture {
180                reader: self,
181                buf,
182                start_len,
183            }
184        }
185
186        #[doc = r#"
187            Reads all bytes from the byte stream and appends them into a string.
188
189            If successful, this function will return the number of bytes read.
190
191            If the data in this stream is not valid UTF-8 then an error will be returned and
192            `buf` will be left unmodified.
193
194            # Examples
195
196            ```no_run
197            # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
198            #
199            use async_std::fs::File;
200            use async_std::prelude::*;
201
202            let mut file = File::open("a.txt").await?;
203
204            let mut buf = String::new();
205            file.read_to_string(&mut buf).await?;
206            #
207            # Ok(()) }) }
208            ```
209        "#]
210        fn read_to_string<'a>(
211            &'a mut self,
212            buf: &'a mut String,
213        ) -> impl Future<Output = io::Result<usize>> + 'a [ReadToStringFuture<'a, Self>]
214        where
215            Self: Unpin,
216        {
217            let start_len = buf.len();
218            ReadToStringFuture {
219                reader: self,
220                bytes: unsafe { mem::replace(buf.as_mut_vec(), Vec::new()) },
221                buf,
222                start_len,
223            }
224        }
225
226        #[doc = r#"
227            Reads the exact number of bytes required to fill `buf`.
228
229            This function reads as many bytes as necessary to completely fill the specified
230            buffer `buf`.
231
232            No guarantees are provided about the contents of `buf` when this function is
233            called, implementations cannot rely on any property of the contents of `buf` being
234            true. It is recommended that implementations only write data to `buf` instead of
235            reading its contents.
236
237            If this function encounters an "end of file" before completely filling the buffer,
238            it returns an error of the kind [`ErrorKind::UnexpectedEof`].  The contents of
239            `buf` are unspecified in this case.
240
241            If any other read error is encountered then this function immediately returns. The
242            contents of `buf` are unspecified in this case.
243
244            If this function returns an error, it is unspecified how many bytes it has read,
245            but it will never read more than would be necessary to completely fill the buffer.
246
247            [`ErrorKind::UnexpectedEof`]: enum.ErrorKind.html#variant.UnexpectedEof
248
249            # Examples
250
251            ```no_run
252            # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
253            #
254            use async_std::fs::File;
255            use async_std::prelude::*;
256
257            let mut file = File::open("a.txt").await?;
258
259            let mut buf = vec![0; 10];
260            file.read_exact(&mut buf).await?;
261            #
262            # Ok(()) }) }
263            ```
264        "#]
265        fn read_exact<'a>(
266            &'a mut self,
267            buf: &'a mut [u8],
268        ) -> impl Future<Output = io::Result<()>> + 'a [ReadExactFuture<'a, Self>]
269        where
270            Self: Unpin,
271        {
272            ReadExactFuture { reader: self, buf }
273        }
274
275        #[doc = r#"
276            Creates an adaptor which will read at most `limit` bytes from it.
277
278            This function returns a new instance of `Read` which will read at most
279            `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
280            read errors will not count towards the number of bytes read and future
281            calls to [`read`] may succeed.
282
283            # Examples
284
285            [`File`]s implement `Read`:
286
287            [`File`]: ../fs/struct.File.html
288            [`Ok(0)`]: ../../std/result/enum.Result.html#variant.Ok
289            [`read`]: tymethod.read
290
291            ```no_run
292            # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
293            #
294            use async_std::io::prelude::*;
295            use async_std::fs::File;
296
297            let f = File::open("foo.txt").await?;
298            let mut buffer = [0; 5];
299
300            // read at most five bytes
301            let mut handle = f.take(5);
302
303            handle.read(&mut buffer).await?;
304            #
305            # Ok(()) }) }
306            ```
307        "#]
308        fn take(self, limit: u64) -> Take<Self>
309        where
310            Self: Sized,
311        {
312            Take { inner: self, limit }
313        }
314
315        #[doc = r#"
316            Creates a "by reference" adaptor for this instance of `Read`.
317
318            The returned adaptor also implements `Read` and will simply borrow this
319            current reader.
320
321            # Examples
322
323            [`File`][file]s implement `Read`:
324
325            [file]: ../fs/struct.File.html
326
327            ```no_run
328            # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
329            #
330            use async_std::prelude::*;
331            use async_std::fs::File;
332
333            let mut f = File::open("foo.txt").await?;
334            let mut buffer = Vec::new();
335            let mut other_buffer = Vec::new();
336
337            {
338                let reference = f.by_ref();
339
340                // read at most 5 bytes
341                reference.take(5).read_to_end(&mut buffer).await?;
342
343            } // drop our &mut reference so we can use f again
344
345            // original file still usable, read the rest
346            f.read_to_end(&mut other_buffer).await?;
347            #
348            # Ok(()) }) }
349            ```
350        "#]
351        fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
352
353
354        #[doc = r#"
355            Transforms this `Read` instance to a `Stream` over its bytes.
356
357            The returned type implements `Stream` where the `Item` is
358            `Result<u8, io::Error>`.
359            The yielded item is `Ok` if a byte was successfully read and `Err`
360            otherwise. EOF is mapped to returning `None` from this iterator.
361
362            # Examples
363
364            [`File`][file]s implement `Read`:
365
366            [file]: ../fs/struct.File.html
367
368            ```no_run
369            # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
370            #
371            use async_std::prelude::*;
372            use async_std::fs::File;
373
374            let f = File::open("foo.txt").await?;
375            let mut s = f.bytes();
376
377            while let Some(byte) = s.next().await {
378                println!("{}", byte.unwrap());
379            }
380            #
381            # Ok(()) }) }
382            ```
383        "#]
384        fn bytes(self) -> Bytes<Self> where Self: Sized {
385            Bytes { inner: self }
386        }
387
388        #[doc = r#"
389            Creates an adaptor which will chain this stream with another.
390
391            The returned `Read` instance will first read all bytes from this object
392            until EOF is encountered. Afterwards the output is equivalent to the
393            output of `next`.
394
395            # Examples
396
397            [`File`][file]s implement `Read`:
398
399            [file]: ../fs/struct.File.html
400
401            ```no_run
402            # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
403            #
404            use async_std::prelude::*;
405            use async_std::fs::File;
406
407            let f1 = File::open("foo.txt").await?;
408            let f2 = File::open("bar.txt").await?;
409
410            let mut handle = f1.chain(f2);
411            let mut buffer = String::new();
412
413            // read the value into a String. We could use any Read method here,
414            // this is just one example.
415            handle.read_to_string(&mut buffer).await?;
416            #
417            # Ok(()) }) }
418            ```
419        "#]
420        fn chain<R: Read>(self, next: R) -> Chain<Self, R> where Self: Sized {
421            Chain { first: self, second: next, done_first: false }
422        }
423
424    }
425
426    impl<T: Read + Unpin + ?Sized> Read for Box<T> {
427        fn poll_read(
428            self: Pin<&mut Self>,
429            cx: &mut Context<'_>,
430            buf: &mut [u8],
431        ) -> Poll<io::Result<usize>> {
432            unreachable!("this impl only appears in the rendered docs")
433        }
434    }
435
436    impl<T: Read + Unpin + ?Sized> Read for &mut T {
437        fn poll_read(
438            self: Pin<&mut Self>,
439            cx: &mut Context<'_>,
440            buf: &mut [u8],
441        ) -> Poll<io::Result<usize>> {
442            unreachable!("this impl only appears in the rendered docs")
443        }
444    }
445
446    impl<P> Read for Pin<P>
447    where
448        P: DerefMut + Unpin,
449        <P as Deref>::Target: Read,
450    {
451        fn poll_read(
452            self: Pin<&mut Self>,
453            cx: &mut Context<'_>,
454            buf: &mut [u8],
455        ) -> Poll<io::Result<usize>> {
456            unreachable!("this impl only appears in the rendered docs")
457        }
458    }
459
460    impl Read for &[u8] {
461        fn poll_read(
462            self: Pin<&mut Self>,
463            cx: &mut Context<'_>,
464            buf: &mut [u8],
465        ) -> Poll<io::Result<usize>> {
466            unreachable!("this impl only appears in the rendered docs")
467        }
468    }
469}
470
471/// Initializes a buffer if necessary.
472///
473/// Currently, a buffer is always initialized because `read_initializer`
474/// feature is not stable.
475#[inline]
476unsafe fn initialize<R: futures_io::AsyncRead>(_reader: &R, buf: &mut [u8]) {
477    std::ptr::write_bytes(buf.as_mut_ptr(), 0, buf.len())
478}
479
480#[cfg(test)]
481mod tests {
482    use crate::io;
483    use crate::prelude::*;
484
485    #[test]
486    fn test_read_by_ref() -> io::Result<()> {
487        crate::task::block_on( async move {
488            let mut f = io::Cursor::new(vec![0u8, 1, 2, 3, 4, 5, 6, 7, 8]);
489            let mut buffer = Vec::new();
490            let mut other_buffer = Vec::new();
491
492            {
493                let reference = f.by_ref();
494
495                // read at most 5 bytes
496                assert_eq!(reference.take(5).read_to_end(&mut buffer).await?, 5);
497                assert_eq!(&buffer, &[0, 1, 2, 3, 4])
498            } // drop our &mut reference so we can use f again
499
500            // original file still usable, read the rest
501            assert_eq!(f.read_to_end(&mut other_buffer).await?, 4);
502            assert_eq!(&other_buffer, &[5, 6, 7, 8]);
503            Ok(())
504        })
505    }
506}