use std::ptr;
use dope_sys::{
io::Close,
memory,
memory::{buffer, buffer::provided},
};
use o3::{base::num::bounded, buffer::bytes::bounded::MAX};
use crate::reactor::{
buffers::{Cleanup, Create, Selected},
cq::Buffer,
mappings,
};
#[derive(Debug)]
pub struct Context<L: memory::raw::Receive> {
buffers: mappings::Mapping<u8>,
layout: L,
}
impl<L: memory::raw::Receive> provided::Context for Context<L> {
type Error = Create<L>;
type Cleanup = Cleanup<L>;
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::Mapping::allocate(bytes)?;
Ok(Self { buffers, layout })
}
}
impl<L: memory::raw::Receive> Context<L> {
pub unsafe fn project(&self, bid: u16, len: usize) -> &mut [u8] {
let address = Buffer(bid).address(self.as_ptr(), self.layout.capacity());
unsafe { &mut *ptr::slice_from_raw_parts_mut(address.cast_mut(), len) }
}
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::U32<0, { MAX as u32 }> = buffer.len.into();
let address = buffer.index.address(self.as_ptr(), self.layout.capacity());
ptr::slice_from_raw_parts_mut(address.cast_mut(), len.get() as usize)
}
}
impl<L: memory::raw::Receive> memory::Context for Context<L> {
type Layout = L;
fn layout(&self) -> L {
self.layout
}
}
impl<L: memory::raw::Receive> Close for Context<L> {
type State = <mappings::Mapping<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) }
}
}