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;
27
28use super::map;
29use crate::hashset::GenericHashSet;
30use crate::shared_ptr::DefaultSharedPtr;
31use crate::GenericOrdMap;
32
33#[macro_export]
48macro_rules! ordset {
49 () => { $crate::ordset::OrdSet::new() };
50
51 ( $($x:expr),* ) => {{
52 let mut l = $crate::ordset::OrdSet::new();
53 $(
54 l.insert($x);
55 )*
56 l
57 }};
58}
59
60pub type OrdSet<A> = GenericOrdSet<A, DefaultSharedPtr>;
65
66pub struct GenericOrdSet<A, P: SharedPointerKind> {
79 map: GenericOrdMap<A, (), P>,
80}
81
82impl<A, P: SharedPointerKind> GenericOrdSet<A, P> {
83 #[inline]
85 #[must_use]
86 pub fn new() -> Self {
87 GenericOrdSet {
88 map: GenericOrdMap::new(),
89 }
90 }
91
92 #[inline]
103 #[must_use]
104 pub fn unit(a: A) -> Self {
105 GenericOrdSet {
106 map: GenericOrdMap::unit(a, ()),
107 }
108 }
109
110 #[inline]
127 #[must_use]
128 pub fn is_empty(&self) -> bool {
129 self.len() == 0
130 }
131
132 #[inline]
144 #[must_use]
145 pub fn len(&self) -> usize {
146 self.map.len()
147 }
148
149 pub fn ptr_eq(&self, other: &Self) -> bool {
159 self.map.ptr_eq(&other.map)
160 }
161
162 pub fn clear(&mut self) {
179 self.map.clear();
180 }
181}
182
183impl<A, P> GenericOrdSet<A, P>
184where
185 A: Ord,
186 P: SharedPointerKind,
187{
188 #[must_use]
194 pub fn get_min(&self) -> Option<&A> {
195 self.map.get_min().map(|v| &v.0)
196 }
197
198 #[must_use]
204 pub fn get_max(&self) -> Option<&A> {
205 self.map.get_max().map(|v| &v.0)
206 }
207
208 #[must_use]
210 pub fn iter(&self) -> Iter<'_, A, P> {
211 Iter {
212 it: self.map.iter(),
213 }
214 }
215
216 #[must_use]
218 pub fn range<R, BA>(&self, range: R) -> RangedIter<'_, A, P>
219 where
220 R: RangeBounds<BA>,
221 A: Borrow<BA>,
222 BA: Ord + ?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<BA>(&self, a: &BA) -> bool
263 where
264 BA: Ord + ?Sized,
265 A: Borrow<BA>,
266 {
267 self.map.contains_key(a)
268 }
269
270 pub fn get<BK>(&self, k: &BK) -> Option<&A>
304 where
305 BK: Ord + ?Sized,
306 A: Borrow<BK>,
307 {
308 self.map.get_key_value(k).map(|(k, _)| k)
309 }
310
311 #[must_use]
327 pub fn get_prev<BK>(&self, k: &BK) -> Option<&A>
328 where
329 BK: Ord + ?Sized,
330 A: Borrow<BK>,
331 {
332 self.map.get_prev(k).map(|(k, _)| k)
333 }
334
335 #[must_use]
351 pub fn get_next<BK>(&self, k: &BK) -> Option<&A>
352 where
353 BK: Ord + ?Sized,
354 A: Borrow<BK>,
355 {
356 self.map.get_next(k).map(|(k, _)| k)
357 }
358
359 #[must_use]
364 pub fn is_subset<RS>(&self, other: RS) -> bool
365 where
366 RS: Borrow<Self>,
367 {
368 let other = other.borrow();
369 if other.len() < self.len() {
370 return false;
371 }
372 self.iter().all(|a| other.contains(a))
373 }
374
375 #[must_use]
381 pub fn is_proper_subset<RS>(&self, other: RS) -> bool
382 where
383 RS: Borrow<Self>,
384 {
385 self.len() != other.borrow().len() && self.is_subset(other)
386 }
387
388 #[cfg(any(test, fuzzing))]
390 #[allow(unreachable_pub)]
391 pub fn check_sane(&self)
392 where
393 A: std::fmt::Debug,
394 {
395 self.map.check_sane();
396 }
397}
398
399impl<A, P> GenericOrdSet<A, P>
400where
401 A: Ord + Clone,
402 P: SharedPointerKind,
403{
404 #[inline]
422 pub fn insert(&mut self, a: A) -> Option<A> {
423 self.map.insert_key_value(a, ()).map(|(k, _)| k)
424 }
425
426 #[inline]
430 pub fn remove<BA>(&mut self, a: &BA) -> Option<A>
431 where
432 BA: Ord + ?Sized,
433 A: Borrow<BA>,
434 {
435 self.map.remove_with_key(a).map(|(k, _)| k)
436 }
437
438 pub fn remove_min(&mut self) -> Option<A> {
442 let key = self.get_min()?.clone();
444 self.remove(&key)
445 }
446
447 pub fn remove_max(&mut self) -> Option<A> {
451 let key = self.get_max()?.clone();
453 self.remove(&key)
454 }
455
456 #[must_use]
473 pub fn update(&self, a: A) -> Self {
474 let mut out = self.clone();
475 out.insert(a);
476 out
477 }
478
479 #[must_use]
484 pub fn without<BA>(&self, a: &BA) -> Self
485 where
486 BA: Ord + ?Sized,
487 A: Borrow<BA>,
488 {
489 let mut out = self.clone();
490 out.remove(a);
491 out
492 }
493
494 #[must_use]
499 pub fn without_min(&self) -> (Option<A>, Self) {
500 match self.get_min() {
501 Some(v) => (Some(v.clone()), self.without(v)),
502 None => (None, self.clone()),
503 }
504 }
505
506 #[must_use]
511 pub fn without_max(&self) -> (Option<A>, Self) {
512 match self.get_max() {
513 Some(v) => (Some(v.clone()), self.without(v)),
514 None => (None, self.clone()),
515 }
516 }
517
518 #[must_use]
533 pub fn union(self, other: Self) -> Self {
534 let (mut to_mutate, to_consume) = if self.len() >= other.len() {
535 (self, other)
536 } else {
537 (other, self)
538 };
539 for value in to_consume {
540 to_mutate.insert(value);
541 }
542 to_mutate
543 }
544
545 #[must_use]
549 pub fn unions<I>(i: I) -> Self
550 where
551 I: IntoIterator<Item = Self>,
552 {
553 i.into_iter().fold(Self::default(), Self::union)
554 }
555
556 #[deprecated(
576 since = "2.0.1",
577 note = "to avoid conflicting behaviors between std and imbl, the `difference` alias for `symmetric_difference` will be removed."
578 )]
579 #[must_use]
580 pub fn difference(self, other: Self) -> Self {
581 self.symmetric_difference(other)
582 }
583
584 #[must_use]
599 pub fn symmetric_difference(mut self, other: Self) -> Self {
600 for value in other {
601 if self.remove(&value).is_none() {
602 self.insert(value);
603 }
604 }
605 self
606 }
607
608 #[must_use]
624 pub fn relative_complement(mut self, other: Self) -> Self {
625 for value in other {
626 let _ = self.remove(&value);
627 }
628 self
629 }
630
631 #[must_use]
646 pub fn intersection(self, other: Self) -> Self {
647 let mut out = Self::default();
648 for value in other {
649 if self.contains(&value) {
650 out.insert(value);
651 }
652 }
653 out
654 }
655
656 #[must_use]
664 pub fn split<BA>(self, split: &BA) -> (Self, Self)
665 where
666 BA: Ord + ?Sized,
667 A: Borrow<BA>,
668 {
669 let (left, _, right) = self.split_member(split);
670 (left, right)
671 }
672
673 #[must_use]
683 pub fn split_member<BA>(self, split: &BA) -> (Self, bool, Self)
684 where
685 BA: Ord + ?Sized,
686 A: Borrow<BA>,
687 {
688 let mut left = Self::default();
689 let mut right = Self::default();
690 let mut present = false;
691 for value in self {
692 match value.borrow().cmp(split) {
693 Ordering::Less => {
694 left.insert(value);
695 }
696 Ordering::Equal => {
697 present = true;
698 }
699 Ordering::Greater => {
700 right.insert(value);
701 }
702 }
703 }
704 (left, present, right)
705 }
706
707 #[must_use]
712 pub fn take(&self, n: usize) -> Self {
713 self.iter().take(n).cloned().collect()
714 }
715
716 #[must_use]
721 pub fn skip(&self, n: usize) -> Self {
722 self.iter().skip(n).cloned().collect()
723 }
724}
725
726impl<A, P: SharedPointerKind> Clone for GenericOrdSet<A, P> {
729 #[inline]
733 fn clone(&self) -> Self {
734 GenericOrdSet {
735 map: self.map.clone(),
736 }
737 }
738}
739
740impl<A: Ord, P: SharedPointerKind> PartialEq for GenericOrdSet<A, P> {
742 fn eq(&self, other: &Self) -> bool {
743 self.map.eq(&other.map)
744 }
745}
746
747impl<A: Ord, P: SharedPointerKind> Eq for GenericOrdSet<A, P> {}
748
749impl<A: Ord, P: SharedPointerKind> PartialOrd for GenericOrdSet<A, P> {
750 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
751 Some(self.cmp(other))
752 }
753}
754
755impl<A: Ord, P: SharedPointerKind> Ord for GenericOrdSet<A, P> {
756 fn cmp(&self, other: &Self) -> Ordering {
757 self.iter().cmp(other.iter())
758 }
759}
760
761impl<A: Ord + Hash, P: SharedPointerKind> Hash for GenericOrdSet<A, P> {
762 fn hash<H>(&self, state: &mut H)
763 where
764 H: Hasher,
765 {
766 for i in self.iter() {
767 i.hash(state);
768 }
769 }
770}
771
772impl<A, P: SharedPointerKind> Default for GenericOrdSet<A, P> {
773 fn default() -> Self {
774 GenericOrdSet::new()
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.union(other)
783 }
784}
785
786impl<A: Ord + Clone, P: SharedPointerKind> Add for &GenericOrdSet<A, P> {
787 type Output = GenericOrdSet<A, P>;
788
789 fn add(self, other: Self) -> Self::Output {
790 self.clone().union(other.clone())
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.intersection(other)
799 }
800}
801
802impl<A: Ord + Clone, P: SharedPointerKind> Mul for &GenericOrdSet<A, P> {
803 type Output = GenericOrdSet<A, P>;
804
805 fn mul(self, other: Self) -> Self::Output {
806 self.clone().intersection(other.clone())
807 }
808}
809
810impl<A: Ord + Clone, P: SharedPointerKind> Sum for GenericOrdSet<A, P> {
811 fn sum<I>(it: I) -> Self
812 where
813 I: Iterator<Item = Self>,
814 {
815 it.fold(Self::new(), |a, b| a + b)
816 }
817}
818
819impl<A, R, P> Extend<R> for GenericOrdSet<A, P>
820where
821 A: Ord + Clone + From<R>,
822 P: SharedPointerKind,
823{
824 fn extend<I>(&mut self, iter: I)
825 where
826 I: IntoIterator<Item = R>,
827 {
828 for value in iter {
829 self.insert(From::from(value));
830 }
831 }
832}
833
834impl<A: Ord + Debug, P: SharedPointerKind> Debug for GenericOrdSet<A, P> {
835 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
836 f.debug_set().entries(self.iter()).finish()
837 }
838}
839
840pub struct Iter<'a, A, P: SharedPointerKind> {
844 it: map::Iter<'a, A, (), P>,
845}
846
847impl<'a, A, P: SharedPointerKind> Clone for Iter<'a, A, P> {
849 fn clone(&self) -> Self {
850 Iter {
851 it: self.it.clone(),
852 }
853 }
854}
855
856impl<'a, A, P: SharedPointerKind> Iterator for Iter<'a, A, P>
857where
858 A: 'a + Ord,
859{
860 type Item = &'a A;
861
862 fn next(&mut self) -> Option<Self::Item> {
866 self.it.next().map(|(k, _)| k)
867 }
868
869 fn size_hint(&self) -> (usize, Option<usize>) {
870 self.it.size_hint()
871 }
872}
873
874impl<'a, A, P> DoubleEndedIterator for Iter<'a, A, P>
875where
876 A: 'a + Ord,
877 P: SharedPointerKind,
878{
879 fn next_back(&mut self) -> Option<Self::Item> {
880 self.it.next_back().map(|(k, _)| k)
881 }
882}
883
884impl<'a, A, P> ExactSizeIterator for Iter<'a, A, P>
885where
886 A: 'a + Ord,
887 P: SharedPointerKind,
888{
889}
890
891impl<'a, A, P> FusedIterator for Iter<'a, A, P>
892where
893 A: 'a + Ord,
894 P: SharedPointerKind,
895{
896}
897
898pub struct RangedIter<'a, A, P: SharedPointerKind> {
904 it: map::RangedIter<'a, A, (), P>,
905}
906
907impl<'a, A, P> Iterator for RangedIter<'a, A, P>
908where
909 A: 'a + Ord,
910 P: SharedPointerKind,
911{
912 type Item = &'a A;
913
914 fn next(&mut self) -> Option<Self::Item> {
918 self.it.next().map(|(k, _)| k)
919 }
920
921 fn size_hint(&self) -> (usize, Option<usize>) {
922 self.it.size_hint()
923 }
924}
925
926impl<'a, A, P> DoubleEndedIterator for RangedIter<'a, A, P>
927where
928 A: 'a + Ord,
929 P: SharedPointerKind,
930{
931 fn next_back(&mut self) -> Option<Self::Item> {
932 self.it.next_back().map(|(k, _)| k)
933 }
934}
935
936pub struct ConsumingIter<A, P: SharedPointerKind> {
938 it: map::ConsumingIter<A, (), P>,
939}
940
941impl<A, P> Iterator for ConsumingIter<A, P>
942where
943 A: Clone,
944 P: SharedPointerKind,
945{
946 type Item = A;
947
948 fn next(&mut self) -> Option<Self::Item> {
952 self.it.next().map(|v| v.0)
953 }
954}
955
956impl<A, P> DoubleEndedIterator for ConsumingIter<A, P>
957where
958 A: Clone,
959 P: SharedPointerKind,
960{
961 fn next_back(&mut self) -> Option<Self::Item> {
962 self.it.next_back().map(|v| v.0)
963 }
964}
965
966impl<A, P> ExactSizeIterator for ConsumingIter<A, P>
967where
968 A: Clone,
969 P: SharedPointerKind,
970{
971}
972
973impl<A, P> FusedIterator for ConsumingIter<A, P>
974where
975 A: Clone,
976 P: SharedPointerKind,
977{
978}
979
980pub struct DiffIter<'a, 'b, A, P: SharedPointerKind> {
982 it: map::DiffIter<'a, 'b, A, (), P>,
983}
984
985#[derive(PartialEq, Eq, Debug)]
987pub enum DiffItem<'a, 'b, A> {
988 Add(&'b A),
990 Remove(&'a A),
992}
993
994impl<'a, 'b, A, P> Iterator for DiffIter<'a, 'b, A, P>
995where
996 A: Ord + PartialEq,
997 P: SharedPointerKind,
998{
999 type Item = DiffItem<'a, 'b, A>;
1000
1001 fn next(&mut self) -> Option<Self::Item> {
1005 self.it.next().map(|item| match item {
1006 map::DiffItem::Add(k, _) => DiffItem::Add(k),
1007 map::DiffItem::Remove(k, _) => DiffItem::Remove(k),
1008 map::DiffItem::Update { .. } => unreachable!(),
1011 })
1012 }
1013}
1014
1015impl<'a, 'b, A, P> FusedIterator for DiffIter<'a, 'b, A, P>
1016where
1017 A: Ord + PartialEq,
1018 P: SharedPointerKind,
1019{
1020}
1021
1022impl<A, R, P> FromIterator<R> for GenericOrdSet<A, P>
1023where
1024 A: Ord + Clone + From<R>,
1025 P: SharedPointerKind,
1026{
1027 fn from_iter<T>(i: T) -> Self
1028 where
1029 T: IntoIterator<Item = R>,
1030 {
1031 let mut out = Self::new();
1032 for item in i {
1033 out.insert(From::from(item));
1034 }
1035 out
1036 }
1037}
1038
1039impl<'a, A, P> IntoIterator for &'a GenericOrdSet<A, P>
1040where
1041 A: 'a + Ord,
1042 P: SharedPointerKind,
1043{
1044 type Item = &'a A;
1045 type IntoIter = Iter<'a, A, P>;
1046
1047 fn into_iter(self) -> Self::IntoIter {
1048 self.iter()
1049 }
1050}
1051
1052impl<A, P> IntoIterator for GenericOrdSet<A, P>
1053where
1054 A: Ord + Clone,
1055 P: SharedPointerKind,
1056{
1057 type Item = A;
1058 type IntoIter = ConsumingIter<A, P>;
1059
1060 fn into_iter(self) -> Self::IntoIter {
1061 ConsumingIter {
1062 it: self.map.into_iter(),
1063 }
1064 }
1065}
1066
1067impl<A, OA, P1, P2> From<&GenericOrdSet<&A, P2>> for GenericOrdSet<OA, P1>
1070where
1071 A: ToOwned<Owned = OA> + Ord + ?Sized,
1072 OA: Borrow<A> + Ord + Clone,
1073 P1: SharedPointerKind,
1074 P2: SharedPointerKind,
1075{
1076 fn from(set: &GenericOrdSet<&A, P2>) -> Self {
1077 set.iter().map(|a| (*a).to_owned()).collect()
1078 }
1079}
1080
1081impl<'a, A, P> From<&'a [A]> for GenericOrdSet<A, P>
1082where
1083 A: Ord + Clone,
1084 P: SharedPointerKind,
1085{
1086 fn from(slice: &'a [A]) -> Self {
1087 slice.iter().cloned().collect()
1088 }
1089}
1090
1091impl<A: Ord + Clone, P: SharedPointerKind> From<Vec<A>> for GenericOrdSet<A, P> {
1092 fn from(vec: Vec<A>) -> Self {
1093 vec.into_iter().collect()
1094 }
1095}
1096
1097impl<A: Ord + Clone, P: SharedPointerKind> From<&Vec<A>> for GenericOrdSet<A, P> {
1098 fn from(vec: &Vec<A>) -> Self {
1099 vec.iter().cloned().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.into_iter().collect()
1108 }
1109}
1110
1111impl<A: Eq + Hash + Ord + Clone, P: SharedPointerKind> From<&collections::HashSet<A>>
1112 for GenericOrdSet<A, P>
1113{
1114 fn from(hash_set: &collections::HashSet<A>) -> Self {
1115 hash_set.iter().cloned().collect()
1116 }
1117}
1118
1119impl<A: Ord + Clone, P: SharedPointerKind> From<collections::BTreeSet<A>> for GenericOrdSet<A, P> {
1120 fn from(btree_set: collections::BTreeSet<A>) -> Self {
1121 btree_set.into_iter().collect()
1122 }
1123}
1124
1125impl<A: Ord + Clone, P: SharedPointerKind> From<&collections::BTreeSet<A>> for GenericOrdSet<A, P> {
1126 fn from(btree_set: &collections::BTreeSet<A>) -> Self {
1127 btree_set.iter().cloned().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().collect()
1136 }
1137}
1138
1139impl<A: Hash + Eq + Ord + Clone, S: BuildHasher, P1: SharedPointerKind, P2: SharedPointerKind>
1140 From<&GenericHashSet<A, S, P2>> for GenericOrdSet<A, P1>
1141{
1142 fn from(hashset: &GenericHashSet<A, S, P2>) -> Self {
1143 hashset.into_iter().cloned().collect()
1144 }
1145}
1146
1147#[cfg(test)]
1148mod test {
1149 use super::*;
1150 use crate::proptest::*;
1151 use proptest::proptest;
1152 use static_assertions::{assert_impl_all, assert_not_impl_any};
1153
1154 assert_impl_all!(OrdSet<i32>: Send, Sync);
1155 assert_not_impl_any!(OrdSet<*const i32>: Send, Sync);
1156 assert_covariant!(OrdSet<T> in T);
1157
1158 #[test]
1159 fn match_strings_with_string_slices() {
1160 let mut set: OrdSet<String> = From::from(&ordset!["foo", "bar"]);
1161 set = set.without("bar");
1162 assert!(!set.contains("bar"));
1163 set.remove("foo");
1164 assert!(!set.contains("foo"));
1165 }
1166
1167 #[test]
1168 fn ranged_iter() {
1169 let set = ordset![1, 2, 3, 4, 5];
1170 let range: Vec<i32> = set.range(..).cloned().collect();
1171 assert_eq!(vec![1, 2, 3, 4, 5], range);
1172 let range: Vec<i32> = set.range(..).rev().cloned().collect();
1173 assert_eq!(vec![5, 4, 3, 2, 1], range);
1174 let range: Vec<i32> = set.range(2..5).cloned().collect();
1175 assert_eq!(vec![2, 3, 4], range);
1176 let range: Vec<i32> = set.range(2..5).rev().cloned().collect();
1177 assert_eq!(vec![4, 3, 2], range);
1178 let range: Vec<i32> = set.range(3..).cloned().collect();
1179 assert_eq!(vec![3, 4, 5], range);
1180 let range: Vec<i32> = set.range(3..).rev().cloned().collect();
1181 assert_eq!(vec![5, 4, 3], range);
1182 let range: Vec<i32> = set.range(..4).cloned().collect();
1183 assert_eq!(vec![1, 2, 3], range);
1184 let range: Vec<i32> = set.range(..4).rev().cloned().collect();
1185 assert_eq!(vec![3, 2, 1], range);
1186 let range: Vec<i32> = set.range(..=3).cloned().collect();
1187 assert_eq!(vec![1, 2, 3], range);
1188 let range: Vec<i32> = set.range(..=3).rev().cloned().collect();
1189 assert_eq!(vec![3, 2, 1], range);
1190 }
1191
1192 proptest! {
1193 #[test]
1194 fn proptest_a_set(ref s in ord_set(".*", 10..100)) {
1195 assert!(s.len() < 100);
1196 assert!(s.len() >= 10);
1197 }
1198
1199 #[test]
1200 fn long_ranged_iter(max in 1..1000) {
1201 let range = 0..max;
1202 let expected: Vec<i32> = range.clone().collect();
1203 let set: OrdSet<i32> = OrdSet::from_iter(range.clone());
1204 let result: Vec<i32> = set.range(..).cloned().collect();
1205 assert_eq!(expected, result);
1206
1207 let expected: Vec<i32> = range.clone().rev().collect();
1208 let set: OrdSet<i32> = OrdSet::from_iter(range);
1209 let result: Vec<i32> = set.range(..).rev().cloned().collect();
1210 assert_eq!(expected, result);
1211 }
1212 }
1213}