use std::{num::NonZero, ptr};
use dope_sys::{
io::Close,
memory,
memory::{buffer, buffer::provided},
};
use o3::{
base::num::bounded,
buffer::{bytes::bounded::MAX, storage::provided::native},
};
use crate::reactor::{
buffers::{Cleanup, Create, Selected},
cq::Buffer,
mappings,
};
#[derive(Debug)]
pub struct Context<L: memory::raw::Receive> {
buffers: mappings::Buffer<u8>,
layout: L,
}
impl<L: memory::raw::Receive> provided::Context for Context<L> {
type Error = Create;
type Cleanup = Cleanup;
type Complete = Selected<L::Extent, <L::Extent as memory::raw::Extent>::Length>;
fn new(layout: L) -> Result<Self, Self::Error> {
let bytes = usize::from(layout.entries().get()) * layout.capacity().get() as usize;
let buffers = mappings::Buffer::allocate(bytes)?;
Ok(Self { buffers, layout })
}
}
impl<L: memory::raw::Receive> Context<L> {
pub(crate) fn into_region(self) -> mappings::Region {
self.buffers.into_region()
}
pub(in crate::reactor::buffers) fn as_ptr(&self) -> *const u8 {
self.buffers.as_ptr()
}
pub(super) fn prefix(&self, buffer: &<Self as provided::Context>::Complete) -> *mut [u8] {
let len: bounded::raw::U32<0, { MAX as u32 }> = buffer.len.into();
let address = native::raw::Context::buffer_ptr(self, buffer.index.0);
ptr::slice_from_raw_parts_mut(address, len.get() as usize)
}
}
impl<L: memory::raw::Receive> memory::Context for Context<L> {
type Layout = L;
fn layout(&self) -> L {
self.layout
}
}
unsafe impl<L: memory::raw::Receive> native::raw::Context for Context<L> {
fn resident(&self) -> NonZero<u32> {
self.layout.capacity()
}
fn buffer_ptr(&self, bid: u16) -> *mut u8 {
Buffer(bid)
.address(self.as_ptr(), self.layout.capacity())
.cast_mut()
}
}
impl<L: memory::raw::Receive> Close for Context<L> {
type State = <mappings::Buffer<u8> as Close>::State;
fn try_close(self) -> Result<(), Self::State> {
self.buffers.try_close()
}
}
impl<L: memory::raw::Receive>
buffer::raw::Context<Selected<L::Extent, <L::Extent as memory::raw::Extent>::Length>>
for Context<L>
{
unsafe fn bytes<'a>(
&'a self,
buffer: &'a Selected<L::Extent, <L::Extent as memory::raw::Extent>::Length>,
) -> &'a [u8] {
unsafe { &*self.prefix(buffer) }
}
}