#![allow(dead_code)]
use std::collections::BTreeSet;
use std::fmt::{self, Display};
use parse::NextPrev;
#[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq)]
pub struct Range(pub char, pub char);
impl fmt::Display for Range {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})", self.0, self.1)
}
}
impl Range {
fn contains(&self, c: char) -> bool {
self.0 <= c && self.1 >= c
}
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Set(BTreeSet<Range>);
impl fmt::Display for Set {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let Set(ref set) = *self;
let len = BTreeSet::len(set);
for (count, s) in set.iter().enumerate() {
if count < len - 1 { try!(write!(f, "{}, ", s)) }
else { return write!(f, "{}", s) }
}
Ok(())
}
}
impl Set {
pub fn contains(&self, c: char) -> bool {
for range in &self.0 {
if range.contains(c) { return true }
}
false
}
pub fn new() -> Self { Set(BTreeSet::new()) }
pub fn insert(&mut self, value: Range) {
let mut ret = BTreeSet::new();
let mut subset = false;
{ let Set(ref set) = *self;
let Range(mut min_val, mut max_val) = value;
if min_val > max_val { panic!("First value cannot be greater than the second.") }
for &Range(min, max) in &*set {
if min_val < min && max_val >= min.prev() && max_val <= max { max_val = max }
else if min_val >= min && min_val <= max.next() && max_val > max { min_val = min }
else if min_val >= min && max_val <= max {
ret.insert(Range(min, max));
subset = true;
}
else if min_val < min && max_val > max {}
else { ret.insert(Range(min, max)); }
}
if !subset { ret.insert(Range(min_val, max_val)); }
}
*self = Set(ret);
}
pub fn is_empty(&self) -> bool { self.0.is_empty() }
pub fn remove(&mut self, value: Range) {
let mut ret = BTreeSet::new();
{ let Set(ref set) = *self;
let Range(min_val, max_val) = value;
if min_val > max_val { panic!("First value cannot be greater than the second.") }
for &Range(min, max) in &*set {
if min_val <= min && max_val >= min && max_val < max { ret.insert(Range(max_val.next(), max)); }
else if min_val > min && min_val <= max && max_val >= max { ret.insert(Range(min, min_val.prev())); }
else if min_val > min && max_val < max {
ret.insert(Range(min, min_val.prev()));
ret.insert(Range(max_val.next(), max));
break;
} else if min_val <= min && max_val >= max {}
else { ret.insert(Range(min, max)); }
}
}
*self = Set(ret)
}
pub fn union(&self, value: &Self) -> Self {
let mut ret = self.clone();
for &x in &value.0 { ret.insert(x) }
ret
}
pub fn intersection(&self, value: &Self) -> Self {
let diff = self.difference(value);
self.difference(&diff)
}
pub fn difference(&self, value: &Self) -> Self {
let mut ret = self.clone();
for &x in &value.0 { ret.remove(x) }
ret
}
pub fn symmetric_difference(&self, value: &Self) -> Self {
let union = self.union(value);
let intersection = self.intersection(value);
union.difference(&intersection)
}
}