use super::{Backing, Error, Rc, RefCell, State, Store, encode};
pub struct Participant<B: Backing> {
pub(super) state: Rc<RefCell<State<B>>>,
pub(super) mask: u8,
}
pub struct Read<'a, B: Backing> {
state: &'a State<B>,
mask: u8,
}
pub struct Write<'a, B: Backing> {
state: &'a mut State<B>,
mask: u8,
}
impl<B: Backing> Participant<B> {
pub fn read<R>(&self, operation: impl for<'a> FnOnce(Read<'a, B>) -> R) -> Result<R, Error> {
read(&self.state, self.mask, operation)
}
pub fn update<R>(
&mut self,
operation: impl for<'a> FnOnce(Write<'a, B>) -> R,
) -> Result<R, Error> {
update(&self.state, self.mask, operation)
}
}
impl<B: Backing> Store<B> {
fn grants(&self, participants: &[&Participant<B>]) -> Result<u8, Error> {
let mut mask = 0;
for participant in participants {
if !Rc::ptr_eq(&self.state, &participant.state) || mask & participant.mask != 0 {
return Err(Error::Authority);
}
mask |= participant.mask;
}
if mask == 0 {
return Err(Error::Authority);
}
Ok(mask)
}
pub fn read<R>(
&self,
participants: &[&Participant<B>],
operation: impl for<'a> FnOnce(Read<'a, B>) -> R,
) -> Result<R, Error> {
read(&self.state, self.grants(participants)?, operation)
}
pub fn update<R>(
&mut self,
participants: &[&Participant<B>],
operation: impl for<'a> FnOnce(Write<'a, B>) -> R,
) -> Result<R, Error> {
update(&self.state, self.grants(participants)?, operation)
}
}
fn read<B: Backing, R>(
state: &Rc<RefCell<State<B>>>,
mask: u8,
operation: impl for<'a> FnOnce(Read<'a, B>) -> R,
) -> Result<R, Error> {
let state = state.try_borrow().map_err(|_| Error::Busy)?;
if state.poisoned {
return Err(Error::Poisoned);
}
Ok(operation(Read {
state: &state,
mask,
}))
}
fn update<B: Backing, R>(
state: &Rc<RefCell<State<B>>>,
mask: u8,
operation: impl for<'a> FnOnce(Write<'a, B>) -> R,
) -> Result<R, Error> {
let mut state = state.try_borrow_mut().map_err(|_| Error::Busy)?;
if state.poisoned {
return Err(Error::Poisoned);
}
state.poisoned = true;
let result = operation(Write {
state: &mut state,
mask,
});
state.poisoned = false;
Ok(result)
}
fn index<B: Backing>(state: &State<B>, mask: u8, root: u64) -> Result<usize, Error> {
state
.slots
.iter()
.position(|slot| slot.root.id == root)
.filter(|&index| mask & (1 << index) != 0)
.ok_or(Error::Authority)
}
fn get<B: Backing>(state: &State<B>, mask: u8, root: u64) -> Result<&[u8], Error> {
let bytes = state.slots[index(state, mask, root)?].record.get();
Ok(&bytes[32..bytes.len() - 32])
}
impl<B: Backing> Read<'_, B> {
pub fn get(&self, root: u64) -> Result<&[u8], Error> {
get(self.state, self.mask, root)
}
}
impl<B: Backing> Write<'_, B> {
pub fn get(&self, root: u64) -> Result<&[u8], Error> {
get(self.state, self.mask, root)
}
pub fn set(&mut self, root: u64, value: &[u8]) -> Result<(), Error> {
let index = index(self.state, self.mask, root)?;
let slot = &mut self.state.slots[index];
let bytes = encode(slot.root, value)?;
slot.record.set(bytes).map_err(Error::Backing)
}
}