use std::{io, marker::PhantomData, mem::ManuallyDrop};
pub use compio_driver::BorrowedBuffer;
use crate::Runtime;
#[derive(Debug)]
pub struct BufferPool {
inner: ManuallyDrop<compio_driver::BufferPool>,
runtime_id: u64,
_marker: PhantomData<*const ()>,
}
impl BufferPool {
pub fn new(buffer_len: u16, buffer_size: usize) -> io::Result<Self> {
let (inner, runtime_id) = Runtime::with_current(|runtime| {
let buffer_pool = runtime.create_buffer_pool(buffer_len, buffer_size)?;
let runtime_id = runtime.id();
io::Result::Ok((buffer_pool, runtime_id))
})?;
Ok(Self {
inner: ManuallyDrop::new(inner),
runtime_id,
_marker: Default::default(),
})
}
pub fn try_inner(&self) -> io::Result<&compio_driver::BufferPool> {
let current_runtime_id = Runtime::with_current(|runtime| runtime.id());
if current_runtime_id == self.runtime_id {
Ok(&self.inner)
} else {
Err(io::Error::other("runtime and buffer pool mismatch"))
}
}
}
impl Drop for BufferPool {
fn drop(&mut self) {
let _ = Runtime::try_with_current(|runtime| {
if self.runtime_id != runtime.id() {
return;
}
unsafe {
let inner = ManuallyDrop::take(&mut self.inner);
let _ = runtime.release_buffer_pool(inner);
}
});
}
}