use std::sync::Arc;
use super::{Outcome, Stm, TRef};
#[derive(Clone)]
pub struct TArray<A> {
cells: Arc<[TRef<A>]>,
}
impl<A> TArray<A>
where
A: Clone + Send + Sync + 'static,
{
pub fn make(values: Vec<A>) -> Stm<TArray<A>, ()> {
Stm::from_fn(move |_| {
Outcome::Done(TArray {
cells: values.iter().cloned().map(TRef::new).collect(),
})
})
}
pub fn len(&self) -> usize {
self.cells.len()
}
pub fn is_empty(&self) -> bool {
self.cells.is_empty()
}
pub fn cell(&self, index: usize) -> Option<&TRef<A>> {
self.cells.get(index)
}
pub fn get<E: Send + 'static>(&self, index: usize) -> Stm<Option<A>, E> {
let a = self.clone();
Stm::from_fn(move |txn| Outcome::Done(a.cells.get(index).map(|c| c.read_txn(txn))))
}
pub fn set<E: Send + 'static>(&self, index: usize, value: A) -> Stm<bool, E> {
let a = self.clone();
Stm::from_fn(move |txn| match a.cells.get(index) {
Some(c) => {
c.set_txn(txn, value.clone());
Outcome::Done(true)
}
None => Outcome::Done(false),
})
}
pub fn update<E, F>(&self, index: usize, f: F) -> Stm<bool, E>
where
E: Send + 'static,
F: Fn(A) -> A + Send + Sync + 'static,
{
let a = self.clone();
Stm::from_fn(move |txn| match a.cells.get(index) {
Some(c) => {
let cur = c.read_txn(txn);
c.set_txn(txn, f(cur));
Outcome::Done(true)
}
None => Outcome::Done(false),
})
}
pub fn to_vec<E: Send + 'static>(&self) -> Stm<Vec<A>, E> {
let a = self.clone();
Stm::from_fn(move |txn| Outcome::Done(a.cells.iter().map(|c| c.read_txn(txn)).collect()))
}
pub fn fold<B, E, F>(&self, init: B, f: F) -> Stm<B, E>
where
B: Clone + Send + Sync + 'static,
E: Send + 'static,
F: Fn(B, A) -> B + Send + Sync + 'static,
{
let a = self.clone();
Stm::from_fn(move |txn| {
let mut acc = init.clone();
for c in a.cells.iter() {
acc = f(acc, c.read_txn(txn));
}
Outcome::Done(acc)
})
}
}