Skip to content

Commit

Permalink
feat(io): buffer pool IO traits (#356)
Browse files Browse the repository at this point in the history
* feat(io): buffer pool traits

* fix(io): name of Buffer

* feat(io): impl for Cursor

* feat(io): owned managed buffer

* feat(io): use IoBuf instead of Deref

Closes #365
  • Loading branch information
Berrysoft authored Dec 24, 2024
1 parent 9dc5210 commit 569a726
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
67 changes: 67 additions & 0 deletions compio-io/src/read/managed.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
use std::io::Cursor;

use compio_buf::IoBuf;

use crate::IoResult;

/// # AsyncReadManaged
///
/// Async read with buffer pool
pub trait AsyncReadManaged {
/// Buffer pool type
type BufferPool;
/// Filled buffer type
type Buffer: IoBuf;

/// Read some bytes from this source with [`BufferPool`] and return
/// a [`Buffer`].
///
/// If `len` == 0, will use [`BufferPool`] inner buffer size as the max len,
/// if `len` > 0, `min(len, inner buffer size)` will be the read max len
async fn read_managed(
&mut self,
buffer_pool: &Self::BufferPool,
len: usize,
) -> IoResult<Self::Buffer>;
}

/// # AsyncReadAtManaged
///
/// Async read with buffer pool and position
pub trait AsyncReadManagedAt {
/// Buffer pool type
type BufferPool;
/// Filled buffer type
type Buffer: IoBuf;

/// Read some bytes from this source at position with [`BufferPool`] and
/// return a [`Buffer`].
///
/// If `len` == 0, will use [`BufferPool`] inner buffer size as the max len,
/// if `len` > 0, `min(len, inner buffer size)` will be the read max len
async fn read_managed_at(
&self,
pos: u64,
buffer_pool: &Self::BufferPool,
len: usize,
) -> IoResult<Self::Buffer>;
}

impl<A: AsyncReadManagedAt> AsyncReadManaged for Cursor<A> {
type Buffer = A::Buffer;
type BufferPool = A::BufferPool;

async fn read_managed(
&mut self,
buffer_pool: &Self::BufferPool,
len: usize,
) -> IoResult<Self::Buffer> {
let pos = self.position();
let buf = self
.get_ref()
.read_managed_at(pos, buffer_pool, len)
.await?;
self.set_position(pos + buf.buf_len() as u64);
Ok(buf)
}
}
2 changes: 2 additions & 0 deletions compio-io/src/read/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ use compio_buf::{BufResult, IntoInner, IoBuf, IoBufMut, IoVectoredBufMut, buf_tr
mod buf;
#[macro_use]
mod ext;
mod managed;

pub use buf::*;
pub use ext::*;
pub use managed::*;

use crate::util::slice_to_buf;

Expand Down

0 comments on commit 569a726

Please sign in to comment.