use std::collections::BTreeSet;
use crate::traits::FiniteRelation;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UnaryRelation<T: Ord> {
values: BTreeSet<T>,
}
impl<T: Ord> UnaryRelation<T> {
#[must_use]
pub fn new() -> Self {
Self {
values: BTreeSet::new(),
}
}
#[must_use]
pub fn from_values<I>(values: I) -> Self
where
I: IntoIterator<Item = T>,
{
values.into_iter().collect()
}
#[must_use]
pub fn singleton(value: T) -> Self {
let mut values = BTreeSet::new();
values.insert(value);
Self { values }
}
pub fn insert(&mut self, value: T) -> bool {
self.values.insert(value)
}
#[must_use]
pub fn contains(&self, value: &T) -> bool {
self.values.contains(value)
}
pub fn iter(&self) -> impl Iterator<Item = &T> {
self.values.iter()
}
#[must_use]
pub fn union(&self, other: &Self) -> Self
where
T: Clone,
{
self.values.union(&other.values).cloned().collect()
}
#[must_use]
pub fn intersection(&self, other: &Self) -> Self
where
T: Clone,
{
self.values.intersection(&other.values).cloned().collect()
}
#[must_use]
pub fn difference(&self, other: &Self) -> Self
where
T: Clone,
{
self.values.difference(&other.values).cloned().collect()
}
#[must_use]
pub fn is_subset(&self, other: &Self) -> bool {
self.values.is_subset(&other.values)
}
#[must_use]
pub fn to_vec(&self) -> Vec<T>
where
T: Clone,
{
self.values.iter().cloned().collect()
}
}
impl<T: Ord> Default for UnaryRelation<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: Ord> FiniteRelation for UnaryRelation<T> {
fn len(&self) -> usize {
self.values.len()
}
}
impl<T: Ord> FromIterator<T> for UnaryRelation<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
Self {
values: iter.into_iter().collect(),
}
}
}
impl<T: Ord> Extend<T> for UnaryRelation<T> {
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
self.values.extend(iter);
}
}
impl<T: Ord> IntoIterator for UnaryRelation<T> {
type Item = T;
type IntoIter = std::collections::btree_set::IntoIter<T>;
fn into_iter(self) -> Self::IntoIter {
self.values.into_iter()
}
}
impl<'a, T: Ord> IntoIterator for &'a UnaryRelation<T> {
type Item = &'a T;
type IntoIter = std::collections::btree_set::Iter<'a, T>;
fn into_iter(self) -> Self::IntoIter {
self.values.iter()
}
}