compio_io/read/
managed.rs

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