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
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
//! [`PagedVec`]: a growable vector stored in fixed-size pages.
//!
//! Elements live in pages of `PAGE` elements. A page is allocated once, with
//! room for at least `PAGE` elements, and never reallocated, so growing the
//! vector never moves or copies existing elements:
//!
//! - an element keeps its address while it stays at the same index, through
//!   any number of [`push`](PagedVec::push)es, [`extend`](Extend::extend)s
//!   and [`reserve`](PagedVec::reserve)s;
//! - growth costs one page allocation every `PAGE` pushes instead of an
//!   O(n) copy of the elements. The page directory (one `Vec` header per
//!   page) still grows like a `Vec`, but it is `PAGE` times shorter, so the
//!   occasional copy and the momentary doubling are small.
//!
//! Operations that change which element sits at an index ([`insert`],
//! [`remove`], [`swap`], [`swap_remove`], [`retain`], [`dedup`](PagedVec::dedup),
//! [`drain`](PagedVec::drain)) can move elements between addresses, as they
//! do in a `Vec`. Splitting at a page boundary transfers whole pages without
//! moving their elements. Draining removes its range eagerly, even if the
//! returned iterator is leaked.
//!
//! The price is that the elements are not one contiguous slice: there is no
//! `as_slice` or `Deref<Target = [T]>`. Use [`pages`](PagedVec::pages) for
//! slice access one page at a time, or
//! [`with_contiguous_mut`](PagedVec::with_contiguous_mut) to run a slice
//! algorithm on all elements at the cost of a temporary buffer.
//!
//! Sorting goes through that buffer, so it uses the standard library's slice
//! sorts. Searching needs no buffer: a binary search over the pages finds the
//! page, then the slice search runs inside it.
//!
//! | Operation | Cost |
//! |---|---|
//! | [`pop`](PagedVec::pop), [`get`](PagedVec::get), indexing | O(1) |
//! | [`push`](PagedVec::push) | amortized O(1): a page allocation every `PAGE` pushes, rare directory growth |
//! | [`insert`], [`remove`] | O(len − index): elements shift across pages |
//! | [`truncate`](PagedVec::truncate), [`clear`](PagedVec::clear) | O(removed) drops; pages are kept |
//! | [`dedup`](PagedVec::dedup) and variants | O(len), no allocation |
//! | [`split_off`](PagedVec::split_off) | O(transferred allocated pages) at a page boundary; otherwise O(len − at) |
//! | [`append`](PagedVec::append), [`extend_from_slice`](PagedVec::extend_from_slice) | O(added), plus page allocation; cloning costs extra |
//! | [`drain`](PagedVec::drain) | O(len − start + allocated pages), eager removal |
//! | [`range`](PagedVec::range), [`range_mut`](PagedVec::range_mut) | O(1) setup; O(1) amortized per element, no allocation |
//! | [`binary_search`](PagedVec::binary_search), [`partition_point`](PagedVec::partition_point) | O(log n), no allocation |
//! | [`sort`](PagedVec::sort) and variants | the slice sort's cost, plus moving all elements out and back and a temporary buffer of `len` elements |
//!
//! The name follows Rust's `Vec`; other languages may know it as a list.
//!
//! ```
//! use paged_collections::paged_vec::PagedVec;
//!
//! let mut v: PagedVec<u64, 4> = PagedVec::new();
//! v.push(10);
//! let first: *const u64 = &v[0];
//! v.extend(0..1000);
//! // The first page was never reallocated.
//! assert!(core::ptr::eq(first, &v[0]));
//! assert_eq!(v.len(), 1001);
//! assert_eq!(v.pages().next(), Some(&[10, 0, 1, 2][..]));
//! ```
//!
//! With the `rayon` feature, borrowed iterators are indexed across page
//! boundaries. A parallel iterator can also collect into or extend a
//! `PagedVec` in iteration order.
//!
//! ```rust
//! # #[cfg(feature = "rayon")] {
//! use paged_collections::paged_vec::PagedVec;
//! use rayon::prelude::*;
//!
//! let mut v: PagedVec<_, 3> = (0..5).into_par_iter().collect();
//! v.par_extend(5..7);
//! v.par_iter_mut().for_each(|value| *value *= 2);
//! assert_eq!(v.par_iter().copied().rev().collect::<Vec<_>>(), [12, 10, 8, 6, 4, 2, 0]);
//! # }
//! ```
//!
//! [`insert`]: PagedVec::insert
//! [`remove`]: PagedVec::remove
//! [`swap`]: PagedVec::swap
//! [`swap_remove`]: PagedVec::swap_remove
//! [`retain`]: PagedVec::retain

use alloc::collections::TryReserveError;
use alloc::vec::Vec;
use core::cmp::Ordering;
use core::fmt;
use core::hash::{Hash, Hasher};
use core::iter::FusedIterator;
use core::marker::PhantomData;
use core::ops::{Bound, Index, IndexMut, RangeBounds};

use crate::page::{DEFAULT_PAGE, split};

/// A growable vector whose elements never move while the vector grows.
///
/// `PAGE` is the number of elements per page; it must be non-zero. See the
/// [module docs](crate::paged_vec).
///
/// Invariants, for `n = len`:
///
/// - page `i` holds elements `i * PAGE ..` and has length
///   `min(PAGE, n.saturating_sub(i * PAGE))`, so pages after the last used
///   one are empty spares;
/// - every page has capacity at least `PAGE`. Every page is created by
///   `new_page`/`try_new_page` and never grows past `PAGE` elements, so it
///   never reallocates (`Vec` guarantees that `push` and `insert` do not
///   reallocate when the capacity suffices).
pub struct PagedVec<T, const PAGE: usize = DEFAULT_PAGE> {
    pages: Vec<Vec<T>>,
    len: usize,
}

impl<T, const PAGE: usize> PagedVec<T, PAGE> {
    /// Number of elements per page.
    pub const PAGE: usize = PAGE;

    /// An empty vector. Does not allocate.
    #[inline]
    pub const fn new() -> Self {
        const { assert!(PAGE > 0, "page size must be non-zero") };
        Self {
            pages: Vec::new(),
            len: 0,
        }
    }

    /// An empty vector with pages allocated for `capacity` elements.
    pub fn with_capacity(capacity: usize) -> Self {
        let mut v = Self::new();
        v.reserve(capacity);
        v
    }

    #[inline]
    fn new_page() -> Vec<T> {
        Vec::with_capacity(PAGE)
    }

    fn try_new_page() -> Result<Vec<T>, TryReserveError> {
        let mut page = Vec::new();
        page.try_reserve_exact(PAGE)?;
        Ok(page)
    }

    /// Number of pages that hold at least one element.
    #[inline]
    fn used_pages(&self) -> usize {
        self.len.div_ceil(PAGE)
    }

    /// Number of elements.
    #[inline]
    pub fn len(&self) -> usize {
        self.len
    }

    /// Whether there are no elements.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Number of elements the allocated pages hold.
    #[inline]
    pub fn capacity(&self) -> usize {
        self.pages.len().saturating_mul(PAGE)
    }

    /// Number of allocated pages, including empty spares.
    #[inline]
    pub fn allocated_pages(&self) -> usize {
        self.pages.len()
    }

    /// Allocates pages so that `additional` more elements fit without
    /// allocating. Pages are allocated now, not on first use.
    ///
    /// # Panics
    ///
    /// Panics if the length overflows `usize` or an allocation size
    /// overflows `isize::MAX` bytes.
    pub fn reserve(&mut self, additional: usize) {
        let needed = self
            .len
            .checked_add(additional)
            .expect("capacity overflow")
            .div_ceil(PAGE);
        if let Some(missing) = needed.checked_sub(self.pages.len()) {
            self.pages.reserve(missing);
            while self.pages.len() < needed {
                self.pages.push(Self::new_page());
            }
        }
    }

    /// Like [`reserve`](PagedVec::reserve), but returns an error instead of
    /// panicking or aborting. On error, pages allocated so far are kept.
    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
        let Some(total) = self.len.checked_add(additional) else {
            return Err(capacity_overflow());
        };
        let needed = total.div_ceil(PAGE);
        if let Some(missing) = needed.checked_sub(self.pages.len()) {
            self.pages.try_reserve(missing)?;
            while self.pages.len() < needed {
                self.pages.push(Self::try_new_page()?);
            }
        }
        Ok(())
    }

    /// Frees the spare pages after the last used one. Never moves elements:
    /// the last used page keeps its full capacity.
    pub fn shrink_to_fit(&mut self) {
        self.pages.truncate(self.used_pages());
        self.pages.shrink_to_fit();
    }

    /// Appends an element.
    ///
    /// Creates no reference to existing elements: it writes only the new
    /// slot, through `Vec::push` on a page that has room, so raw pointers to
    /// existing elements (for example from [`pages`](PagedVec::pages)) stay
    /// valid under the aliasing model.
    ///
    /// # Panics
    ///
    /// Panics if the length would overflow `usize` (possible only for
    /// zero-sized `T`).
    #[inline]
    pub fn push(&mut self, value: T) {
        let p = self.reserve_slot();
        self.pages[p].push(value);
    }

    /// Makes room for one more element and returns the page it goes in.
    fn reserve_slot(&mut self) -> usize {
        let new_len = self.len.checked_add(1).expect("PagedVec length overflow");
        let (p, _) = split::<PAGE>(self.len);
        if p == self.pages.len() {
            self.pages.push(Self::new_page());
        }
        self.len = new_len;
        let page = &self.pages[p];
        debug_assert!(page.len() < PAGE && page.capacity() >= PAGE);
        p
    }

    /// Appends an element and returns a reference to it.
    ///
    /// # Panics
    ///
    /// Panics if the length would overflow `usize` (possible only for
    /// zero-sized `T`).
    pub fn push_mut(&mut self, value: T) -> &mut T {
        let p = self.reserve_slot();
        let page = &mut self.pages[p];
        page.push(value);
        match page.last_mut() {
            Some(last) => last,
            None => unreachable!(),
        }
    }

    /// Removes and returns the last element.
    pub fn pop(&mut self) -> Option<T> {
        let last = self.len.checked_sub(1)?;
        let value = self.pages[last / PAGE].pop();
        debug_assert!(value.is_some());
        self.len = last;
        value
    }

    /// The element at `index`.
    #[inline]
    pub fn get(&self, index: usize) -> Option<&T> {
        let (p, offset) = split::<PAGE>(index);
        self.pages.get(p)?.get(offset)
    }

    /// The element at `index`, mutably.
    #[inline]
    pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
        let (p, offset) = split::<PAGE>(index);
        self.pages.get_mut(p)?.get_mut(offset)
    }

    /// The first element.
    #[inline]
    pub fn first(&self) -> Option<&T> {
        self.get(0)
    }

    /// The first element, mutably.
    #[inline]
    pub fn first_mut(&mut self) -> Option<&mut T> {
        self.get_mut(0)
    }

    /// The last element.
    #[inline]
    pub fn last(&self) -> Option<&T> {
        self.get(self.len.checked_sub(1)?)
    }

    /// The last element, mutably.
    #[inline]
    pub fn last_mut(&mut self) -> Option<&mut T> {
        self.get_mut(self.len.checked_sub(1)?)
    }

    /// Swaps the elements at `a` and `b`.
    ///
    /// # Panics
    ///
    /// Panics if `a` or `b` is out of bounds.
    pub fn swap(&mut self, a: usize, b: usize) {
        assert!(
            a < self.len && b < self.len,
            "swap indices (are {a} and {b}) should be < len (is {})",
            self.len
        );
        let (pa, oa) = split::<PAGE>(a);
        let (pb, ob) = split::<PAGE>(b);
        match pa.cmp(&pb) {
            Ordering::Equal => self.pages[pa].swap(oa, ob),
            Ordering::Less => {
                let (low, high) = self.pages.split_at_mut(pb);
                core::mem::swap(&mut low[pa][oa], &mut high[0][ob]);
            }
            Ordering::Greater => {
                let (low, high) = self.pages.split_at_mut(pa);
                core::mem::swap(&mut high[0][oa], &mut low[pb][ob]);
            }
        }
    }

    /// Inserts `value` at `index`, shifting the elements after it up by one.
    /// Costs O(len − index), plus a page allocation every `PAGE` elements.
    ///
    /// # Panics
    ///
    /// Panics if `index > len`.
    pub fn insert(&mut self, index: usize, value: T) {
        assert!(
            index <= self.len,
            "insertion index (is {index}) should be <= len (is {})",
            self.len
        );
        // Allocate first, so nothing below can fail.
        let new_len = self.len.checked_add(1).expect("PagedVec length overflow");
        let (last_page, _) = split::<PAGE>(self.len);
        if last_page == self.pages.len() {
            self.pages.push(Self::new_page());
        }
        let (mut p, mut offset) = split::<PAGE>(index);
        let mut carry = value;
        // Only moves from here on: no user code runs, so nothing can panic.
        loop {
            let page = &mut self.pages[p];
            if page.len() < PAGE {
                page.insert(offset, carry);
                break;
            }
            // A full page passes its last element to the front of the next.
            let Some(out) = page.pop() else {
                unreachable!()
            };
            page.insert(offset, carry);
            carry = out;
            p += 1;
            offset = 0;
        }
        self.len = new_len;
    }

    /// Removes and returns the element at `index`, shifting the elements
    /// after it down by one. Costs O(len − index).
    ///
    /// # Panics
    ///
    /// Panics if `index >= len`.
    pub fn remove(&mut self, index: usize) -> T {
        assert!(
            index < self.len,
            "removal index (is {index}) should be < len (is {})",
            self.len
        );
        let used = self.used_pages();
        let (p, offset) = split::<PAGE>(index);
        let removed = self.pages[p].remove(offset);
        // Each later page passes its first element to the end of the one
        // before, which has just dropped to `PAGE - 1` elements.
        for q in p + 1..used {
            let first = self.pages[q].remove(0);
            self.pages[q - 1].push(first);
        }
        self.len -= 1;
        removed
    }

    /// Removes and returns the element at `index`, replacing it with the
    /// last element. O(1).
    ///
    /// # Panics
    ///
    /// Panics if `index >= len`.
    pub fn swap_remove(&mut self, index: usize) -> T {
        assert!(
            index < self.len,
            "swap_remove index (is {index}) should be < len (is {})",
            self.len
        );
        let last = self.len - 1;
        if index != last {
            self.swap(index, last);
        }
        match self.pop() {
            Some(value) => value,
            None => unreachable!(),
        }
    }

    /// Shortens the vector to `len` elements, dropping the rest one at a
    /// time from the back. Does nothing if `len >= self.len()`. Pages are
    /// kept.
    ///
    /// If a drop panics, the panicking element is gone and the elements
    /// before it stay in the vector.
    pub fn truncate(&mut self, len: usize) {
        if core::mem::needs_drop::<T>() {
            // Each element leaves the vector before it drops, so a panicking
            // drop leaves the vector consistent.
            while self.len > len {
                drop(self.pop());
            }
            return;
        }
        // Nothing to drop, so nothing can panic: cut whole pages at once.
        while self.len > len {
            let (p, _) = split::<PAGE>(self.len - 1);
            let start = p * PAGE;
            let new_len = len.max(start);
            self.len = new_len;
            self.pages[p].truncate(new_len - start);
        }
    }

    /// Drops every element. Pages are kept; see
    /// [`shrink_to_fit`](PagedVec::shrink_to_fit).
    pub fn clear(&mut self) {
        self.truncate(0);
    }

    /// Resizes to `new_len`, filling new slots with `f()` or truncating.
    /// If `f` panics, the elements pushed so far stay.
    pub fn resize_with(&mut self, new_len: usize, mut f: impl FnMut() -> T) {
        if new_len <= self.len {
            self.truncate(new_len);
            return;
        }
        self.reserve(new_len - self.len);
        while self.len < new_len {
            self.push(f());
        }
    }

    /// Resizes to `new_len`, filling new slots with clones of `value` or
    /// truncating.
    pub fn resize(&mut self, new_len: usize, value: T)
    where
        T: Clone,
    {
        self.resize_with(new_len, || value.clone());
    }

    /// Appends clones of `other`. Costs O(other.len()), plus cloning and
    /// page allocation. Existing elements keep their addresses. If cloning
    /// panics, the clones already pushed stay in the vector.
    ///
    /// # Panics
    ///
    /// Panics on capacity overflow, as [`reserve`](PagedVec::reserve) does.
    pub fn extend_from_slice(&mut self, other: &[T])
    where
        T: Clone,
    {
        self.reserve(other.len());
        for value in other {
            self.push(value.clone());
        }
    }

    /// Splits into `..at` and a returned vector holding `at..`, in order.
    /// Elements staying in `self` keep their addresses. At a multiple of
    /// `PAGE`, whole pages (including spares) transfer without moving their
    /// elements, costing O(transferred allocated pages). Otherwise the
    /// returned elements move, costing O(len − at), and `self` keeps its
    /// pages. Splitting at `len` returns an unallocated empty vector.
    ///
    /// Allocation happens before moving anything; an allocation panic
    /// leaves the elements unchanged.
    ///
    /// # Panics
    ///
    /// Panics if `at > len` or allocation size overflows.
    pub fn split_off(&mut self, at: usize) -> Self {
        assert!(
            at <= self.len,
            "split index (is {at}) should be <= len (is {})",
            self.len
        );
        let result = self.split_buffer(at);
        self.split_into(at, result)
    }

    // Allocate all storage before the first move. Aligned splits need only
    // directory entries; unaligned splits need fresh full-capacity pages.
    fn split_buffer(&self, at: usize) -> Self {
        if at == self.len {
            Self::new()
        } else if at % PAGE == 0 {
            Self {
                pages: Vec::with_capacity(self.pages.len() - at / PAGE),
                len: 0,
            }
        } else {
            Self::with_capacity(self.len - at)
        }
    }

    // `result` is empty, with directory capacity for an aligned split or
    // preallocated pages for an unaligned one, as in `split_buffer(at)`.
    // Nothing below allocates or invokes user code; pages are filled only
    // by individual pushes.
    fn split_into(&mut self, at: usize, mut result: Self) -> Self {
        if at == self.len {
            return result;
        }
        if at % PAGE == 0 {
            result.len = self.len - at;
            for page in self.pages.drain(at / PAGE..) {
                result.pages.push(page);
            }
            self.len = at;
        } else {
            while self.len > at {
                let Some(value) = self.pop() else {
                    unreachable!()
                };
                result.push(value);
            }
            result.reverse();
        }
        result
    }

    /// Moves all elements of `other` to the end, in order. Costs O(other.len()),
    /// plus page allocation. Existing elements in `self` keep their
    /// addresses; moved elements may change addresses. `other` becomes
    /// empty and keeps all its capacity.
    ///
    /// All allocation happens before moving anything. If it panics, both
    /// vectors keep their elements, though `self` may gain spare pages.
    /// After reserving, the individual pushes cannot allocate or panic.
    ///
    /// # Panics
    ///
    /// Panics on capacity overflow, as [`reserve`](PagedVec::reserve) does.
    pub fn append(&mut self, other: &mut Self) {
        self.reserve(other.len);
        let used = other.used_pages();
        other.len = 0;
        for page in &mut other.pages[..used] {
            for value in page.drain(..) {
                self.push(value);
            }
        }
    }

    /// Removes `range` eagerly and returns its elements in order. Costs
    /// O(len − start + allocated pages), with up to O(len − start) extra
    /// element storage and a directory for transferred pages. Elements
    /// before the range keep their addresses; elements after it shift down
    /// and may change addresses. An empty range moves nothing. When the
    /// start is a page boundary, the removed pages are reused, including a
    /// partial last page. If both ends are page boundaries, the following
    /// pages also keep their element addresses. Spare (empty) pages stay in
    /// the vector, up to its page count before the call; pages handed to the
    /// iterator with the removed elements are freed with it, so capacity can
    /// drop by the pages the removed range occupied.
    ///
    /// Unlike [`Vec::drain`], removal finishes before this method returns.
    /// Dropping the iterator drops the unconsumed removed elements;
    /// leaking it only leaks those elements and their storage. Neither
    /// changes the remaining vector. Allocation happens before any moves.
    ///
    /// # Panics
    ///
    /// Panics if the start exceeds the end, the end exceeds `len`, a bound
    /// overflows `usize`, or allocation size overflows.
    pub fn drain<R: RangeBounds<usize>>(&mut self, range: R) -> Drain<'_, T, PAGE> {
        let (start, end) = range_indices(range, self.len);
        let pages_before = self.pages.len();
        let removed = if start == end {
            Self::new()
        } else if end == self.len {
            self.split_off(start)
        } else if start % PAGE == 0 && end % PAGE == 0 {
            let mut result = Self {
                pages: Vec::with_capacity((end - start) / PAGE),
                len: end - start,
            };
            for page in self.pages.drain(start / PAGE..end / PAGE) {
                result.pages.push(page);
            }
            self.len -= result.len;
            result
        } else if start % PAGE == 0 {
            // Preserve the removed pages even when the last is partial.
            // Allocate both outputs before moving the unaligned tail.
            let tail_buffer = self.split_buffer(end);
            let removed_buffer = Self {
                pages: Vec::with_capacity(self.pages.len() - start / PAGE),
                len: 0,
            };
            let tail = self.split_into(end, tail_buffer);
            let result = self.split_into(start, removed_buffer);
            // The prefix is full pages. Its original directory has room
            // for these fresh tail pages: the combined length is smaller
            // than the original length. No element pushes are needed.
            for page in tail.pages {
                self.pages.push(page);
            }
            self.len += tail.len;
            result
        } else {
            let new_len = self.len - (end - start);
            let result = self.split_buffer(new_len);
            // Rotate [removed, tail] to [tail, removed] using only swaps.
            // Allocate first, then split off the removed suffix without
            // further allocation. The prefix is never touched.
            for (lo, hi) in [(start, end), (end, self.len), (start, self.len)] {
                for offset in 0..(hi - lo) / 2 {
                    self.swap(lo + offset, hi - 1 - offset);
                }
            }
            self.split_into(new_len, result)
        };
        // Aligned splits hand over trailing spare pages too; give back up to
        // the original page count so `drain` keeps capacity like
        // `Vec::drain`. The directory never shrank, so this cannot allocate.
        let mut removed = removed;
        let used = removed.used_pages();
        let back = (removed.pages.len() - used).min(pages_before.saturating_sub(self.pages.len()));
        if back > 0 {
            self.pages.extend(removed.pages.drain(used..used + back));
        }
        Drain {
            inner: removed.into_iter(),
            _borrow: PhantomData,
        }
    }

    /// Visits `range` in order, yielding each element for which `filter`
    /// returns `true`. The filter may mutate each element before deciding.
    ///
    /// Dropping the iterator early keeps the unvisited elements in order.
    /// If the filter panics, the element being tested is kept, including
    /// any mutations to it. Pages are kept and no memory is allocated.
    /// After the first removal, later elements are shifted down in one pass.
    ///
    /// # Panics
    ///
    /// Panics if the start exceeds the end, the end exceeds `len`, or a
    /// bound overflows `usize`.
    ///
    /// # Examples
    ///
    /// ```
    /// use paged_collections::paged_vec::PagedVec;
    ///
    /// let mut values: PagedVec<i32, 2> = (0..6).collect();
    /// let removed: Vec<_> = values.extract_if(1..5, |x| *x % 2 == 0).collect();
    /// assert_eq!(removed, [2, 4]);
    /// assert!(values.into_iter().eq([0, 1, 3, 5]));
    /// ```
    pub fn extract_if<R, F>(&mut self, range: R, filter: F) -> ExtractIf<'_, T, F, PAGE>
    where
        R: RangeBounds<usize>,
        F: FnMut(&mut T) -> bool,
    {
        let original_len = self.len;
        let (next, end) = range_indices(range, original_len);
        ExtractIf {
            vec: self,
            next,
            end,
            original_len,
            filter,
        }
    }

    /// Removes consecutive equal elements, keeping the first of each run.
    /// Costs O(len), without allocation. Elements before the first removed
    /// one keep their addresses; later kept elements move down. If equality
    /// panics, the guarantees of [`dedup_by`](PagedVec::dedup_by) apply.
    pub fn dedup(&mut self)
    where
        T: PartialEq,
    {
        self.dedup_by(|later, earlier| later == earlier);
    }

    /// Removes consecutive elements with equal keys, keeping the first of
    /// each run. `key` receives mutable access, later element first, as in
    /// [`Vec::dedup_by_key`]. Costs O(len), plus key computation, without
    /// allocation. Addresses and panic behaviour are as in
    /// [`dedup_by`](PagedVec::dedup_by).
    pub fn dedup_by_key<K: PartialEq>(&mut self, mut key: impl FnMut(&mut T) -> K) {
        self.dedup_by(|later, earlier| key(later) == key(earlier));
    }

    /// Removes consecutive elements for which `same_bucket(later, earlier)`
    /// returns `true`, keeping `earlier`. Costs O(len), without allocation.
    /// Elements before the first removed one keep their addresses; later
    /// kept elements move down.
    ///
    /// Duplicates are dropped at the end. If the closure panics, only the
    /// duplicates already identified are dropped; the kept prefix, element
    /// being compared and unvisited tail remain in order, including closure
    /// mutations. If a duplicate's destructor panics, duplicates not yet
    /// dropped remain at the end, as in [`retain`](PagedVec::retain).
    pub fn dedup_by(&mut self, mut same_bucket: impl FnMut(&mut T, &mut T) -> bool) {
        struct Guard<'a, T, const PAGE: usize> {
            vec: &'a mut PagedVec<T, PAGE>,
            read: usize,
            write: usize,
        }

        impl<T, const PAGE: usize> Drop for Guard<'_, T, PAGE> {
            fn drop(&mut self) {
                let mut write = self.write;
                for read in self.read..self.vec.len {
                    self.vec.swap(write, read);
                    write += 1;
                }
                self.vec.truncate(write);
            }
        }

        if self.len < 2 {
            return;
        }
        let len = self.len;
        let mut guard = Guard {
            vec: self,
            read: 1,
            write: 1,
        };
        while guard.read < len {
            let (earlier_page, earlier_offset) = split::<PAGE>(guard.write - 1);
            let (later_page, later_offset) = split::<PAGE>(guard.read);
            let duplicate = if earlier_page == later_page {
                let (earlier, later) = guard.vec.pages[later_page].split_at_mut(later_offset);
                same_bucket(&mut later[0], &mut earlier[earlier_offset])
            } else {
                let (earlier, later) = guard.vec.pages.split_at_mut(later_page);
                same_bucket(
                    &mut later[0][later_offset],
                    &mut earlier[earlier_page][earlier_offset],
                )
            };
            if !duplicate {
                if guard.write != guard.read {
                    guard.vec.swap(guard.write, guard.read);
                }
                guard.write += 1;
            }
            guard.read += 1;
        }
    }

    /// Keeps only the elements for which `keep` returns `true`, in order.
    ///
    /// Rejected elements are dropped together at the end, not as they are
    /// visited. If `keep` panics, the elements already rejected are dropped
    /// and the rest (kept, the one being tested, and the unvisited) stay in
    /// order. If dropping a rejected element panics, the rejected elements
    /// not yet dropped stay at the end of the vector.
    pub fn retain(&mut self, mut keep: impl FnMut(&T) -> bool) {
        self.retain_mut(|x| keep(x));
    }

    /// Like [`retain`](PagedVec::retain), with mutable access to each
    /// element.
    pub fn retain_mut(&mut self, mut keep: impl FnMut(&mut T) -> bool) {
        /// Kept elements are compacted into `..write`; rejected ones collect
        /// in `write..read`; `read..` is unvisited.
        struct Guard<'a, T, const PAGE: usize> {
            vec: &'a mut PagedVec<T, PAGE>,
            read: usize,
            write: usize,
        }

        impl<T, const PAGE: usize> Drop for Guard<'_, T, PAGE> {
            fn drop(&mut self) {
                // Move the unvisited tail down past the kept prefix, then
                // drop the rejected elements, which are now at the end. On
                // the normal path `read == len` and this only truncates.
                let mut write = self.write;
                for read in self.read..self.vec.len {
                    self.vec.swap(write, read);
                    write += 1;
                }
                self.vec.truncate(write);
            }
        }

        let len = self.len;
        let mut guard = Guard {
            vec: self,
            read: 0,
            write: 0,
        };
        while guard.read < len {
            let read = guard.read;
            let Some(x) = guard.vec.get_mut(read) else {
                unreachable!()
            };
            if keep(x) {
                if guard.write != read {
                    guard.vec.swap(guard.write, read);
                }
                guard.write += 1;
            }
            guard.read += 1;
        }
    }

    /// Runs `f` on all elements as one contiguous mutable slice, then puts
    /// them back in their new order.
    ///
    /// The elements are moved into a temporary buffer of `len` elements and
    /// back into the same pages, so the pages keep their addresses (as with
    /// any reordering, an element's address follows its index, not the
    /// element). The buffer costs `len * size_of::<T>()` bytes for the
    /// duration of the call.
    ///
    /// If `f` panics, the elements are put back in whatever order `f` left
    /// them, and the panic continues.
    ///
    /// ```
    /// use paged_collections::paged_vec::PagedVec;
    ///
    /// let mut v: PagedVec<u32, 2> = [3, 1, 2, 5, 4].into();
    /// v.with_contiguous_mut(|s| s.rotate_left(2));
    /// assert!(v.iter().copied().eq([2, 5, 4, 3, 1]));
    /// ```
    pub fn with_contiguous_mut<R>(&mut self, f: impl FnOnce(&mut [T]) -> R) -> R {
        /// Moves the buffer back into the pages, `PAGE` elements each, on
        /// return and on unwind.
        struct Refill<'a, T, const PAGE: usize> {
            pages: &'a mut [Vec<T>],
            buf: Vec<T>,
        }

        impl<T, const PAGE: usize> Drop for Refill<'_, T, PAGE> {
            fn drop(&mut self) {
                // One `push` at a time: `Vec` guarantees that `push` does
                // not reallocate when the capacity suffices (bulk methods
                // make no such promise), each page kept its capacity of at
                // least `PAGE` (`Vec` never shrinks on its own), and each
                // gets at most `PAGE` elements. So nothing here allocates or
                // panics, and no page moves.
                let mut rest = self.buf.drain(..);
                for page in self.pages.iter_mut() {
                    debug_assert!(page.is_empty() && page.capacity() >= PAGE);
                    for value in rest.by_ref().take(PAGE) {
                        page.push(value);
                    }
                }
                debug_assert_eq!(rest.len(), 0);
            }
        }

        // Allocate before moving anything, so a failed allocation changes
        // nothing. The guard exists before the first move; gathering only
        // pushes into `buf`, which has room for every element, so it cannot
        // panic either.
        let used = self.used_pages();
        let mut refill = Refill::<T, PAGE> {
            pages: &mut self.pages[..used],
            buf: Vec::with_capacity(self.len),
        };
        for page in refill.pages.iter_mut() {
            for value in page.drain(..) {
                refill.buf.push(value);
            }
        }
        f(&mut refill.buf)
    }

    /// Sorts stably, with the standard library's stable sort. See
    /// [`with_contiguous_mut`](PagedVec::with_contiguous_mut) for the
    /// temporary buffer and panic behaviour: if a comparison panics, the
    /// vector holds the same elements in an unspecified order.
    pub fn sort(&mut self)
    where
        T: Ord,
    {
        self.with_contiguous_mut(|s| s.sort());
    }

    /// Sorts stably with a comparator. See [`sort`](PagedVec::sort).
    pub fn sort_by(&mut self, compare: impl FnMut(&T, &T) -> Ordering) {
        self.with_contiguous_mut(|s| s.sort_by(compare));
    }

    /// Sorts stably by a key. See [`sort`](PagedVec::sort).
    pub fn sort_by_key<K: Ord>(&mut self, key: impl FnMut(&T) -> K) {
        self.with_contiguous_mut(|s| s.sort_by_key(key));
    }

    /// Sorts stably by a key computed at most once per element. See
    /// [`sort`](PagedVec::sort).
    pub fn sort_by_cached_key<K: Ord>(&mut self, key: impl FnMut(&T) -> K) {
        self.with_contiguous_mut(|s| s.sort_by_cached_key(key));
    }

    /// Sorts without preserving the order of equal elements, with the
    /// standard library's unstable sort. See [`sort`](PagedVec::sort).
    pub fn sort_unstable(&mut self)
    where
        T: Ord,
    {
        self.with_contiguous_mut(|s| s.sort_unstable());
    }

    /// Unstable sort with a comparator. See [`sort`](PagedVec::sort).
    pub fn sort_unstable_by(&mut self, compare: impl FnMut(&T, &T) -> Ordering) {
        self.with_contiguous_mut(|s| s.sort_unstable_by(compare));
    }

    /// Unstable sort by a key. See [`sort`](PagedVec::sort).
    pub fn sort_unstable_by_key<K: Ord>(&mut self, key: impl FnMut(&T) -> K) {
        self.with_contiguous_mut(|s| s.sort_unstable_by_key(key));
    }

    /// Reverses the order of the elements in place, without a buffer.
    pub fn reverse(&mut self) {
        let n = self.len;
        for i in 0..n / 2 {
            self.swap(i, n - 1 - i);
        }
    }

    /// Whether some element equals `x`. O(len).
    pub fn contains(&self, x: &T) -> bool
    where
        T: PartialEq,
    {
        self.pages().any(|page| page.contains(x))
    }

    /// Binary search in a sorted vector, like
    /// [`slice::binary_search`]: `Ok` with the index of a matching element
    /// (any one, if several match), or `Err` with the index where `x` would
    /// be inserted to keep the order.
    pub fn binary_search(&self, x: &T) -> Result<usize, usize>
    where
        T: Ord,
    {
        self.binary_search_by(|y| y.cmp(x))
    }

    /// Binary search with a comparator that returns the order of the
    /// element relative to the target, like [`slice::binary_search_by`].
    /// The result is unspecified, but not undefined, if the vector is not
    /// sorted consistently with `f`.
    pub fn binary_search_by<'a>(
        &'a self,
        mut f: impl FnMut(&'a T) -> Ordering,
    ) -> Result<usize, usize> {
        let pages: &'a [Vec<T>] = &self.pages[..self.used_pages()];
        // The first page whose last element is not less than the target is
        // the only one that can hold the first match or the insertion point.
        // Searched by hand: `partition_point`'s closure gets a reference
        // too short-lived to pass to `f`.
        let (mut lo, mut hi) = (0, pages.len());
        while lo < hi {
            let mid = lo + (hi - lo) / 2;
            let page: &'a Vec<T> = &pages[mid];
            if page.last().is_some_and(|y| f(y) == Ordering::Less) {
                lo = mid + 1;
            } else {
                hi = mid;
            }
        }
        let p = lo;
        let Some(page) = pages.get(p) else {
            return Err(self.len);
        };
        let base = p * PAGE;
        match page.binary_search_by(f) {
            Ok(i) => Ok(base + i),
            Err(i) => Err(base + i),
        }
    }

    /// Binary search by a key, like [`slice::binary_search_by_key`].
    pub fn binary_search_by_key<'a, K: Ord>(
        &'a self,
        key: &K,
        mut f: impl FnMut(&'a T) -> K,
    ) -> Result<usize, usize> {
        self.binary_search_by(|y| f(y).cmp(key))
    }

    /// The index of the first element for which `pred` is false, given that
    /// `pred` is true for a prefix and false for the rest, like
    /// [`slice::partition_point`].
    pub fn partition_point(&self, mut pred: impl FnMut(&T) -> bool) -> usize {
        let pages = &self.pages[..self.used_pages()];
        let p = pages.partition_point(|page| page.last().is_some_and(&mut pred));
        match pages.get(p) {
            Some(page) => p * PAGE + page.partition_point(pred),
            None => self.len,
        }
    }

    /// Iterates over the elements.
    pub fn iter(&self) -> Iter<'_, T> {
        Iter {
            pages: self.pages[..self.used_pages()].iter(),
            front: [].iter(),
            back: [].iter(),
            remaining: self.len,
        }
    }

    /// Iterates over the elements mutably.
    pub fn iter_mut(&mut self) -> IterMut<'_, T> {
        let used = self.used_pages();
        IterMut {
            pages: self.pages[..used].iter_mut(),
            front: [].iter_mut(),
            back: [].iter_mut(),
            remaining: self.len,
        }
    }

    /// Iterates over `range` in order, from either end, with an exact length.
    /// Setup costs O(1), seeking directly to the boundary pages. Does not
    /// allocate or move elements.
    ///
    /// # Panics
    ///
    /// Panics if the start exceeds the end, the end exceeds `len`, or a
    /// bound overflows `usize`, like slicing a slice.
    pub fn range<R: RangeBounds<usize>>(&self, range: R) -> Iter<'_, T> {
        let (start, end) = range_indices(range, self.len);
        if start == end {
            return Iter {
                pages: [].iter(),
                front: [].iter(),
                back: [].iter(),
                remaining: 0,
            };
        }
        let first = start / PAGE;
        let last = (end - 1) / PAGE;
        let mut pages = self.pages[first..=last].iter();
        let Some(page) = pages.next() else {
            unreachable!()
        };
        let front_end = if first == last {
            end - first * PAGE
        } else {
            page.len()
        };
        let front = page[start % PAGE..front_end].iter();
        let back = match pages.next_back() {
            Some(page) => page[..end - last * PAGE].iter(),
            None => [].iter(),
        };
        Iter {
            pages,
            front,
            back,
            remaining: end - start,
        }
    }

    /// Like [`range`](PagedVec::range), with mutable access to each element.
    /// Setup costs O(1); no allocation or moves. Panics on the same invalid
    /// bounds as [`range`](PagedVec::range).
    pub fn range_mut<R: RangeBounds<usize>>(&mut self, range: R) -> IterMut<'_, T> {
        let (start, end) = range_indices(range, self.len);
        if start == end {
            return IterMut {
                pages: [].iter_mut(),
                front: [].iter_mut(),
                back: [].iter_mut(),
                remaining: 0,
            };
        }
        let first = start / PAGE;
        let last = (end - 1) / PAGE;
        let mut pages = self.pages[first..=last].iter_mut();
        let Some(page) = pages.next() else {
            unreachable!()
        };
        let front_end = if first == last {
            end - first * PAGE
        } else {
            page.len()
        };
        let front = page[start % PAGE..front_end].iter_mut();
        let back = match pages.next_back() {
            Some(page) => page[..end - last * PAGE].iter_mut(),
            None => [].iter_mut(),
        };
        IterMut {
            pages,
            front,
            back,
            remaining: end - start,
        }
    }

    /// The non-empty pages as slices, in order. Every page but the last is
    /// full.
    pub fn pages(
        &self,
    ) -> impl ExactSizeIterator<Item = &[T]> + DoubleEndedIterator + FusedIterator + Clone {
        self.pages[..self.used_pages()].iter().map(Vec::as_slice)
    }

    /// The non-empty pages as mutable slices, in order.
    pub fn pages_mut(
        &mut self,
    ) -> impl ExactSizeIterator<Item = &mut [T]> + DoubleEndedIterator + FusedIterator {
        let used = self.used_pages();
        self.pages[..used].iter_mut().map(Vec::as_mut_slice)
    }
}

// Resolve excluded starts and included ends with checked addition, including
// bounds supplied by a custom RangeBounds implementation.
#[track_caller]
fn range_indices(range: impl RangeBounds<usize>, len: usize) -> (usize, usize) {
    let start = match range.start_bound() {
        Bound::Included(&start) => start,
        Bound::Excluded(&start) => start.checked_add(1).expect("range start index overflow"),
        Bound::Unbounded => 0,
    };
    let end = match range.end_bound() {
        Bound::Included(&end) => end.checked_add(1).expect("range end index overflow"),
        Bound::Excluded(&end) => end,
        Bound::Unbounded => len,
    };
    assert!(
        start <= end,
        "range start (is {start}) should be <= end (is {end})"
    );
    assert!(
        end <= len,
        "range end (is {end}) should be <= len (is {len})"
    );
    (start, end)
}

pub(crate) fn capacity_overflow() -> TryReserveError {
    // `try_reserve` has no public constructor for its error; a request over
    // `isize::MAX` bytes always fails with the capacity-overflow kind.
    match Vec::<u8>::new().try_reserve(usize::MAX) {
        Err(e) => e,
        Ok(()) => unreachable!(),
    }
}

impl<T, const PAGE: usize> Default for PagedVec<T, PAGE> {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

/// Clones page by page. Each new page gets the full capacity `PAGE`, so the
/// clone keeps the stable-address guarantee.
impl<T: Clone, const PAGE: usize> Clone for PagedVec<T, PAGE> {
    fn clone(&self) -> Self {
        let mut pages = Vec::with_capacity(self.used_pages());
        for page in self.pages() {
            let mut new = Self::new_page();
            new.extend_from_slice(page);
            pages.push(new);
        }
        Self {
            pages,
            len: self.len,
        }
    }
}

impl<T: fmt::Debug, const PAGE: usize> fmt::Debug for PagedVec<T, PAGE> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.iter()).finish()
    }
}

/// Element-wise, regardless of page size.
impl<T: PartialEq<U>, U, const PAGE: usize, const PAGE2: usize> PartialEq<PagedVec<U, PAGE2>>
    for PagedVec<T, PAGE>
{
    fn eq(&self, other: &PagedVec<U, PAGE2>) -> bool {
        self.len == other.len && self.iter().zip(other.iter()).all(|(a, b)| a == b)
    }
}

impl<T: Eq, const PAGE: usize> Eq for PagedVec<T, PAGE> {}

/// Lexicographic, like slices.
impl<T: PartialOrd, const PAGE: usize, const PAGE2: usize> PartialOrd<PagedVec<T, PAGE2>>
    for PagedVec<T, PAGE>
{
    fn partial_cmp(&self, other: &PagedVec<T, PAGE2>) -> Option<Ordering> {
        self.iter().partial_cmp(other.iter())
    }
}

impl<T: Ord, const PAGE: usize> Ord for PagedVec<T, PAGE> {
    fn cmp(&self, other: &Self) -> Ordering {
        self.iter().cmp(other.iter())
    }
}

/// Hashes the length, then each element. Consistent with `Eq` across page
/// sizes; not guaranteed to equal the hash of a slice with the same elements.
impl<T: Hash, const PAGE: usize> Hash for PagedVec<T, PAGE> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        state.write_usize(self.len);
        for x in self {
            x.hash(state);
        }
    }
}

impl<T, const PAGE: usize> Index<usize> for PagedVec<T, PAGE> {
    type Output = T;

    #[inline]
    #[track_caller]
    fn index(&self, index: usize) -> &T {
        match self.get(index) {
            Some(x) => x,
            None => panic!(
                "index out of bounds: the len is {} but the index is {index}",
                self.len
            ),
        }
    }
}

impl<T, const PAGE: usize> IndexMut<usize> for PagedVec<T, PAGE> {
    #[inline]
    #[track_caller]
    fn index_mut(&mut self, index: usize) -> &mut T {
        let len = self.len;
        match self.get_mut(index) {
            Some(x) => x,
            None => panic!("index out of bounds: the len is {len} but the index is {index}"),
        }
    }
}

impl<T, const PAGE: usize> Extend<T> for PagedVec<T, PAGE> {
    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
        let iter = iter.into_iter();
        self.reserve(iter.size_hint().0);
        for x in iter {
            self.push(x);
        }
    }
}

impl<'a, T: Copy + 'a, const PAGE: usize> Extend<&'a T> for PagedVec<T, PAGE> {
    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
        self.extend(iter.into_iter().copied());
    }
}

impl<T, const PAGE: usize> FromIterator<T> for PagedVec<T, PAGE> {
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        let mut v = Self::new();
        v.extend(iter);
        v
    }
}

impl<T, const PAGE: usize> From<Vec<T>> for PagedVec<T, PAGE> {
    fn from(v: Vec<T>) -> Self {
        v.into_iter().collect()
    }
}

impl<T, const N: usize, const PAGE: usize> From<[T; N]> for PagedVec<T, PAGE> {
    fn from(a: [T; N]) -> Self {
        a.into_iter().collect()
    }
}

impl<'a, T, const PAGE: usize> IntoIterator for &'a PagedVec<T, PAGE> {
    type Item = &'a T;
    type IntoIter = Iter<'a, T>;

    fn into_iter(self) -> Iter<'a, T> {
        self.iter()
    }
}

impl<'a, T, const PAGE: usize> IntoIterator for &'a mut PagedVec<T, PAGE> {
    type Item = &'a mut T;
    type IntoIter = IterMut<'a, T>;

    fn into_iter(self) -> IterMut<'a, T> {
        self.iter_mut()
    }
}

impl<T, const PAGE: usize> IntoIterator for PagedVec<T, PAGE> {
    type Item = T;
    type IntoIter = IntoIter<T>;

    fn into_iter(mut self) -> IntoIter<T> {
        let used = self.used_pages();
        self.pages.truncate(used);
        IntoIter {
            pages: self.pages.into_iter(),
            front: Vec::new().into_iter(),
            back: Vec::new().into_iter(),
            remaining: self.len,
        }
    }
}

/// Defines a flattening iterator over pages. `$pages` yields pages and
/// `$elems(page)` turns one into an element iterator; `front` and `back`
/// hold the partly consumed pages at either end.
macro_rules! paged_iter {
    ($(#[$m:meta])* $name:ident<$($lt:lifetime,)? $t:ident>, $item:ty, $pages:ty, $elems:ty, $into:expr) => {
        $(#[$m])*
        pub struct $name<$($lt,)? $t> {
            pages: $pages,
            front: $elems,
            back: $elems,
            remaining: usize,
        }

        impl<$($lt,)? $t> Iterator for $name<$($lt,)? $t> {
            type Item = $item;

            fn next(&mut self) -> Option<$item> {
                loop {
                    if let Some(x) = self.front.next() {
                        self.remaining -= 1;
                        return Some(x);
                    }
                    match self.pages.next() {
                        Some(page) => self.front = $into(page),
                        None => {
                            let x = self.back.next()?;
                            self.remaining -= 1;
                            return Some(x);
                        }
                    }
                }
            }

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

        impl<$($lt,)? $t> DoubleEndedIterator for $name<$($lt,)? $t> {
            fn next_back(&mut self) -> Option<$item> {
                loop {
                    if let Some(x) = self.back.next_back() {
                        self.remaining -= 1;
                        return Some(x);
                    }
                    match self.pages.next_back() {
                        Some(page) => self.back = $into(page),
                        None => {
                            let x = self.front.next_back()?;
                            self.remaining -= 1;
                            return Some(x);
                        }
                    }
                }
            }
        }

        impl<$($lt,)? $t> ExactSizeIterator for $name<$($lt,)? $t> {}
        impl<$($lt,)? $t> FusedIterator for $name<$($lt,)? $t> {}
    };
}

paged_iter!(
    /// Iterator over references to the elements of a [`PagedVec`].
    Iter<'a, T>, &'a T, core::slice::Iter<'a, Vec<T>>, core::slice::Iter<'a, T>,
    |page: &'a Vec<T>| page.iter()
);

paged_iter!(
    /// Iterator over mutable references to the elements of a [`PagedVec`].
    IterMut<'a, T>, &'a mut T, core::slice::IterMut<'a, Vec<T>>, core::slice::IterMut<'a, T>,
    |page: &'a mut Vec<T>| page.iter_mut()
);

paged_iter!(
    /// Owning iterator over the elements of a [`PagedVec`].
    IntoIter<T>, T, alloc::vec::IntoIter<Vec<T>>, alloc::vec::IntoIter<T>,
    |page: Vec<T>| page.into_iter()
);

/// Owning iterator over elements eagerly removed by [`PagedVec::drain`].
///
/// The vector stays mutably borrowed for this iterator's lifetime, though
/// removal has already finished. Dropping it drops the remaining removed
/// elements; leaking it leaves the vector intact and leaks only the removed
/// elements and their storage.
pub struct Drain<'a, T, const PAGE: usize = DEFAULT_PAGE> {
    inner: IntoIter<T>,
    _borrow: PhantomData<&'a mut PagedVec<T, PAGE>>,
}

impl<T, const PAGE: usize> Iterator for Drain<'_, T, PAGE> {
    type Item = T;

    fn next(&mut self) -> Option<T> {
        self.inner.next()
    }

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

impl<T, const PAGE: usize> DoubleEndedIterator for Drain<'_, T, PAGE> {
    fn next_back(&mut self) -> Option<T> {
        self.inner.next_back()
    }
}

impl<T, const PAGE: usize> ExactSizeIterator for Drain<'_, T, PAGE> {}
impl<T, const PAGE: usize> FusedIterator for Drain<'_, T, PAGE> {}

impl<T: fmt::Debug, const PAGE: usize> fmt::Debug for Drain<'_, T, PAGE> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let middle = self
            .inner
            .pages
            .as_slice()
            .iter()
            .flat_map(|page| page.iter());
        f.debug_list()
            .entries(
                self.inner
                    .front
                    .as_slice()
                    .iter()
                    .chain(middle)
                    .chain(self.inner.back.as_slice()),
            )
            .finish()
    }
}

/// The elements removed by [`PagedVec::extract_if`].
///
/// Dropping this iterator moves any unvisited elements down to fill the gap
/// left by removals. Forgetting it after a removal leaks the unvisited
/// suffix and leaves the compacted prefix in the vector.
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct ExtractIf<'a, T, F, const PAGE: usize = DEFAULT_PAGE> {
    vec: &'a mut PagedVec<T, PAGE>,
    // Before the first removal, all slots up to original_len are owned by
    // vec. After it, vec owns 0..vec.len, while next..original_len holds
    // initialized elements owned by this iterator. Slots in the gap
    // vec.len..next are logically uninitialized.
    next: usize,
    end: usize,
    original_len: usize,
    filter: F,
}

impl<T, F, const PAGE: usize> ExtractIf<'_, T, F, PAGE> {
    /// Shortens the vector on the first removal, transferring ownership
    /// of the suffix to this iterator without dropping or moving elements.
    fn hide_tail(&mut self) {
        let (page, mut len) = split::<PAGE>(self.next);
        let used = self.vec.used_pages();
        for page in &mut self.vec.pages[page..used] {
            // SAFETY: len is at most the current page length. The iterator
            // takes ownership of the elements beyond it in this page.
            unsafe { page.set_len(len) };
            len = 0;
        }
        self.vec.len = self.next;
    }

    fn current_ptr(&mut self) -> *mut T {
        let (page, offset) = split::<PAGE>(self.next);
        self.vec.pages[page].as_mut_ptr().wrapping_add(offset)
    }

    fn take_next(&mut self) -> T {
        let slot = self.current_ptr();
        self.next += 1;
        // SAFETY: the caller has hidden the tail, and the previous next
        // index names its first initialized element. Advancing next moves
        // ownership of this slot out of the iterator.
        unsafe { slot.read() }
    }
}

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

    fn next(&mut self) -> Option<T> {
        while self.next < self.end {
            let slot = self.current_ptr();
            // SAFETY: next is below original_len and names an initialized
            // element, including when the tail is hidden from the vector.
            // The reference is exclusive and ends before we move the value.
            let value = unsafe { &mut *slot };
            if (self.filter)(value) {
                if self.vec.len == self.original_len {
                    self.hide_tail();
                }
                return Some(self.take_next());
            }
            if self.vec.len == self.original_len {
                self.next += 1;
            } else {
                let kept = self.take_next();
                self.vec.push(kept);
            }
        }
        None
    }

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

impl<T, F: FnMut(&mut T) -> bool, const PAGE: usize> FusedIterator for ExtractIf<'_, T, F, PAGE> {}

impl<T, F, const PAGE: usize> Drop for ExtractIf<'_, T, F, PAGE> {
    fn drop(&mut self) {
        if self.vec.len == self.original_len {
            return;
        }
        while self.next < self.original_len {
            let kept = self.take_next();
            // The gap leaves room in the original pages, so push cannot
            // allocate. No filter or destructors run during compaction.
            self.vec.push(kept);
        }
    }
}

impl<T, F, const PAGE: usize> fmt::Debug for ExtractIf<'_, T, F, PAGE> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ExtractIf")
            .field("remaining", &(self.end - self.next))
            .finish_non_exhaustive()
    }
}

impl<T> Clone for Iter<'_, T> {
    fn clone(&self) -> Self {
        Self {
            pages: self.pages.clone(),
            front: self.front.clone(),
            back: self.back.clone(),
            remaining: self.remaining,
        }
    }
}

impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.clone()).finish()
    }
}

#[cfg(feature = "rayon")]
pub use rayon_impl::{ParIter, ParIterMut};

#[cfg(feature = "rayon")]
mod rayon_impl {
    use super::*;
    use rayon::iter::plumbing::{Consumer, Producer, ProducerCallback, UnindexedConsumer, bridge};
    use rayon::prelude::*;

    // Both producers describe the same layout. The mutable producer splits
    // the page directory before taking any element slices from it.
    macro_rules! parallel_iter {
        (
            $(#[$doc:meta])* $name:ident, $producer:ident, $sequential:ident,
            $bound:ident, [$($mutability:tt)*], $iter:ident,
            $split_at:ident, $split_first:ident, $split_last:ident
        ) => {
            $(#[$doc])*
            #[derive(Debug)]
            pub struct $name<'a, T, const PAGE: usize = DEFAULT_PAGE>($producer<'a, T, PAGE>);

            #[derive(Debug)]
            struct $producer<'a, T, const PAGE: usize> {
                head: &'a $($mutability)* [T],
                // Every page here is full. Only the two ends can be partial.
                middle: &'a $($mutability)* [Vec<T>],
                tail: &'a $($mutability)* [T],
            }

            impl<'a, T, const PAGE: usize> $producer<'a, T, PAGE> {
                fn new(pages: &'a $($mutability)* [Vec<T>]) -> Self {
                    match pages.$split_last() {
                        Some((tail, middle)) => Self { head: &$($mutability)* [], middle, tail },
                        None => Self::from_head(&$($mutability)* []),
                    }
                }

                fn from_head(head: &'a $($mutability)* [T]) -> Self {
                    Self {
                        head,
                        middle: &$($mutability)* [],
                        tail: &$($mutability)* [],
                    }
                }

                fn len(&self) -> usize {
                    self.head.len() + self.middle.len() * PAGE + self.tail.len()
                }
            }

            impl<'a, T: $bound, const PAGE: usize> IntoParallelIterator
                for &'a $($mutability)* PagedVec<T, PAGE>
            {
                type Item = &'a $($mutability)* T;
                type Iter = $name<'a, T, PAGE>;

                fn into_par_iter(self) -> Self::Iter {
                    let used = self.used_pages();
                    $name($producer::new(&$($mutability)* self.pages[..used]))
                }
            }

            impl<'a, T: $bound, const PAGE: usize> ParallelIterator for $name<'a, T, PAGE> {
                type Item = &'a $($mutability)* T;

                fn drive_unindexed<C: UnindexedConsumer<Self::Item>>(self, consumer: C) -> C::Result {
                    bridge(self, consumer)
                }

                fn opt_len(&self) -> Option<usize> {
                    Some(self.len())
                }
            }

            impl<T: $bound, const PAGE: usize> IndexedParallelIterator for $name<'_, T, PAGE> {
                fn len(&self) -> usize {
                    self.0.len()
                }

                fn drive<C: Consumer<Self::Item>>(self, consumer: C) -> C::Result {
                    bridge(self, consumer)
                }

                fn with_producer<CB: ProducerCallback<Self::Item>>(self, callback: CB) -> CB::Output {
                    callback.callback(self.0)
                }
            }

            impl<'a, T: $bound, const PAGE: usize> Producer for $producer<'a, T, PAGE> {
                type Item = &'a $($mutability)* T;
                type IntoIter = $sequential<'a, T>;

                fn into_iter(self) -> Self::IntoIter {
                    let remaining = self.len();
                    $sequential {
                        pages: self.middle.$iter(),
                        front: self.head.$iter(),
                        back: self.tail.$iter(),
                        remaining,
                    }
                }

                fn split_at(self, index: usize) -> (Self, Self) {
                    let Self { head, middle, tail } = self;
                    if index <= head.len() {
                        let (left, right) = head.$split_at(index);
                        return (
                            Self::from_head(left),
                            Self { head: right, middle, tail },
                        );
                    }

                    let index = index - head.len();
                    let middle_len = middle.len() * PAGE;
                    if index >= middle_len {
                        let (left, right) = tail.$split_at(index - middle_len);
                        return (
                            Self { head, middle, tail: left },
                            Self::from_head(right),
                        );
                    }

                    let (page, offset) = split::<PAGE>(index);
                    let (left, right) = middle.$split_at(page);
                    if offset == 0 {
                        return (
                            Self { head, middle: left, tail: &$($mutability)* [] },
                            Self { head: &$($mutability)* [], middle: right, tail },
                        );
                    }

                    let (page, right) = right.$split_first().expect("split inside a full page");
                    let (left_tail, right_head) = page.$split_at(offset);
                    (
                        Self { head, middle: left, tail: left_tail },
                        Self { head: right_head, middle: right, tail },
                    )
                }
            }
        };
    }

    parallel_iter!(
        /// Indexed parallel iterator over references to the elements of a [`PagedVec`].
        ParIter,
        PageProducer,
        Iter,
        Sync,
        [],
        iter,
        split_at,
        split_first,
        split_last
    );
    parallel_iter!(
        /// Indexed parallel iterator over mutable references to the elements of a [`PagedVec`].
        ParIterMut, PageProducerMut, IterMut, Send, [mut], iter_mut, split_at_mut, split_first_mut,
        split_last_mut
    );

    impl<T, const PAGE: usize> Clone for ParIter<'_, T, PAGE> {
        fn clone(&self) -> Self {
            let PageProducer { head, middle, tail } = self.0;
            Self(PageProducer { head, middle, tail })
        }
    }

    impl<T: Send, const PAGE: usize> FromParallelIterator<T> for PagedVec<T, PAGE> {
        fn from_par_iter<I: IntoParallelIterator<Item = T>>(iter: I) -> Self {
            let mut out = Self::new();
            out.par_extend(iter);
            out
        }
    }

    impl<T: Send, const PAGE: usize> ParallelExtend<T> for PagedVec<T, PAGE> {
        fn par_extend<I: IntoParallelIterator<Item = T>>(&mut self, iter: I) {
            let chunks = iter.into_par_iter().collect_vec_list();
            self.reserve(chunks.iter().map(Vec::len).sum());
            self.extend(chunks.into_iter().flatten());
        }
    }
}

#[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 elements.
    impl<T: Serialize, const PAGE: usize> Serialize for PagedVec<T, PAGE> {
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            serializer.collect_seq(self.iter())
        }
    }

    /// Deserializes from a sequence of elements. Memory is linear in the
    /// number of elements read; the length hint is capped.
    impl<'de, T: Deserialize<'de>, const PAGE: usize> Deserialize<'de> for PagedVec<T, PAGE> {
        fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
            struct SeqVisitor<T, const PAGE: usize>(PhantomData<T>);

            impl<'de, T: Deserialize<'de>, const PAGE: usize> Visitor<'de> for SeqVisitor<T, PAGE> {
                type Value = PagedVec<T, PAGE>;

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

                fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
                    // Preallocate at most about 1 MiB of whole pages (elements
                    // plus directory entry) so a hostile length hint cannot
                    // force a huge allocation; none if one page is larger.
                    let budget = usize::try_from(1_u32 << 20).unwrap_or(usize::MAX);
                    let page_bytes = PAGE
                        .saturating_mul(core::mem::size_of::<T>())
                        .saturating_add(core::mem::size_of::<Vec<T>>());
                    let max_hint = (budget / page_bytes).saturating_mul(PAGE);
                    let hint = seq.size_hint().unwrap_or(0).min(max_hint);
                    let mut v = PagedVec::with_capacity(hint);
                    while let Some(x) = seq.next_element()? {
                        v.push(x);
                    }
                    Ok(v)
                }
            }

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

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::vec;

    fn addresses<T, const PAGE: usize>(v: &PagedVec<T, PAGE>) -> Vec<*const T> {
        v.iter().map(|x| x as *const T).collect()
    }

    /// `push` must not retag existing elements: a raw pointer taken from a
    /// shared page slice (as the Python bindings' NumPy views are) stays
    /// usable for reads and interior-mutable writes across pushes into the
    /// same page and new pages. Meaningful under Miri.
    #[test]
    fn push_keeps_raw_pointers_into_the_page_valid() {
        use core::cell::Cell;
        let mut v: PagedVec<Cell<u32>, 4> = PagedVec::new();
        v.push(Cell::new(1));
        let page: *const Cell<u32> = v.pages().next().unwrap().as_ptr();
        for i in 0..10 {
            v.push(Cell::new(i));
            v.extend([Cell::new(i)]);
            v.reserve(3);
            // SAFETY: element 0 never moves (page capacity >= PAGE, never
            // reallocated) and nothing has a `&mut` to it.
            let first = unsafe { &*page };
            first.set(first.get() + 1);
        }
        assert_eq!(v[0].get(), 11);
    }

    #[test]
    fn push_never_moves_elements() {
        let mut v: PagedVec<u32, 3> = PagedVec::new();
        v.extend(0..7);
        let before = addresses(&v);
        for i in 7..1000 {
            v.push(i);
        }
        v.reserve(5000);
        assert_eq!(&addresses(&v)[..7], &before[..]);
        // A clone keeps full-capacity pages, so its partial page is stable.
        let mut c: PagedVec<u32, 3> = (0..4).collect::<PagedVec<_, 3>>().clone();
        let at3: *const u32 = &c[3];
        c.extend(4..100);
        assert!(core::ptr::eq(at3, &c[3]));
    }

    #[test]
    fn insert_and_remove_shift_across_pages() {
        let mut v: PagedVec<u32, 3> = (0..7).collect();
        let mut model: Vec<u32> = (0..7).collect();
        for (i, x) in [(0, 100), (3, 101), (9, 102), (5, 103), (2, 104)] {
            v.insert(i, x);
            model.insert(i, x);
            assert!(v.iter().eq(model.iter()));
        }
        for i in [0, 4, 9, 3, 0] {
            assert_eq!(v.remove(i), model.remove(i));
            assert!(v.iter().eq(model.iter()));
        }
        assert_eq!(v.swap_remove(1), model.swap_remove(1));
        assert!(v.iter().eq(model.iter()));
        let pages: Vec<&[u32]> = v.pages().collect();
        assert!(pages[..pages.len() - 1].iter().all(|p| p.len() == 3));
    }

    #[test]
    fn truncate_retain_and_iterators() {
        let mut v: PagedVec<u32, 4> = (0..10).collect();
        v.retain(|x| x % 3 != 0);
        assert!(v.iter().copied().eq([1, 2, 4, 5, 7, 8]));
        assert!(v.iter().rev().copied().eq([8, 7, 5, 4, 2, 1]));
        let mut it = v.iter();
        assert_eq!(
            (it.next(), it.next_back(), it.len()),
            (Some(&1), Some(&8), 4)
        );
        for x in &mut v {
            *x *= 10;
        }
        v.truncate(3);
        assert_eq!(v.into_iter().collect::<Vec<_>>(), vec![10, 20, 40]);

        let mut v: PagedVec<u32, 4> = (0..10).collect();
        assert_eq!(v.allocated_pages(), 3);
        v.clear();
        assert!(v.is_empty() && v.iter().next().is_none());
        assert_eq!(v.allocated_pages(), 3);
        v.shrink_to_fit();
        assert_eq!(v.allocated_pages(), 0);
        v.resize(5, 7);
        assert_eq!(v.len(), 5);
        assert_eq!((v.first(), v.last()), (Some(&7), Some(&7)));
        assert_eq!(v.get(5), None);
    }

    #[test]
    fn equality_order_and_debug_ignore_page_size() {
        let a: PagedVec<u32, 2> = (0..5).collect();
        let b: PagedVec<u32, 3> = (0..5).collect();
        assert_eq!(a, b);
        assert!(a < (1..2).collect::<PagedVec<u32, 2>>());
        assert_eq!(alloc::format!("{a:?}"), "[0, 1, 2, 3, 4]");
        assert_eq!(a.clone(), a);
    }

    #[test]
    fn zero_sized_elements() {
        let mut v: PagedVec<(), 4> = PagedVec::new();
        v.resize(10, ());
        assert_eq!(v.len(), 10);
        v.insert(3, ());
        v.remove(0);
        assert_eq!(v.iter().count(), 10);
    }

    #[cfg(feature = "std")]
    #[test]
    fn retain_panic_keeps_unvisited_in_order() {
        extern crate std;
        let mut v: PagedVec<u32, 3> = (0..10).collect();
        let mut calls = 0;
        let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            v.retain(|&x| {
                calls += 1;
                assert!(calls != 6, "boom");
                x % 2 == 0
            })
        }));
        assert!(r.is_err());
        // 0..5 visited (1 and 3 rejected), 5 was being tested.
        assert!(v.iter().copied().eq([0, 2, 4, 5, 6, 7, 8, 9]));
    }

    #[cfg(feature = "serde")]
    #[test]
    fn serde_round_trip() {
        let v: PagedVec<u32, 3> = (0..8).collect();
        let json = serde_json::to_string(&v).unwrap();
        assert_eq!(json, "[0,1,2,3,4,5,6,7]");
        let back: PagedVec<u32, 3> = serde_json::from_str(&json).unwrap();
        assert_eq!(back, v);
    }
}