use o3::alloc::{self, array};
use std::{cell, num::NonZero, ops, slice};
use crate::{
driver::{
route::{self, indices::SlotIndex, table::Capacity},
settings,
},
io::fd::domain::Index,
};
pub(super) mod outbound;
#[derive(Clone, Copy)]
struct Prefix {
mapped: u32,
allocated: u32,
}
#[derive(Clone, Copy)]
struct Lease {
start: u32,
len: NonZero<u32>,
state: State,
}
#[derive(Clone, Copy)]
enum State {
Live,
Retired(NonZero<u32>),
}
pub(in crate::io::fd::domain) struct Table {
mapping: array::raw::Block<cell::Cell<Index>, Capacity, cell::Cell<Prefix>>,
routes: [cell::Cell<Option<Lease>>; route::CAPACITY],
}
impl Lease {
fn range(self) -> ops::Range<u32> {
self.start..self.start + self.len.get()
}
}
impl Table {
pub(in crate::io::fd::domain) const fn capacity(&self) -> Capacity {
*self.mapping.extent()
}
pub(in crate::io::fd::domain) fn try_new(
layout: settings::FileSlots,
) -> Result<Self, alloc::Error> {
let start = layout.accept().raw();
let prefix = cell::Cell::new(Prefix {
mapped: 0,
allocated: 0,
});
let mapping = array::raw::Block::try_new(layout.outbound(), prefix)?.init(|offset| {
cell::Cell::new(Index(unsafe { SlotIndex::encode(start + offset as u32) }))
});
Ok(Self {
mapping,
routes: [const { cell::Cell::new(None) }; route::CAPACITY],
})
}
fn get<const LIVE: bool>(&self, owner: route::Id, local: SlotIndex) -> Option<Index> {
let lease = self.routes[owner.raw() as usize].get()?;
if LIVE && matches!(lease.state, State::Retired(_)) || local.raw() >= lease.len.get() {
return None;
}
let index = (lease.start + local.raw()) as usize;
Some(unsafe { self.mapping.get_unchecked(index) }.get())
}
fn span(&self, start: u32, end: u32) -> &[cell::Cell<Index>] {
unsafe { self.mapping.get_unchecked(start as usize..end as usize) }
}
fn rotate(&self, start: u32, middle: u32, end: u32) {
let left = (middle - start) as usize;
let right = (end - middle) as usize;
if left == 0 || right == 0 {
return;
}
let values = unsafe {
let cells = self.span(start, end);
slice::from_raw_parts_mut(cells.as_ptr().cast::<Index>().cast_mut(), cells.len())
};
values.rotate_left(left);
}
}
const _: () = {
assert!(size_of::<Lease>() == 3 * size_of::<u32>());
assert!(size_of::<Option<Lease>>() == size_of::<Lease>());
};