use crate::avl::{Iter, Tree, WeakTree};
pub use crate::chunk::DEFAULT_SIZE;
use core::{
borrow::Borrow,
cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd},
default::Default,
fmt::{self, Debug, Formatter},
hash::{Hash, Hasher},
iter::FromIterator,
ops::{RangeBounds, RangeFull},
};
#[cfg(feature = "serde")]
use serde::{
de::{SeqAccess, Visitor},
ser::SerializeSeq,
Deserialize, Deserializer, Serialize, Serializer,
};
#[cfg(feature = "serde")]
use core::marker::PhantomData;
#[cfg(feature = "rayon")]
use rayon::{
iter::{FromParallelIterator, IntoParallelIterator},
prelude::*,
};
#[derive(Clone)]
pub struct Set<K: Ord + Clone, const SIZE: usize>(Tree<K, (), SIZE>);
pub type SetS<K> = Set<K, { DEFAULT_SIZE / 2 }>;
pub type SetM<K> = Set<K, DEFAULT_SIZE>;
pub type SetL<K> = Set<K, { DEFAULT_SIZE * 2 }>;
#[derive(Clone)]
pub struct WeakSetRef<K: Ord + Clone, const SIZE: usize>(WeakTree<K, (), SIZE>);
pub type WeakSetRefS<K> = WeakSetRef<K, 32>;
pub type WeakSetRefM<K> = WeakSetRef<K, 128>;
pub type WeakSetRefL<K> = WeakSetRef<K, 512>;
impl<K, const SIZE: usize> WeakSetRef<K, SIZE>
where
K: Ord + Clone,
{
pub fn upgrade(&self) -> Option<Set<K, SIZE>> {
self.0.upgrade().map(Set)
}
}
impl<K, const SIZE: usize> Hash for Set<K, SIZE>
where
K: Hash + Ord + Clone,
{
fn hash<H: Hasher>(&self, state: &mut H) {
self.0.hash(state)
}
}
impl<K, const SIZE: usize> Default for Set<K, SIZE>
where
K: Ord + Clone,
{
fn default() -> Set<K, SIZE> {
Set::new()
}
}
impl<K, const SIZE: usize> PartialEq for Set<K, SIZE>
where
K: Ord + Clone,
{
fn eq(&self, other: &Set<K, SIZE>) -> bool {
self.0 == other.0
}
}
impl<K, const SIZE: usize> Eq for Set<K, SIZE> where K: Eq + Ord + Clone {}
impl<K, const SIZE: usize> PartialOrd for Set<K, SIZE>
where
K: Ord + Clone,
{
fn partial_cmp(&self, other: &Set<K, SIZE>) -> Option<Ordering> {
self.0.partial_cmp(&other.0)
}
}
impl<K, const SIZE: usize> Ord for Set<K, SIZE>
where
K: Ord + Clone,
{
fn cmp(&self, other: &Set<K, SIZE>) -> Ordering {
self.0.cmp(&other.0)
}
}
impl<K, const SIZE: usize> Debug for Set<K, SIZE>
where
K: Debug + Ord + Clone,
{
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.debug_set().entries(self.into_iter()).finish()
}
}
impl<K, const SIZE: usize> FromIterator<K> for Set<K, SIZE>
where
K: Ord + Clone,
{
fn from_iter<T: IntoIterator<Item = K>>(iter: T) -> Self {
Set::new().insert_many(iter)
}
}
pub struct SetIter<
'a,
R: RangeBounds<Q> + 'a,
Q: Ord + ?Sized,
K: 'a + Clone + Ord + Borrow<Q>,
const SIZE: usize,
>(Iter<'a, R, Q, K, (), SIZE>);
impl<'a, R, Q, K, const SIZE: usize> Iterator for SetIter<'a, R, Q, K, SIZE>
where
Q: Ord + ?Sized,
R: RangeBounds<Q> + 'a,
K: 'a + Clone + Ord + Borrow<Q>,
{
type Item = &'a K;
fn next(&mut self) -> Option<Self::Item> {
self.0.next().map(|(k, ())| k)
}
}
impl<'a, R, Q, K, const SIZE: usize> DoubleEndedIterator for SetIter<'a, R, Q, K, SIZE>
where
Q: Ord + ?Sized,
R: RangeBounds<Q> + 'a,
K: 'a + Clone + Ord + Borrow<Q>,
{
fn next_back(&mut self) -> Option<Self::Item> {
self.0.next_back().map(|(k, ())| k)
}
}
impl<'a, K, const SIZE: usize> IntoIterator for &'a Set<K, SIZE>
where
K: 'a + Ord + Clone,
{
type Item = &'a K;
type IntoIter = SetIter<'a, RangeFull, K, K, SIZE>;
fn into_iter(self) -> Self::IntoIter {
SetIter(self.0.into_iter())
}
}
#[cfg(feature = "serde")]
impl<V, const SIZE: usize> Serialize for Set<V, SIZE>
where
V: Serialize + Clone + Ord,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_seq(Some(self.len()))?;
for v in self {
seq.serialize_element(v)?
}
seq.end()
}
}
#[cfg(feature = "serde")]
struct SetVisitor<V: Clone + Ord, const SIZE: usize> {
marker: PhantomData<fn() -> Set<V, SIZE>>,
}
#[cfg(feature = "serde")]
impl<'a, V, const SIZE: usize> Visitor<'a> for SetVisitor<V, SIZE>
where
V: Deserialize<'a> + Clone + Ord,
{
type Value = Set<V, SIZE>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("expecting an immutable_chunkmap::Set")
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'a>,
{
let mut t = Set::<V, SIZE>::new();
while let Some(v) = seq.next_element()? {
t.insert_cow(v);
}
Ok(t)
}
}
#[cfg(feature = "serde")]
impl<'a, V, const SIZE: usize> Deserialize<'a> for Set<V, SIZE>
where
V: Deserialize<'a> + Clone + Ord,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'a>,
{
deserializer.deserialize_seq(SetVisitor {
marker: PhantomData,
})
}
}
#[cfg(feature = "rayon")]
impl<'a, V, const SIZE: usize> IntoParallelIterator for &'a Set<V, SIZE>
where
V: 'a + Ord + Clone + Send + Sync,
{
type Item = &'a V;
type Iter = rayon::vec::IntoIter<&'a V>;
fn into_par_iter(self) -> Self::Iter {
self.into_iter().collect::<Vec<_>>().into_par_iter()
}
}
#[cfg(feature = "rayon")]
impl<V, const SIZE: usize> FromParallelIterator<V> for Set<V, SIZE>
where
V: Ord + Clone + Send + Sync,
{
fn from_par_iter<I>(i: I) -> Self
where
I: IntoParallelIterator<Item = V>,
{
i.into_par_iter()
.fold_with(Set::new(), |mut m, v| {
m.insert_cow(v);
m
})
.reduce_with(|m0, m1| m0.union(&m1))
.unwrap_or_else(Set::new)
}
}
impl<K, const SIZE: usize> Set<K, SIZE>
where
K: Ord + Clone,
{
pub fn new() -> Self {
Set(Tree::new())
}
pub fn downgrade(&self) -> WeakSetRef<K, SIZE> {
WeakSetRef(self.0.downgrade())
}
pub fn strong_count(&self) -> usize {
self.0.strong_count()
}
pub fn weak_count(&self) -> usize {
self.0.weak_count()
}
pub fn insert_many<E: IntoIterator<Item = K>>(&self, elts: E) -> Self {
let root = self.0.insert_many(elts.into_iter().map(|k| (k, ())));
Set(root)
}
pub fn remove_many<Q, E>(&self, elts: E) -> Self
where
Q: Ord,
K: Borrow<Q>,
E: IntoIterator<Item = Q>,
{
let root = self
.0
.update_many(elts.into_iter().map(|k| (k, ())), &mut |_, _, _| None);
Set(root)
}
pub fn update_many<Q, E, F>(&self, elts: E, mut f: F) -> Self
where
Q: Ord,
K: Borrow<Q>,
E: IntoIterator<Item = Q>,
F: FnMut(Q, Option<&K>) -> Option<K>,
{
let root =
self.0
.update_many(elts.into_iter().map(|k| (k, ())), &mut |q, (), cur| {
let cur = cur.map(|(k, ())| k);
f(q, cur).map(|k| (k, ()))
});
Set(root)
}
pub fn insert(&self, k: K) -> (Self, bool) {
if self.contains(&k) {
(self.clone(), true)
} else {
(Set(self.0.insert(k, ()).0), false)
}
}
pub fn insert_cow(&mut self, k: K) -> bool {
self.0.insert_cow(k, ()).is_some()
}
pub fn contains<'a, Q>(&'a self, k: &Q) -> bool
where
Q: ?Sized + Ord,
K: Borrow<Q>,
{
self.0.get(k).is_some()
}
pub fn get<'a, Q>(&'a self, k: &Q) -> Option<&'a K>
where
Q: ?Sized + Ord,
K: Borrow<Q>,
{
self.0.get_key(k)
}
pub fn remove<Q: Sized + Ord>(&self, k: &Q) -> (Self, bool)
where
K: Borrow<Q>,
{
let (t, prev) = self.0.remove(k);
(Set(t), prev.is_some())
}
pub fn remove_cow<Q: Sized + Ord>(&mut self, k: &Q) -> bool
where
K: Borrow<Q>,
{
self.0.remove_cow(k).is_some()
}
pub fn union(&self, other: &Set<K, SIZE>) -> Self {
Set(Tree::union(&self.0, &other.0, &mut |_, (), ()| Some(())))
}
pub fn intersect(&self, other: &Set<K, SIZE>) -> Self {
Set(Tree::intersect(
&self.0,
&other.0,
&mut |_, (), ()| Some(()),
))
}
pub fn diff(&self, other: &Set<K, SIZE>) -> Self
where
K: Debug,
{
Set(Tree::diff(&self.0, &other.0, &mut |_, (), ()| None))
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn range<'a, Q, R>(&'a self, r: R) -> SetIter<'a, R, Q, K, SIZE>
where
Q: Ord + ?Sized + 'a,
K: 'a + Clone + Ord + Borrow<Q>,
R: RangeBounds<Q> + 'a,
{
SetIter(self.0.range(r))
}
}
impl<K, const SIZE: usize> Set<K, SIZE>
where
K: Ord + Clone + Debug,
{
#[allow(dead_code)]
pub(crate) fn invariant(&self) -> () {
self.0.invariant()
}
}