paged-collections 0.2.0

Paged sparse sets, maps and stable-address containers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
//! [`PagedSparseSet`]: a sparse set whose sparse index is paged.
//!
//! A sparse set keeps its keys in a contiguous *dense* array and finds them
//! through a *sparse* index from slot index to dense position. Here the sparse
//! index is split into pages that are allocated on first use, so memory
//! follows the key ranges actually used instead of the largest key.
//!
//! | Operation | Cost |
//! |---|---|
//! | [`insert`](PagedSparseSet::insert), [`remove`](PagedSparseSet::remove), [`contains`](PagedSparseSet::contains) | O(1) (O(depth) with [`Radix`](crate::page::Radix), O(log pages) with [`Tree`](crate::page::Tree)) |
//! | [`clear`](PagedSparseSet::clear) | O(1): pages are kept and old slots are ignored |
//! | iteration, [`as_slice`](PagedSparseSet::as_slice) | over the dense array only |
//! | [`range`](PagedSparseSet::range), [`first`](PagedSparseSet::first), [`next_occupant`](PagedSparseSet::next_occupant), ... | in slot-index order, over the sparse pages and slots in the range (stale slots included) |
//!
//! Lookups follow Briggs and Torczon: a slot is trusted only if it points
//! inside the dense array at a key with the same slot index. Stale slots, left
//! by [`clear`](PagedSparseSet::clear), are therefore harmless.
//!
//! ```
//! use paged_collections::sparse_set::PagedSparseSet;
//!
//! let mut set: PagedSparseSet<u32> = PagedSparseSet::new();
//! assert!(set.insert(3_000_000));
//! assert!(set.insert(7));
//! assert!(!set.insert(7));
//! assert!(set.contains(3_000_000));
//! // Two 4 KiB pages instead of a 12 MB flat sparse array.
//! assert_eq!(set.allocated_pages(), 2);
//!
//! assert!(set.remove(7));
//! assert_eq!(set.as_slice(), &[3_000_000]);
//! ```
//!
//! With the `rayon` feature, the borrowed parallel iterator is indexed and
//! follows dense order.
//!
//! ```rust
//! # #[cfg(feature = "rayon")] {
//! use paged_collections::sparse_set::PagedSparseSet;
//! use rayon::prelude::*;
//!
//! let set: PagedSparseSet<u32> = [7, 2, 9].into_iter().collect();
//! assert_eq!(set.par_iter().copied().collect::<Vec<_>>(), [7, 2, 9]);
//! # }
//! ```

use alloc::collections::TryReserveError;
use alloc::vec::Vec;
use core::fmt;
use core::hash::{Hash, Hasher};
use core::iter::{Chain, FusedIterator};
use core::num::NonZeroU32;
use core::ops::{
    BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Bound, RangeBounds, Sub,
    SubAssign,
};
use core::slice;

use crate::hash::hash_unordered;
use crate::key::Key;
use crate::page::{DEFAULT_PAGE, Directory, Flat, PageStore, split};

/// One slot of the sparse index: the dense position plus one, or `None`.
///
/// Storing the position plus one in a [`NonZeroU32`] keeps the slot at four
/// bytes and makes `None` the all-zero default. It limits a set to
/// `u32::MAX` keys.
pub type Slot = Option<NonZeroU32>;

/// A set of [`Key`]s with O(1) insert, remove and lookup, and a contiguous
/// array of its keys.
///
/// - `PAGE` is the number of slots per page of the sparse index; it must be
///   non-zero. See [`DEFAULT_PAGE`].
/// - `D` picks the page directory: [`Flat`] (default) for dense keys,
///   [`Radix`](crate::page::Radix) for keys spread over the 64-bit range,
///   or [`Tree`](crate::page::Tree). See [`crate::page`].
///
/// The set holds at most one key per slot index. With plain integer keys that
/// is the usual set semantics. With generational keys, [`insert`] refuses a
/// key whose slot is held by another generation, and [`replace`] overwrites
/// it.
///
/// Keys are kept in insertion order until a removal, which moves the last key
/// into the gap.
///
/// # Set operations
///
/// [`union`](Self::union), [`intersection`](Self::intersection),
/// [`difference`](Self::difference), and
/// [`symmetric_difference`](Self::symmetric_difference) iterate over borrowed
/// keys. The corresponding operators `|`, `&`, `-`, and `^` on borrowed sets
/// create a set with the left operand's page size and directory. The assignment
/// operators `|=`, `&=`, `-=`, and `^=` update a set in place. Removals can
/// reorder keys by moving the last key into each gap.
/// [`is_disjoint`](Self::is_disjoint), [`is_subset`](Self::is_subset), and
/// [`is_superset`](Self::is_superset) test relationships between sets.
///
/// ```
/// use paged_collections::page::Radix;
/// use paged_collections::sparse_set::PagedSparseSet;
///
/// let mut a: PagedSparseSet<u16, 4> = [1, 2].into_iter().collect();
/// let b: PagedSparseSet<u16, 64, Radix> = [2, 3].into_iter().collect();
/// assert_eq!((&a | &b).as_slice(), &[1, 2, 3]);
/// a &= &b;
/// assert!(a.is_subset(&b));
/// ```
///
/// [`insert`]: PagedSparseSet::insert
/// [`replace`]: PagedSparseSet::replace
pub struct PagedSparseSet<K, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> {
    dense: Vec<K>,
    sparse: D::Store<Slot, PAGE>,
}

/// Encodes a dense position that is already in the set.
#[inline]
fn encode(pos: usize) -> Slot {
    pos.checked_add(1)
        .and_then(|p| u32::try_from(p).ok())
        .and_then(NonZeroU32::new)
}

impl<K: Key, const PAGE: usize, D: Directory> PagedSparseSet<K, PAGE, D> {
    /// Number of slots per page of the sparse index.
    pub const PAGE_SIZE: usize = PAGE;

    /// Creates an empty set. No memory is allocated until the first insert.
    pub fn new() -> Self {
        Self {
            dense: Vec::new(),
            sparse: Default::default(),
        }
    }

    /// Creates an empty set whose dense array can hold `capacity` keys
    /// without reallocating. Pages are still allocated on demand.
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            dense: Vec::with_capacity(capacity),
            sparse: Default::default(),
        }
    }

    /// Number of keys in the set.
    #[inline]
    pub fn len(&self) -> usize {
        self.dense.len()
    }

    /// Whether the set has no keys.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.dense.is_empty()
    }

    /// Number of keys the dense array can hold without reallocating.
    #[inline]
    pub fn capacity(&self) -> usize {
        self.dense.capacity()
    }

    /// Number of allocated pages in the sparse index.
    #[inline]
    pub fn allocated_pages(&self) -> usize {
        self.sparse.allocated()
    }

    /// Reserves room in the dense array for at least `additional` more keys.
    pub fn reserve(&mut self, additional: usize) {
        self.dense.reserve(additional);
    }

    /// Like [`reserve`](Self::reserve), but returns an error instead of
    /// panicking or aborting when the capacity overflows or the allocation
    /// fails.
    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
        self.dense.try_reserve(additional)
    }

    /// Dense position of the key occupying slot `index`, if any.
    #[inline]
    pub(crate) fn occupant_pos(&self, index: usize) -> Option<usize> {
        let (page, offset) = split::<PAGE>(index);
        let slot = self.sparse.get(page)?[offset]?;
        // Stored slots never exceed the dense length, which fits in `usize`.
        let pos = slot.get() as usize - 1;
        match self.dense.get(pos) {
            Some(key) if key.index() == index => Some(pos),
            _ => None,
        }
    }

    /// Writes slot `index`, whose page must already be allocated.
    #[inline]
    fn set_slot(&mut self, index: usize, slot: Slot) {
        let (page, offset) = split::<PAGE>(index);
        let page = self.sparse.get_mut(page);
        debug_assert!(page.is_some(), "slot {index} has no page");
        if let Some(page) = page {
            page[offset] = slot;
        }
    }

    /// Dense position of `key`, if it is in the set.
    ///
    /// Positions index [`as_slice`](Self::as_slice) and change when keys are
    /// removed or the set is sorted.
    #[inline]
    pub fn position(&self, key: K) -> Option<usize> {
        self.occupant_pos(key.index())
            .filter(|&pos| self.dense[pos] == key)
    }

    /// Whether `key` is in the set.
    #[inline]
    pub fn contains(&self, key: K) -> bool {
        self.position(key).is_some()
    }

    /// The stored key equal to `key`, including its generation.
    ///
    /// # Examples
    ///
    /// ```
    /// use paged_collections::sparse_set::PagedSparseSet;
    ///
    /// let mut set: PagedSparseSet<usize> = PagedSparseSet::new();
    /// set.insert(7);
    /// assert_eq!(set.get(7), Some(&7));
    /// assert_eq!(set.get(8), None);
    /// ```
    #[inline]
    pub fn get(&self, key: K) -> Option<&K> {
        self.position(key).map(|pos| &self.dense[pos])
    }

    /// The key occupying slot `index`, if any.
    ///
    /// With generational keys this finds whichever generation is present.
    #[inline]
    pub fn occupant(&self, index: usize) -> Option<&K> {
        self.occupant_pos(index).map(|pos| &self.dense[pos])
    }

    /// Adds `key` and returns `true`, or returns `false` and leaves the set
    /// unchanged if its slot is already held (by `key` or by another key with
    /// the same index).
    ///
    /// # Panics
    ///
    /// Panics if the set already holds `u32::MAX` keys, or if a page or the
    /// directory cannot be allocated.
    pub fn insert(&mut self, key: K) -> bool {
        let index = key.index();
        if self.occupant_pos(index).is_some() {
            return false;
        }
        self.insert_vacant(key, index);
        true
    }

    /// Appends `key`, whose slot `index` the caller has checked is vacant.
    ///
    /// If this panics, the set is unchanged as far as lookups can tell, and
    /// `len` is unchanged.
    pub(crate) fn insert_vacant(&mut self, key: K, index: usize) {
        let pos = self.dense.len();
        let slot = encode(pos).expect("PagedSparseSet cannot hold more than u32::MAX keys");
        let (page, offset) = split::<PAGE>(index);
        self.sparse.get_or_alloc(page)[offset] = Some(slot);
        // If this push panics, the slot points one past the dense array and is
        // ignored by every lookup.
        self.dense.push(key);
    }

    /// Adds `key`, overwriting any key that holds its slot, and returns the
    /// key it overwrote.
    ///
    /// An overwritten key keeps its dense position.
    ///
    /// # Panics
    ///
    /// As [`insert`](Self::insert).
    pub fn replace(&mut self, key: K) -> Option<K> {
        let index = key.index();
        match self.occupant_pos(index) {
            Some(pos) => Some(self.overwrite_at(pos, key)),
            None => {
                self.insert_vacant(key, index);
                None
            }
        }
    }

    /// Replaces the key at dense position `pos` with `key`, which must have
    /// the same slot index, and returns the old key.
    #[inline]
    pub(crate) fn overwrite_at(&mut self, pos: usize, key: K) -> K {
        debug_assert_eq!(self.dense[pos].index(), key.index());
        core::mem::replace(&mut self.dense[pos], key)
    }

    /// Removes the key at dense position `pos` by moving the last key into
    /// its place, as `Vec::swap_remove` does.
    pub(crate) fn remove_at(&mut self, pos: usize) -> K {
        // Read both slot indices before changing anything, so that nothing
        // after the first mutation calls into `Key`.
        let index = self.dense[pos].index();
        let moved_index = match self.dense.last() {
            Some(last) if self.dense.len() - 1 != pos => Some(last.index()),
            _ => None,
        };
        let key = self.dense.swap_remove(pos);
        self.set_slot(index, None);
        if let Some(moved_index) = moved_index {
            self.set_slot(moved_index, encode(pos));
        }
        key
    }

    /// Removes `key` and returns whether it was present.
    ///
    /// The last key moves into the removed key's position.
    pub fn remove(&mut self, key: K) -> bool {
        self.take(key).is_some()
    }

    /// Removes and returns the stored key equal to `key`, including its
    /// generation. The last key moves into the removed key's position.
    ///
    /// # Examples
    ///
    /// ```
    /// use paged_collections::sparse_set::PagedSparseSet;
    ///
    /// let mut set: PagedSparseSet<usize> = PagedSparseSet::new();
    /// set.insert(7);
    /// assert_eq!(set.take(7), Some(7));
    /// assert_eq!(set.take(7), None);
    /// ```
    pub fn take(&mut self, key: K) -> Option<K> {
        self.position(key).map(|pos| self.remove_at(pos))
    }

    /// Removes whichever key occupies slot `index` and returns it.
    pub fn remove_occupant(&mut self, index: usize) -> Option<K> {
        self.occupant_pos(index).map(|pos| self.remove_at(pos))
    }

    /// Keeps only the keys for which `keep` returns `true`.
    ///
    /// `keep` is called once per key. Kept keys may change position.
    pub fn retain(&mut self, mut keep: impl FnMut(&K) -> bool) {
        let mut pos = 0;
        while pos < self.dense.len() {
            if keep(&self.dense[pos]) {
                pos += 1;
            } else {
                // The key moved into `pos` has not been visited yet.
                self.remove_at(pos);
            }
        }
    }

    /// Removes every key in O(1).
    ///
    /// Pages stay allocated for reuse; use [`reset`](Self::reset) to free
    /// them.
    pub fn clear(&mut self) {
        self.dense.clear();
    }

    /// Removes every key and frees every page. The dense array keeps its
    /// capacity.
    pub fn reset(&mut self) {
        self.dense.clear();
        self.sparse.clear();
    }

    /// Frees every page without touching the dense array, which the caller
    /// must have emptied.
    pub(crate) fn free_pages(&mut self) {
        debug_assert!(self.dense.is_empty());
        self.sparse.clear();
    }

    /// Shrinks the dense array and the page directory. Frees every page if
    /// the set is empty.
    pub fn shrink_to_fit(&mut self) {
        self.dense.shrink_to_fit();
        if self.dense.is_empty() {
            self.sparse.clear();
        }
        self.sparse.shrink_to_fit();
    }

    /// The keys as a slice, in dense order.
    #[inline]
    pub fn as_slice(&self) -> &[K] {
        &self.dense
    }

    /// Iterates over the keys in dense order.
    #[inline]
    pub fn iter(&self) -> core::slice::Iter<'_, K> {
        self.dense.iter()
    }

    /// Removes every key and returns them in dense order.
    ///
    /// The set is empty as soon as this returns, even if the iterator is
    /// leaked; dropping it drops the keys not yet yielded. Pages and the
    /// dense array's capacity are kept, as with [`clear`](Self::clear).
    ///
    /// ```
    /// use paged_collections::sparse_set::PagedSparseSet;
    ///
    /// let mut set: PagedSparseSet<u32> = [5, 1, 9].into_iter().collect();
    /// assert_eq!(set.drain().collect::<Vec<_>>(), [5, 1, 9]);
    /// assert!(set.is_empty() && !set.contains(5));
    /// ```
    pub fn drain(&mut self) -> Drain<'_, K> {
        // Clearing the dense array is enough: every slot left behind is
        // stale and ignored by lookups.
        Drain(self.dense.drain(..))
    }

    /// Removes the keys for which `pred` returns `true` and yields them.
    ///
    /// Each key is tested exactly once. A removal moves the last key into
    /// the gap, so keys are tested in dense order except that a moved key
    /// is tested next. Keys not yet tested when the iterator is dropped stay
    /// in the set; use [`retain`](Self::retain) if the removed keys are not
    /// needed.
    ///
    /// ```
    /// use paged_collections::sparse_set::PagedSparseSet;
    ///
    /// let mut set: PagedSparseSet<u32> = (0..6).collect();
    /// let mut odd: Vec<u32> = set.extract_if(|&k| k % 2 == 1).collect();
    /// odd.sort();
    /// assert_eq!(odd, [1, 3, 5]);
    /// assert_eq!(set.len(), 3);
    /// ```
    pub fn extract_if<F: FnMut(&K) -> bool>(&mut self, pred: F) -> ExtractIf<'_, K, F, PAGE, D> {
        ExtractIf {
            set: self,
            pos: 0,
            pred,
        }
    }

    /// Dense positions of the keys whose slot index is in `indices`, in
    /// slot-index order.
    pub(crate) fn positions(&self, indices: &impl RangeBounds<usize>) -> Positions<'_, K, PAGE, D> {
        let (first, last) = match resolve(indices) {
            Some(span) if !self.dense.is_empty() => span,
            _ => (1, 0),
        };
        #[allow(clippy::reversed_empty_ranges)]
        let pages = if first <= last {
            split::<PAGE>(first).0..=split::<PAGE>(last).0
        } else {
            1..=0
        };
        Positions {
            pages: self.sparse.pages_in(pages),
            dense: &self.dense,
            first,
            last,
            front: None,
            back: None,
        }
    }

    /// Iterates over the keys whose slot index lies between the slot indices
    /// of the bounds, in slot-index order.
    ///
    /// The bounds are keys, compared by [`Key::index`]: for plain integer
    /// keys this is the usual key range, independent of dense order. A
    /// generational key bounds by its index only. An empty or inverted range
    /// yields nothing.
    ///
    /// This walks the sparse index: it costs O(pages and slots in the
    /// range), including slots left stale by [`clear`](Self::clear) (which
    /// [`reset`](Self::reset) frees), not O(keys yielded).
    ///
    /// ```
    /// use paged_collections::sparse_set::PagedSparseSet;
    ///
    /// let set: PagedSparseSet<u32, 4> = [9, 2, 30, 5].into_iter().collect();
    /// assert_eq!(set.range(3..=30).copied().collect::<Vec<_>>(), [5, 9, 30]);
    /// assert_eq!((set.first(), set.last()), (Some(&2), Some(&30)));
    /// assert_eq!(set.next_occupant(6), Some(&9));
    /// ```
    pub fn range(&self, keys: impl RangeBounds<K>) -> Range<'_, K, PAGE, D> {
        Range(self.positions(&index_bounds(&keys)))
    }

    /// The key with the smallest slot index. Costs as [`range`](Self::range).
    pub fn first(&self) -> Option<&K> {
        self.range(..).next()
    }

    /// The key with the largest slot index. Costs as [`range`](Self::range).
    pub fn last(&self) -> Option<&K> {
        self.range(..).next_back()
    }

    /// The key at slot `index` or the first one after it.
    pub fn next_occupant(&self, index: usize) -> Option<&K> {
        Range(self.positions(&(index..))).next()
    }

    /// The key at slot `index` or the last one before it.
    pub fn prev_occupant(&self, index: usize) -> Option<&K> {
        Range(self.positions(&(..=index))).next_back()
    }

    /// Removes and returns the key with the smallest slot index.
    pub fn pop_first(&mut self) -> Option<K> {
        let pos = self.positions(&..).next()?;
        Some(self.remove_at(pos))
    }

    /// Removes and returns the key with the largest slot index.
    pub fn pop_last(&mut self) -> Option<K> {
        let pos = self.positions(&..).next_back()?;
        Some(self.remove_at(pos))
    }

    /// Iterates over keys in `self` absent from `other`, in `self`'s dense order.
    ///
    /// ```
    /// use paged_collections::sparse_set::PagedSparseSet;
    ///
    /// let a: PagedSparseSet<u16> = [3, 1, 2].into_iter().collect();
    /// let b: PagedSparseSet<u16> = [1, 4].into_iter().collect();
    /// assert!(a.difference(&b).copied().eq([3, 2]));
    /// ```
    pub fn difference<'a, const P2: usize, D2: Directory>(
        &'a self,
        other: &'a PagedSparseSet<K, P2, D2>,
    ) -> Difference<'a, K, P2, D2> {
        Difference {
            iter: self.iter(),
            other,
        }
    }

    /// Iterates over keys present in both sets.
    ///
    /// Order follows the smaller set's dense order, or `self`'s dense order
    /// if the sets contain the same number of keys.
    ///
    /// ```
    /// use paged_collections::sparse_set::PagedSparseSet;
    ///
    /// let a: PagedSparseSet<u16> = [1, 2, 3].into_iter().collect();
    /// let b: PagedSparseSet<u16> = [2, 1].into_iter().collect();
    /// assert!(a.intersection(&b).copied().eq([2, 1]));
    /// ```
    pub fn intersection<'a, const P2: usize, D2: Directory>(
        &'a self,
        other: &'a PagedSparseSet<K, P2, D2>,
    ) -> Intersection<'a, K, PAGE, D, P2, D2> {
        let (iter, probe) = if self.len() <= other.len() {
            (self.iter(), IntersectionProbe::Right(other))
        } else {
            (other.iter(), IntersectionProbe::Left(self))
        };
        Intersection { iter, probe }
    }

    /// Iterates over keys present in exactly one set.
    ///
    /// Yields [`self.difference(other)`](Self::difference), then
    /// `other.difference(self)`. Different generations of the same slot are
    /// unequal, so both are yielded. Collecting into a `PagedSparseSet` keeps
    /// `self`'s key because [`insert`](Self::insert) refuses an occupied slot.
    ///
    /// ```
    /// use paged_collections::sparse_set::PagedSparseSet;
    ///
    /// let a: PagedSparseSet<u16> = [3, 1, 2].into_iter().collect();
    /// let b: PagedSparseSet<u16> = [2, 5, 4].into_iter().collect();
    /// assert!(a.symmetric_difference(&b).copied().eq([3, 1, 5, 4]));
    /// ```
    pub fn symmetric_difference<'a, const P2: usize, D2: Directory>(
        &'a self,
        other: &'a PagedSparseSet<K, P2, D2>,
    ) -> SymmetricDifference<'a, K, PAGE, D, P2, D2> {
        SymmetricDifference {
            iter: self.difference(other).chain(other.difference(self)),
        }
    }

    /// Iterates over keys present in either set.
    ///
    /// Yields `self`'s keys in dense order, then `other.difference(self)`.
    /// Different generations of the same slot are unequal, so both are
    /// yielded. Collecting into a `PagedSparseSet` keeps `self`'s key because
    /// [`insert`](Self::insert) refuses an occupied slot.
    ///
    /// ```
    /// use paged_collections::sparse_set::PagedSparseSet;
    ///
    /// let a: PagedSparseSet<u16> = [3, 1, 2].into_iter().collect();
    /// let b: PagedSparseSet<u16> = [2, 5, 4].into_iter().collect();
    /// assert!(a.union(&b).copied().eq([3, 1, 2, 5, 4]));
    /// ```
    pub fn union<'a, const P2: usize, D2: Directory>(
        &'a self,
        other: &'a PagedSparseSet<K, P2, D2>,
    ) -> Union<'a, K, PAGE, D> {
        Union {
            iter: self.iter().chain(other.difference(self)),
        }
    }

    /// Whether the sets have no keys in common. Iterates over the smaller set.
    ///
    /// ```
    /// use paged_collections::sparse_set::PagedSparseSet;
    ///
    /// let a: PagedSparseSet<u16> = [1, 2].into_iter().collect();
    /// let b: PagedSparseSet<u16> = [3].into_iter().collect();
    /// assert!(a.is_disjoint(&b));
    /// ```
    pub fn is_disjoint<const P2: usize, D2: Directory>(
        &self,
        other: &PagedSparseSet<K, P2, D2>,
    ) -> bool {
        self.intersection(other).next().is_none()
    }

    /// Whether every key in `self` is also in `other`.
    ///
    /// ```
    /// use paged_collections::sparse_set::PagedSparseSet;
    ///
    /// let a: PagedSparseSet<u16> = [2].into_iter().collect();
    /// let b: PagedSparseSet<u16> = [1, 2].into_iter().collect();
    /// assert!(a.is_subset(&b));
    /// ```
    pub fn is_subset<const P2: usize, D2: Directory>(
        &self,
        other: &PagedSparseSet<K, P2, D2>,
    ) -> bool {
        self.len() <= other.len() && self.iter().all(|&key| other.contains(key))
    }

    /// Whether every key in `other` is also in `self`.
    ///
    /// ```
    /// use paged_collections::sparse_set::PagedSparseSet;
    ///
    /// let a: PagedSparseSet<u16> = [1, 2].into_iter().collect();
    /// let b: PagedSparseSet<u16> = [2].into_iter().collect();
    /// assert!(a.is_superset(&b));
    /// ```
    pub fn is_superset<const P2: usize, D2: Directory>(
        &self,
        other: &PagedSparseSet<K, P2, D2>,
    ) -> bool {
        other.is_subset(self)
    }

    /// Swaps the keys at dense positions `a` and `b` and fixes their index
    /// slots. Panics if either is out of bounds.
    pub(crate) fn swap_positions(&mut self, a: usize, b: usize) {
        // Validate both positions and read indices before changing anything.
        let a_index = self.dense[a].index();
        let b_index = self.dense[b].index();
        self.dense.swap(a, b);
        self.set_slot(a_index, encode(b));
        self.set_slot(b_index, encode(a));
    }

    /// Rewrites every slot after the dense array was reordered.
    fn reindex(&mut self) {
        for pos in 0..self.dense.len() {
            let index = self.dense[pos].index();
            self.set_slot(index, encode(pos));
        }
    }

    /// Reorders the dense array with `reorder`, then rewrites the index.
    ///
    /// The index is rewritten even if `reorder` panics, so a caught panic in
    /// a user comparator leaves the set consistent (in some order).
    pub(crate) fn reorder_dense(&mut self, reorder: impl FnOnce(&mut [K])) {
        struct Reindex<'a, K: Key, const PAGE: usize, D: Directory>(
            &'a mut PagedSparseSet<K, PAGE, D>,
        );
        impl<K: Key, const PAGE: usize, D: Directory> Drop for Reindex<'_, K, PAGE, D> {
            fn drop(&mut self) {
                self.0.reindex();
            }
        }
        let guard = Reindex(self);
        reorder(&mut guard.0.dense);
    }

    /// Sorts the dense array by `compare`, keeping the order of equal keys,
    /// and updates the index.
    ///
    /// If `compare` panics, the keys are left in an unspecified order but the
    /// set stays consistent.
    pub fn sort_by(&mut self, compare: impl FnMut(&K, &K) -> core::cmp::Ordering) {
        self.reorder_dense(|dense| dense.sort_by(compare));
    }

    /// Sorts the dense array by a key function, keeping the order of keys
    /// with equal sort keys, and updates the index.
    ///
    /// If `f` panics, the keys are left in an unspecified order but the set
    /// stays consistent.
    pub fn sort_by_key<T: Ord>(&mut self, f: impl FnMut(&K) -> T) {
        self.reorder_dense(|dense| dense.sort_by_key(f));
    }

    /// Sorts the dense array in ascending order and updates the index.
    ///
    /// Stable, which matters only if equal keys can be told apart; prefer
    /// [`sort_unstable`](Self::sort_unstable) otherwise: it allocates nothing.
    pub fn sort(&mut self)
    where
        K: Ord,
    {
        self.reorder_dense(<[K]>::sort);
    }

    /// Sorts the dense array by `compare` (unstable) and updates the index.
    ///
    /// If `compare` panics, the keys are left in an unspecified order but the
    /// set stays consistent.
    pub fn sort_unstable_by(&mut self, compare: impl FnMut(&K, &K) -> core::cmp::Ordering) {
        self.reorder_dense(|dense| dense.sort_unstable_by(compare));
    }

    /// Sorts the dense array by a key function (unstable) and updates the
    /// index.
    ///
    /// If `f` panics, the keys are left in an unspecified order but the set
    /// stays consistent.
    pub fn sort_unstable_by_key<T: Ord>(&mut self, f: impl FnMut(&K) -> T) {
        self.reorder_dense(|dense| dense.sort_unstable_by_key(f));
    }

    /// Sorts the dense array in ascending order (unstable) and updates the
    /// index.
    pub fn sort_unstable(&mut self)
    where
        K: Ord,
    {
        self.reorder_dense(<[K]>::sort_unstable);
    }
}

impl<K: Key, const PAGE: usize, D: Directory> Default for PagedSparseSet<K, PAGE, D> {
    fn default() -> Self {
        Self::new()
    }
}

impl<K: Key, const PAGE: usize, D: Directory> Clone for PagedSparseSet<K, PAGE, D>
where
    D::Store<Slot, PAGE>: Clone,
{
    fn clone(&self) -> Self {
        Self {
            dense: self.dense.clone(),
            sparse: self.sparse.clone(),
        }
    }
}

impl<K: Key + fmt::Debug, const PAGE: usize, D: Directory> fmt::Debug
    for PagedSparseSet<K, PAGE, D>
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_set().entries(self.dense.iter()).finish()
    }
}

/// Compares exact keys with [`contains`](PagedSparseSet::contains), in any
/// order and across page sizes and directories.
impl<K: Key, const PAGE: usize, D: Directory, const P2: usize, D2: Directory>
    PartialEq<PagedSparseSet<K, P2, D2>> for PagedSparseSet<K, PAGE, D>
{
    fn eq(&self, other: &PagedSparseSet<K, P2, D2>) -> bool {
        self.len() == other.len() && self.iter().all(|&key| other.contains(key))
    }
}

/// Exact key equality gives sets an equivalence relation under [`PartialEq`].
impl<K: Key, const PAGE: usize, D: Directory> Eq for PagedSparseSet<K, PAGE, D> {}

/// Hashes the keys in any order, consistent with [`PartialEq`].
impl<K: Key + Hash, const PAGE: usize, D: Directory> Hash for PagedSparseSet<K, PAGE, D> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        hash_unordered(self.iter(), state);
    }
}

impl<K: Key, const PAGE: usize, D: Directory> Extend<K> for PagedSparseSet<K, PAGE, D> {
    fn extend<I: IntoIterator<Item = K>>(&mut self, iter: I) {
        for key in iter {
            self.insert(key);
        }
    }
}

impl<'a, K: Key + 'a, const PAGE: usize, D: Directory> Extend<&'a K>
    for PagedSparseSet<K, PAGE, D>
{
    fn extend<I: IntoIterator<Item = &'a K>>(&mut self, iter: I) {
        self.extend(iter.into_iter().copied());
    }
}

impl<K: Key, const PAGE: usize, D: Directory> FromIterator<K> for PagedSparseSet<K, PAGE, D> {
    fn from_iter<I: IntoIterator<Item = K>>(iter: I) -> Self {
        let mut set = Self::new();
        set.extend(iter);
        set
    }
}

impl<'a, K: Key, const PAGE: usize, D: Directory> IntoIterator for &'a PagedSparseSet<K, PAGE, D> {
    type Item = &'a K;
    type IntoIter = core::slice::Iter<'a, K>;

    fn into_iter(self) -> Self::IntoIter {
        self.dense.iter()
    }
}

impl<K: Key, const PAGE: usize, D: Directory> IntoIterator for PagedSparseSet<K, PAGE, D> {
    type Item = K;
    type IntoIter = alloc::vec::IntoIter<K>;

    fn into_iter(self) -> Self::IntoIter {
        self.dense.into_iter()
    }
}

/// The slot-index bounds of a key range.
pub(crate) fn index_bounds<K: Key>(keys: &impl RangeBounds<K>) -> (Bound<usize>, Bound<usize>) {
    (
        keys.start_bound().map(|key| key.index()),
        keys.end_bound().map(|key| key.index()),
    )
}

/// The inclusive slot indices `first..=last` of `indices`, or `None` if it
/// is empty.
fn resolve(indices: &impl RangeBounds<usize>) -> Option<(usize, usize)> {
    let first = match indices.start_bound() {
        Bound::Included(&index) => Some(index),
        Bound::Excluded(&index) => index.checked_add(1),
        Bound::Unbounded => Some(0),
    }?;
    let last = match indices.end_bound() {
        Bound::Included(&index) => Some(index),
        Bound::Excluded(&index) => index.checked_sub(1),
        Bound::Unbounded => Some(usize::MAX),
    }?;
    (first <= last).then_some((first, last))
}

/// One page of the sparse index being walked by [`Positions`]: its first
/// slot index and the offsets still to visit.
struct Part<'a, const PAGE: usize> {
    base: usize,
    page: &'a [Slot; PAGE],
    offsets: core::ops::Range<usize>,
}

impl<const PAGE: usize> Clone for Part<'_, PAGE> {
    fn clone(&self) -> Self {
        Self {
            base: self.base,
            page: self.page,
            offsets: self.offsets.clone(),
        }
    }
}

/// Dense positions of the keys in a range of slot indices, in slot-index
/// order, found by walking the sparse index and validating each slot the way
/// lookups do.
pub(crate) struct Positions<'a, K, const PAGE: usize, D: Directory + 'a> {
    pages: <D::Store<Slot, PAGE> as PageStore<Slot, PAGE>>::Pages<'a>,
    dense: &'a [K],
    first: usize,
    last: usize,
    front: Option<Part<'a, PAGE>>,
    back: Option<Part<'a, PAGE>>,
}

impl<'a, K, const PAGE: usize, D: Directory + 'a> Clone for Positions<'a, K, PAGE, D> {
    fn clone(&self) -> Self {
        Self {
            pages: self.pages.clone(),
            dense: self.dense,
            first: self.first,
            last: self.last,
            front: self.front.clone(),
            back: self.back.clone(),
        }
    }
}

impl<'a, K: Key, const PAGE: usize, D: Directory + 'a> Positions<'a, K, PAGE, D> {
    /// The dense keys the positions index.
    #[inline]
    pub(crate) fn dense(&self) -> &'a [K] {
        self.dense
    }

    /// The part of page `number` inside `first..=last`.
    fn part(&self, number: usize, page: &'a [Slot; PAGE]) -> Part<'a, PAGE> {
        let base = number.saturating_mul(PAGE);
        let end = match self.last.checked_sub(base) {
            Some(offset) => offset.saturating_add(1).min(PAGE),
            // Only a store that breaks the page contract yields a page past
            // `last`.
            None => 0,
        };
        Part {
            base,
            page,
            offsets: self.first.saturating_sub(base).min(end)..end,
        }
    }

    /// The dense position slot `offset` of `part` points at, if valid.
    #[inline]
    fn valid(&self, part: &Part<'a, PAGE>, offset: usize) -> Option<usize> {
        let pos = part.page[offset]?.get() as usize - 1;
        let key = self.dense.get(pos)?;
        (key.index() == part.base + offset).then_some(pos)
    }
}

impl<'a, K: Key, const PAGE: usize, D: Directory + 'a> Iterator for Positions<'a, K, PAGE, D> {
    type Item = usize;

    fn next(&mut self) -> Option<usize> {
        loop {
            if let Some(mut part) = self.front.take() {
                while let Some(offset) = part.offsets.next() {
                    if let Some(pos) = self.valid(&part, offset) {
                        self.front = Some(part);
                        return Some(pos);
                    }
                }
            }
            match self.pages.next() {
                Some((number, page)) => self.front = Some(self.part(number, page)),
                // The pages are exhausted: finish the page the back end
                // started.
                None => self.front = Some(self.back.take()?),
            }
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        // Each valid slot names a distinct dense position.
        (0, Some(self.dense.len()))
    }
}

impl<'a, K: Key, const PAGE: usize, D: Directory + 'a> DoubleEndedIterator
    for Positions<'a, K, PAGE, D>
{
    fn next_back(&mut self) -> Option<usize> {
        loop {
            if let Some(mut part) = self.back.take() {
                while let Some(offset) = part.offsets.next_back() {
                    if let Some(pos) = self.valid(&part, offset) {
                        self.back = Some(part);
                        return Some(pos);
                    }
                }
            }
            match self.pages.next_back() {
                Some((number, page)) => self.back = Some(self.part(number, page)),
                None => self.back = Some(self.front.take()?),
            }
        }
    }
}

impl<'a, K: Key, const PAGE: usize, D: Directory + 'a> FusedIterator for Positions<'a, K, PAGE, D> {}

/// The keys in a range of slot indices, from [`PagedSparseSet::range`].
pub struct Range<'a, K, const PAGE: usize = DEFAULT_PAGE, D: Directory + 'a = Flat>(
    Positions<'a, K, PAGE, D>,
);

impl<'a, K: Key, const PAGE: usize, D: Directory + 'a> Iterator for Range<'a, K, PAGE, D> {
    type Item = &'a K;

    #[inline]
    fn next(&mut self) -> Option<&'a K> {
        let pos = self.0.next()?;
        Some(&self.0.dense[pos])
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

impl<'a, K: Key, const PAGE: usize, D: Directory + 'a> DoubleEndedIterator
    for Range<'a, K, PAGE, D>
{
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        let pos = self.0.next_back()?;
        Some(&self.0.dense[pos])
    }
}

impl<'a, K: Key, const PAGE: usize, D: Directory + 'a> FusedIterator for Range<'a, K, PAGE, D> {}

impl<'a, K, const PAGE: usize, D: Directory + 'a> Clone for Range<'a, K, PAGE, D> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

impl<'a, K: Key + fmt::Debug, const PAGE: usize, D: Directory + 'a> fmt::Debug
    for Range<'a, K, PAGE, D>
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.clone()).finish()
    }
}

/// The keys removed by [`PagedSparseSet::drain`], in dense order.
#[derive(Debug)]
pub struct Drain<'a, K>(alloc::vec::Drain<'a, K>);

impl<K> Iterator for Drain<'_, K> {
    type Item = K;

    #[inline]
    fn next(&mut self) -> Option<K> {
        self.0.next()
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

impl<K> DoubleEndedIterator for Drain<'_, K> {
    #[inline]
    fn next_back(&mut self) -> Option<K> {
        self.0.next_back()
    }
}

impl<K> ExactSizeIterator for Drain<'_, K> {}

impl<K> FusedIterator for Drain<'_, K> {}

/// The keys removed by [`PagedSparseSet::extract_if`].
pub struct ExtractIf<'a, K, F, const PAGE: usize = DEFAULT_PAGE, D: Directory = Flat> {
    set: &'a mut PagedSparseSet<K, PAGE, D>,
    pos: usize,
    pred: F,
}

impl<K: Key, F: FnMut(&K) -> bool, const PAGE: usize, D: Directory> Iterator
    for ExtractIf<'_, K, F, PAGE, D>
{
    type Item = K;

    fn next(&mut self) -> Option<K> {
        while self.pos < self.set.dense.len() {
            let pos = self.pos;
            // Advance first: if `pred` panics, this key is not tested again.
            self.pos += 1;
            if (self.pred)(&self.set.dense[pos]) {
                // The last key moves into `pos` and is tested next.
                self.pos = pos;
                return Some(self.set.remove_at(pos));
            }
        }
        None
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, Some(self.set.dense.len() - self.pos))
    }
}

impl<K: Key, F: FnMut(&K) -> bool, const PAGE: usize, D: Directory> FusedIterator
    for ExtractIf<'_, K, F, PAGE, D>
{
}

impl<K: Key + fmt::Debug, F, const PAGE: usize, D: Directory> fmt::Debug
    for ExtractIf<'_, K, F, PAGE, D>
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ExtractIf")
            .field("untested", &&self.set.dense[self.pos..])
            .finish_non_exhaustive()
    }
}

/// An iterator over the keys yielded by [`PagedSparseSet::difference`].
pub struct Difference<'a, K, const P2: usize, D2: Directory> {
    iter: slice::Iter<'a, K>,
    other: &'a PagedSparseSet<K, P2, D2>,
}

impl<'a, K: Key, const P2: usize, D2: Directory> Iterator for Difference<'a, K, P2, D2> {
    type Item = &'a K;

    fn next(&mut self) -> Option<Self::Item> {
        self.iter.find(|&&key| !self.other.contains(key))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, Some(self.iter.len()))
    }
}

impl<K: Key, const P2: usize, D2: Directory> FusedIterator for Difference<'_, K, P2, D2> {}

impl<K, const P2: usize, D2: Directory> Clone for Difference<'_, K, P2, D2> {
    fn clone(&self) -> Self {
        Self {
            iter: self.iter.clone(),
            other: self.other,
        }
    }
}

impl<K: Key + fmt::Debug, const P2: usize, D2: Directory> fmt::Debug for Difference<'_, K, P2, D2> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.clone()).finish()
    }
}

enum IntersectionProbe<'a, K, const PAGE: usize, D: Directory, const P2: usize, D2: Directory> {
    Left(&'a PagedSparseSet<K, PAGE, D>),
    Right(&'a PagedSparseSet<K, P2, D2>),
}

// Manual impls: a derive would require `K: Clone`.
impl<K, const PAGE: usize, D: Directory, const P2: usize, D2: Directory> Clone
    for IntersectionProbe<'_, K, PAGE, D, P2, D2>
{
    fn clone(&self) -> Self {
        *self
    }
}

impl<K, const PAGE: usize, D: Directory, const P2: usize, D2: Directory> Copy
    for IntersectionProbe<'_, K, PAGE, D, P2, D2>
{
}

/// An iterator over the keys yielded by [`PagedSparseSet::intersection`].
pub struct Intersection<'a, K, const PAGE: usize, D: Directory, const P2: usize, D2: Directory> {
    iter: slice::Iter<'a, K>,
    probe: IntersectionProbe<'a, K, PAGE, D, P2, D2>,
}

impl<'a, K: Key, const PAGE: usize, D: Directory, const P2: usize, D2: Directory> Iterator
    for Intersection<'a, K, PAGE, D, P2, D2>
{
    type Item = &'a K;

    fn next(&mut self) -> Option<Self::Item> {
        match self.probe {
            IntersectionProbe::Left(set) => self.iter.find(|&&key| set.contains(key)),
            IntersectionProbe::Right(set) => self.iter.find(|&&key| set.contains(key)),
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, Some(self.iter.len()))
    }
}

impl<K: Key, const PAGE: usize, D: Directory, const P2: usize, D2: Directory> FusedIterator
    for Intersection<'_, K, PAGE, D, P2, D2>
{
}

impl<K, const PAGE: usize, D: Directory, const P2: usize, D2: Directory> Clone
    for Intersection<'_, K, PAGE, D, P2, D2>
{
    fn clone(&self) -> Self {
        Self {
            iter: self.iter.clone(),
            probe: self.probe,
        }
    }
}

impl<K: Key + fmt::Debug, const PAGE: usize, D: Directory, const P2: usize, D2: Directory>
    fmt::Debug for Intersection<'_, K, PAGE, D, P2, D2>
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.clone()).finish()
    }
}

/// An iterator over the keys yielded by [`PagedSparseSet::symmetric_difference`].
pub struct SymmetricDifference<
    'a,
    K,
    const PAGE: usize,
    D: Directory,
    const P2: usize,
    D2: Directory,
> {
    iter: Chain<Difference<'a, K, P2, D2>, Difference<'a, K, PAGE, D>>,
}

impl<'a, K: Key, const PAGE: usize, D: Directory, const P2: usize, D2: Directory> Iterator
    for SymmetricDifference<'a, K, PAGE, D, P2, D2>
{
    type Item = &'a K;

    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}

impl<K: Key, const PAGE: usize, D: Directory, const P2: usize, D2: Directory> FusedIterator
    for SymmetricDifference<'_, K, PAGE, D, P2, D2>
{
}

impl<K, const PAGE: usize, D: Directory, const P2: usize, D2: Directory> Clone
    for SymmetricDifference<'_, K, PAGE, D, P2, D2>
{
    fn clone(&self) -> Self {
        Self {
            iter: self.iter.clone(),
        }
    }
}

impl<K: Key + fmt::Debug, const PAGE: usize, D: Directory, const P2: usize, D2: Directory>
    fmt::Debug for SymmetricDifference<'_, K, PAGE, D, P2, D2>
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.clone()).finish()
    }
}

/// An iterator over the keys yielded by [`PagedSparseSet::union`].
pub struct Union<'a, K, const PAGE: usize, D: Directory> {
    iter: Chain<slice::Iter<'a, K>, Difference<'a, K, PAGE, D>>,
}

impl<'a, K: Key, const PAGE: usize, D: Directory> Iterator for Union<'a, K, PAGE, D> {
    type Item = &'a K;

    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}

impl<K: Key, const PAGE: usize, D: Directory> FusedIterator for Union<'_, K, PAGE, D> {}

impl<K, const PAGE: usize, D: Directory> Clone for Union<'_, K, PAGE, D> {
    fn clone(&self) -> Self {
        Self {
            iter: self.iter.clone(),
        }
    }
}

impl<K: Key + fmt::Debug, const PAGE: usize, D: Directory> fmt::Debug for Union<'_, K, PAGE, D> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.clone()).finish()
    }
}

/// Collects the [`union`](PagedSparseSet::union) into a new set.
impl<K: Key, const PAGE: usize, D: Directory, const P2: usize, D2: Directory>
    BitOr<&PagedSparseSet<K, P2, D2>> for &PagedSparseSet<K, PAGE, D>
{
    type Output = PagedSparseSet<K, PAGE, D>;

    fn bitor(self, other: &PagedSparseSet<K, P2, D2>) -> Self::Output {
        let mut set = PagedSparseSet::with_capacity(self.len());
        set.extend(self.union(other));
        set
    }
}

/// Collects the [`intersection`](PagedSparseSet::intersection) into a new set.
impl<K: Key, const PAGE: usize, D: Directory, const P2: usize, D2: Directory>
    BitAnd<&PagedSparseSet<K, P2, D2>> for &PagedSparseSet<K, PAGE, D>
{
    type Output = PagedSparseSet<K, PAGE, D>;

    fn bitand(self, other: &PagedSparseSet<K, P2, D2>) -> Self::Output {
        let mut set = PagedSparseSet::with_capacity(self.len().min(other.len()));
        set.extend(self.intersection(other));
        set
    }
}

/// Collects the [`difference`](PagedSparseSet::difference) into a new set.
impl<K: Key, const PAGE: usize, D: Directory, const P2: usize, D2: Directory>
    Sub<&PagedSparseSet<K, P2, D2>> for &PagedSparseSet<K, PAGE, D>
{
    type Output = PagedSparseSet<K, PAGE, D>;

    fn sub(self, other: &PagedSparseSet<K, P2, D2>) -> Self::Output {
        let mut set = PagedSparseSet::with_capacity(self.len().saturating_sub(other.len()));
        set.extend(self.difference(other));
        set
    }
}

/// Collects the [`symmetric difference`](PagedSparseSet::symmetric_difference) into a new set.
impl<K: Key, const PAGE: usize, D: Directory, const P2: usize, D2: Directory>
    BitXor<&PagedSparseSet<K, P2, D2>> for &PagedSparseSet<K, PAGE, D>
{
    type Output = PagedSparseSet<K, PAGE, D>;

    fn bitxor(self, other: &PagedSparseSet<K, P2, D2>) -> Self::Output {
        let mut set = PagedSparseSet::with_capacity(self.len().abs_diff(other.len()));
        set.extend(self.symmetric_difference(other));
        set
    }
}

/// Inserts the right operand's keys in dense order, keeping occupied slots.
impl<K: Key, const PAGE: usize, D: Directory, const P2: usize, D2: Directory>
    BitOrAssign<&PagedSparseSet<K, P2, D2>> for PagedSparseSet<K, PAGE, D>
{
    fn bitor_assign(&mut self, other: &PagedSparseSet<K, P2, D2>) {
        self.extend(other);
    }
}

/// Keeps the keys present in both sets. Swap removal can reorder keys.
impl<K: Key, const PAGE: usize, D: Directory, const P2: usize, D2: Directory>
    BitAndAssign<&PagedSparseSet<K, P2, D2>> for PagedSparseSet<K, PAGE, D>
{
    fn bitand_assign(&mut self, other: &PagedSparseSet<K, P2, D2>) {
        self.retain(|&key| other.contains(key));
    }
}

/// Removes keys present in the right operand. Swap removal can reorder keys.
impl<K: Key, const PAGE: usize, D: Directory, const P2: usize, D2: Directory>
    SubAssign<&PagedSparseSet<K, P2, D2>> for PagedSparseSet<K, PAGE, D>
{
    fn sub_assign(&mut self, other: &PagedSparseSet<K, P2, D2>) {
        if other.len() < self.len() {
            for &key in other {
                self.remove(key);
            }
        } else {
            self.retain(|&key| !other.contains(key));
        }
    }
}

/// Toggles each key in the right operand. Swap removal can reorder keys.
/// When the operands hold different generations of the same slot, the left
/// operand keeps its key and skips the right operand's key.
impl<K: Key, const PAGE: usize, D: Directory, const P2: usize, D2: Directory>
    BitXorAssign<&PagedSparseSet<K, P2, D2>> for PagedSparseSet<K, PAGE, D>
{
    fn bitxor_assign(&mut self, other: &PagedSparseSet<K, P2, D2>) {
        for &key in other {
            if !self.remove(key) {
                self.insert(key);
            }
        }
    }
}

#[cfg(feature = "rayon")]
mod rayon_impl {
    use super::*;
    use rayon::prelude::*;

    impl<'a, K: Key + Sync, const PAGE: usize, D: Directory> IntoParallelIterator
        for &'a PagedSparseSet<K, PAGE, D>
    {
        type Item = &'a K;
        type Iter = rayon::slice::Iter<'a, K>;

        fn into_par_iter(self) -> Self::Iter {
            self.as_slice().par_iter()
        }
    }
}

#[cfg(feature = "serde")]
mod serde_impl {
    use super::*;
    use core::marker::PhantomData;
    use serde::de::{Deserialize, Deserializer, SeqAccess, Visitor};
    use serde::ser::{Serialize, Serializer};

    /// Serializes as a sequence of keys in dense order.
    impl<K: Key + Serialize, const PAGE: usize, D: Directory> Serialize for PagedSparseSet<K, PAGE, D> {
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            serializer.collect_seq(self.dense.iter())
        }
    }

    /// Deserializes from a sequence of keys. A key whose slot is already
    /// taken is skipped, as `HashSet` skips duplicates.
    ///
    /// Memory follows the key indices, not the input length: with the
    /// [`Flat`] directory one large index allocates a directory entry for
    /// every page below it, and an index near `usize::MAX` panics. For
    /// untrusted input, use [`Radix`](crate::page::Radix) or
    /// [`Tree`](crate::page::Tree), or validate the keys first.
    impl<'de, K: Key + Deserialize<'de>, const PAGE: usize, D: Directory> Deserialize<'de>
        for PagedSparseSet<K, PAGE, D>
    {
        fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
            struct SeqVisitor<K, const PAGE: usize, D>(PhantomData<(K, D)>);

            impl<'de, K: Key + Deserialize<'de>, const PAGE: usize, D: Directory> Visitor<'de>
                for SeqVisitor<K, PAGE, D>
            {
                type Value = PagedSparseSet<K, PAGE, D>;

                fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                    f.write_str("a sequence of keys")
                }

                fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
                    // Cap the hint so a hostile length cannot force a huge
                    // allocation.
                    let hint = seq.size_hint().unwrap_or(0).min(4096);
                    let mut set = PagedSparseSet::with_capacity(hint);
                    while let Some(key) = seq.next_element()? {
                        set.insert(key);
                    }
                    Ok(set)
                }
            }

            deserializer.deserialize_seq(SeqVisitor::<K, PAGE, D>(PhantomData))
        }
    }
}

// The tests use `u32` keys, which implement `Key` only on 32- and 64-bit
// targets.
#[cfg(all(test, any(target_pointer_width = "32", target_pointer_width = "64")))]
mod tests {
    use super::*;
    use crate::page::Radix;
    #[cfg(target_pointer_width = "64")]
    use crate::page::Tree;

    #[derive(Clone, Copy, PartialEq, Eq, Debug)]
    struct Gen(u32);

    impl Key for Gen {
        fn index(self) -> usize {
            (self.0 & 0xffff) as usize
        }
    }

    #[cfg(target_pointer_width = "64")]
    #[test]
    fn wide_keys_allocate_few_pages() {
        let mut set: PagedSparseSet<u64, 64, Tree> = PagedSparseSet::new();
        for k in [0, u64::MAX, u64::MAX / 2, 1 << 40] {
            assert!(set.insert(k));
        }
        assert_eq!(set.allocated_pages(), 4);
        assert!(set.contains(u64::MAX));
        assert!(!set.contains(u64::MAX - 1));
    }

    #[test]
    fn remove_moves_last_key() {
        let mut set: PagedSparseSet<u32, 4> = [1, 2, 3, 40].into_iter().collect();
        assert!(set.remove(1));
        assert_eq!(set.as_slice(), &[40, 2, 3]);
        assert_eq!(set.position(40), Some(0));
        assert!(!set.remove(1));
        assert!(!set.contains(1));
    }

    #[test]
    fn swap_positions_reindexes_both_keys() {
        let old = Gen(2);
        let new = Gen(2 | 1 << 16);
        let mut set: PagedSparseSet<Gen, 4> = [Gen(1), old, Gen(40)].into_iter().collect();
        assert_eq!(set.replace(new), Some(old));
        set.swap_positions(1, 2);
        assert_eq!(set.as_slice(), &[Gen(1), Gen(40), new]);
        for (pos, &key) in set.iter().enumerate() {
            assert_eq!(set.position(key), Some(pos));
        }
        assert!(!set.contains(old));
        set.swap_positions(0, 0);
        assert_eq!(set.position(Gen(1)), Some(0));
        assert!(set.remove(Gen(40)));
        assert_eq!(set.position(new), Some(1));
    }

    #[test]
    fn clear_is_lazy_but_correct() {
        let mut set: PagedSparseSet<u32, 4> = (0..10).collect();
        set.clear();
        assert!(set.is_empty());
        assert_eq!(set.allocated_pages(), 3);
        for k in 0..10 {
            assert!(!set.contains(k));
        }
        assert!(set.insert(9));
        assert!(!set.contains(0));
        assert_eq!(set.position(9), Some(0));
        set.reset();
        assert_eq!(set.allocated_pages(), 0);
    }

    #[test]
    fn generations_compete_for_one_slot() {
        let old = Gen(7);
        let new = Gen(7 | 1 << 16);
        let mut set: PagedSparseSet<Gen> = PagedSparseSet::new();
        assert!(set.insert(old));
        assert!(!set.insert(new));
        assert!(!set.contains(new));
        assert_eq!(set.occupant(7), Some(&old));
        assert_eq!(set.replace(new), Some(old));
        assert!(set.contains(new) && !set.contains(old));
        assert!(!set.remove(old));
        assert_eq!(set.remove_occupant(7), Some(new));
        assert!(set.is_empty());
    }

    #[test]
    fn retain_and_sort_keep_index_consistent() {
        let mut set: PagedSparseSet<u32, 8> = [9, 3, 7, 1, 8, 2].into_iter().collect();
        set.retain(|&k| k % 3 != 0);
        set.sort_unstable();
        assert_eq!(set.as_slice(), &[1, 2, 7, 8]);
        for (pos, &k) in set.as_slice().iter().enumerate() {
            assert_eq!(set.position(k), Some(pos));
        }
        assert!(!set.contains(3) && !set.contains(9));
    }

    #[test]
    fn stable_sorts_keep_ties_in_order() {
        let mut set: PagedSparseSet<u32, 4> = [5, 9, 2, 7, 40, 12].into_iter().collect();
        set.sort_by_key(|&k| k % 2);
        assert_eq!(set.as_slice(), &[2, 40, 12, 5, 9, 7]);
        set.sort_by(|a, b| (b / 10).cmp(&(a / 10)));
        assert_eq!(set.as_slice(), &[40, 12, 2, 5, 9, 7]);
        for (pos, &key) in set.as_slice().iter().enumerate() {
            assert_eq!(set.position(key), Some(pos));
        }
        set.sort();
        assert_eq!(set.as_slice(), &[2, 5, 7, 9, 12, 40]);
        assert_eq!(set.position(12), Some(4));
        assert_eq!(set.as_slice().binary_search(&9), Ok(3));
    }

    #[test]
    fn equality_ignores_order() {
        let a: PagedSparseSet<u32> = [1, 2, 3].into_iter().collect();
        let b: PagedSparseSet<u32> = [3, 1, 2].into_iter().collect();
        let c: PagedSparseSet<u32> = [1, 2].into_iter().collect();
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn set_algebra_preserves_the_left_generation_when_stored() {
        let old = Gen(7);
        let new = Gen(7 | 1 << 16);
        let common = Gen(42);
        let left_only = Gen(13);
        let right_only = Gen(21);
        let left: PagedSparseSet<Gen, 4> = [old, common, left_only].into_iter().collect();
        let right: PagedSparseSet<Gen, 64, Radix> = [new, common, right_only].into_iter().collect();

        let union = left.union(&right).copied();
        assert!(union.clone().eq([old, common, left_only, new, right_only]));
        assert_eq!(
            union.collect::<PagedSparseSet<Gen>>().occupant(7),
            Some(&old)
        );
        assert_eq!(
            (&left | &right).as_slice(),
            &[old, common, left_only, right_only]
        );
        assert_eq!((&right | &left).occupant(7), Some(&new));

        let symmetric = left.symmetric_difference(&right).copied();
        assert!(symmetric.clone().eq([old, left_only, new, right_only]));
        assert_eq!(
            symmetric.collect::<PagedSparseSet<Gen>>().occupant(7),
            Some(&old)
        );
        assert_eq!((&left ^ &right).as_slice(), &[old, left_only, right_only]);
        assert_eq!((&right ^ &left).occupant(7), Some(&new));

        let mut assigned = left;
        assigned ^= &right;
        assert_eq!(assigned.as_slice(), &[old, left_only, right_only]);
        assert_eq!(assigned.occupant(7), Some(&old));
        assert!(!assigned.contains(new));
        assert!(!assigned.contains(common));
    }

    #[test]
    fn set_algebra_across_page_sizes_and_directories() {
        let left: PagedSparseSet<u32, 4> = [90, 7, 1, 4].into_iter().collect();
        let right: PagedSparseSet<u32, 64, Radix> = [1, 7, 128].into_iter().collect();
        assert!(left.difference(&right).copied().eq([90, 4]));
        assert!(left.intersection(&right).copied().eq([1, 7]));
        assert!(right.intersection(&left).copied().eq([1, 7]));
        assert!(left.union(&right).copied().eq([90, 7, 1, 4, 128]));
        assert!(left.symmetric_difference(&right).copied().eq([90, 4, 128]));

        let tie: PagedSparseSet<u32, 64, Radix> = [1, 7, 128, 256].into_iter().collect();
        assert!(left.intersection(&tie).copied().eq([7, 1]));

        let union: PagedSparseSet<u32, 4> = &left | &right;
        let intersection: PagedSparseSet<u32, 4> = &left & &right;
        let difference: PagedSparseSet<u32, 4> = &left - &right;
        let symmetric: PagedSparseSet<u32, 4> = &left ^ &right;
        assert_eq!(union.as_slice(), &[90, 7, 1, 4, 128]);
        assert_eq!(intersection.as_slice(), &[1, 7]);
        assert_eq!(difference.as_slice(), &[90, 4]);
        assert_eq!(symmetric.as_slice(), &[90, 4, 128]);

        let mut assigned = left.clone();
        assigned |= &right;
        assert_eq!(assigned, union);
        let mut assigned = left.clone();
        assigned &= &right;
        assert_eq!(assigned, intersection);
        let mut assigned = left.clone();
        assigned -= &right;
        assert_eq!(assigned, difference);
        let mut assigned = left;
        assigned ^= &right;
        assert_eq!(assigned, symmetric);
    }

    #[test]
    fn empty_sets_and_set_relationships() {
        let empty = PagedSparseSet::<u32, 4>::new();
        let set: PagedSparseSet<u32, 64, Radix> = [2, 1].into_iter().collect();
        let subset: PagedSparseSet<u32, 4> = [1].into_iter().collect();
        let disjoint: PagedSparseSet<u32, 4> = [3, 4, 5].into_iter().collect();

        assert_eq!(empty.difference(&set).next(), None);
        assert!(set.difference(&empty).copied().eq([2, 1]));
        assert_eq!(set.intersection(&empty).next(), None);
        assert!(empty.union(&set).copied().eq([2, 1]));
        assert!(set.symmetric_difference(&empty).copied().eq([2, 1]));
        assert_eq!(empty.union(&empty).next(), None);
        assert_eq!(empty.symmetric_difference(&empty).next(), None);

        assert!(empty.is_subset(&empty) && empty.is_superset(&empty));
        assert!(empty.is_disjoint(&empty));
        assert!(empty.is_subset(&set) && set.is_superset(&empty));
        assert!(!set.is_subset(&empty) && !empty.is_superset(&set));
        assert!(empty.is_disjoint(&set) && set.is_disjoint(&empty));
        assert!(subset.is_subset(&set) && set.is_superset(&subset));
        assert!(!set.is_subset(&subset) && !subset.is_superset(&set));
        assert!(!subset.is_disjoint(&set) && !set.is_disjoint(&subset));
        assert!(set.is_subset(&set) && set.is_superset(&set));
        assert!(!set.is_disjoint(&set));
        assert!(set.is_disjoint(&disjoint) && disjoint.is_disjoint(&set));
        assert!(!set.is_subset(&disjoint) && !disjoint.is_superset(&set));
    }

    #[test]
    fn set_iterators_report_remaining_bounds_and_keys() {
        fn assert_exhausted(mut iter: impl FusedIterator) {
            assert!(iter.next().is_none());
            assert_eq!(iter.size_hint(), (0, Some(0)));
            assert!(iter.next().is_none());
        }

        let left: PagedSparseSet<u32, 4> = [4, 2, 7, 3].into_iter().collect();
        let right: PagedSparseSet<u32, 64, Radix> = [7, 2, 5].into_iter().collect();

        let mut difference = left.difference(&right);
        assert_eq!(difference.size_hint(), (0, Some(4)));
        assert_eq!(difference.next(), Some(&4));
        assert_eq!(difference.size_hint(), (0, Some(3)));
        assert_eq!(alloc::format!("{difference:?}"), "[3]");
        assert_eq!(difference.next(), Some(&3));
        assert_exhausted(difference);

        let mut intersection = left.intersection(&right);
        assert_eq!(intersection.size_hint(), (0, Some(3)));
        assert_eq!(intersection.next(), Some(&7));
        assert_eq!(intersection.size_hint(), (0, Some(2)));
        assert_eq!(alloc::format!("{intersection:?}"), "[2]");
        assert_eq!(intersection.next(), Some(&2));
        assert_exhausted(intersection);

        let mut union = left.union(&right);
        assert_eq!(union.size_hint(), (4, Some(7)));
        assert_eq!(union.next(), Some(&4));
        assert_eq!(union.size_hint(), (3, Some(6)));
        assert_eq!(alloc::format!("{union:?}"), "[2, 7, 3, 5]");
        assert!(union.by_ref().take(3).copied().eq([2, 7, 3]));
        assert_eq!(union.size_hint(), (0, Some(3)));
        assert_eq!(union.next(), Some(&5));
        assert_exhausted(union);

        let mut symmetric = left.symmetric_difference(&right);
        assert_eq!(symmetric.size_hint(), (0, Some(7)));
        assert_eq!(symmetric.next(), Some(&4));
        assert_eq!(symmetric.size_hint(), (0, Some(6)));
        assert_eq!(alloc::format!("{symmetric:?}"), "[3, 5]");
        assert_eq!(symmetric.next(), Some(&3));
        assert_eq!(symmetric.size_hint(), (0, Some(3)));
        assert_eq!(symmetric.next(), Some(&5));
        assert_exhausted(symmetric);
    }
}