compio_io/read/
managed.rs

1use std::io::Cursor;
2
3use compio_buf::IoBuf;
4
5use crate::IoResult;
6
7/// # AsyncReadManaged
8///
9/// Async read with buffer pool
10pub trait AsyncReadManaged {
11    /// Buffer pool type
12    type BufferPool;
13    /// Filled buffer type
14    type Buffer: IoBuf;
15
16    /// Read some bytes from this source with [`BufferPool`] and return
17    /// a [`Buffer`].
18    ///
19    /// If `len` == 0, will use [`BufferPool`] inner buffer size as the max len,
20    /// if `len` > 0, `min(len, inner buffer size)` will be the read max len
21    async fn read_managed(
22        &mut self,
23        buffer_pool: &Self::BufferPool,
24        len: usize,
25    ) -> IoResult<Self::Buffer>;
26}
27
28/// # AsyncReadAtManaged
29///
30/// Async read with buffer pool and position
31pub trait AsyncReadManagedAt {
32    /// Buffer pool type
33    type BufferPool;
34    /// Filled buffer type
35    type Buffer: IoBuf;
36
37    /// Read some bytes from this source at position with [`BufferPool`] and
38    /// return a [`Buffer`].
39    ///
40    /// If `len` == 0, will use [`BufferPool`] inner buffer size as the max len,
41    /// if `len` > 0, `min(len, inner buffer size)` will be the read max len
42    async fn read_managed_at(
43        &self,
44        pos: u64,
45        buffer_pool: &Self::BufferPool,
46        len: usize,
47    ) -> IoResult<Self::Buffer>;
48}
49
50impl<A: AsyncReadManagedAt> AsyncReadManaged for Cursor<A> {
51    type Buffer = A::Buffer;
52    type BufferPool = A::BufferPool;
53
54    async fn read_managed(
55        &mut self,
56        buffer_pool: &Self::BufferPool,
57        len: usize,
58    ) -> IoResult<Self::Buffer> {
59        let pos = self.position();
60        let buf = self
61            .get_ref()
62            .read_managed_at(pos, buffer_pool, len)
63            .await?;
64        self.set_position(pos + buf.buf_len() as u64);
65        Ok(buf)
66    }
67}