compio_runtime/runtime/
buffer_pool.rs1use std::{io, marker::PhantomData, mem::ManuallyDrop};
4
5pub use compio_driver::BorrowedBuffer;
6
7use crate::Runtime;
8
9#[derive(Debug)]
16pub struct BufferPool {
17 inner: ManuallyDrop<compio_driver::BufferPool>,
18 runtime_id: u64,
19
20 _marker: PhantomData<*const ()>,
22}
23
24impl BufferPool {
25 pub fn new(buffer_len: u16, buffer_size: usize) -> io::Result<Self> {
32 let (inner, runtime_id) = Runtime::with_current(|runtime| {
33 let buffer_pool = runtime.create_buffer_pool(buffer_len, buffer_size)?;
34 let runtime_id = runtime.id();
35
36 io::Result::Ok((buffer_pool, runtime_id))
37 })?;
38
39 Ok(Self {
40 inner: ManuallyDrop::new(inner),
41 runtime_id,
42 _marker: Default::default(),
43 })
44 }
45
46 pub fn try_inner(&self) -> io::Result<&compio_driver::BufferPool> {
52 let current_runtime_id = Runtime::with_current(|runtime| runtime.id());
53 if current_runtime_id == self.runtime_id {
54 Ok(&self.inner)
55 } else {
56 Err(io::Error::other("runtime and buffer pool mismatch"))
57 }
58 }
59}
60
61impl Drop for BufferPool {
62 fn drop(&mut self) {
63 let _ = Runtime::try_with_current(|runtime| {
64 if self.runtime_id != runtime.id() {
65 return;
66 }
67
68 unsafe {
69 let inner = ManuallyDrop::take(&mut self.inner);
71
72 let _ = runtime.release_buffer_pool(inner);
74 }
75 });
76 }
77}