compio_io/read/
mod.rs

1#[cfg(feature = "allocator_api")]
2use std::alloc::Allocator;
3use std::{io::Cursor, ops::DerefMut, rc::Rc, sync::Arc};
4
5use compio_buf::{BufResult, IntoInner, IoBuf, IoBufMut, IoVectoredBufMut, buf_try, t_alloc};
6
7mod buf;
8#[macro_use]
9mod ext;
10mod managed;
11
12pub use buf::*;
13pub use ext::*;
14pub use managed::*;
15
16use crate::util::slice_to_buf;
17
18/// AsyncRead
19///
20/// Async read with a ownership of a buffer
21pub trait AsyncRead {
22    /// Read some bytes from this source into the [`IoBufMut`] buffer and return
23    /// a [`BufResult`], consisting of the buffer and a [`usize`] indicating
24    /// how many bytes were read.
25    ///
26    /// # Caution
27    /// - This function read data to the **beginning** of the buffer; that is,
28    ///   all existing data in the buffer will be overwritten. To read data to
29    ///   the end of the buffer, use [`AsyncReadExt::append`].
30    /// - Implementor **MUST** update the buffer init via
31    ///   [`SetBufInit::set_buf_init`] after reading, and no further update
32    ///   should be made by caller.
33    ///
34    /// [`SetBufInit::set_buf_init`]: compio_buf::SetBufInit::set_buf_init
35    async fn read<B: IoBufMut>(&mut self, buf: B) -> BufResult<usize, B>;
36
37    /// Like `read`, except that it reads into a type implements
38    /// [`IoVectoredBufMut`].
39    ///
40    /// The default implementation will try to read into the buffers in order,
41    /// and stop whenever the reader returns an error, `Ok(0)`, or a length
42    /// less than the length of the buf passed in, meaning it's possible that
43    /// not all buffer space is filled. If guaranteed full read is desired,
44    /// it is recommended to use [`AsyncReadExt::read_vectored_exact`]
45    /// instead.
46    ///
47    /// # Caution
48    ///
49    /// Implementor **MUST** update the buffer init via
50    /// [`SetBufInit::set_buf_init`] after reading.
51    ///
52    /// [`SetBufInit::set_buf_init`]: compio_buf::SetBufInit::set_buf_init
53    async fn read_vectored<V: IoVectoredBufMut>(&mut self, buf: V) -> BufResult<usize, V> {
54        loop_read_vectored!(buf, iter, self.read(iter))
55    }
56}
57
58impl<A: AsyncRead + ?Sized> AsyncRead for &mut A {
59    #[inline(always)]
60    async fn read<T: IoBufMut>(&mut self, buf: T) -> BufResult<usize, T> {
61        (**self).read(buf).await
62    }
63
64    #[inline(always)]
65    async fn read_vectored<T: IoVectoredBufMut>(&mut self, buf: T) -> BufResult<usize, T> {
66        (**self).read_vectored(buf).await
67    }
68}
69
70impl<R: AsyncRead + ?Sized, #[cfg(feature = "allocator_api")] A: Allocator> AsyncRead
71    for t_alloc!(Box, R, A)
72{
73    #[inline(always)]
74    async fn read<T: IoBufMut>(&mut self, buf: T) -> BufResult<usize, T> {
75        (**self).read(buf).await
76    }
77
78    #[inline(always)]
79    async fn read_vectored<T: IoVectoredBufMut>(&mut self, buf: T) -> BufResult<usize, T> {
80        (**self).read_vectored(buf).await
81    }
82}
83
84impl AsyncRead for &[u8] {
85    #[inline]
86    async fn read<T: IoBufMut>(&mut self, mut buf: T) -> BufResult<usize, T> {
87        let len = slice_to_buf(self, &mut buf);
88        *self = &self[len..];
89        BufResult(Ok(len), buf)
90    }
91
92    async fn read_vectored<T: IoVectoredBufMut>(&mut self, mut buf: T) -> BufResult<usize, T> {
93        let mut this = *self; // An immutable slice to track the read position
94
95        for mut buf in buf.iter_buf_mut() {
96            let n = slice_to_buf(this, buf.deref_mut());
97            this = &this[n..];
98            if this.is_empty() {
99                break;
100            }
101        }
102
103        let len = self.len() - this.len();
104        *self = this;
105
106        BufResult(Ok(len), buf)
107    }
108}
109
110/// # AsyncReadAt
111///
112/// Async read with a ownership of a buffer and a position
113pub trait AsyncReadAt {
114    /// Like [`AsyncRead::read`], except that it reads at a specified position.
115    async fn read_at<T: IoBufMut>(&self, buf: T, pos: u64) -> BufResult<usize, T>;
116
117    /// Like [`AsyncRead::read_vectored`], except that it reads at a specified
118    /// position.
119    async fn read_vectored_at<T: IoVectoredBufMut>(&self, buf: T, pos: u64) -> BufResult<usize, T> {
120        loop_read_vectored!(buf, iter, self.read_at(iter, pos))
121    }
122}
123
124macro_rules! impl_read_at {
125    (@ptr $($ty:ty),*) => {
126        $(
127            impl<A: AsyncReadAt + ?Sized> AsyncReadAt for $ty {
128                async fn read_at<T: IoBufMut>(&self, buf: T, pos: u64) -> BufResult<usize, T> {
129                    (**self).read_at(buf, pos).await
130                }
131
132                async fn read_vectored_at<T: IoVectoredBufMut>(&self, buf: T, pos: u64) -> BufResult<usize, T> {
133                    (**self).read_vectored_at(buf, pos).await
134                }
135            }
136        )*
137    };
138
139    (@ptra $($ty:ident),*) => {
140        $(
141            #[cfg(feature = "allocator_api")]
142            impl<R: AsyncReadAt + ?Sized, A: Allocator> AsyncReadAt for $ty<R, A> {
143                async fn read_at<T: IoBufMut>(&self, buf: T, pos: u64) -> BufResult<usize, T> {
144                    (**self).read_at(buf, pos).await
145                }
146
147                async fn read_vectored_at<T: IoVectoredBufMut>(&self, buf: T, pos: u64) -> BufResult<usize, T> {
148                    (**self).read_vectored_at(buf, pos).await
149                }
150            }
151            #[cfg(not(feature = "allocator_api"))]
152            impl_read_at!(@ptr $ty<A>);
153        )*
154    };
155
156    (@slice $($(const $len:ident =>)? $ty:ty), *) => {
157        $(
158            impl<$(const $len: usize)?> AsyncReadAt for $ty {
159                async fn read_at<T: IoBufMut>(&self, mut buf: T, pos: u64) -> BufResult<usize, T> {
160                    let pos = pos.min(self.len() as u64);
161                    let len = slice_to_buf(&self[pos as usize..], &mut buf);
162                    BufResult(Ok(len), buf)
163                }
164
165                async fn read_vectored_at<T:IoVectoredBufMut>(&self, mut buf: T, pos: u64) -> BufResult<usize, T> {
166                    let slice = &self[pos as usize..];
167                    let mut this = slice;
168
169                    for mut buf in buf.iter_buf_mut() {
170                        let n = slice_to_buf(this, buf.deref_mut());
171                        this = &this[n..];
172                        if this.is_empty() {
173                            break;
174                        }
175                    }
176
177                    BufResult(Ok(slice.len() - this.len()), buf)
178                }
179            }
180        )*
181    }
182}
183
184impl_read_at!(@ptr &A, &mut A);
185impl_read_at!(@ptra Box, Rc, Arc);
186impl_read_at!(@slice [u8], const LEN => [u8; LEN]);
187
188impl<#[cfg(feature = "allocator_api")] A: Allocator> AsyncReadAt for t_alloc!(Vec, u8, A) {
189    async fn read_at<T: IoBufMut>(&self, buf: T, pos: u64) -> BufResult<usize, T> {
190        self.as_slice().read_at(buf, pos).await
191    }
192
193    async fn read_vectored_at<T: IoVectoredBufMut>(&self, buf: T, pos: u64) -> BufResult<usize, T> {
194        self.as_slice().read_vectored_at(buf, pos).await
195    }
196}
197
198impl<A: AsyncReadAt> AsyncRead for Cursor<A> {
199    #[inline]
200    async fn read<T: IoBufMut>(&mut self, buf: T) -> BufResult<usize, T> {
201        let pos = self.position();
202        let (n, buf) = buf_try!(self.get_ref().read_at(buf, pos).await);
203        self.set_position(pos + n as u64);
204        BufResult(Ok(n), buf)
205    }
206
207    #[inline]
208    async fn read_vectored<T: IoVectoredBufMut>(&mut self, buf: T) -> BufResult<usize, T> {
209        let pos = self.position();
210        let (n, buf) = buf_try!(self.get_ref().read_vectored_at(buf, pos).await);
211        self.set_position(pos + n as u64);
212        BufResult(Ok(n), buf)
213    }
214}