mod access;
#[cfg(test)]
mod tests;
use super::{AllocationUsage, Error as MapError, Map, Range};
pub use access::{Participant, Read, Write};
use alloc::{alloc::Global, rc::Rc, vec::Vec};
use core::{alloc::Allocator, cell::RefCell, ops::Bound::Unbounded};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Root {
pub id: u64,
pub participant: u64,
pub schema: u64,
pub entries: usize,
pub key_bytes: usize,
pub value_bytes: usize,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Error {
Declaration,
Authority,
Claimed,
Busy,
Poisoned,
Collection(MapError),
}
impl From<MapError> for Error {
fn from(error: MapError) -> Self {
Self::Collection(error)
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum ExportError<E> {
Session(Error),
Pages(super::paged::ExportError<E>),
}
pub type RootMap<const K: usize, const V: usize, A = Global, P = A> = (Root, Map<K, V, A, P>);
pub struct AdmissionError<
const K: usize,
const V: usize,
A: Allocator + Clone,
P: Allocator + Clone,
> {
pub error: Error,
pub maps: Vec<RootMap<K, V, A, P>>,
}
impl<const K: usize, const V: usize, A: Allocator + Clone, P: Allocator + Clone> core::fmt::Debug
for AdmissionError<K, V, A, P>
{
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("AdmissionError")
.field("error", &self.error)
.finish_non_exhaustive()
}
}
struct State<const K: usize, const V: usize, A: Allocator + Clone, P: Allocator + Clone> {
maps: Vec<RootMap<K, V, A, P>>,
claimed: u64,
poisoned: bool,
}
type Shared<const K: usize, const V: usize, A, P> = Rc<RefCell<State<K, V, A, P>>>;
pub struct Session<
const K: usize,
const V: usize,
A: Allocator + Clone = Global,
P: Allocator + Clone = A,
> {
state: Shared<K, V, A, P>,
}
impl<const K: usize, const V: usize, A: Allocator + Clone, P: Allocator + Clone>
Session<K, V, A, P>
{
pub fn from_maps(
maps: Vec<RootMap<K, V, A, P>>,
expected: &[Root],
) -> Result<Self, AdmissionError<K, V, A, P>> {
let check = || {
if maps.is_empty() || maps.len() > 64 || maps.len() != expected.len() {
return Err(Error::Declaration);
}
let mut previous = 0;
for ((root, map), expected) in maps.iter().zip(expected) {
if root != expected
|| root.id <= previous
|| root.participant == 0
|| root.schema == 0
|| root.key_bytes > K
|| root.value_bytes > V
|| root.entries != map.limit
{
return Err(Error::Declaration);
}
map.healthy()?;
if root.key_bytes < K || root.value_bytes < V {
for (key, value) in Range::new(map, Unbounded, Unbounded) {
if key.as_slice().len() > root.key_bytes
|| value.as_slice().len() > root.value_bytes
{
return Err(Error::Collection(MapError::Limit));
}
}
}
previous = root.id;
}
Ok(())
};
if let Err(error) = check() {
return Err(AdmissionError { error, maps });
}
Ok(Self {
state: Rc::new(RefCell::new(State {
maps,
claimed: 0,
poisoned: false,
})),
})
}
pub fn take(&mut self, participant: u64) -> Result<Participant<K, V, A, P>, Error> {
let mut state = self.state.try_borrow_mut().map_err(|_| Error::Busy)?;
state.healthy()?;
let mask = state
.maps
.iter()
.enumerate()
.filter(|(_, (root, _))| root.participant == participant)
.fold(0, |mask, (index, _)| mask | (1u64 << index));
if mask == 0 {
return Err(Error::Authority);
}
if mask & state.claimed != 0 {
return Err(Error::Claimed);
}
state.claimed |= mask;
Ok(Participant {
state: self.state.clone(),
mask,
})
}
pub fn quarantine(&mut self) -> Result<(), Error> {
self.state
.try_borrow_mut()
.map_err(|_| Error::Busy)?
.poisoned = true;
Ok(())
}
pub fn into_maps(self) -> Result<Vec<RootMap<K, V, A, P>>, Self> {
if Rc::strong_count(&self.state) != 1 || self.state.borrow().poisoned {
return Err(self);
}
match Rc::try_unwrap(self.state) {
Ok(state) => Ok(state.into_inner().maps),
Err(state) => Err(Self { state }),
}
}
}
impl<const K: usize, const V: usize, A: Allocator + Clone, P: Allocator + Clone> State<K, V, A, P> {
fn healthy(&self) -> Result<(), Error> {
if self.poisoned {
Err(Error::Poisoned)
} else {
Ok(())
}
}
fn index(&self, mask: u64, root: u64) -> Result<usize, Error> {
self.maps
.iter()
.position(|(declaration, _)| declaration.id == root)
.filter(|&index| mask & (1u64 << index) != 0)
.ok_or(Error::Authority)
}
fn usage(&self, mask: u64, root: u64) -> Result<AllocationUsage, Error> {
Ok(self.maps[self.index(mask, root)?].1.allocation_usage()?)
}
}