1use alloc::collections::TryReserveError;
48use alloc::vec::Vec;
49use core::fmt;
50use core::hash::{Hash, Hasher};
51use core::iter::{Chain, FusedIterator};
52use core::num::NonZeroU32;
53use core::ops::{
54 BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Bound, RangeBounds, Sub,
55 SubAssign,
56};
57use core::slice;
58
59use crate::hash::hash_unordered;
60use crate::key::Key;
61use crate::page::{DEFAULT_PAGE, Directory, Flat, PageStore, split};
62
63pub type Slot = Option<NonZeroU32>;
69
70pub struct PagedSparseSet<K, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> {
113 dense: Vec<K>,
114 sparse: D::Store<Slot, PAGE>,
115}
116
117#[inline]
119fn encode(pos: usize) -> Slot {
120 pos.checked_add(1)
121 .and_then(|p| u32::try_from(p).ok())
122 .and_then(NonZeroU32::new)
123}
124
125impl<K: Key, const PAGE: usize, D: Directory> PagedSparseSet<K, PAGE, D> {
126 pub const PAGE_SIZE: usize = PAGE;
128
129 pub fn new() -> Self {
131 Self {
132 dense: Vec::new(),
133 sparse: Default::default(),
134 }
135 }
136
137 pub fn with_capacity(capacity: usize) -> Self {
140 Self {
141 dense: Vec::with_capacity(capacity),
142 sparse: Default::default(),
143 }
144 }
145
146 #[inline]
148 pub fn len(&self) -> usize {
149 self.dense.len()
150 }
151
152 #[inline]
154 pub fn is_empty(&self) -> bool {
155 self.dense.is_empty()
156 }
157
158 #[inline]
160 pub fn capacity(&self) -> usize {
161 self.dense.capacity()
162 }
163
164 #[inline]
166 pub fn allocated_pages(&self) -> usize {
167 self.sparse.allocated()
168 }
169
170 pub fn reserve(&mut self, additional: usize) {
172 self.dense.reserve(additional);
173 }
174
175 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
179 self.dense.try_reserve(additional)
180 }
181
182 #[inline]
184 pub(crate) fn occupant_pos(&self, index: usize) -> Option<usize> {
185 let (page, offset) = split::<PAGE>(index);
186 let slot = self.sparse.get(page)?[offset]?;
187 let pos = slot.get() as usize - 1;
189 match self.dense.get(pos) {
190 Some(key) if key.index() == index => Some(pos),
191 _ => None,
192 }
193 }
194
195 #[inline]
197 fn set_slot(&mut self, index: usize, slot: Slot) {
198 let (page, offset) = split::<PAGE>(index);
199 let page = self.sparse.get_mut(page);
200 debug_assert!(page.is_some(), "slot {index} has no page");
201 if let Some(page) = page {
202 page[offset] = slot;
203 }
204 }
205
206 #[inline]
211 pub fn position(&self, key: K) -> Option<usize> {
212 self.occupant_pos(key.index())
213 .filter(|&pos| self.dense[pos] == key)
214 }
215
216 #[inline]
218 pub fn contains(&self, key: K) -> bool {
219 self.position(key).is_some()
220 }
221
222 #[inline]
235 pub fn get(&self, key: K) -> Option<&K> {
236 self.position(key).map(|pos| &self.dense[pos])
237 }
238
239 #[inline]
243 pub fn occupant(&self, index: usize) -> Option<&K> {
244 self.occupant_pos(index).map(|pos| &self.dense[pos])
245 }
246
247 pub fn insert(&mut self, key: K) -> bool {
256 let index = key.index();
257 if self.occupant_pos(index).is_some() {
258 return false;
259 }
260 self.insert_vacant(key, index);
261 true
262 }
263
264 pub(crate) fn insert_vacant(&mut self, key: K, index: usize) {
269 let pos = self.dense.len();
270 let slot = encode(pos).expect("PagedSparseSet cannot hold more than u32::MAX keys");
271 let (page, offset) = split::<PAGE>(index);
272 self.sparse.get_or_alloc(page)[offset] = Some(slot);
273 self.dense.push(key);
276 }
277
278 pub fn replace(&mut self, key: K) -> Option<K> {
287 let index = key.index();
288 match self.occupant_pos(index) {
289 Some(pos) => Some(self.overwrite_at(pos, key)),
290 None => {
291 self.insert_vacant(key, index);
292 None
293 }
294 }
295 }
296
297 #[inline]
300 pub(crate) fn overwrite_at(&mut self, pos: usize, key: K) -> K {
301 debug_assert_eq!(self.dense[pos].index(), key.index());
302 core::mem::replace(&mut self.dense[pos], key)
303 }
304
305 pub(crate) fn remove_at(&mut self, pos: usize) -> K {
308 let index = self.dense[pos].index();
311 let moved_index = match self.dense.last() {
312 Some(last) if self.dense.len() - 1 != pos => Some(last.index()),
313 _ => None,
314 };
315 let key = self.dense.swap_remove(pos);
316 self.set_slot(index, None);
317 if let Some(moved_index) = moved_index {
318 self.set_slot(moved_index, encode(pos));
319 }
320 key
321 }
322
323 pub fn remove(&mut self, key: K) -> bool {
327 self.take(key).is_some()
328 }
329
330 pub fn take(&mut self, key: K) -> Option<K> {
344 self.position(key).map(|pos| self.remove_at(pos))
345 }
346
347 pub fn remove_occupant(&mut self, index: usize) -> Option<K> {
349 self.occupant_pos(index).map(|pos| self.remove_at(pos))
350 }
351
352 pub fn retain(&mut self, mut keep: impl FnMut(&K) -> bool) {
356 let mut pos = 0;
357 while pos < self.dense.len() {
358 if keep(&self.dense[pos]) {
359 pos += 1;
360 } else {
361 self.remove_at(pos);
363 }
364 }
365 }
366
367 pub fn clear(&mut self) {
372 self.dense.clear();
373 }
374
375 pub fn reset(&mut self) {
378 self.dense.clear();
379 self.sparse.clear();
380 }
381
382 pub(crate) fn free_pages(&mut self) {
385 debug_assert!(self.dense.is_empty());
386 self.sparse.clear();
387 }
388
389 pub fn shrink_to_fit(&mut self) {
392 self.dense.shrink_to_fit();
393 if self.dense.is_empty() {
394 self.sparse.clear();
395 }
396 self.sparse.shrink_to_fit();
397 }
398
399 #[inline]
401 pub fn as_slice(&self) -> &[K] {
402 &self.dense
403 }
404
405 #[inline]
407 pub fn iter(&self) -> core::slice::Iter<'_, K> {
408 self.dense.iter()
409 }
410
411 pub fn drain(&mut self) -> Drain<'_, K> {
425 Drain(self.dense.drain(..))
428 }
429
430 pub fn extract_if<F: FnMut(&K) -> bool>(&mut self, pred: F) -> ExtractIf<'_, K, F, PAGE, D> {
448 ExtractIf {
449 set: self,
450 pos: 0,
451 pred,
452 }
453 }
454
455 pub(crate) fn positions(&self, indices: &impl RangeBounds<usize>) -> Positions<'_, K, PAGE, D> {
458 let (first, last) = match resolve(indices) {
459 Some(span) if !self.dense.is_empty() => span,
460 _ => (1, 0),
461 };
462 #[allow(clippy::reversed_empty_ranges)]
463 let pages = if first <= last {
464 split::<PAGE>(first).0..=split::<PAGE>(last).0
465 } else {
466 1..=0
467 };
468 Positions {
469 pages: self.sparse.pages_in(pages),
470 dense: &self.dense,
471 first,
472 last,
473 front: None,
474 back: None,
475 }
476 }
477
478 pub fn range(&self, keys: impl RangeBounds<K>) -> Range<'_, K, PAGE, D> {
499 Range(self.positions(&index_bounds(&keys)))
500 }
501
502 pub fn first(&self) -> Option<&K> {
504 self.range(..).next()
505 }
506
507 pub fn last(&self) -> Option<&K> {
509 self.range(..).next_back()
510 }
511
512 pub fn next_occupant(&self, index: usize) -> Option<&K> {
514 Range(self.positions(&(index..))).next()
515 }
516
517 pub fn prev_occupant(&self, index: usize) -> Option<&K> {
519 Range(self.positions(&(..=index))).next_back()
520 }
521
522 pub fn pop_first(&mut self) -> Option<K> {
524 let pos = self.positions(&..).next()?;
525 Some(self.remove_at(pos))
526 }
527
528 pub fn pop_last(&mut self) -> Option<K> {
530 let pos = self.positions(&..).next_back()?;
531 Some(self.remove_at(pos))
532 }
533
534 pub fn difference<'a, const P2: usize, D2: Directory>(
544 &'a self,
545 other: &'a PagedSparseSet<K, P2, D2>,
546 ) -> Difference<'a, K, P2, D2> {
547 Difference {
548 iter: self.iter(),
549 other,
550 }
551 }
552
553 pub fn intersection<'a, const P2: usize, D2: Directory>(
566 &'a self,
567 other: &'a PagedSparseSet<K, P2, D2>,
568 ) -> Intersection<'a, K, PAGE, D, P2, D2> {
569 let (iter, probe) = if self.len() <= other.len() {
570 (self.iter(), IntersectionProbe::Right(other))
571 } else {
572 (other.iter(), IntersectionProbe::Left(self))
573 };
574 Intersection { iter, probe }
575 }
576
577 pub fn symmetric_difference<'a, const P2: usize, D2: Directory>(
592 &'a self,
593 other: &'a PagedSparseSet<K, P2, D2>,
594 ) -> SymmetricDifference<'a, K, PAGE, D, P2, D2> {
595 SymmetricDifference {
596 iter: self.difference(other).chain(other.difference(self)),
597 }
598 }
599
600 pub fn union<'a, const P2: usize, D2: Directory>(
615 &'a self,
616 other: &'a PagedSparseSet<K, P2, D2>,
617 ) -> Union<'a, K, PAGE, D> {
618 Union {
619 iter: self.iter().chain(other.difference(self)),
620 }
621 }
622
623 pub fn is_disjoint<const P2: usize, D2: Directory>(
633 &self,
634 other: &PagedSparseSet<K, P2, D2>,
635 ) -> bool {
636 self.intersection(other).next().is_none()
637 }
638
639 pub fn is_subset<const P2: usize, D2: Directory>(
649 &self,
650 other: &PagedSparseSet<K, P2, D2>,
651 ) -> bool {
652 self.len() <= other.len() && self.iter().all(|&key| other.contains(key))
653 }
654
655 pub fn is_superset<const P2: usize, D2: Directory>(
665 &self,
666 other: &PagedSparseSet<K, P2, D2>,
667 ) -> bool {
668 other.is_subset(self)
669 }
670
671 pub(crate) fn swap_positions(&mut self, a: usize, b: usize) {
674 let a_index = self.dense[a].index();
676 let b_index = self.dense[b].index();
677 self.dense.swap(a, b);
678 self.set_slot(a_index, encode(b));
679 self.set_slot(b_index, encode(a));
680 }
681
682 fn reindex(&mut self) {
684 for pos in 0..self.dense.len() {
685 let index = self.dense[pos].index();
686 self.set_slot(index, encode(pos));
687 }
688 }
689
690 pub(crate) fn reorder_dense(&mut self, reorder: impl FnOnce(&mut [K])) {
695 struct Reindex<'a, K: Key, const PAGE: usize, D: Directory>(
696 &'a mut PagedSparseSet<K, PAGE, D>,
697 );
698 impl<K: Key, const PAGE: usize, D: Directory> Drop for Reindex<'_, K, PAGE, D> {
699 fn drop(&mut self) {
700 self.0.reindex();
701 }
702 }
703 let guard = Reindex(self);
704 reorder(&mut guard.0.dense);
705 }
706
707 pub fn sort_by(&mut self, compare: impl FnMut(&K, &K) -> core::cmp::Ordering) {
713 self.reorder_dense(|dense| dense.sort_by(compare));
714 }
715
716 pub fn sort_by_key<T: Ord>(&mut self, f: impl FnMut(&K) -> T) {
722 self.reorder_dense(|dense| dense.sort_by_key(f));
723 }
724
725 pub fn sort(&mut self)
730 where
731 K: Ord,
732 {
733 self.reorder_dense(<[K]>::sort);
734 }
735
736 pub fn sort_unstable_by(&mut self, compare: impl FnMut(&K, &K) -> core::cmp::Ordering) {
741 self.reorder_dense(|dense| dense.sort_unstable_by(compare));
742 }
743
744 pub fn sort_unstable_by_key<T: Ord>(&mut self, f: impl FnMut(&K) -> T) {
750 self.reorder_dense(|dense| dense.sort_unstable_by_key(f));
751 }
752
753 pub fn sort_unstable(&mut self)
756 where
757 K: Ord,
758 {
759 self.reorder_dense(<[K]>::sort_unstable);
760 }
761}
762
763impl<K: Key, const PAGE: usize, D: Directory> Default for PagedSparseSet<K, PAGE, D> {
764 fn default() -> Self {
765 Self::new()
766 }
767}
768
769impl<K: Key, const PAGE: usize, D: Directory> Clone for PagedSparseSet<K, PAGE, D>
770where
771 D::Store<Slot, PAGE>: Clone,
772{
773 fn clone(&self) -> Self {
774 Self {
775 dense: self.dense.clone(),
776 sparse: self.sparse.clone(),
777 }
778 }
779}
780
781impl<K: Key + fmt::Debug, const PAGE: usize, D: Directory> fmt::Debug
782 for PagedSparseSet<K, PAGE, D>
783{
784 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
785 f.debug_set().entries(self.dense.iter()).finish()
786 }
787}
788
789impl<K: Key, const PAGE: usize, D: Directory, const P2: usize, D2: Directory>
792 PartialEq<PagedSparseSet<K, P2, D2>> for PagedSparseSet<K, PAGE, D>
793{
794 fn eq(&self, other: &PagedSparseSet<K, P2, D2>) -> bool {
795 self.len() == other.len() && self.iter().all(|&key| other.contains(key))
796 }
797}
798
799impl<K: Key, const PAGE: usize, D: Directory> Eq for PagedSparseSet<K, PAGE, D> {}
801
802impl<K: Key + Hash, const PAGE: usize, D: Directory> Hash for PagedSparseSet<K, PAGE, D> {
804 fn hash<H: Hasher>(&self, state: &mut H) {
805 hash_unordered(self.iter(), state);
806 }
807}
808
809impl<K: Key, const PAGE: usize, D: Directory> Extend<K> for PagedSparseSet<K, PAGE, D> {
810 fn extend<I: IntoIterator<Item = K>>(&mut self, iter: I) {
811 for key in iter {
812 self.insert(key);
813 }
814 }
815}
816
817impl<'a, K: Key + 'a, const PAGE: usize, D: Directory> Extend<&'a K>
818 for PagedSparseSet<K, PAGE, D>
819{
820 fn extend<I: IntoIterator<Item = &'a K>>(&mut self, iter: I) {
821 self.extend(iter.into_iter().copied());
822 }
823}
824
825impl<K: Key, const PAGE: usize, D: Directory> FromIterator<K> for PagedSparseSet<K, PAGE, D> {
826 fn from_iter<I: IntoIterator<Item = K>>(iter: I) -> Self {
827 let mut set = Self::new();
828 set.extend(iter);
829 set
830 }
831}
832
833impl<'a, K: Key, const PAGE: usize, D: Directory> IntoIterator for &'a PagedSparseSet<K, PAGE, D> {
834 type Item = &'a K;
835 type IntoIter = core::slice::Iter<'a, K>;
836
837 fn into_iter(self) -> Self::IntoIter {
838 self.dense.iter()
839 }
840}
841
842impl<K: Key, const PAGE: usize, D: Directory> IntoIterator for PagedSparseSet<K, PAGE, D> {
843 type Item = K;
844 type IntoIter = alloc::vec::IntoIter<K>;
845
846 fn into_iter(self) -> Self::IntoIter {
847 self.dense.into_iter()
848 }
849}
850
851pub(crate) fn index_bounds<K: Key>(keys: &impl RangeBounds<K>) -> (Bound<usize>, Bound<usize>) {
853 (
854 keys.start_bound().map(|key| key.index()),
855 keys.end_bound().map(|key| key.index()),
856 )
857}
858
859fn resolve(indices: &impl RangeBounds<usize>) -> Option<(usize, usize)> {
862 let first = match indices.start_bound() {
863 Bound::Included(&index) => Some(index),
864 Bound::Excluded(&index) => index.checked_add(1),
865 Bound::Unbounded => Some(0),
866 }?;
867 let last = match indices.end_bound() {
868 Bound::Included(&index) => Some(index),
869 Bound::Excluded(&index) => index.checked_sub(1),
870 Bound::Unbounded => Some(usize::MAX),
871 }?;
872 (first <= last).then_some((first, last))
873}
874
875struct Part<'a, const PAGE: usize> {
878 base: usize,
879 page: &'a [Slot; PAGE],
880 offsets: core::ops::Range<usize>,
881}
882
883impl<const PAGE: usize> Clone for Part<'_, PAGE> {
884 fn clone(&self) -> Self {
885 Self {
886 base: self.base,
887 page: self.page,
888 offsets: self.offsets.clone(),
889 }
890 }
891}
892
893pub(crate) struct Positions<'a, K, const PAGE: usize, D: Directory + 'a> {
897 pages: <D::Store<Slot, PAGE> as PageStore<Slot, PAGE>>::Pages<'a>,
898 dense: &'a [K],
899 first: usize,
900 last: usize,
901 front: Option<Part<'a, PAGE>>,
902 back: Option<Part<'a, PAGE>>,
903}
904
905impl<'a, K, const PAGE: usize, D: Directory + 'a> Clone for Positions<'a, K, PAGE, D> {
906 fn clone(&self) -> Self {
907 Self {
908 pages: self.pages.clone(),
909 dense: self.dense,
910 first: self.first,
911 last: self.last,
912 front: self.front.clone(),
913 back: self.back.clone(),
914 }
915 }
916}
917
918impl<'a, K: Key, const PAGE: usize, D: Directory + 'a> Positions<'a, K, PAGE, D> {
919 #[inline]
921 pub(crate) fn dense(&self) -> &'a [K] {
922 self.dense
923 }
924
925 fn part(&self, number: usize, page: &'a [Slot; PAGE]) -> Part<'a, PAGE> {
927 let base = number.saturating_mul(PAGE);
928 let end = match self.last.checked_sub(base) {
929 Some(offset) => offset.saturating_add(1).min(PAGE),
930 None => 0,
933 };
934 Part {
935 base,
936 page,
937 offsets: self.first.saturating_sub(base).min(end)..end,
938 }
939 }
940
941 #[inline]
943 fn valid(&self, part: &Part<'a, PAGE>, offset: usize) -> Option<usize> {
944 let pos = part.page[offset]?.get() as usize - 1;
945 let key = self.dense.get(pos)?;
946 (key.index() == part.base + offset).then_some(pos)
947 }
948}
949
950impl<'a, K: Key, const PAGE: usize, D: Directory + 'a> Iterator for Positions<'a, K, PAGE, D> {
951 type Item = usize;
952
953 fn next(&mut self) -> Option<usize> {
954 loop {
955 if let Some(mut part) = self.front.take() {
956 while let Some(offset) = part.offsets.next() {
957 if let Some(pos) = self.valid(&part, offset) {
958 self.front = Some(part);
959 return Some(pos);
960 }
961 }
962 }
963 match self.pages.next() {
964 Some((number, page)) => self.front = Some(self.part(number, page)),
965 None => self.front = Some(self.back.take()?),
968 }
969 }
970 }
971
972 fn size_hint(&self) -> (usize, Option<usize>) {
973 (0, Some(self.dense.len()))
975 }
976}
977
978impl<'a, K: Key, const PAGE: usize, D: Directory + 'a> DoubleEndedIterator
979 for Positions<'a, K, PAGE, D>
980{
981 fn next_back(&mut self) -> Option<usize> {
982 loop {
983 if let Some(mut part) = self.back.take() {
984 while let Some(offset) = part.offsets.next_back() {
985 if let Some(pos) = self.valid(&part, offset) {
986 self.back = Some(part);
987 return Some(pos);
988 }
989 }
990 }
991 match self.pages.next_back() {
992 Some((number, page)) => self.back = Some(self.part(number, page)),
993 None => self.back = Some(self.front.take()?),
994 }
995 }
996 }
997}
998
999impl<'a, K: Key, const PAGE: usize, D: Directory + 'a> FusedIterator for Positions<'a, K, PAGE, D> {}
1000
1001pub struct Range<'a, K, const PAGE: usize = DEFAULT_PAGE, D: Directory + 'a = Flat>(
1003 Positions<'a, K, PAGE, D>,
1004);
1005
1006impl<'a, K: Key, const PAGE: usize, D: Directory + 'a> Iterator for Range<'a, K, PAGE, D> {
1007 type Item = &'a K;
1008
1009 #[inline]
1010 fn next(&mut self) -> Option<&'a K> {
1011 let pos = self.0.next()?;
1012 Some(&self.0.dense[pos])
1013 }
1014
1015 #[inline]
1016 fn size_hint(&self) -> (usize, Option<usize>) {
1017 self.0.size_hint()
1018 }
1019}
1020
1021impl<'a, K: Key, const PAGE: usize, D: Directory + 'a> DoubleEndedIterator
1022 for Range<'a, K, PAGE, D>
1023{
1024 #[inline]
1025 fn next_back(&mut self) -> Option<Self::Item> {
1026 let pos = self.0.next_back()?;
1027 Some(&self.0.dense[pos])
1028 }
1029}
1030
1031impl<'a, K: Key, const PAGE: usize, D: Directory + 'a> FusedIterator for Range<'a, K, PAGE, D> {}
1032
1033impl<'a, K, const PAGE: usize, D: Directory + 'a> Clone for Range<'a, K, PAGE, D> {
1034 fn clone(&self) -> Self {
1035 Self(self.0.clone())
1036 }
1037}
1038
1039impl<'a, K: Key + fmt::Debug, const PAGE: usize, D: Directory + 'a> fmt::Debug
1040 for Range<'a, K, PAGE, D>
1041{
1042 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1043 f.debug_list().entries(self.clone()).finish()
1044 }
1045}
1046
1047#[derive(Debug)]
1049pub struct Drain<'a, K>(alloc::vec::Drain<'a, K>);
1050
1051impl<K> Iterator for Drain<'_, K> {
1052 type Item = K;
1053
1054 #[inline]
1055 fn next(&mut self) -> Option<K> {
1056 self.0.next()
1057 }
1058
1059 #[inline]
1060 fn size_hint(&self) -> (usize, Option<usize>) {
1061 self.0.size_hint()
1062 }
1063}
1064
1065impl<K> DoubleEndedIterator for Drain<'_, K> {
1066 #[inline]
1067 fn next_back(&mut self) -> Option<K> {
1068 self.0.next_back()
1069 }
1070}
1071
1072impl<K> ExactSizeIterator for Drain<'_, K> {}
1073
1074impl<K> FusedIterator for Drain<'_, K> {}
1075
1076pub struct ExtractIf<'a, K, F, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> {
1078 set: &'a mut PagedSparseSet<K, PAGE, D>,
1079 pos: usize,
1080 pred: F,
1081}
1082
1083impl<K: Key, F: FnMut(&K) -> bool, const PAGE: usize, D: Directory> Iterator
1084 for ExtractIf<'_, K, F, PAGE, D>
1085{
1086 type Item = K;
1087
1088 fn next(&mut self) -> Option<K> {
1089 while self.pos < self.set.dense.len() {
1090 let pos = self.pos;
1091 self.pos += 1;
1093 if (self.pred)(&self.set.dense[pos]) {
1094 self.pos = pos;
1096 return Some(self.set.remove_at(pos));
1097 }
1098 }
1099 None
1100 }
1101
1102 fn size_hint(&self) -> (usize, Option<usize>) {
1103 (0, Some(self.set.dense.len() - self.pos))
1104 }
1105}
1106
1107impl<K: Key, F: FnMut(&K) -> bool, const PAGE: usize, D: Directory> FusedIterator
1108 for ExtractIf<'_, K, F, PAGE, D>
1109{
1110}
1111
1112impl<K: Key + fmt::Debug, F, const PAGE: usize, D: Directory> fmt::Debug
1113 for ExtractIf<'_, K, F, PAGE, D>
1114{
1115 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1116 f.debug_struct("ExtractIf")
1117 .field("untested", &&self.set.dense[self.pos..])
1118 .finish_non_exhaustive()
1119 }
1120}
1121
1122pub struct Difference<'a, K, const P2: usize, D2: Directory> {
1124 iter: slice::Iter<'a, K>,
1125 other: &'a PagedSparseSet<K, P2, D2>,
1126}
1127
1128impl<'a, K: Key, const P2: usize, D2: Directory> Iterator for Difference<'a, K, P2, D2> {
1129 type Item = &'a K;
1130
1131 fn next(&mut self) -> Option<Self::Item> {
1132 self.iter.find(|&&key| !self.other.contains(key))
1133 }
1134
1135 fn size_hint(&self) -> (usize, Option<usize>) {
1136 (0, Some(self.iter.len()))
1137 }
1138}
1139
1140impl<K: Key, const P2: usize, D2: Directory> FusedIterator for Difference<'_, K, P2, D2> {}
1141
1142impl<K, const P2: usize, D2: Directory> Clone for Difference<'_, K, P2, D2> {
1143 fn clone(&self) -> Self {
1144 Self {
1145 iter: self.iter.clone(),
1146 other: self.other,
1147 }
1148 }
1149}
1150
1151impl<K: Key + fmt::Debug, const P2: usize, D2: Directory> fmt::Debug for Difference<'_, K, P2, D2> {
1152 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1153 f.debug_list().entries(self.clone()).finish()
1154 }
1155}
1156
1157enum IntersectionProbe<'a, K, const PAGE: usize, D: Directory, const P2: usize, D2: Directory> {
1158 Left(&'a PagedSparseSet<K, PAGE, D>),
1159 Right(&'a PagedSparseSet<K, P2, D2>),
1160}
1161
1162impl<K, const PAGE: usize, D: Directory, const P2: usize, D2: Directory> Clone
1164 for IntersectionProbe<'_, K, PAGE, D, P2, D2>
1165{
1166 fn clone(&self) -> Self {
1167 *self
1168 }
1169}
1170
1171impl<K, const PAGE: usize, D: Directory, const P2: usize, D2: Directory> Copy
1172 for IntersectionProbe<'_, K, PAGE, D, P2, D2>
1173{
1174}
1175
1176pub struct Intersection<'a, K, const PAGE: usize, D: Directory, const P2: usize, D2: Directory> {
1178 iter: slice::Iter<'a, K>,
1179 probe: IntersectionProbe<'a, K, PAGE, D, P2, D2>,
1180}
1181
1182impl<'a, K: Key, const PAGE: usize, D: Directory, const P2: usize, D2: Directory> Iterator
1183 for Intersection<'a, K, PAGE, D, P2, D2>
1184{
1185 type Item = &'a K;
1186
1187 fn next(&mut self) -> Option<Self::Item> {
1188 match self.probe {
1189 IntersectionProbe::Left(set) => self.iter.find(|&&key| set.contains(key)),
1190 IntersectionProbe::Right(set) => self.iter.find(|&&key| set.contains(key)),
1191 }
1192 }
1193
1194 fn size_hint(&self) -> (usize, Option<usize>) {
1195 (0, Some(self.iter.len()))
1196 }
1197}
1198
1199impl<K: Key, const PAGE: usize, D: Directory, const P2: usize, D2: Directory> FusedIterator
1200 for Intersection<'_, K, PAGE, D, P2, D2>
1201{
1202}
1203
1204impl<K, const PAGE: usize, D: Directory, const P2: usize, D2: Directory> Clone
1205 for Intersection<'_, K, PAGE, D, P2, D2>
1206{
1207 fn clone(&self) -> Self {
1208 Self {
1209 iter: self.iter.clone(),
1210 probe: self.probe,
1211 }
1212 }
1213}
1214
1215impl<K: Key + fmt::Debug, const PAGE: usize, D: Directory, const P2: usize, D2: Directory>
1216 fmt::Debug for Intersection<'_, K, PAGE, D, P2, D2>
1217{
1218 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1219 f.debug_list().entries(self.clone()).finish()
1220 }
1221}
1222
1223pub struct SymmetricDifference<
1225 'a,
1226 K,
1227 const PAGE: usize,
1228 D: Directory,
1229 const P2: usize,
1230 D2: Directory,
1231> {
1232 iter: Chain<Difference<'a, K, P2, D2>, Difference<'a, K, PAGE, D>>,
1233}
1234
1235impl<'a, K: Key, const PAGE: usize, D: Directory, const P2: usize, D2: Directory> Iterator
1236 for SymmetricDifference<'a, K, PAGE, D, P2, D2>
1237{
1238 type Item = &'a K;
1239
1240 fn next(&mut self) -> Option<Self::Item> {
1241 self.iter.next()
1242 }
1243
1244 fn size_hint(&self) -> (usize, Option<usize>) {
1245 self.iter.size_hint()
1246 }
1247}
1248
1249impl<K: Key, const PAGE: usize, D: Directory, const P2: usize, D2: Directory> FusedIterator
1250 for SymmetricDifference<'_, K, PAGE, D, P2, D2>
1251{
1252}
1253
1254impl<K, const PAGE: usize, D: Directory, const P2: usize, D2: Directory> Clone
1255 for SymmetricDifference<'_, K, PAGE, D, P2, D2>
1256{
1257 fn clone(&self) -> Self {
1258 Self {
1259 iter: self.iter.clone(),
1260 }
1261 }
1262}
1263
1264impl<K: Key + fmt::Debug, const PAGE: usize, D: Directory, const P2: usize, D2: Directory>
1265 fmt::Debug for SymmetricDifference<'_, K, PAGE, D, P2, D2>
1266{
1267 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1268 f.debug_list().entries(self.clone()).finish()
1269 }
1270}
1271
1272pub struct Union<'a, K, const PAGE: usize, D: Directory> {
1274 iter: Chain<slice::Iter<'a, K>, Difference<'a, K, PAGE, D>>,
1275}
1276
1277impl<'a, K: Key, const PAGE: usize, D: Directory> Iterator for Union<'a, K, PAGE, D> {
1278 type Item = &'a K;
1279
1280 fn next(&mut self) -> Option<Self::Item> {
1281 self.iter.next()
1282 }
1283
1284 fn size_hint(&self) -> (usize, Option<usize>) {
1285 self.iter.size_hint()
1286 }
1287}
1288
1289impl<K: Key, const PAGE: usize, D: Directory> FusedIterator for Union<'_, K, PAGE, D> {}
1290
1291impl<K, const PAGE: usize, D: Directory> Clone for Union<'_, K, PAGE, D> {
1292 fn clone(&self) -> Self {
1293 Self {
1294 iter: self.iter.clone(),
1295 }
1296 }
1297}
1298
1299impl<K: Key + fmt::Debug, const PAGE: usize, D: Directory> fmt::Debug for Union<'_, K, PAGE, D> {
1300 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1301 f.debug_list().entries(self.clone()).finish()
1302 }
1303}
1304
1305impl<K: Key, const PAGE: usize, D: Directory, const P2: usize, D2: Directory>
1307 BitOr<&PagedSparseSet<K, P2, D2>> for &PagedSparseSet<K, PAGE, D>
1308{
1309 type Output = PagedSparseSet<K, PAGE, D>;
1310
1311 fn bitor(self, other: &PagedSparseSet<K, P2, D2>) -> Self::Output {
1312 let mut set = PagedSparseSet::with_capacity(self.len());
1313 set.extend(self.union(other));
1314 set
1315 }
1316}
1317
1318impl<K: Key, const PAGE: usize, D: Directory, const P2: usize, D2: Directory>
1320 BitAnd<&PagedSparseSet<K, P2, D2>> for &PagedSparseSet<K, PAGE, D>
1321{
1322 type Output = PagedSparseSet<K, PAGE, D>;
1323
1324 fn bitand(self, other: &PagedSparseSet<K, P2, D2>) -> Self::Output {
1325 let mut set = PagedSparseSet::with_capacity(self.len().min(other.len()));
1326 set.extend(self.intersection(other));
1327 set
1328 }
1329}
1330
1331impl<K: Key, const PAGE: usize, D: Directory, const P2: usize, D2: Directory>
1333 Sub<&PagedSparseSet<K, P2, D2>> for &PagedSparseSet<K, PAGE, D>
1334{
1335 type Output = PagedSparseSet<K, PAGE, D>;
1336
1337 fn sub(self, other: &PagedSparseSet<K, P2, D2>) -> Self::Output {
1338 let mut set = PagedSparseSet::with_capacity(self.len().saturating_sub(other.len()));
1339 set.extend(self.difference(other));
1340 set
1341 }
1342}
1343
1344impl<K: Key, const PAGE: usize, D: Directory, const P2: usize, D2: Directory>
1346 BitXor<&PagedSparseSet<K, P2, D2>> for &PagedSparseSet<K, PAGE, D>
1347{
1348 type Output = PagedSparseSet<K, PAGE, D>;
1349
1350 fn bitxor(self, other: &PagedSparseSet<K, P2, D2>) -> Self::Output {
1351 let mut set = PagedSparseSet::with_capacity(self.len().abs_diff(other.len()));
1352 set.extend(self.symmetric_difference(other));
1353 set
1354 }
1355}
1356
1357impl<K: Key, const PAGE: usize, D: Directory, const P2: usize, D2: Directory>
1359 BitOrAssign<&PagedSparseSet<K, P2, D2>> for PagedSparseSet<K, PAGE, D>
1360{
1361 fn bitor_assign(&mut self, other: &PagedSparseSet<K, P2, D2>) {
1362 self.extend(other);
1363 }
1364}
1365
1366impl<K: Key, const PAGE: usize, D: Directory, const P2: usize, D2: Directory>
1368 BitAndAssign<&PagedSparseSet<K, P2, D2>> for PagedSparseSet<K, PAGE, D>
1369{
1370 fn bitand_assign(&mut self, other: &PagedSparseSet<K, P2, D2>) {
1371 self.retain(|&key| other.contains(key));
1372 }
1373}
1374
1375impl<K: Key, const PAGE: usize, D: Directory, const P2: usize, D2: Directory>
1377 SubAssign<&PagedSparseSet<K, P2, D2>> for PagedSparseSet<K, PAGE, D>
1378{
1379 fn sub_assign(&mut self, other: &PagedSparseSet<K, P2, D2>) {
1380 if other.len() < self.len() {
1381 for &key in other {
1382 self.remove(key);
1383 }
1384 } else {
1385 self.retain(|&key| !other.contains(key));
1386 }
1387 }
1388}
1389
1390impl<K: Key, const PAGE: usize, D: Directory, const P2: usize, D2: Directory>
1394 BitXorAssign<&PagedSparseSet<K, P2, D2>> for PagedSparseSet<K, PAGE, D>
1395{
1396 fn bitxor_assign(&mut self, other: &PagedSparseSet<K, P2, D2>) {
1397 for &key in other {
1398 if !self.remove(key) {
1399 self.insert(key);
1400 }
1401 }
1402 }
1403}
1404
1405#[cfg(feature = "rayon")]
1406mod rayon_impl {
1407 use super::*;
1408 use rayon::prelude::*;
1409
1410 impl<'a, K: Key + Sync, const PAGE: usize, D: Directory> IntoParallelIterator
1411 for &'a PagedSparseSet<K, PAGE, D>
1412 {
1413 type Item = &'a K;
1414 type Iter = rayon::slice::Iter<'a, K>;
1415
1416 fn into_par_iter(self) -> Self::Iter {
1417 self.as_slice().par_iter()
1418 }
1419 }
1420}
1421
1422#[cfg(feature = "serde")]
1423mod serde_impl {
1424 use super::*;
1425 use core::marker::PhantomData;
1426 use serde::de::{Deserialize, Deserializer, SeqAccess, Visitor};
1427 use serde::ser::{Serialize, Serializer};
1428
1429 impl<K: Key + Serialize, const PAGE: usize, D: Directory> Serialize for PagedSparseSet<K, PAGE, D> {
1431 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1432 serializer.collect_seq(self.dense.iter())
1433 }
1434 }
1435
1436 impl<'de, K: Key + Deserialize<'de>, const PAGE: usize, D: Directory> Deserialize<'de>
1445 for PagedSparseSet<K, PAGE, D>
1446 {
1447 fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
1448 struct SeqVisitor<K, const PAGE: usize, D>(PhantomData<(K, D)>);
1449
1450 impl<'de, K: Key + Deserialize<'de>, const PAGE: usize, D: Directory> Visitor<'de>
1451 for SeqVisitor<K, PAGE, D>
1452 {
1453 type Value = PagedSparseSet<K, PAGE, D>;
1454
1455 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1456 f.write_str("a sequence of keys")
1457 }
1458
1459 fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
1460 let hint = seq.size_hint().unwrap_or(0).min(4096);
1463 let mut set = PagedSparseSet::with_capacity(hint);
1464 while let Some(key) = seq.next_element()? {
1465 set.insert(key);
1466 }
1467 Ok(set)
1468 }
1469 }
1470
1471 deserializer.deserialize_seq(SeqVisitor::<K, PAGE, D>(PhantomData))
1472 }
1473 }
1474}
1475
1476#[cfg(all(test, any(target_pointer_width = "32", target_pointer_width = "64")))]
1479mod tests {
1480 use super::*;
1481 use crate::page::Radix;
1482 #[cfg(target_pointer_width = "64")]
1483 use crate::page::Tree;
1484
1485 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
1486 struct Gen(u32);
1487
1488 impl Key for Gen {
1489 fn index(self) -> usize {
1490 (self.0 & 0xffff) as usize
1491 }
1492 }
1493
1494 #[cfg(target_pointer_width = "64")]
1495 #[test]
1496 fn wide_keys_allocate_few_pages() {
1497 let mut set: PagedSparseSet<u64, 64, Tree> = PagedSparseSet::new();
1498 for k in [0, u64::MAX, u64::MAX / 2, 1 << 40] {
1499 assert!(set.insert(k));
1500 }
1501 assert_eq!(set.allocated_pages(), 4);
1502 assert!(set.contains(u64::MAX));
1503 assert!(!set.contains(u64::MAX - 1));
1504 }
1505
1506 #[test]
1507 fn remove_moves_last_key() {
1508 let mut set: PagedSparseSet<u32, 4> = [1, 2, 3, 40].into_iter().collect();
1509 assert!(set.remove(1));
1510 assert_eq!(set.as_slice(), &[40, 2, 3]);
1511 assert_eq!(set.position(40), Some(0));
1512 assert!(!set.remove(1));
1513 assert!(!set.contains(1));
1514 }
1515
1516 #[test]
1517 fn swap_positions_reindexes_both_keys() {
1518 let old = Gen(2);
1519 let new = Gen(2 | 1 << 16);
1520 let mut set: PagedSparseSet<Gen, 4> = [Gen(1), old, Gen(40)].into_iter().collect();
1521 assert_eq!(set.replace(new), Some(old));
1522 set.swap_positions(1, 2);
1523 assert_eq!(set.as_slice(), &[Gen(1), Gen(40), new]);
1524 for (pos, &key) in set.iter().enumerate() {
1525 assert_eq!(set.position(key), Some(pos));
1526 }
1527 assert!(!set.contains(old));
1528 set.swap_positions(0, 0);
1529 assert_eq!(set.position(Gen(1)), Some(0));
1530 assert!(set.remove(Gen(40)));
1531 assert_eq!(set.position(new), Some(1));
1532 }
1533
1534 #[test]
1535 fn clear_is_lazy_but_correct() {
1536 let mut set: PagedSparseSet<u32, 4> = (0..10).collect();
1537 set.clear();
1538 assert!(set.is_empty());
1539 assert_eq!(set.allocated_pages(), 3);
1540 for k in 0..10 {
1541 assert!(!set.contains(k));
1542 }
1543 assert!(set.insert(9));
1544 assert!(!set.contains(0));
1545 assert_eq!(set.position(9), Some(0));
1546 set.reset();
1547 assert_eq!(set.allocated_pages(), 0);
1548 }
1549
1550 #[test]
1551 fn generations_compete_for_one_slot() {
1552 let old = Gen(7);
1553 let new = Gen(7 | 1 << 16);
1554 let mut set: PagedSparseSet<Gen> = PagedSparseSet::new();
1555 assert!(set.insert(old));
1556 assert!(!set.insert(new));
1557 assert!(!set.contains(new));
1558 assert_eq!(set.occupant(7), Some(&old));
1559 assert_eq!(set.replace(new), Some(old));
1560 assert!(set.contains(new) && !set.contains(old));
1561 assert!(!set.remove(old));
1562 assert_eq!(set.remove_occupant(7), Some(new));
1563 assert!(set.is_empty());
1564 }
1565
1566 #[test]
1567 fn retain_and_sort_keep_index_consistent() {
1568 let mut set: PagedSparseSet<u32, 8> = [9, 3, 7, 1, 8, 2].into_iter().collect();
1569 set.retain(|&k| k % 3 != 0);
1570 set.sort_unstable();
1571 assert_eq!(set.as_slice(), &[1, 2, 7, 8]);
1572 for (pos, &k) in set.as_slice().iter().enumerate() {
1573 assert_eq!(set.position(k), Some(pos));
1574 }
1575 assert!(!set.contains(3) && !set.contains(9));
1576 }
1577
1578 #[test]
1579 fn stable_sorts_keep_ties_in_order() {
1580 let mut set: PagedSparseSet<u32, 4> = [5, 9, 2, 7, 40, 12].into_iter().collect();
1581 set.sort_by_key(|&k| k % 2);
1582 assert_eq!(set.as_slice(), &[2, 40, 12, 5, 9, 7]);
1583 set.sort_by(|a, b| (b / 10).cmp(&(a / 10)));
1584 assert_eq!(set.as_slice(), &[40, 12, 2, 5, 9, 7]);
1585 for (pos, &key) in set.as_slice().iter().enumerate() {
1586 assert_eq!(set.position(key), Some(pos));
1587 }
1588 set.sort();
1589 assert_eq!(set.as_slice(), &[2, 5, 7, 9, 12, 40]);
1590 assert_eq!(set.position(12), Some(4));
1591 assert_eq!(set.as_slice().binary_search(&9), Ok(3));
1592 }
1593
1594 #[test]
1595 fn equality_ignores_order() {
1596 let a: PagedSparseSet<u32> = [1, 2, 3].into_iter().collect();
1597 let b: PagedSparseSet<u32> = [3, 1, 2].into_iter().collect();
1598 let c: PagedSparseSet<u32> = [1, 2].into_iter().collect();
1599 assert_eq!(a, b);
1600 assert_ne!(a, c);
1601 }
1602
1603 #[test]
1604 fn set_algebra_preserves_the_left_generation_when_stored() {
1605 let old = Gen(7);
1606 let new = Gen(7 | 1 << 16);
1607 let common = Gen(42);
1608 let left_only = Gen(13);
1609 let right_only = Gen(21);
1610 let left: PagedSparseSet<Gen, 4> = [old, common, left_only].into_iter().collect();
1611 let right: PagedSparseSet<Gen, 64, Radix> = [new, common, right_only].into_iter().collect();
1612
1613 let union = left.union(&right).copied();
1614 assert!(union.clone().eq([old, common, left_only, new, right_only]));
1615 assert_eq!(
1616 union.collect::<PagedSparseSet<Gen>>().occupant(7),
1617 Some(&old)
1618 );
1619 assert_eq!(
1620 (&left | &right).as_slice(),
1621 &[old, common, left_only, right_only]
1622 );
1623 assert_eq!((&right | &left).occupant(7), Some(&new));
1624
1625 let symmetric = left.symmetric_difference(&right).copied();
1626 assert!(symmetric.clone().eq([old, left_only, new, right_only]));
1627 assert_eq!(
1628 symmetric.collect::<PagedSparseSet<Gen>>().occupant(7),
1629 Some(&old)
1630 );
1631 assert_eq!((&left ^ &right).as_slice(), &[old, left_only, right_only]);
1632 assert_eq!((&right ^ &left).occupant(7), Some(&new));
1633
1634 let mut assigned = left;
1635 assigned ^= &right;
1636 assert_eq!(assigned.as_slice(), &[old, left_only, right_only]);
1637 assert_eq!(assigned.occupant(7), Some(&old));
1638 assert!(!assigned.contains(new));
1639 assert!(!assigned.contains(common));
1640 }
1641
1642 #[test]
1643 fn set_algebra_across_page_sizes_and_directories() {
1644 let left: PagedSparseSet<u32, 4> = [90, 7, 1, 4].into_iter().collect();
1645 let right: PagedSparseSet<u32, 64, Radix> = [1, 7, 128].into_iter().collect();
1646 assert!(left.difference(&right).copied().eq([90, 4]));
1647 assert!(left.intersection(&right).copied().eq([1, 7]));
1648 assert!(right.intersection(&left).copied().eq([1, 7]));
1649 assert!(left.union(&right).copied().eq([90, 7, 1, 4, 128]));
1650 assert!(left.symmetric_difference(&right).copied().eq([90, 4, 128]));
1651
1652 let tie: PagedSparseSet<u32, 64, Radix> = [1, 7, 128, 256].into_iter().collect();
1653 assert!(left.intersection(&tie).copied().eq([7, 1]));
1654
1655 let union: PagedSparseSet<u32, 4> = &left | &right;
1656 let intersection: PagedSparseSet<u32, 4> = &left & &right;
1657 let difference: PagedSparseSet<u32, 4> = &left - &right;
1658 let symmetric: PagedSparseSet<u32, 4> = &left ^ &right;
1659 assert_eq!(union.as_slice(), &[90, 7, 1, 4, 128]);
1660 assert_eq!(intersection.as_slice(), &[1, 7]);
1661 assert_eq!(difference.as_slice(), &[90, 4]);
1662 assert_eq!(symmetric.as_slice(), &[90, 4, 128]);
1663
1664 let mut assigned = left.clone();
1665 assigned |= &right;
1666 assert_eq!(assigned, union);
1667 let mut assigned = left.clone();
1668 assigned &= &right;
1669 assert_eq!(assigned, intersection);
1670 let mut assigned = left.clone();
1671 assigned -= &right;
1672 assert_eq!(assigned, difference);
1673 let mut assigned = left;
1674 assigned ^= &right;
1675 assert_eq!(assigned, symmetric);
1676 }
1677
1678 #[test]
1679 fn empty_sets_and_set_relationships() {
1680 let empty = PagedSparseSet::<u32, 4>::new();
1681 let set: PagedSparseSet<u32, 64, Radix> = [2, 1].into_iter().collect();
1682 let subset: PagedSparseSet<u32, 4> = [1].into_iter().collect();
1683 let disjoint: PagedSparseSet<u32, 4> = [3, 4, 5].into_iter().collect();
1684
1685 assert_eq!(empty.difference(&set).next(), None);
1686 assert!(set.difference(&empty).copied().eq([2, 1]));
1687 assert_eq!(set.intersection(&empty).next(), None);
1688 assert!(empty.union(&set).copied().eq([2, 1]));
1689 assert!(set.symmetric_difference(&empty).copied().eq([2, 1]));
1690 assert_eq!(empty.union(&empty).next(), None);
1691 assert_eq!(empty.symmetric_difference(&empty).next(), None);
1692
1693 assert!(empty.is_subset(&empty) && empty.is_superset(&empty));
1694 assert!(empty.is_disjoint(&empty));
1695 assert!(empty.is_subset(&set) && set.is_superset(&empty));
1696 assert!(!set.is_subset(&empty) && !empty.is_superset(&set));
1697 assert!(empty.is_disjoint(&set) && set.is_disjoint(&empty));
1698 assert!(subset.is_subset(&set) && set.is_superset(&subset));
1699 assert!(!set.is_subset(&subset) && !subset.is_superset(&set));
1700 assert!(!subset.is_disjoint(&set) && !set.is_disjoint(&subset));
1701 assert!(set.is_subset(&set) && set.is_superset(&set));
1702 assert!(!set.is_disjoint(&set));
1703 assert!(set.is_disjoint(&disjoint) && disjoint.is_disjoint(&set));
1704 assert!(!set.is_subset(&disjoint) && !disjoint.is_superset(&set));
1705 }
1706
1707 #[test]
1708 fn set_iterators_report_remaining_bounds_and_keys() {
1709 fn assert_exhausted(mut iter: impl FusedIterator) {
1710 assert!(iter.next().is_none());
1711 assert_eq!(iter.size_hint(), (0, Some(0)));
1712 assert!(iter.next().is_none());
1713 }
1714
1715 let left: PagedSparseSet<u32, 4> = [4, 2, 7, 3].into_iter().collect();
1716 let right: PagedSparseSet<u32, 64, Radix> = [7, 2, 5].into_iter().collect();
1717
1718 let mut difference = left.difference(&right);
1719 assert_eq!(difference.size_hint(), (0, Some(4)));
1720 assert_eq!(difference.next(), Some(&4));
1721 assert_eq!(difference.size_hint(), (0, Some(3)));
1722 assert_eq!(alloc::format!("{difference:?}"), "[3]");
1723 assert_eq!(difference.next(), Some(&3));
1724 assert_exhausted(difference);
1725
1726 let mut intersection = left.intersection(&right);
1727 assert_eq!(intersection.size_hint(), (0, Some(3)));
1728 assert_eq!(intersection.next(), Some(&7));
1729 assert_eq!(intersection.size_hint(), (0, Some(2)));
1730 assert_eq!(alloc::format!("{intersection:?}"), "[2]");
1731 assert_eq!(intersection.next(), Some(&2));
1732 assert_exhausted(intersection);
1733
1734 let mut union = left.union(&right);
1735 assert_eq!(union.size_hint(), (4, Some(7)));
1736 assert_eq!(union.next(), Some(&4));
1737 assert_eq!(union.size_hint(), (3, Some(6)));
1738 assert_eq!(alloc::format!("{union:?}"), "[2, 7, 3, 5]");
1739 assert!(union.by_ref().take(3).copied().eq([2, 7, 3]));
1740 assert_eq!(union.size_hint(), (0, Some(3)));
1741 assert_eq!(union.next(), Some(&5));
1742 assert_exhausted(union);
1743
1744 let mut symmetric = left.symmetric_difference(&right);
1745 assert_eq!(symmetric.size_hint(), (0, Some(7)));
1746 assert_eq!(symmetric.next(), Some(&4));
1747 assert_eq!(symmetric.size_hint(), (0, Some(6)));
1748 assert_eq!(alloc::format!("{symmetric:?}"), "[3, 5]");
1749 assert_eq!(symmetric.next(), Some(&3));
1750 assert_eq!(symmetric.size_hint(), (0, Some(3)));
1751 assert_eq!(symmetric.next(), Some(&5));
1752 assert_exhausted(symmetric);
1753 }
1754}