Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(io): buffer pool IO traits #356

Merged
merged 5 commits into from
Dec 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading