1use alloc::{
21 borrow::{
22 Borrow,
23 ToOwned,
24 },
25 collections::btree_set,
26 fmt::{
27 Debug,
28 Error,
29 Formatter,
30 },
31 vec::Vec,
32};
33
34use core::{
35 cmp::Ordering,
36 hash::{
37 Hash,
38 Hasher,
39 },
40 iter::{
41 FromIterator,
42 IntoIterator,
43 Sum,
44 },
45 ops::{
46 Add,
47 Deref,
48 Mul,
49 RangeBounds,
50 },
51};
52
53#[cfg(has_specialisation)]
54use crate::util::linear_search_by;
55use crate::{
56 nodes::btree::{
57 BTreeValue,
58 ConsumingIter as ConsumingNodeIter,
59 DiffIter as NodeDiffIter,
60 Insert,
61 Iter as NodeIter,
62 Node,
63 Remove,
64 },
65 util::{
66 Pool,
67 PoolRef,
68 },
69};
70
71pub use crate::nodes::btree::DiffItem;
72
73#[macro_export]
85macro_rules! ordset {
86 () => { $crate::ordset::OrdSet::new() };
87
88 ( $($x:expr),* ) => {{
89 let mut l = $crate::ordset::OrdSet::new();
90 $(
91 l.insert($x);
92 )*
93 l
94 }};
95}
96
97#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
98struct Value<A>(A);
99
100impl<A> Deref for Value<A> {
101 type Target = A;
102
103 fn deref(&self) -> &Self::Target { &self.0 }
104}
105
106#[cfg(not(has_specialisation))]
109impl<A: Ord> BTreeValue for Value<A> {
110 type Key = A;
111
112 fn ptr_eq(&self, _other: &Self) -> bool { false }
113
114 fn search_key<BK>(slice: &[Self], key: &BK) -> Result<usize, usize>
115 where
116 BK: Ord + ?Sized,
117 Self::Key: Borrow<BK>, {
118 slice.binary_search_by(|value| Self::Key::borrow(value).cmp(key))
119 }
120
121 fn search_value(slice: &[Self], key: &Self) -> Result<usize, usize> {
122 slice.binary_search_by(|value| value.cmp(key))
123 }
124
125 fn cmp_keys<BK>(&self, other: &BK) -> Ordering
126 where
127 BK: Ord + ?Sized,
128 Self::Key: Borrow<BK>, {
129 Self::Key::borrow(self).cmp(other)
130 }
131
132 fn cmp_values(&self, other: &Self) -> Ordering { self.cmp(other) }
133}
134
135#[cfg(has_specialisation)]
136impl<A: Ord> BTreeValue for Value<A> {
137 type Key = A;
138
139 fn ptr_eq(&self, _other: &Self) -> bool { false }
140
141 default fn search_key<BK>(slice: &[Self], key: &BK) -> Result<usize, usize>
142 where
143 BK: Ord + ?Sized,
144 Self::Key: Borrow<BK>, {
145 slice.binary_search_by(|value| Self::Key::borrow(value).cmp(key))
146 }
147
148 default fn search_value(slice: &[Self], key: &Self) -> Result<usize, usize> {
149 slice.binary_search_by(|value| value.cmp(key))
150 }
151
152 fn cmp_keys<BK>(&self, other: &BK) -> Ordering
153 where
154 BK: Ord + ?Sized,
155 Self::Key: Borrow<BK>, {
156 Self::Key::borrow(self).cmp(other)
157 }
158
159 fn cmp_values(&self, other: &Self) -> Ordering { self.cmp(other) }
160}
161
162#[cfg(has_specialisation)]
163impl<A: Ord + Copy> BTreeValue for Value<A> {
164 fn search_key<BK>(slice: &[Self], key: &BK) -> Result<usize, usize>
165 where
166 BK: Ord + ?Sized,
167 Self::Key: Borrow<BK>, {
168 linear_search_by(slice, |value| Self::Key::borrow(value).cmp(key))
169 }
170
171 fn search_value(slice: &[Self], key: &Self) -> Result<usize, usize> {
172 linear_search_by(slice, |value| value.cmp(key))
173 }
174}
175
176def_pool!(OrdSetPool<A>, Node<Value<A>>);
177
178pub struct OrdSet<A> {
193 size: usize,
194 pool: OrdSetPool<A>,
195 root: PoolRef<Node<Value<A>>>,
196}
197
198impl<A> OrdSet<A> {
199 #[must_use]
201 pub fn new() -> Self {
202 let pool = OrdSetPool::default();
203 let root = PoolRef::default(&pool.0);
204 OrdSet { size: 0, pool, root }
205 }
206
207 #[cfg(feature = "pool")]
209 #[must_use]
210 pub fn with_pool(pool: &OrdSetPool<A>) -> Self {
211 let root = PoolRef::default(&pool.0);
212 OrdSet { size: 0, pool: pool.clone(), root }
213 }
214
215 #[inline]
226 #[must_use]
227 pub fn unit(a: A) -> Self {
228 let pool = OrdSetPool::default();
229 let root = PoolRef::new(&pool.0, Node::unit(Value(a)));
230 OrdSet { size: 1, pool, root }
231 }
232
233 #[inline]
246 #[must_use]
247 pub fn is_empty(&self) -> bool { self.len() == 0 }
248
249 #[inline]
261 #[must_use]
262 pub fn len(&self) -> usize { self.size }
263
264 pub fn ptr_eq(&self, other: &Self) -> bool {
274 core::ptr::eq(self, other) || PoolRef::ptr_eq(&self.root, &other.root)
275 }
276
277 #[cfg(feature = "pool")]
282 pub fn pool(&self) -> &OrdSetPool<A> { &self.pool }
283
284 pub fn clear(&mut self) {
301 if !self.is_empty() {
302 self.root = PoolRef::default(&self.pool.0);
303 self.size = 0;
304 }
305 }
306}
307
308impl<A> OrdSet<A>
309where A: Ord
310{
311 #[must_use]
317 pub fn get_min(&self) -> Option<&A> { self.root.min().map(Deref::deref) }
318
319 #[must_use]
325 pub fn get_max(&self) -> Option<&A> { self.root.max().map(Deref::deref) }
326
327 #[must_use]
329 pub fn iter(&self) -> Iter<'_, A> {
330 Iter { it: NodeIter::new(&self.root, self.size, ..) }
331 }
332
333 #[must_use]
335 pub fn range<R, BA>(&self, range: R) -> RangedIter<'_, A>
336 where
337 R: RangeBounds<BA>,
338 A: Borrow<BA>,
339 BA: Ord + ?Sized, {
340 RangedIter { it: NodeIter::new(&self.root, self.size, range) }
341 }
342
343 #[must_use]
355 pub fn diff<'a>(&'a self, other: &'a Self) -> DiffIter<'_, A> {
356 DiffIter { it: NodeDiffIter::new(&self.root, &other.root) }
357 }
358
359 #[inline]
373 #[must_use]
374 pub fn contains<BA>(&self, a: &BA) -> bool
375 where
376 BA: Ord + ?Sized,
377 A: Borrow<BA>, {
378 self.root.lookup(a).is_some()
379 }
380
381 #[must_use]
397 pub fn get_prev(&self, key: &A) -> Option<&A> {
398 self.root.lookup_prev(key).map(|v| &v.0)
399 }
400
401 #[must_use]
417 pub fn get_next(&self, key: &A) -> Option<&A> {
418 self.root.lookup_next(key).map(|v| &v.0)
419 }
420
421 #[must_use]
426 pub fn is_subset<RS>(&self, other: RS) -> bool
427 where RS: Borrow<Self> {
428 let other = other.borrow();
429 if other.len() < self.len() {
430 return false;
431 }
432 self.iter().all(|a| other.contains(&a))
433 }
434
435 #[must_use]
441 pub fn is_proper_subset<RS>(&self, other: RS) -> bool
442 where RS: Borrow<Self> {
443 self.len() != other.borrow().len() && self.is_subset(other)
444 }
445}
446
447impl<A> OrdSet<A>
448where A: Ord + Clone
449{
450 #[inline]
465 pub fn insert(&mut self, a: A) -> Option<A> {
466 let new_root = {
467 let root = PoolRef::make_mut(&self.pool.0, &mut self.root);
468 match root.insert(&self.pool.0, Value(a)) {
469 Insert::Replaced(Value(old_value)) => return Some(old_value),
470 Insert::Added => {
471 self.size += 1;
472 return None;
473 }
474 Insert::Split(left, median, right) => PoolRef::new(
475 &self.pool.0,
476 Node::new_from_split(&self.pool.0, left, median, right),
477 ),
478 }
479 };
480 self.size += 1;
481 self.root = new_root;
482 None
483 }
484
485 #[inline]
489 pub fn remove<BA>(&mut self, a: &BA) -> Option<A>
490 where
491 BA: Ord + ?Sized,
492 A: Borrow<BA>, {
493 let (new_root, removed_value) = {
494 let root = PoolRef::make_mut(&self.pool.0, &mut self.root);
495 match root.remove(&self.pool.0, a) {
496 Remove::Update(value, root) => {
497 (PoolRef::new(&self.pool.0, root), Some(value.0))
498 }
499 Remove::Removed(value) => {
500 self.size -= 1;
501 return Some(value.0);
502 }
503 Remove::NoChange => return None,
504 }
505 };
506 self.size -= 1;
507 self.root = new_root;
508 removed_value
509 }
510
511 pub fn remove_min(&mut self) -> Option<A> {
515 let key = match self.get_min() {
517 None => return None,
518 Some(v) => v,
519 }
520 .clone();
521 self.remove(&key)
522 }
523
524 pub fn remove_max(&mut self) -> Option<A> {
528 let key = match self.get_max() {
530 None => return None,
531 Some(v) => v,
532 }
533 .clone();
534 self.remove(&key)
535 }
536
537 #[must_use]
551 pub fn update(&self, a: A) -> Self {
552 let mut out = self.clone();
553 out.insert(a);
554 out
555 }
556
557 #[must_use]
562 pub fn without<BA>(&self, a: &BA) -> Self
563 where
564 BA: Ord + ?Sized,
565 A: Borrow<BA>, {
566 let mut out = self.clone();
567 out.remove(a);
568 out
569 }
570
571 #[must_use]
576 pub fn without_min(&self) -> (Option<A>, Self) {
577 match self.get_min() {
578 Some(v) => (Some(v.clone()), self.without(&v)),
579 None => (None, self.clone()),
580 }
581 }
582
583 #[must_use]
588 pub fn without_max(&self) -> (Option<A>, Self) {
589 match self.get_max() {
590 Some(v) => (Some(v.clone()), self.without(&v)),
591 None => (None, self.clone()),
592 }
593 }
594
595 #[must_use]
610 pub fn union(mut self, other: Self) -> Self {
611 for value in other {
612 self.insert(value);
613 }
614 self
615 }
616
617 #[must_use]
621 pub fn unions<I>(i: I) -> Self
622 where I: IntoIterator<Item = Self> {
623 i.into_iter().fold(Self::default(), Self::union)
624 }
625
626 #[must_use]
646 pub fn difference(self, other: Self) -> Self {
647 self.symmetric_difference(other)
648 }
649
650 #[must_use]
665 pub fn symmetric_difference(mut self, other: Self) -> Self {
666 for value in other {
667 if self.remove(&value).is_none() {
668 self.insert(value);
669 }
670 }
671 self
672 }
673
674 #[must_use]
690 pub fn relative_complement(mut self, other: Self) -> Self {
691 for value in other {
692 let _ = self.remove(&value);
693 }
694 self
695 }
696
697 #[must_use]
712 pub fn intersection(self, other: Self) -> Self {
713 let mut out = Self::default();
714 for value in other {
715 if self.contains(&value) {
716 out.insert(value);
717 }
718 }
719 out
720 }
721
722 #[must_use]
730 pub fn split<BA>(self, split: &BA) -> (Self, Self)
731 where
732 BA: Ord + ?Sized,
733 A: Borrow<BA>, {
734 let (left, _, right) = self.split_member(split);
735 (left, right)
736 }
737
738 #[must_use]
748 pub fn split_member<BA>(self, split: &BA) -> (Self, bool, Self)
749 where
750 BA: Ord + ?Sized,
751 A: Borrow<BA>, {
752 let mut left = Self::default();
753 let mut right = Self::default();
754 let mut present = false;
755 for value in self {
756 match value.borrow().cmp(split) {
757 Ordering::Less => {
758 left.insert(value);
759 }
760 Ordering::Equal => {
761 present = true;
762 }
763 Ordering::Greater => {
764 right.insert(value);
765 }
766 }
767 }
768 (left, present, right)
769 }
770
771 #[must_use]
776 pub fn take(&self, n: usize) -> Self {
777 self.iter().take(n).cloned().collect()
778 }
779
780 #[must_use]
785 pub fn skip(&self, n: usize) -> Self {
786 self.iter().skip(n).cloned().collect()
787 }
788}
789
790impl<A> Clone for OrdSet<A> {
793 #[inline]
797 fn clone(&self) -> Self {
798 OrdSet { size: self.size, pool: self.pool.clone(), root: self.root.clone() }
799 }
800}
801
802impl<A: Ord> PartialEq for OrdSet<A> {
803 fn eq(&self, other: &Self) -> bool {
804 PoolRef::ptr_eq(&self.root, &other.root)
805 || (self.len() == other.len() && self.diff(other).next().is_none())
806 }
807}
808
809impl<A: Ord + Eq> Eq for OrdSet<A> {}
810
811impl<A: Ord> PartialOrd for OrdSet<A> {
812 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
813 self.iter().partial_cmp(other.iter())
814 }
815}
816
817impl<A: Ord> Ord for OrdSet<A> {
818 fn cmp(&self, other: &Self) -> Ordering { self.iter().cmp(other.iter()) }
819}
820
821impl<A: Ord + Hash> Hash for OrdSet<A> {
822 fn hash<H>(&self, state: &mut H)
823 where H: Hasher {
824 for i in self.iter() {
825 i.hash(state);
826 }
827 }
828}
829
830impl<A> Default for OrdSet<A> {
831 fn default() -> Self { OrdSet::new() }
832}
833
834impl<A: Ord + Clone> Add for OrdSet<A> {
835 type Output = OrdSet<A>;
836
837 fn add(self, other: Self) -> Self::Output { self.union(other) }
838}
839
840impl<'a, A: Ord + Clone> Add for &'a OrdSet<A> {
841 type Output = OrdSet<A>;
842
843 fn add(self, other: Self) -> Self::Output {
844 self.clone().union(other.clone())
845 }
846}
847
848impl<A: Ord + Clone> Mul for OrdSet<A> {
849 type Output = OrdSet<A>;
850
851 fn mul(self, other: Self) -> Self::Output { self.intersection(other) }
852}
853
854impl<'a, A: Ord + Clone> Mul for &'a OrdSet<A> {
855 type Output = OrdSet<A>;
856
857 fn mul(self, other: Self) -> Self::Output {
858 self.clone().intersection(other.clone())
859 }
860}
861
862impl<A: Ord + Clone> Sum for OrdSet<A> {
863 fn sum<I>(it: I) -> Self
864 where I: Iterator<Item = Self> {
865 it.fold(Self::new(), |a, b| a + b)
866 }
867}
868
869impl<A, R> Extend<R> for OrdSet<A>
870where A: Ord + Clone + From<R>
871{
872 fn extend<I>(&mut self, iter: I)
873 where I: IntoIterator<Item = R> {
874 for value in iter {
875 self.insert(From::from(value));
876 }
877 }
878}
879
880impl<A: Ord + Debug> Debug for OrdSet<A> {
881 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
882 f.debug_set().entries(self.iter()).finish()
883 }
884}
885
886pub struct Iter<'a, A> {
890 it: NodeIter<'a, Value<A>>,
891}
892
893impl<'a, A> Iterator for Iter<'a, A>
894where A: 'a + Ord
895{
896 type Item = &'a A;
897
898 fn next(&mut self) -> Option<Self::Item> { self.it.next().map(Deref::deref) }
902
903 fn size_hint(&self) -> (usize, Option<usize>) {
904 (self.it.remaining, Some(self.it.remaining))
905 }
906}
907
908impl<'a, A> DoubleEndedIterator for Iter<'a, A>
909where A: 'a + Ord
910{
911 fn next_back(&mut self) -> Option<Self::Item> {
912 self.it.next_back().map(Deref::deref)
913 }
914}
915
916impl<'a, A> ExactSizeIterator for Iter<'a, A> where A: 'a + Ord {}
917
918pub struct RangedIter<'a, A> {
924 it: NodeIter<'a, Value<A>>,
925}
926
927impl<'a, A> Iterator for RangedIter<'a, A>
928where A: 'a + Ord
929{
930 type Item = &'a A;
931
932 fn next(&mut self) -> Option<Self::Item> { self.it.next().map(Deref::deref) }
936
937 fn size_hint(&self) -> (usize, Option<usize>) { self.it.size_hint() }
938}
939
940impl<'a, A> DoubleEndedIterator for RangedIter<'a, A>
941where A: 'a + Ord
942{
943 fn next_back(&mut self) -> Option<Self::Item> {
944 self.it.next_back().map(Deref::deref)
945 }
946}
947
948pub struct ConsumingIter<A> {
950 it: ConsumingNodeIter<Value<A>>,
951}
952
953impl<A> Iterator for ConsumingIter<A>
954where A: Ord + Clone
955{
956 type Item = A;
957
958 fn next(&mut self) -> Option<Self::Item> { self.it.next().map(|v| v.0) }
962}
963
964pub struct DiffIter<'a, A> {
966 it: NodeDiffIter<'a, Value<A>>,
967}
968
969impl<'a, A> Iterator for DiffIter<'a, A>
970where A: Ord + PartialEq
971{
972 type Item = DiffItem<'a, A>;
973
974 fn next(&mut self) -> Option<Self::Item> {
978 self.it.next().map(|item| match item {
979 DiffItem::Add(v) => DiffItem::Add(v.deref()),
980 DiffItem::Update { old, new } => {
981 DiffItem::Update { old: old.deref(), new: new.deref() }
982 }
983 DiffItem::Remove(v) => DiffItem::Remove(v.deref()),
984 })
985 }
986}
987
988impl<A, R> FromIterator<R> for OrdSet<A>
989where A: Ord + Clone + From<R>
990{
991 fn from_iter<T>(i: T) -> Self
992 where T: IntoIterator<Item = R> {
993 let mut out = Self::new();
994 for item in i {
995 out.insert(From::from(item));
996 }
997 out
998 }
999}
1000
1001impl<'a, A> IntoIterator for &'a OrdSet<A>
1002where A: 'a + Ord
1003{
1004 type IntoIter = Iter<'a, A>;
1005 type Item = &'a A;
1006
1007 fn into_iter(self) -> Self::IntoIter { self.iter() }
1008}
1009
1010impl<A> IntoIterator for OrdSet<A>
1011where A: Ord + Clone
1012{
1013 type IntoIter = ConsumingIter<A>;
1014 type Item = A;
1015
1016 fn into_iter(self) -> Self::IntoIter {
1017 ConsumingIter { it: ConsumingNodeIter::new(&self.root, self.size) }
1018 }
1019}
1020
1021impl<'s, 'a, A, OA> From<&'s OrdSet<&'a A>> for OrdSet<OA>
1024where
1025 A: ToOwned<Owned = OA> + Ord + ?Sized,
1026 OA: Borrow<A> + Ord + Clone,
1027{
1028 fn from(set: &OrdSet<&A>) -> Self {
1029 set.iter().map(|a| (*a).to_owned()).collect()
1030 }
1031}
1032
1033impl<'a, A> From<&'a [A]> for OrdSet<A>
1034where A: Ord + Clone
1035{
1036 fn from(slice: &'a [A]) -> Self { slice.iter().cloned().collect() }
1037}
1038
1039impl<A: Ord + Clone> From<Vec<A>> for OrdSet<A> {
1040 fn from(vec: Vec<A>) -> Self { vec.into_iter().collect() }
1041}
1042
1043impl<'a, A: Ord + Clone> From<&'a Vec<A>> for OrdSet<A> {
1044 fn from(vec: &Vec<A>) -> Self { vec.iter().cloned().collect() }
1045}
1046
1047impl<A: Ord + Clone> From<btree_set::BTreeSet<A>> for OrdSet<A> {
1048 fn from(btree_set: btree_set::BTreeSet<A>) -> Self {
1049 btree_set.into_iter().collect()
1050 }
1051}
1052
1053impl<'a, A: Ord + Clone> From<&'a btree_set::BTreeSet<A>> for OrdSet<A> {
1054 fn from(btree_set: &btree_set::BTreeSet<A>) -> Self {
1055 btree_set.iter().cloned().collect()
1056 }
1057}
1058
1059#[cfg(test)]
1060mod test {
1061 use super::*;
1062
1063 #[test]
1064 fn match_strings_with_string_slices() {
1065 let mut set: OrdSet<String> = From::from(&ordset!["foo", "bar"]);
1066 set = set.without("bar");
1067 assert!(!set.contains("bar"));
1068 set.remove("foo");
1069 assert!(!set.contains("foo"));
1070 }
1071
1072 #[test]
1073 fn ranged_iter() {
1074 let set: OrdSet<i32> = ordset![1, 2, 3, 4, 5];
1075 let range: Vec<i32> = set.range(..).cloned().collect();
1076 assert_eq!(vec![1, 2, 3, 4, 5], range);
1077 let range: Vec<i32> = set.range(..).rev().cloned().collect();
1078 assert_eq!(vec![5, 4, 3, 2, 1], range);
1079 let range: Vec<i32> = set.range(2..5).cloned().collect();
1080 assert_eq!(vec![2, 3, 4], range);
1081 let range: Vec<i32> = set.range(2..5).rev().cloned().collect();
1082 assert_eq!(vec![4, 3, 2], range);
1083 let range: Vec<i32> = set.range(3..).cloned().collect();
1084 assert_eq!(vec![3, 4, 5], range);
1085 let range: Vec<i32> = set.range(3..).rev().cloned().collect();
1086 assert_eq!(vec![5, 4, 3], range);
1087 let range: Vec<i32> = set.range(..4).cloned().collect();
1088 assert_eq!(vec![1, 2, 3], range);
1089 let range: Vec<i32> = set.range(..4).rev().cloned().collect();
1090 assert_eq!(vec![3, 2, 1], range);
1091 let range: Vec<i32> = set.range(..=3).cloned().collect();
1092 assert_eq!(vec![1, 2, 3], range);
1093 let range: Vec<i32> = set.range(..=3).rev().cloned().collect();
1094 assert_eq!(vec![3, 2, 1], range);
1095 }
1096}