use std::ops::Deref;
use std::rc::Rc;
use std::cell::RefCell;
use std::fmt::{self, Debug};
use order::PartialOrder;
use progress::Timestamp;
use progress::count_map::CountMap;
pub struct Capability<T: Timestamp> {
time: T,
internal: Rc<RefCell<CountMap<T>>>,
}
impl<T: Timestamp> Capability<T> {
#[inline]
pub fn time(&self) -> &T {
&self.time
}
#[inline]
pub fn delayed(&self, new_time: &T) -> Capability<T> {
if !self.time.less_equal(new_time) {
panic!("Attempted to delay {:?} to {:?}, which is not `less_equal` the capability's time.", self, new_time);
}
mint(new_time.clone(), self.internal.clone())
}
#[inline]
pub fn downgrade(&mut self, new_time: &T) {
let new_cap = self.delayed(new_time);
*self = new_cap;
}
}
pub fn mint<T: Timestamp>(time: T, internal: Rc<RefCell<CountMap<T>>>) -> Capability<T> {
internal.borrow_mut().update(&time, 1);
Capability {
time: time,
internal: internal
}
}
impl<T: Timestamp> Drop for Capability<T> {
fn drop(&mut self) {
self.internal.borrow_mut().update(&self.time, -1);
}
}
impl<T: Timestamp> Clone for Capability<T> {
fn clone(&self) -> Capability<T> {
mint(self.time.clone(), self.internal.clone())
}
}
impl<T: Timestamp> Deref for Capability<T> {
type Target = T;
fn deref(&self) -> &T {
&self.time
}
}
impl<T: Timestamp> Debug for Capability<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Capability {{ time: {:?}, internal: ... }}", self.time)
}
}
impl<T: Timestamp> PartialEq for Capability<T> {
fn eq(&self, other: &Self) -> bool {
self.time() == other.time() && Rc::ptr_eq(&self.internal, &other.internal)
}
}
impl<T: Timestamp> Eq for Capability<T> { }
impl<T: Timestamp> PartialOrder for Capability<T> {
fn less_equal(&self, other: &Self) -> bool {
self.time().less_equal(other.time()) && Rc::ptr_eq(&self.internal, &other.internal)
}
}
pub struct CapabilitySet<T: Timestamp> {
elements: Vec<Capability<T>>,
}
impl<T: Timestamp> CapabilitySet<T> {
pub fn new() -> Self {
CapabilitySet { elements: Vec::new() }
}
pub fn insert(&mut self, capability: Capability<T>) {
if !self.elements.iter().any(|c| c.less_equal(&capability)) {
self.elements.retain(|c| !capability.less_equal(c));
self.elements.push(capability);
}
}
pub fn delayed(&self, time: &T) -> Capability<T> {
self.elements.iter().find(|c| c.time().less_equal(time)).unwrap().delayed(time)
}
pub fn downgrade(&mut self, frontier: &[T]) {
let count = self.elements.len();
for time in frontier.iter() {
let capability = self.delayed(time);
self.elements.push(capability);
}
self.elements.drain(..count);
}
}