use std::{
cmp::Ordering,
collections::BTreeSet,
fmt::Display,
ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Sub, SubAssign},
};
use crate::detail;
#[derive(Debug, Clone, PartialEq, Eq, Default, Hash)]
pub struct Set<T> {
data: BTreeSet<T>,
}
impl<T: Ord> Set<T> {
pub fn new() -> Self {
Self { data: BTreeSet::new() }
}
pub fn len(&self) -> usize {
self.data.len()
}
pub fn is_empty(&self) -> bool {
self.data.is_empty()
}
pub fn iter(&self) -> std::collections::btree_set::Iter<'_, T> {
self.data.iter()
}
pub fn find(&self, value: &T) -> Option<&T> {
self.data.iter().find(|&e| e == value)
}
pub fn contains(&self, value: &T) -> bool {
self.data.contains(value)
}
pub fn min(&self) -> Option<&T> {
self.data.first()
}
pub fn max(&self) -> Option<&T> {
self.data.last()
}
pub fn is_disjoint(&self, other: &Self) -> bool {
self.data.is_disjoint(&other.data)
}
pub fn add(&mut self, value: T) -> bool {
self.data.insert(value)
}
pub fn remove(&mut self, value: &T) -> bool {
self.data.remove(value)
}
pub fn pop(&mut self) -> Option<T> {
self.data.pop_first()
}
pub fn clear(&mut self) {
self.data.clear()
}
}
impl<T: Ord, const N: usize> From<[T; N]> for Set<T> {
fn from(value: [T; N]) -> Self {
Self { data: BTreeSet::from(value) }
}
}
impl<T: Ord> PartialOrd for Set<T> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
match (self.data.is_subset(&other.data), self.data.is_superset(&other.data)) {
(true, true) => Some(Ordering::Equal),
(true, false) => Some(Ordering::Less),
(false, true) => Some(Ordering::Greater),
(false, false) => None,
}
}
}
#[auto_impl_ops::auto_ops]
impl<T: Ord + Clone> BitAndAssign for Set<T> {
fn bitand_assign(&mut self, rhs: Self) {
self.data = &self.data & &rhs.data;
}
}
#[auto_impl_ops::auto_ops]
impl<T: Ord + Clone> BitOrAssign for Set<T> {
fn bitor_assign(&mut self, rhs: Self) {
self.data = &self.data | &rhs.data;
}
}
#[auto_impl_ops::auto_ops]
impl<T: Ord + Clone> BitXorAssign for Set<T> {
fn bitxor_assign(&mut self, rhs: Self) {
self.data = &self.data ^ &rhs.data;
}
}
#[auto_impl_ops::auto_ops]
impl<T: Ord + Clone> SubAssign for Set<T> {
fn sub_assign(&mut self, rhs: Self) {
self.data = &self.data - &rhs.data;
}
}
impl<T: Ord> Extend<T> for Set<T> {
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
self.data.extend(iter)
}
}
impl<T: Display> Display for Set<T> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
detail::print(f, self.data.iter(), '{', '}')
}
}
impl<T: Ord> FromIterator<T> for Set<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let data = iter.into_iter().collect();
Self { data }
}
}
impl<T> IntoIterator for Set<T> {
type Item = T;
type IntoIter = std::collections::btree_set::IntoIter<T>;
fn into_iter(self) -> Self::IntoIter {
self.data.into_iter()
}
}