1use std::borrow::Borrow;
19use std::cmp::Ordering;
20use std::collections;
21use std::fmt::{Debug, Error, Formatter};
22use std::hash::{BuildHasher, Hash, Hasher};
23use std::iter::{FromIterator, FusedIterator, Sum};
24use std::ops::{Add, Mul, RangeBounds};
25
26use archery::SharedPointerKind;
27use equivalent::Comparable;
28
29use super::map;
30use crate::hashset::GenericHashSet;
31use crate::shared_ptr::DefaultSharedPtr;
32use crate::GenericOrdMap;
33
34#[macro_export]
49macro_rules! ordset {
50 () => { $crate::ordset::OrdSet::new() };
51
52 ( $($x:expr),* ) => {{
53 let mut l = $crate::ordset::OrdSet::new();
54 $(
55 l.insert($x);
56 )*
57 l
58 }};
59}
60
61pub type OrdSet<A> = GenericOrdSet<A, DefaultSharedPtr>;
66
67pub struct GenericOrdSet<A, P: SharedPointerKind> {
80 map: GenericOrdMap<A, (), P>,
81}
82
83impl<A, P: SharedPointerKind> GenericOrdSet<A, P> {
84 #[inline]
86 #[must_use]
87 pub fn new() -> Self {
88 GenericOrdSet {
89 map: GenericOrdMap::new(),
90 }
91 }
92
93 #[inline]
104 #[must_use]
105 pub fn unit(a: A) -> Self {
106 GenericOrdSet {
107 map: GenericOrdMap::unit(a, ()),
108 }
109 }
110
111 #[inline]
128 #[must_use]
129 pub fn is_empty(&self) -> bool {
130 self.len() == 0
131 }
132
133 #[inline]
145 #[must_use]
146 pub fn len(&self) -> usize {
147 self.map.len()
148 }
149
150 pub fn ptr_eq(&self, other: &Self) -> bool {
160 self.map.ptr_eq(&other.map)
161 }
162
163 pub fn clear(&mut self) {
180 self.map.clear();
181 }
182}
183
184impl<A, P> GenericOrdSet<A, P>
185where
186 A: Ord,
187 P: SharedPointerKind,
188{
189 #[must_use]
195 pub fn get_min(&self) -> Option<&A> {
196 self.map.get_min().map(|v| &v.0)
197 }
198
199 #[must_use]
205 pub fn get_max(&self) -> Option<&A> {
206 self.map.get_max().map(|v| &v.0)
207 }
208
209 #[must_use]
211 pub fn iter(&self) -> Iter<'_, A, P> {
212 Iter {
213 it: self.map.iter(),
214 }
215 }
216
217 #[must_use]
219 pub fn range<R, Q>(&self, range: R) -> RangedIter<'_, A, P>
220 where
221 R: RangeBounds<Q>,
222 Q: Comparable<A> + ?Sized,
223 {
224 RangedIter {
225 it: self.map.range(range),
226 }
227 }
228
229 #[must_use]
241 pub fn diff<'a, 'b>(&'a self, other: &'b Self) -> DiffIter<'a, 'b, A, P> {
242 DiffIter {
243 it: self.map.diff(&other.map),
244 }
245 }
246
247 #[inline]
261 #[must_use]
262 pub fn contains<Q>(&self, value: &Q) -> bool
263 where
264 Q: Comparable<A> + ?Sized,
265 {
266 self.map.contains_key(value)
267 }
268
269 pub fn get<Q>(&self, value: &Q) -> Option<&A>
303 where
304 Q: Comparable<A> + ?Sized,
305 {
306 self.map.get_key_value(value).map(|(k, _)| k)
307 }
308
309 #[must_use]
325 pub fn get_prev<Q>(&self, value: &Q) -> Option<&A>
326 where
327 Q: Comparable<A> + ?Sized,
328 {
329 self.map.get_prev(value).map(|(k, _)| k)
330 }
331
332 #[must_use]
348 pub fn get_next<Q>(&self, value: &Q) -> Option<&A>
349 where
350 Q: Comparable<A> + ?Sized,
351 {
352 self.map.get_next(value).map(|(k, _)| k)
353 }
354
355 #[must_use]
360 pub fn is_subset<RS>(&self, other: RS) -> bool
361 where
362 RS: Borrow<Self>,
363 {
364 let other = other.borrow();
365 if other.len() < self.len() {
366 return false;
367 }
368 self.iter().all(|a| other.contains(a))
369 }
370
371 #[must_use]
377 pub fn is_proper_subset<RS>(&self, other: RS) -> bool
378 where
379 RS: Borrow<Self>,
380 {
381 self.len() != other.borrow().len() && self.is_subset(other)
382 }
383
384 #[cfg(any(test, fuzzing))]
386 #[allow(unreachable_pub)]
387 pub fn check_sane(&self)
388 where
389 A: std::fmt::Debug,
390 {
391 self.map.check_sane();
392 }
393}
394
395impl<A, P> GenericOrdSet<A, P>
396where
397 A: Ord + Clone,
398 P: SharedPointerKind,
399{
400 #[inline]
418 pub fn insert(&mut self, a: A) -> Option<A> {
419 self.map.insert_key_value(a, ()).map(|(k, _)| k)
420 }
421
422 #[inline]
426 pub fn remove<Q>(&mut self, value: &Q) -> Option<A>
427 where
428 Q: Comparable<A> + ?Sized,
429 {
430 self.map.remove_with_key(value).map(|(k, _)| k)
431 }
432
433 pub fn remove_min(&mut self) -> Option<A> {
437 let key = self.get_min()?.clone();
439 self.remove(&key)
440 }
441
442 pub fn remove_max(&mut self) -> Option<A> {
446 let key = self.get_max()?.clone();
448 self.remove(&key)
449 }
450
451 #[must_use]
468 pub fn update(&self, a: A) -> Self {
469 let mut out = self.clone();
470 out.insert(a);
471 out
472 }
473
474 #[must_use]
479 pub fn without<Q>(&self, value: &Q) -> Self
480 where
481 Q: Comparable<A> + ?Sized,
482 {
483 let mut out = self.clone();
484 out.remove(value);
485 out
486 }
487
488 #[must_use]
493 pub fn without_min(&self) -> (Option<A>, Self) {
494 match self.get_min() {
495 Some(v) => (Some(v.clone()), self.without(v)),
496 None => (None, self.clone()),
497 }
498 }
499
500 #[must_use]
505 pub fn without_max(&self) -> (Option<A>, Self) {
506 match self.get_max() {
507 Some(v) => (Some(v.clone()), self.without(v)),
508 None => (None, self.clone()),
509 }
510 }
511
512 #[must_use]
527 pub fn union(self, other: Self) -> Self {
528 let (mut to_mutate, to_consume) = if self.len() >= other.len() {
529 (self, other)
530 } else {
531 (other, self)
532 };
533 for value in to_consume {
534 to_mutate.insert(value);
535 }
536 to_mutate
537 }
538
539 #[must_use]
543 pub fn unions<I>(i: I) -> Self
544 where
545 I: IntoIterator<Item = Self>,
546 {
547 i.into_iter().fold(Self::default(), Self::union)
548 }
549
550 #[deprecated(
570 since = "2.0.1",
571 note = "to avoid conflicting behaviors between std and imbl, the `difference` alias for `symmetric_difference` will be removed."
572 )]
573 #[must_use]
574 pub fn difference(self, other: Self) -> Self {
575 self.symmetric_difference(other)
576 }
577
578 #[must_use]
593 pub fn symmetric_difference(mut self, other: Self) -> Self {
594 for value in other {
595 if self.remove(&value).is_none() {
596 self.insert(value);
597 }
598 }
599 self
600 }
601
602 #[must_use]
618 pub fn relative_complement(mut self, other: Self) -> Self {
619 for value in other {
620 let _ = self.remove(&value);
621 }
622 self
623 }
624
625 #[must_use]
640 pub fn intersection(self, other: Self) -> Self {
641 let mut out = Self::default();
642 for value in other {
643 if self.contains(&value) {
644 out.insert(value);
645 }
646 }
647 out
648 }
649
650 #[must_use]
658 pub fn split<Q>(self, split: &Q) -> (Self, Self)
659 where
660 Q: Comparable<A> + ?Sized,
661 {
662 let (left, _, right) = self.split_member(split);
663 (left, right)
664 }
665
666 #[must_use]
676 pub fn split_member<Q>(self, split: &Q) -> (Self, bool, Self)
677 where
678 Q: Comparable<A> + ?Sized,
679 {
680 let mut left = Self::default();
681 let mut right = Self::default();
682 let mut present = false;
683 for value in self {
684 match split.compare(&value).reverse() {
685 Ordering::Less => {
686 left.insert(value);
687 }
688 Ordering::Equal => {
689 present = true;
690 }
691 Ordering::Greater => {
692 right.insert(value);
693 }
694 }
695 }
696 (left, present, right)
697 }
698
699 #[must_use]
704 pub fn take(&self, n: usize) -> Self {
705 self.iter().take(n).cloned().collect()
706 }
707
708 #[must_use]
713 pub fn skip(&self, n: usize) -> Self {
714 self.iter().skip(n).cloned().collect()
715 }
716}
717
718impl<A, P: SharedPointerKind> Clone for GenericOrdSet<A, P> {
721 #[inline]
725 fn clone(&self) -> Self {
726 GenericOrdSet {
727 map: self.map.clone(),
728 }
729 }
730}
731
732impl<A: Ord, P: SharedPointerKind> PartialEq for GenericOrdSet<A, P> {
734 fn eq(&self, other: &Self) -> bool {
735 self.map.eq(&other.map)
736 }
737}
738
739impl<A: Ord, P: SharedPointerKind> Eq for GenericOrdSet<A, P> {}
740
741impl<A: Ord, P: SharedPointerKind> PartialOrd for GenericOrdSet<A, P> {
742 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
743 Some(self.cmp(other))
744 }
745}
746
747impl<A: Ord, P: SharedPointerKind> Ord for GenericOrdSet<A, P> {
748 fn cmp(&self, other: &Self) -> Ordering {
749 self.iter().cmp(other.iter())
750 }
751}
752
753impl<A: Ord + Hash, P: SharedPointerKind> Hash for GenericOrdSet<A, P> {
754 fn hash<H>(&self, state: &mut H)
755 where
756 H: Hasher,
757 {
758 for i in self.iter() {
759 i.hash(state);
760 }
761 }
762}
763
764impl<A, P: SharedPointerKind> Default for GenericOrdSet<A, P> {
765 fn default() -> Self {
766 GenericOrdSet::new()
767 }
768}
769
770impl<A: Ord + Clone, P: SharedPointerKind> Add for GenericOrdSet<A, P> {
771 type Output = GenericOrdSet<A, P>;
772
773 fn add(self, other: Self) -> Self::Output {
774 self.union(other)
775 }
776}
777
778impl<A: Ord + Clone, P: SharedPointerKind> Add for &GenericOrdSet<A, P> {
779 type Output = GenericOrdSet<A, P>;
780
781 fn add(self, other: Self) -> Self::Output {
782 self.clone().union(other.clone())
783 }
784}
785
786impl<A: Ord + Clone, P: SharedPointerKind> Mul for GenericOrdSet<A, P> {
787 type Output = GenericOrdSet<A, P>;
788
789 fn mul(self, other: Self) -> Self::Output {
790 self.intersection(other)
791 }
792}
793
794impl<A: Ord + Clone, P: SharedPointerKind> Mul for &GenericOrdSet<A, P> {
795 type Output = GenericOrdSet<A, P>;
796
797 fn mul(self, other: Self) -> Self::Output {
798 self.clone().intersection(other.clone())
799 }
800}
801
802impl<A: Ord + Clone, P: SharedPointerKind> Sum for GenericOrdSet<A, P> {
803 fn sum<I>(it: I) -> Self
804 where
805 I: Iterator<Item = Self>,
806 {
807 it.fold(Self::new(), |a, b| a + b)
808 }
809}
810
811impl<A, R, P> Extend<R> for GenericOrdSet<A, P>
812where
813 A: Ord + Clone + From<R>,
814 P: SharedPointerKind,
815{
816 fn extend<I>(&mut self, iter: I)
817 where
818 I: IntoIterator<Item = R>,
819 {
820 for value in iter {
821 self.insert(From::from(value));
822 }
823 }
824}
825
826impl<A: Ord + Debug, P: SharedPointerKind> Debug for GenericOrdSet<A, P> {
827 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
828 f.debug_set().entries(self.iter()).finish()
829 }
830}
831
832pub struct Iter<'a, A, P: SharedPointerKind> {
836 it: map::Iter<'a, A, (), P>,
837}
838
839impl<'a, A, P: SharedPointerKind> Clone for Iter<'a, A, P> {
841 fn clone(&self) -> Self {
842 Iter {
843 it: self.it.clone(),
844 }
845 }
846}
847
848impl<'a, A, P: SharedPointerKind> Iterator for Iter<'a, A, P>
849where
850 A: 'a + Ord,
851{
852 type Item = &'a A;
853
854 fn next(&mut self) -> Option<Self::Item> {
858 self.it.next().map(|(k, _)| k)
859 }
860
861 fn size_hint(&self) -> (usize, Option<usize>) {
862 self.it.size_hint()
863 }
864}
865
866impl<'a, A, P> DoubleEndedIterator for Iter<'a, A, P>
867where
868 A: 'a + Ord,
869 P: SharedPointerKind,
870{
871 fn next_back(&mut self) -> Option<Self::Item> {
872 self.it.next_back().map(|(k, _)| k)
873 }
874}
875
876impl<'a, A, P> ExactSizeIterator for Iter<'a, A, P>
877where
878 A: 'a + Ord,
879 P: SharedPointerKind,
880{
881}
882
883impl<'a, A, P> FusedIterator for Iter<'a, A, P>
884where
885 A: 'a + Ord,
886 P: SharedPointerKind,
887{
888}
889
890pub struct RangedIter<'a, A, P: SharedPointerKind> {
896 it: map::RangedIter<'a, A, (), P>,
897}
898
899impl<'a, A, P> Iterator for RangedIter<'a, A, P>
900where
901 A: 'a + Ord,
902 P: SharedPointerKind,
903{
904 type Item = &'a A;
905
906 fn next(&mut self) -> Option<Self::Item> {
910 self.it.next().map(|(k, _)| k)
911 }
912
913 fn size_hint(&self) -> (usize, Option<usize>) {
914 self.it.size_hint()
915 }
916}
917
918impl<'a, A, P> DoubleEndedIterator for RangedIter<'a, A, P>
919where
920 A: 'a + Ord,
921 P: SharedPointerKind,
922{
923 fn next_back(&mut self) -> Option<Self::Item> {
924 self.it.next_back().map(|(k, _)| k)
925 }
926}
927
928pub struct ConsumingIter<A, P: SharedPointerKind> {
930 it: map::ConsumingIter<A, (), P>,
931}
932
933impl<A, P> Iterator for ConsumingIter<A, P>
934where
935 A: Clone,
936 P: SharedPointerKind,
937{
938 type Item = A;
939
940 fn next(&mut self) -> Option<Self::Item> {
944 self.it.next().map(|v| v.0)
945 }
946}
947
948impl<A, P> DoubleEndedIterator for ConsumingIter<A, P>
949where
950 A: Clone,
951 P: SharedPointerKind,
952{
953 fn next_back(&mut self) -> Option<Self::Item> {
954 self.it.next_back().map(|v| v.0)
955 }
956}
957
958impl<A, P> ExactSizeIterator for ConsumingIter<A, P>
959where
960 A: Clone,
961 P: SharedPointerKind,
962{
963}
964
965impl<A, P> FusedIterator for ConsumingIter<A, P>
966where
967 A: Clone,
968 P: SharedPointerKind,
969{
970}
971
972pub struct DiffIter<'a, 'b, A, P: SharedPointerKind> {
974 it: map::DiffIter<'a, 'b, A, (), P>,
975}
976
977#[derive(PartialEq, Eq, Debug)]
979pub enum DiffItem<'a, 'b, A> {
980 Add(&'b A),
982 Remove(&'a A),
984}
985
986impl<'a, 'b, A, P> Iterator for DiffIter<'a, 'b, A, P>
987where
988 A: Ord + PartialEq,
989 P: SharedPointerKind,
990{
991 type Item = DiffItem<'a, 'b, A>;
992
993 fn next(&mut self) -> Option<Self::Item> {
997 self.it.next().map(|item| match item {
998 map::DiffItem::Add(k, _) => DiffItem::Add(k),
999 map::DiffItem::Remove(k, _) => DiffItem::Remove(k),
1000 map::DiffItem::Update { .. } => unreachable!(),
1003 })
1004 }
1005}
1006
1007impl<'a, 'b, A, P> FusedIterator for DiffIter<'a, 'b, A, P>
1008where
1009 A: Ord + PartialEq,
1010 P: SharedPointerKind,
1011{
1012}
1013
1014impl<A, R, P> FromIterator<R> for GenericOrdSet<A, P>
1015where
1016 A: Ord + Clone + From<R>,
1017 P: SharedPointerKind,
1018{
1019 fn from_iter<T>(i: T) -> Self
1020 where
1021 T: IntoIterator<Item = R>,
1022 {
1023 let mut out = Self::new();
1024 for item in i {
1025 out.insert(From::from(item));
1026 }
1027 out
1028 }
1029}
1030
1031impl<'a, A, P> IntoIterator for &'a GenericOrdSet<A, P>
1032where
1033 A: 'a + Ord,
1034 P: SharedPointerKind,
1035{
1036 type Item = &'a A;
1037 type IntoIter = Iter<'a, A, P>;
1038
1039 fn into_iter(self) -> Self::IntoIter {
1040 self.iter()
1041 }
1042}
1043
1044impl<A, P> IntoIterator for GenericOrdSet<A, P>
1045where
1046 A: Ord + Clone,
1047 P: SharedPointerKind,
1048{
1049 type Item = A;
1050 type IntoIter = ConsumingIter<A, P>;
1051
1052 fn into_iter(self) -> Self::IntoIter {
1053 ConsumingIter {
1054 it: self.map.into_iter(),
1055 }
1056 }
1057}
1058
1059impl<A, OA, P1, P2> From<&GenericOrdSet<&A, P2>> for GenericOrdSet<OA, P1>
1062where
1063 A: ToOwned<Owned = OA> + Ord + ?Sized,
1064 OA: Ord + Clone,
1065 P1: SharedPointerKind,
1066 P2: SharedPointerKind,
1067{
1068 fn from(set: &GenericOrdSet<&A, P2>) -> Self {
1069 set.iter().map(|a| (*a).to_owned()).collect()
1070 }
1071}
1072
1073impl<'a, A, P> From<&'a [A]> for GenericOrdSet<A, P>
1074where
1075 A: Ord + Clone,
1076 P: SharedPointerKind,
1077{
1078 fn from(slice: &'a [A]) -> Self {
1079 slice.iter().cloned().collect()
1080 }
1081}
1082
1083impl<A: Ord + Clone, P: SharedPointerKind> From<Vec<A>> for GenericOrdSet<A, P> {
1084 fn from(vec: Vec<A>) -> Self {
1085 vec.into_iter().collect()
1086 }
1087}
1088
1089impl<A: Ord + Clone, P: SharedPointerKind> From<&Vec<A>> for GenericOrdSet<A, P> {
1090 fn from(vec: &Vec<A>) -> Self {
1091 vec.iter().cloned().collect()
1092 }
1093}
1094
1095impl<A: Eq + Hash + Ord + Clone, P: SharedPointerKind> From<collections::HashSet<A>>
1096 for GenericOrdSet<A, P>
1097{
1098 fn from(hash_set: collections::HashSet<A>) -> Self {
1099 hash_set.into_iter().collect()
1100 }
1101}
1102
1103impl<A: Eq + Hash + Ord + Clone, P: SharedPointerKind> From<&collections::HashSet<A>>
1104 for GenericOrdSet<A, P>
1105{
1106 fn from(hash_set: &collections::HashSet<A>) -> Self {
1107 hash_set.iter().cloned().collect()
1108 }
1109}
1110
1111impl<A: Ord + Clone, P: SharedPointerKind> From<collections::BTreeSet<A>> for GenericOrdSet<A, P> {
1112 fn from(btree_set: collections::BTreeSet<A>) -> Self {
1113 btree_set.into_iter().collect()
1114 }
1115}
1116
1117impl<A: Ord + Clone, P: SharedPointerKind> From<&collections::BTreeSet<A>> for GenericOrdSet<A, P> {
1118 fn from(btree_set: &collections::BTreeSet<A>) -> Self {
1119 btree_set.iter().cloned().collect()
1120 }
1121}
1122
1123impl<A: Hash + Eq + Ord + Clone, S: BuildHasher, P1: SharedPointerKind, P2: SharedPointerKind>
1124 From<GenericHashSet<A, S, P2>> for GenericOrdSet<A, P1>
1125{
1126 fn from(hashset: GenericHashSet<A, S, P2>) -> Self {
1127 hashset.into_iter().collect()
1128 }
1129}
1130
1131impl<A: Hash + Eq + Ord + Clone, S: BuildHasher, P1: SharedPointerKind, P2: SharedPointerKind>
1132 From<&GenericHashSet<A, S, P2>> for GenericOrdSet<A, P1>
1133{
1134 fn from(hashset: &GenericHashSet<A, S, P2>) -> Self {
1135 hashset.into_iter().cloned().collect()
1136 }
1137}
1138
1139#[cfg(test)]
1140mod test {
1141 use super::*;
1142 use crate::proptest::*;
1143 use proptest::proptest;
1144 use static_assertions::{assert_impl_all, assert_not_impl_any};
1145
1146 assert_impl_all!(OrdSet<i32>: Send, Sync);
1147 assert_not_impl_any!(OrdSet<*const i32>: Send, Sync);
1148 assert_covariant!(OrdSet<T> in T);
1149
1150 #[test]
1151 fn match_strings_with_string_slices() {
1152 let mut set: OrdSet<String> = From::from(&ordset!["foo", "bar"]);
1153 set = set.without("bar");
1154 assert!(!set.contains("bar"));
1155 set.remove("foo");
1156 assert!(!set.contains("foo"));
1157 }
1158
1159 #[test]
1160 fn ranged_iter() {
1161 let set = ordset![1, 2, 3, 4, 5];
1162 let range: Vec<i32> = set.range::<_, i32>(..).cloned().collect();
1163 assert_eq!(vec![1, 2, 3, 4, 5], range);
1164 let range: Vec<i32> = set.range::<_, i32>(..).rev().cloned().collect();
1165 assert_eq!(vec![5, 4, 3, 2, 1], range);
1166 let range: Vec<i32> = set.range(2..5).cloned().collect();
1167 assert_eq!(vec![2, 3, 4], range);
1168 let range: Vec<i32> = set.range(2..5).rev().cloned().collect();
1169 assert_eq!(vec![4, 3, 2], range);
1170 let range: Vec<i32> = set.range(3..).cloned().collect();
1171 assert_eq!(vec![3, 4, 5], range);
1172 let range: Vec<i32> = set.range(3..).rev().cloned().collect();
1173 assert_eq!(vec![5, 4, 3], range);
1174 let range: Vec<i32> = set.range(..4).cloned().collect();
1175 assert_eq!(vec![1, 2, 3], range);
1176 let range: Vec<i32> = set.range(..4).rev().cloned().collect();
1177 assert_eq!(vec![3, 2, 1], range);
1178 let range: Vec<i32> = set.range(..=3).cloned().collect();
1179 assert_eq!(vec![1, 2, 3], range);
1180 let range: Vec<i32> = set.range(..=3).rev().cloned().collect();
1181 assert_eq!(vec![3, 2, 1], range);
1182 }
1183
1184 proptest! {
1185 #[test]
1186 fn proptest_a_set(ref s in ord_set(".*", 10..100)) {
1187 assert!(s.len() < 100);
1188 assert!(s.len() >= 10);
1189 }
1190
1191 #[test]
1192 fn long_ranged_iter(max in 1..1000) {
1193 let range = 0..max;
1194 let expected: Vec<i32> = range.clone().collect();
1195 let set: OrdSet<i32> = OrdSet::from_iter(range.clone());
1196 let result: Vec<i32> = set.range::<_, i32>(..).cloned().collect();
1197 assert_eq!(expected, result);
1198
1199 let expected: Vec<i32> = range.clone().rev().collect();
1200 let set: OrdSet<i32> = OrdSet::from_iter(range);
1201 let result: Vec<i32> = set.range::<_, i32>(..).rev().cloned().collect();
1202 assert_eq!(expected, result);
1203 }
1204 }
1205}