async_hal/io/async_read.rs
1use super::Read;
2use core::{
3 pin::Pin,
4 task::{Context, Poll},
5};
6use void::Void;
7
8/// Read bytes asynchronously.
9pub trait AsyncRead {
10 type Error;
11
12 /// Attempt to read from the AsyncRead into buf.
13 /// On success, returns Poll::Ready(Ok(num_bytes_read)).
14 /// If no data is available for reading, this method returns Poll::Pending
15 /// and arranges for the current task to be woken.
16 fn poll_read(
17 self: Pin<&mut Self>,
18 cx: &mut Context,
19 buf: &mut [u8],
20 ) -> Poll<Result<usize, Self::Error>>;
21
22 /// Tries to read some bytes directly into the given `buf` in asynchronous
23 /// manner, returning a future type.
24 ///
25 /// The returned future will resolve to both the I/O stream and the buffer
26 /// as well as the number of bytes read once the read operation is completed.
27 /// ```
28 /// use async_hal::io::AsyncRead;
29 ///
30 /// let mut bytes = [1, 2, 3].as_ref();
31 /// let mut buf = [0; 3];
32 ///
33 /// # let fut = async {
34 /// bytes.read(&mut buf).await?;
35 /// # Ok::<_, void::Void>(())
36 /// # };
37 /// # futures::pin_mut!(fut);
38 /// # async_hal::block_on(fut, || {}).unwrap();
39 ///
40 /// assert_eq!([1, 2, 3], buf);
41 /// ```
42 fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> Read<'a, Self>
43 where
44 Self: Unpin,
45 {
46 Read::new(self, buf)
47 }
48}
49
50macro_rules! deref_async_read {
51 () => {
52 fn poll_read(
53 mut self: Pin<&mut Self>,
54 cx: &mut Context,
55 buf: &mut [u8],
56 ) -> Poll<Result<usize, Self::Error>> {
57 Pin::new(&mut **self).poll_read(cx, buf)
58 }
59 };
60}
61
62#[cfg(feature = "alloc")]
63impl<T: ?Sized + AsyncRead + Unpin> AsyncRead for Box<T> {
64 deref_async_read!();
65}
66
67impl<T: ?Sized + AsyncRead + Unpin> AsyncRead for &mut T {
68 type Error = T::Error;
69
70 deref_async_read!();
71}
72
73impl AsyncRead for &[u8] {
74 type Error = Void;
75
76 fn poll_read(
77 mut self: Pin<&mut Self>,
78 _cx: &mut Context,
79 buf: &mut [u8],
80 ) -> Poll<Result<usize, Void>> {
81 let amt = core::cmp::min(self.len(), buf.len());
82 let (a, b) = self.split_at(amt);
83 buf[..amt].copy_from_slice(a);
84 *self = b;
85 Poll::Ready(Ok(amt))
86 }
87}