virtual-buffer 2.0.0

A cross-platform library for dealing with buffers backed by raw virtual memory
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
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
//! A concurrent, in-place growable vector.

use crate::{
    Allocation, SizedTypeProperties, align_up, assert_unsafe_precondition, page_size,
    vec::{
        GrowthStrategy, TryReserveError,
        TryReserveErrorKind::{AllocError, CapacityOverflow},
        capacity_overflow, handle_error,
    },
};
use core::{
    alloc::Layout,
    borrow::{Borrow, BorrowMut},
    cell::UnsafeCell,
    cmp, fmt,
    hash::{Hash, Hasher},
    iter::FusedIterator,
    marker::PhantomData,
    mem::{ManuallyDrop, MaybeUninit},
    ops::{Deref, DerefMut, Index, IndexMut},
    panic::RefUnwindSafe,
    ptr,
    slice::{self, SliceIndex},
    sync::atomic::{
        AtomicBool, AtomicUsize,
        Ordering::{Acquire, Relaxed, Release},
    },
};

pub mod raw;

/// Used to build a new vector.
///
/// This struct is created by the [`builder`] method on [`Vec`].
///
/// [`builder`]: Vec::builder
#[derive(Clone, Copy, Debug)]
pub struct VecBuilder {
    max_capacity: usize,
    capacity: usize,
    growth_strategy: GrowthStrategy,
}

impl VecBuilder {
    #[inline]
    const fn new(max_capacity: usize) -> Self {
        VecBuilder {
            max_capacity,
            capacity: 0,
            growth_strategy: GrowthStrategy::new(),
        }
    }

    /// The built `Vec` will have the minimum capacity required for `capacity` elements.
    ///
    /// The capacity can be greater due to the alignment to the [page size].
    ///
    /// [page size]: crate#pages
    #[inline]
    pub const fn capacity(&mut self, capacity: usize) -> &mut Self {
        self.capacity = capacity;

        self
    }

    /// The built `Vec` will have the given `growth_strategy`.
    ///
    /// # Panics
    ///
    /// Panics if `growth_strategy` isn't valid per the documentation of [`GrowthStrategy`].
    #[inline]
    #[track_caller]
    pub const fn growth_strategy(&mut self, growth_strategy: GrowthStrategy) -> &mut Self {
        growth_strategy.validate();

        self.growth_strategy = growth_strategy;

        self
    }

    /// Builds the `Vec`.
    ///
    /// # Panics
    ///
    /// - Panics if the `max_capacity` would exceed `isize::MAX` bytes.
    /// - Panics if the `capacity` is greater than the `max_capacity`.
    /// - Panics if [reserving] the allocation returns an error.
    ///
    /// [reserving]: crate#reserving
    #[must_use]
    #[track_caller]
    pub fn build<T>(&self) -> Vec<T> {
        match self.try_build() {
            Ok(vec) => vec,
            Err(err) => handle_error(err),
        }
    }

    /// Tries to build the `Vec`, returning an error when allocation fails.
    ///
    /// # Errors
    ///
    /// - Returns an error if the `max_capacity` would exceed `isize::MAX` bytes.
    /// - Returns an error if the `capacity` is greater than the `max_capacity`.
    /// - Returns an error if [reserving] the allocation returns an error.
    ///
    /// [reserving]: crate#reserving
    pub fn try_build<T>(&self) -> Result<Vec<T>, TryReserveError> {
        Ok(Vec {
            inner: RawVec {
                inner: unsafe {
                    RawVecInner::new(
                        self.max_capacity,
                        self.capacity,
                        self.growth_strategy,
                        Layout::new::<()>(),
                        size_of::<T>(),
                        align_of::<T>(),
                    )
                }?,
                marker: PhantomData,
            },
        })
    }
}

/// A concurrent, in-place growable vector.
///
/// This type behaves similarly to the standard library `Vec` except that it is guaranteed to never
/// reallocate, and as such can support concurrent reads while also supporting growth. The vector
/// grows similarly to the standard library vector, but instead of reallocating, it commits more
/// memory.
///
/// All operations are lock-free. In order to support this, each element consists of a `T` and an
/// `AtomicBool` used to denote whether the element has been initialized. That means that there is
/// a memory overhead equal to `align_of::<T>()`. You can avoid this overhead if you have a byte of
/// memory to spare in your `T` or by packing the bit into an existing atomic field in `T` by using
/// [`RawVec`].
///
/// If you don't specify a [growth strategy], exponential growth with a growth factor of 2 is used,
/// which is the same strategy that the standard library `Vec` uses.
pub struct Vec<T> {
    /// ```compile_fail,E0597
    /// let vec = virtual_buffer::concurrent::vec::Vec::<&'static str>::new(1);
    /// {
    ///     let s = "oh no".to_owned();
    ///     vec.push(&s);
    /// }
    /// dbg!(vec);
    /// ```
    inner: RawVec<Slot<T>>,
}

// SAFETY: `Vec` is an owned collection, which makes it safe to send to another thread as long as
// its element is safe to send to another a thread.
unsafe impl<T: Send> Send for Vec<T> {}

// SAFETY: `Vec` allows pushing through a shared reference, which allows a shared `Vec` to be used
// to send elements to another thread. Additionally, `Vec` allows getting a reference to any
// element from any thread. Therefore, it is safe to share `Vec` between threads as long as the
// element is both sendable and shareable.
unsafe impl<T: Send + Sync> Sync for Vec<T> {}

impl Vec<()> {
    /// Returns a builder for a new `Vec`.
    ///
    /// `max_capacity` is the maximum capacity the vector can ever have. The vector is guaranteed
    /// to never exceed this capacity. The capacity can be excessively huge, as none of the memory
    /// is [committed] until you push elements into the vector or reserve capacity.
    ///
    /// This function is implemented on `Vec<()>` so that you don't have to import the `VecBuilder`
    /// type too. The type parameter has no relation to the built `Vec`.
    ///
    /// [committed]: crate#committing
    #[inline]
    #[must_use]
    pub const fn builder(max_capacity: usize) -> VecBuilder {
        VecBuilder::new(max_capacity)
    }
}

impl<T> Vec<T> {
    /// Creates a new `Vec`.
    ///
    /// `max_capacity` is the maximum capacity the vector can ever have. The vector is guaranteed
    /// to never exceed this capacity. The capacity can be excessively huge, as none of the memory
    /// is [committed] until you push elements into the vector or reserve capacity.
    ///
    /// See the [`builder`] function for more creation options.
    ///
    /// # Panics
    ///
    /// - Panics if the `max_capacity` would exceed `isize::MAX` bytes.
    /// - Panics if [reserving] the allocation returns an error.
    ///
    /// [committed]: crate#committing
    /// [`builder`]: Self::builder
    /// [reserving]: crate#reserving
    #[must_use]
    #[track_caller]
    pub fn new(max_capacity: usize) -> Self {
        Vec {
            inner: unsafe { RawVec::new(max_capacity) },
        }
    }

    /// Creates a dangling `Vec`.
    ///
    /// This is useful as a placeholder value to defer allocation until later or if no allocation
    /// is needed.
    #[inline]
    #[must_use]
    pub const fn dangling() -> Self {
        Vec {
            inner: RawVec::dangling(),
        }
    }

    /// Returns the maximum capacity that was used when creating the `Vec`.
    #[inline]
    #[must_use]
    pub fn max_capacity(&self) -> usize {
        self.inner.max_capacity()
    }

    /// Returns the total number of elements the vector can hold without [committing] more memory.
    ///
    /// [committing]: crate#committing
    #[inline]
    #[must_use]
    pub fn capacity(&self) -> usize {
        self.inner.capacity()
    }

    /// Returns the number of elements in the vector.
    ///
    /// This number may exceed [`capacity`], doesn't correspond to the number of initialized
    /// elements, and also doesn't synchronize with setting the capacity.
    ///
    /// [`capacity`]: Self::capacity
    #[inline]
    #[must_use]
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// Returns `true` if the vector contains no elements.
    ///
    /// This counts elements that failed to be pushed due to an error.
    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Appends an element to the end of the vector. Returns the index of the inserted element.
    #[inline]
    #[track_caller]
    pub fn push(&self, value: T) -> usize {
        self.push_with(|_| value)
    }

    /// Appends an element to the end of the vector.
    ///
    /// `f` is called with the index of the element and the result is written to the element.
    /// Returns the index of the element.
    #[inline]
    #[track_caller]
    pub fn push_with(&self, f: impl FnOnce(usize) -> T) -> usize {
        let (index, slot) = self.inner.push();

        // SAFETY: `RawVec::push` guarantees that the slot is unique for each push.
        unsafe { &mut *slot.value.get() }.write(f(index));

        // SAFETY: We have written the element above.
        unsafe { slot.occupied.store(true, Release) };

        index
    }

    /// Appends an element to the end of the vector. Returns the index of the inserted element.
    #[inline]
    #[track_caller]
    pub fn push_mut(&mut self, value: T) -> usize {
        self.push_with_mut(|_| value)
    }

    /// Appends an element to the end of the vector.
    ///
    /// `f` is called with the index of the element and the result is written to the element.
    /// Returns the index of the element.
    #[inline]
    #[track_caller]
    pub fn push_with_mut(&mut self, f: impl FnOnce(usize) -> T) -> usize {
        let (index, slot) = self.inner.push_mut();

        slot.value.get_mut().write(f(index));

        // SAFETY: We have written the element above.
        unsafe { *slot.occupied.get_mut() = true };

        index
    }

    /// Returns a reference to an element of the vector.
    #[inline]
    #[must_use]
    pub fn get(&self, index: usize) -> Option<&T> {
        self.inner.as_capacity().get(index)?.value()
    }

    /// Returns a mutable reference to an element of the vector.
    #[inline]
    #[must_use]
    pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
        self.inner.as_mut_capacity().get_mut(index)?.value_mut()
    }

    /// Returns a reference to an element of the vector without doing any checks.
    ///
    /// # Safety
    ///
    /// `index` must have been previously acquired through [`push`] or [`push_mut`] on `self`.
    ///
    /// [`push`]: Self::push
    /// [`push_mut`]: Self::push_mut
    #[inline]
    #[must_use]
    pub unsafe fn get_unchecked(&self, index: usize) -> &T {
        // SAFETY: The caller must ensure that the index is in bounds.
        let slot = unsafe { self.inner.as_capacity().get_unchecked(index) };

        let occupied = slot.occupied.load(Acquire);

        assert_unsafe_precondition!(
            occupied,
            "`Vec::get_unchecked` requires that `index` refers to an initialized element",
        );

        // SAFETY: The caller must ensure that the slot has been initialized. The `Acquire`
        // ordering above synchronizes with the `Release` ordering in `push`, making sure that the
        // write is visible here.
        unsafe { slot.value_unchecked() }
    }

    /// Returns a mutable reference to an element of the vector without doing any checks.
    ///
    /// # Safety
    ///
    /// `index` must have been previously acquired through [`push`] or [`push_mut`] on `self`.
    ///
    /// [`push`]: Self::push
    /// [`push_mut`]: Self::push_mut
    #[inline]
    #[must_use]
    pub unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T {
        // SAFETY: The caller must ensure that the index is in bounds.
        let slot = unsafe { self.inner.as_mut_capacity().get_unchecked_mut(index) };

        assert_unsafe_precondition!(
            *slot.occupied.get_mut(),
            "`Vec::get_unchecked` requires that `index` refers to an initialized element",
        );

        // SAFETY: The caller must ensure that the slot has been initialized.
        unsafe { slot.value_unchecked_mut() }
    }

    /// Returns an iterator that yields references to elements of the vector.
    #[inline]
    pub fn iter(&self) -> Iter<'_, T> {
        Iter::new(self)
    }

    /// Returns an iterator that yields mutable references to elements of the vector.
    #[inline]
    pub fn iter_mut(&mut self) -> IterMut<'_, T> {
        IterMut {
            inner: self.inner.iter_mut(),
        }
    }

    /// Reserves capacity for at least `additional` more elements.
    ///
    /// Not to be confused with [reserving virtual memory]; this method is named so as to match the
    /// standard library vector.
    ///
    /// The new capacity is at least `self.len() + additional`. If this capacity is below the one
    /// calculated using the [growth strategy], the latter is used. Does nothing if the capacity is
    /// already sufficient.
    ///
    /// # Panics
    ///
    /// - Panics if `self.len() + additional` would exceed `self.max_capacity()`.
    /// - Panics if [committing] the new capacity fails.
    ///
    /// [reserving virtual memory]: crate#reserving
    /// [growth strategy]: GrowthStrategy
    /// [committing]: crate#committing
    #[track_caller]
    pub fn reserve(&self, additional: usize) {
        self.inner.reserve(additional);
    }

    /// Reserves the minimum capacity required for `additional` more elements.
    ///
    /// Not to be confused with [reserving virtual memory]; this method is named so as to match the
    /// standard library vector.
    ///
    /// The new capacity is at least `self.len() + additional`. The [growth strategy] is ignored,
    /// but the new capacity can still be greater due to the alignment to the [page size]. Does
    /// nothing if the capacity is already sufficient.
    ///
    /// # Panics
    ///
    /// - Panics if `self.len() + additional` would exceed `self.max_capacity()`.
    /// - Panics if [committing] the new capacity fails.
    ///
    /// [reserving virtual memory]: crate#reserving
    /// [growth strategy]: GrowthStrategy
    /// [page size]: crate#pages
    /// [committing]: crate#committing
    #[track_caller]
    pub fn reserve_exact(&self, additional: usize) {
        self.inner.reserve_exact(additional);
    }

    /// Tries to reserve capacity for at least `additional` more elements, returning an error on
    /// failure.
    ///
    /// Not to be confused with [reserving virtual memory]; this method is named so as to match the
    /// standard library vector.
    ///
    /// The new capacity is at least `self.len() + additional`. If this capacity is below the one
    /// calculated using the [growth strategy], the latter is used. Does nothing if the capacity is
    /// already sufficient.
    ///
    /// # Errors
    ///
    /// - Returns an error if `self.len() + additional` would exceed `self.max_capacity()`.
    /// - Returns an error if [committing] the new capacity fails.
    ///
    /// [reserving virtual memory]: crate#reserving
    /// [growth strategy]: GrowthStrategy
    /// [committing]: crate#committing
    pub fn try_reserve(&self, additional: usize) -> Result<(), TryReserveError> {
        self.inner.try_reserve(additional)
    }

    /// Tries to reserve the minimum capacity required for `additional` more elements, returning an
    /// error on failure.
    ///
    /// Not to be confused with [reserving virtual memory]; this method is named so as to match the
    /// standard library vector.
    ///
    /// The new capacity is at least `self.len() + additional`. The [growth strategy] is ignored,
    /// but the new capacity can still be greater due to the alignment to the [page size]. Does
    /// nothing if the capacity is already sufficient.
    ///
    /// # Errors
    ///
    /// - Returns an error if `self.len() + additional` would exceed `self.max_capacity()`.
    /// - Returns an error if [committing] the new capacity fails.
    ///
    /// [reserving virtual memory]: crate#reserving
    /// [growth strategy]: GrowthStrategy
    /// [page size]: crate#pages
    /// [committing]: crate#committing
    pub fn try_reserve_exact(&self, additional: usize) -> Result<(), TryReserveError> {
        self.inner.try_reserve_exact(additional)
    }
}

impl<T> AsRef<Vec<T>> for Vec<T> {
    #[inline]
    fn as_ref(&self) -> &Vec<T> {
        self
    }
}

impl<T> AsMut<Vec<T>> for Vec<T> {
    #[inline]
    fn as_mut(&mut self) -> &mut Vec<T> {
        self
    }
}

impl<T: fmt::Debug> fmt::Debug for Vec<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&self.inner, f)
    }
}

impl<T: PartialEq<U>, U> PartialEq<Vec<U>> for Vec<T> {
    #[inline]
    fn eq(&self, other: &Vec<U>) -> bool {
        self.inner == other.inner
    }
}

impl<T: PartialEq<U>, U> PartialEq<&[U]> for Vec<T> {
    #[inline]
    fn eq(&self, other: &&[U]) -> bool {
        *self == **other
    }
}

impl<T: PartialEq<U>, U> PartialEq<&mut [U]> for Vec<T> {
    #[inline]
    fn eq(&self, other: &&mut [U]) -> bool {
        *self == **other
    }
}

impl<T: PartialEq<U>, U> PartialEq<Vec<U>> for &[T] {
    #[inline]
    fn eq(&self, other: &Vec<U>) -> bool {
        **self == *other
    }
}

impl<T: PartialEq<U>, U> PartialEq<Vec<U>> for &mut [T] {
    #[inline]
    fn eq(&self, other: &Vec<U>) -> bool {
        **self == *other
    }
}

impl<T: PartialEq<U>, U> PartialEq<[U]> for Vec<T> {
    #[inline]
    fn eq(&self, other: &[U]) -> bool {
        let len = self.len();

        if len != other.len() {
            return false;
        }

        #[allow(clippy::needless_range_loop)]
        for index in 0..len {
            let Some(elem) = self.get(index) else {
                return false;
            };

            if *elem != other[index] {
                return false;
            }
        }

        true
    }
}

impl<T: PartialEq<U>, U> PartialEq<Vec<U>> for [T] {
    #[inline]
    fn eq(&self, other: &Vec<U>) -> bool {
        let len = other.len();

        if len != self.len() {
            return false;
        }

        #[allow(clippy::needless_range_loop)]
        for index in 0..len {
            let Some(elem) = other.get(index) else {
                return false;
            };

            if self[index] != *elem {
                return false;
            }
        }

        true
    }
}

#[cfg(feature = "alloc")]
impl<T: PartialEq<U> + Clone, U> PartialEq<Vec<U>> for alloc::borrow::Cow<'_, [T]> {
    #[inline]
    fn eq(&self, other: &Vec<U>) -> bool {
        **self == *other
    }
}

impl<T: PartialEq<U>, U, const N: usize> PartialEq<[U; N]> for Vec<T> {
    #[inline]
    fn eq(&self, other: &[U; N]) -> bool {
        *self == *other.as_slice()
    }
}

impl<T: PartialEq<U>, U, const N: usize> PartialEq<&[U; N]> for Vec<T> {
    #[inline]
    fn eq(&self, other: &&[U; N]) -> bool {
        *self == *other.as_slice()
    }
}

impl<T: Eq> Eq for Vec<T> {}

impl<T> Extend<T> for Vec<T> {
    #[inline]
    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
        for elem in iter {
            self.push_mut(elem);
        }
    }
}

impl<'a, T: Copy> Extend<&'a T> for Vec<T> {
    #[inline]
    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
        for &elem in iter {
            self.push_mut(elem);
        }
    }
}

impl<T: Hash> Hash for Vec<T> {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        Hash::hash(&*self.inner, state);
    }
}

impl<T> Index<usize> for Vec<T> {
    type Output = T;

    #[inline]
    #[track_caller]
    fn index(&self, index: usize) -> &Self::Output {
        if let Some(value) = self.get(index) {
            value
        } else {
            invalid_index(index)
        }
    }
}

impl<T> IndexMut<usize> for Vec<T> {
    #[inline]
    #[track_caller]
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        if let Some(value) = self.get_mut(index) {
            value
        } else {
            invalid_index(index)
        }
    }
}

#[cold]
#[inline(never)]
#[track_caller]
fn invalid_index(index: usize) -> ! {
    panic!("index {index} is out of bounds or not yet initialized");
}

impl<'a, T> IntoIterator for &'a Vec<T> {
    type Item = &'a T;

    type IntoIter = Iter<'a, T>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a, T> IntoIterator for &'a mut Vec<T> {
    type Item = &'a mut T;

    type IntoIter = IterMut<'a, T>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.iter_mut()
    }
}

impl<T> IntoIterator for Vec<T> {
    type Item = T;

    type IntoIter = IntoIter<T>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        IntoIter::new(self)
    }
}

impl<T: PartialOrd> PartialOrd for Vec<T> {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
        PartialOrd::partial_cmp(&self.inner, &other.inner)
    }
}

impl<T: Ord> Ord for Vec<T> {
    #[inline]
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        Ord::cmp(&self.inner, &other.inner)
    }
}

struct Slot<T> {
    occupied: AtomicBool,
    value: UnsafeCell<MaybeUninit<T>>,
}

// While `Slot` does contain interior mutability, this is never exposed to the user and no
// invariants can be broken.
impl<T: RefUnwindSafe> RefUnwindSafe for Slot<T> {}

impl<T> Slot<T> {
    #[inline(always)]
    fn value(&self) -> Option<&T> {
        if self.occupied.load(Acquire) {
            // SAFETY: We checked that the slot has been initialized above. The `Acquire` ordering
            // above synchronizes with the `Release` ordering in `push`, making sure that the write
            // is visible here.
            Some(unsafe { self.value_unchecked() })
        } else {
            None
        }
    }

    #[inline(always)]
    fn value_mut(&mut self) -> Option<&mut T> {
        if *self.occupied.get_mut() {
            // SAFETY: We checked that the slot has been initialized above.
            Some(unsafe { self.value_unchecked_mut() })
        } else {
            None
        }
    }

    #[inline(always)]
    unsafe fn value_unchecked(&self) -> &T {
        // SAFETY: The caller must ensure that access to the cell's inner value is synchronized.
        let value = unsafe { &*self.value.get() };

        // SAFETY: The caller must ensure that the slot has been initialized.
        unsafe { value.assume_init_ref() }
    }

    #[inline(always)]
    unsafe fn value_unchecked_mut(&mut self) -> &mut T {
        // SAFETY: The caller must ensure that the slot has been initialized.
        unsafe { self.value.get_mut().assume_init_mut() }
    }
}

impl<T: Clone> Clone for Slot<T> {
    #[inline]
    fn clone(&self) -> Self {
        let value = self.value();

        Slot {
            occupied: AtomicBool::new(value.is_some()),
            value: UnsafeCell::new(if let Some(value) = value {
                MaybeUninit::new(value.clone())
            } else {
                MaybeUninit::uninit()
            }),
        }
    }
}

impl<T: fmt::Debug> fmt::Debug for Slot<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&self.value(), f)
    }
}

impl<T> Drop for Slot<T> {
    fn drop(&mut self) {
        if *self.occupied.get_mut() {
            // SAFETY: We checked that the slot has been initialized above. We own the value, and
            // the slot is being dropped, which ensures that the value can't be accessed again.
            unsafe { self.value.get_mut().assume_init_drop() };
        }
    }
}

impl<T: PartialEq<U>, U> PartialEq<Slot<U>> for Slot<T> {
    #[allow(clippy::match_same_arms)]
    #[inline]
    fn eq(&self, other: &Slot<U>) -> bool {
        match (self.value(), other.value()) {
            (Some(value), Some(other_value)) => *value == *other_value,
            (Some(_), None) => false,
            (None, Some(_)) => false,
            (None, None) => true,
        }
    }
}

impl<T: Eq> Eq for Slot<T> {}

impl<T: Hash> Hash for Slot<T> {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.value().hash(state);
    }
}

impl<T: PartialOrd> PartialOrd for Slot<T> {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
        PartialOrd::partial_cmp(&self.value(), &other.value())
    }
}

impl<T: Ord> Ord for Slot<T> {
    #[inline]
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        Ord::cmp(&self.value(), &other.value())
    }
}

/// An iterator that yields references to elements of a vector.
///
/// This struct is created by the [`iter`] method on [`Vec`].
///
/// [`iter`]: Vec::iter
pub struct Iter<'a, T> {
    start: *const (),
    end: *const (),
    marker: PhantomData<&'a T>,
}

// SAFETY: `Iter<'a, T>` is equivalent to `&'a [T]`.
unsafe impl<T: Sync> Send for Iter<'_, T> {}

// SAFETY: `Iter<'a, T>` is equivalent to `&'a [T]`.
unsafe impl<T: Sync> Sync for Iter<'_, T> {}

impl<T> Iter<'_, T> {
    #[inline]
    fn new(vec: &Vec<T>) -> Self {
        let start = vec.inner.as_ptr();

        let len = cmp::min(vec.len(), vec.capacity());

        // SAFETY: The `Acquire` ordering in `RawVec::capacity` synchronizes with the `Release`
        // ordering when setting the capacity, making sure that the newly committed memory is
        // visible here.
        let end = unsafe { start.add(len) };

        Iter {
            start: start.cast(),
            end: end.cast(),
            marker: PhantomData,
        }
    }

    #[inline]
    fn start(&self) -> *const Slot<T> {
        self.start.cast()
    }

    #[inline]
    fn end(&self) -> *const Slot<T> {
        self.end.cast()
    }

    #[inline]
    fn len(&self) -> usize {
        // SAFETY:
        // - By our invariant, `self.end` is always greater than or equal to `self.start`.
        // - `start` and `end` were both created from the same object in `Iter::new`.
        // - `Vec::new` ensures that the allocation size doesn't exceed `isize::MAX` bytes.
        // - We know that the allocation doesn't wrap around the address space.
        unsafe { self.end().offset_from_unsigned(self.start()) }
    }

    fn as_slice(&self) -> &[Slot<T>] {
        unsafe { slice::from_raw_parts(self.start(), self.len()) }
    }
}

impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        struct Elements<'a, T>(&'a [Slot<T>]);

        impl<T: fmt::Debug> fmt::Debug for Elements<'_, T> {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.debug_list()
                    .entries(self.0.iter().filter_map(Slot::value))
                    .finish()
            }
        }

        f.debug_tuple("Iter")
            .field(&Elements(self.as_slice()))
            .finish()
    }
}

impl<'a, T> Iterator for Iter<'a, T> {
    type Item = &'a T;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if self.start == self.end {
                break None;
            }

            let start = self.start();

            // SAFETY: We checked that there are still elements remaining above.
            self.start = unsafe { start.add(1) }.cast();

            // SAFETY: Same as the previous.
            let slot = unsafe { &*start };

            if let Some(value) = slot.value() {
                break Some(value);
            }
        }
    }

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

impl<T> DoubleEndedIterator for Iter<'_, T> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        loop {
            if self.start == self.end {
                break None;
            }

            // SAFETY: We checked that there are still elements remaining above.
            let end = unsafe { self.end().sub(1) };

            self.end = end.cast();

            // SAFETY: Same as the previous.
            let slot = unsafe { &*end };

            if let Some(value) = slot.value() {
                break Some(value);
            }
        }
    }
}

impl<T> FusedIterator for Iter<'_, T> {}

/// An iterator that yields mutable references to elements of a vector.
///
/// This struct is created by the [`iter_mut`] method on [`Vec`].
///
/// [`iter_mut`]: Vec::iter_mut
pub struct IterMut<'a, T> {
    inner: slice::IterMut<'a, Slot<T>>,
}

impl<'a, T> Iterator for IterMut<'a, T> {
    type Item = &'a mut T;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        loop {
            let slot = self.inner.next()?;

            if let Some(value) = slot.value_mut() {
                break Some(value);
            }
        }
    }

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

impl<T> DoubleEndedIterator for IterMut<'_, T> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        loop {
            let slot = self.inner.next_back()?;

            if let Some(value) = slot.value_mut() {
                break Some(value);
            }
        }
    }
}

impl<T> FusedIterator for IterMut<'_, T> {}

/// An iterator that moves out of a vector.
///
/// This struct is created by the [`into_iter`] method on [`Vec`].
///
/// [`into_iter`]: Vec::into_iter
pub struct IntoIter<T> {
    start: *mut (),
    end: *mut (),
    #[allow(dead_code)]
    allocation: Allocation,
    marker: PhantomData<T>,
}

// SAFETY: We own the collection, and synchronization to it is ensured using mutable references.
unsafe impl<T: Send> Send for IntoIter<T> {}

// SAFETY: We own the collection, and synchronization to it is ensured using mutable references.
unsafe impl<T: Sync> Sync for IntoIter<T> {}

impl<T> IntoIter<T> {
    #[inline]
    pub(super) fn new(vec: Vec<T>) -> Self {
        let mut vec = ManuallyDrop::new(vec.inner);

        // SAFETY: `vec` is wrapped in a `ManuallyDrop` such that a double-free can't happen even
        // if a panic was possible below.
        let allocation = unsafe { ptr::read(&vec.inner.allocation) };

        let start = vec.as_mut_ptr();

        let len = cmp::min(vec.len_mut(), vec.capacity_mut());

        // SAFETY: The ownership synchronizes with setting the capacity, making sure that the newly
        // committed memory is visible here.
        let end = unsafe { start.add(len) };

        IntoIter {
            start: start.cast(),
            end: end.cast(),
            allocation,
            marker: PhantomData,
        }
    }

    #[inline]
    fn start(&self) -> *mut Slot<T> {
        self.start.cast()
    }

    #[inline]
    fn end(&self) -> *mut Slot<T> {
        self.end.cast()
    }

    #[inline]
    fn len(&self) -> usize {
        // SAFETY:
        // - By our invariant, `self.end` is always greater than or equal to `self.start`.
        // - `start` and `end` were both created from the same object in `IntoIter::new`.
        // - `Vec::new` ensures that the allocation size doesn't exceed `isize::MAX` bytes.
        // - We know that the allocation doesn't wrap around the address space.
        unsafe { self.end().offset_from_unsigned(self.start()) }
    }

    fn as_slice(&self) -> &[Slot<T>] {
        unsafe { slice::from_raw_parts(self.start(), self.len()) }
    }
}

impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        struct Elements<'a, T>(&'a [Slot<T>]);

        impl<T: fmt::Debug> fmt::Debug for Elements<'_, T> {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.debug_list()
                    .entries(self.0.iter().filter_map(Slot::value))
                    .finish()
            }
        }

        f.debug_tuple("IntoIter")
            .field(&Elements(self.as_slice()))
            .finish()
    }
}

impl<T> Drop for IntoIter<T> {
    fn drop(&mut self) {
        let elements = ptr::slice_from_raw_parts_mut(self.start(), self.len());

        // SAFETY: We own the collection, and it is being dropped, which ensures that the elements
        // can't be accessed again.
        unsafe { elements.drop_in_place() };
    }
}

impl<T> Iterator for IntoIter<T> {
    type Item = T;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if self.start == self.end {
                break None;
            }

            let start = self.start();

            // SAFETY: We checked that there are still elements remaining above.
            self.start = unsafe { start.add(1) }.cast();

            // SAFETY: Same as the previous.
            let slot = unsafe { &*start };

            if let Some(value) = slot.value() {
                // SAFETY: We own the collection, and have just decremented the `end` pointer such
                // that this element can't be accessed again.
                break Some(unsafe { ptr::read(value) });
            }
        }
    }

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

impl<T> DoubleEndedIterator for IntoIter<T> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        loop {
            if self.start == self.end {
                break None;
            }

            // SAFETY: We checked that there are still elements remaining above.
            let end = unsafe { self.end().sub(1) };

            self.end = end.cast();

            // SAFETY: Same as the previous.
            let slot = unsafe { &*end };

            if let Some(value) = slot.value() {
                // SAFETY: We own the collection, and have just decremented the `end` pointer such
                // that this element can't be accessed again.
                break Some(unsafe { ptr::read(value) });
            }
        }
    }
}

impl<T> FusedIterator for IntoIter<T> {}

/// A low-level, concurrent, in-place growable vector.
///
/// This is meant to be a low-level primitive used to implement data structures such as the
/// concurrent [`Vec`]. Unlike the concurrent `Vec`, this type stores `T`s directly, and as such
/// doesn't have any memory overhead and derefs to `[T]`. Methods such as [`Vec::get`] are not
/// provided because you should use the slice equivalent. This added flexibility comes at the cost
/// of a bit of unsafety: constructing a `RawVec<T>`, you must ensure that `T` is zeroable, and
/// pushing and accessing elements requires you to handle initialization of the element yourself.
///
/// If you don't specify a [growth strategy], exponential growth with a growth factor of 2 is used,
/// which is the same strategy that the standard library `Vec` uses.
pub struct RawVec<T> {
    inner: RawVecInner,
    marker: PhantomData<T>,
}

struct RawVecInner {
    elements: *mut (),
    capacity: AtomicUsize,
    len: AtomicUsize,
    max_capacity: usize,
    growth_strategy: GrowthStrategy,
    allocation: Allocation,
}

impl RawVec<()> {
    /// Returns a builder for a new `RawVec`.
    ///
    /// `max_capacity` is the maximum capacity the vector can ever have. The vector is guaranteed
    /// to never exceed this capacity. The capacity can be excessively huge, as none of the memory
    /// is [committed] until you push elements into the vector or reserve capacity.
    ///
    /// This function is implemented on `RawVec<()>` so that you don't have to import the
    /// `VecBuilder` type too. The type parameter has no relation to the built `RawVec`.
    ///
    /// [committed]: crate#committing
    #[inline]
    #[must_use]
    pub const fn builder(max_capacity: usize) -> raw::VecBuilder {
        raw::VecBuilder::new(max_capacity)
    }
}

impl<T> RawVec<T> {
    /// Creates a new `RawVec`.
    ///
    /// `max_capacity` is the maximum capacity the vector can ever have. The vector is guaranteed
    /// to never exceed this capacity. The capacity can be excessively huge, as none of the memory
    /// is [committed] until you push elements into the vector or reserve capacity.
    ///
    /// See the [`builder`] function more more creation options.
    ///
    /// # Safety
    ///
    /// `T` must be zeroable.
    ///
    /// # Panics
    ///
    /// - Panics if the `max_capacity` would exceed `isize::MAX` bytes.
    /// - Panics if [reserving] the allocation returns an error.
    ///
    /// [committed]: crate#committing
    /// [`builder`]: Self::builder
    /// [reserving]: crate#reserving
    #[must_use]
    #[track_caller]
    pub unsafe fn new(max_capacity: usize) -> Self {
        unsafe { RawVec::builder(max_capacity).build() }
    }

    /// Creates a dangling `RawVec`.
    ///
    /// This is useful as a placeholder value to defer allocation until later or if no allocation
    /// is needed.
    #[inline]
    #[must_use]
    pub const fn dangling() -> Self {
        RawVec {
            inner: RawVecInner::dangling(align_of::<T>()),
            marker: PhantomData,
        }
    }

    /// Returns a slice of the entire vector.
    ///
    /// This returns a slice with a length equal to the vector's capacity.
    #[inline]
    #[must_use]
    pub fn as_capacity(&self) -> &[T] {
        // SAFETY: The `Acquire` ordering in `RawVec::capacity` synchronizes with the `Release`
        // ordering when setting the capacity, making sure that the newly committed memory is
        // visible here. The constructor of `RawVec` must ensure that `T` is zeroable.
        unsafe { slice::from_raw_parts(self.as_ptr(), self.capacity()) }
    }

    /// Returns a mutable slice of the entire vector.
    ///
    /// This returns a slice with a length equal to the vector's capacity.
    #[inline]
    #[must_use]
    pub fn as_mut_capacity(&mut self) -> &mut [T] {
        // SAFETY: The mutable reference synchronizes with setting the capacity, making sure that
        // the newly committed memory is visible here. The constructor of `RawVec` must ensure that
        // `T` is zeroable.
        unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.capacity_mut()) }
    }

    /// Returns a slice of the entire vector.
    ///
    /// This returns a slice with a length equal to the minimum of the vector's length and its
    /// capacity. As such, it is slightly less efficient than [`as_capacity`].
    ///
    /// This does the same thing as [`RawVec::deref`].
    ///
    /// [`as_capacity`]: Self::as_capacity
    #[inline]
    #[must_use]
    pub fn as_slice(&self) -> &[T] {
        let len = cmp::min(self.len(), self.capacity());

        // SAFETY: The `Acquire` ordering in `RawVec::capacity` synchronizes with the `Release`
        // ordering when setting the capacity, making sure that the newly committed memory is
        // visible here. The constructor of `RawVec` must ensure that `T` is zeroable.
        unsafe { slice::from_raw_parts(self.as_ptr(), len) }
    }

    /// Returns a mutable slice of the entire vector.
    ///
    /// This returns a slice with a length equal to the minimum of the vector's length and its
    /// capacity. As such, it is slightly less efficient than [`as_mut_capacity`].
    ///
    /// This does the same thing as [`RawVec::deref_mut`].
    ///
    /// [`as_mut_capacity`]: Self::as_mut_capacity
    #[inline]
    #[must_use]
    pub fn as_mut_slice(&mut self) -> &mut [T] {
        let len = cmp::min(self.len_mut(), self.capacity_mut());

        // SAFETY: The mutable reference synchronizes with setting the capacity, making sure that
        // the newly committed memory is visible here. The constructor of `RawVec` must ensure that
        // `T` is zeroable.
        unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), len) }
    }

    /// Returns a pointer to the vector's buffer.
    ///
    /// This method is guaranteed to never materialize a reference to the underlying data. This,
    /// coupled with the fact that the vector never reallocates, means that the returned pointer
    /// stays valid until the vector is dropped.
    #[inline]
    #[must_use]
    pub fn as_ptr(&self) -> *const T {
        self.inner.elements.cast()
    }

    /// Returns a mutable pointer to the vector's buffer.
    ///
    /// This method is guaranteed to never materialize a reference to the underlying data. This,
    /// coupled with the fact that the vector never reallocates, means that the returned pointer
    /// stays valid until the vector is dropped.
    #[inline]
    #[must_use]
    pub fn as_mut_ptr(&mut self) -> *mut T {
        self.inner.elements.cast()
    }

    /// Returns the maximum capacity that was used when creating the `RawVec`.
    #[inline]
    #[must_use]
    pub fn max_capacity(&self) -> usize {
        self.inner.max_capacity
    }

    /// Returns the total number of elements the vector can hold without [committing] more memory.
    ///
    /// [committing]: crate#committing
    #[inline]
    #[must_use]
    pub fn capacity(&self) -> usize {
        self.inner.capacity.load(Acquire)
    }

    #[inline]
    fn capacity_mut(&mut self) -> usize {
        *self.inner.capacity.get_mut()
    }

    /// Returns the number of elements in the vector.
    ///
    /// This number may exceed [`capacity`]. It also doesn't synchronize with setting the capacity.
    /// As such, this must not be used in conjunction with [`as_ptr`] to unsafely access any
    /// element unless you compared the length to the capacity.
    ///
    /// [`capacity`]: Self::capacity
    /// [`as_ptr`]: Self::as_ptr
    #[inline]
    #[must_use]
    pub fn len(&self) -> usize {
        self.inner.len.load(Relaxed)
    }

    #[inline]
    fn len_mut(&mut self) -> usize {
        *self.inner.len.get_mut()
    }

    /// Returns `true` if the vector contains no elements.
    ///
    /// This counts elements that failed to be pushed due to an error.
    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Appends an element to the end of the vector.
    ///
    /// Returns the index of the inserted element as well as the element itself. The element is
    /// zeroed; you must initialize it yourself.
    #[inline]
    #[track_caller]
    pub fn push(&self) -> (usize, &T) {
        if T::IS_ZST {
            let mut len = self.inner.len.load(Relaxed);

            loop {
                if len == self.inner.max_capacity {
                    capacity_overflow();
                }

                match self
                    .inner
                    .len
                    .compare_exchange(len, len + 1, Relaxed, Relaxed)
                {
                    Ok(_) => {
                        // SAFETY: `T` is a ZST, which means that all elements live at the same
                        // address. The constructor of `RawVec` must ensure that `T` is zeroable.
                        let slot = unsafe { &*self.as_ptr() };

                        break (len, slot);
                    }
                    Err(new_len) => len = new_len,
                }
            }
        } else {
            // This cannot overflow because `self.inner.max_capacity` can never exceed `isize::MAX`
            // bytes, and because `RawVec::grow_one` decrements the length back if the length
            // overshot `self.inner.max_capacity`.
            let len = self.inner.len.fetch_add(1, Relaxed);

            if len >= self.inner.capacity.load(Acquire) {
                unsafe { self.grow_one(len) };
            }

            // SAFETY: We made sure that the index is in bounds above. The `Acquire` ordering above
            // synchronizes with the `Release` ordering when setting the capacity, making sure that
            // the newly committed memory is visible here. The constructor of `RawVec` must ensure
            // that `T` is zeroable.
            let slot = unsafe { &*self.as_ptr().add(len) };

            (len, slot)
        }
    }

    #[cold]
    #[inline(never)]
    #[track_caller]
    unsafe fn grow_one(&self, len: usize) {
        unsafe { self.inner.grow_one(len, size_of::<T>()) }
    }

    /// Appends an element to the end of the vector.
    ///
    /// Returns the index of the inserted element as well as the element itself. The element is
    /// zeroed; you must initialize it yourself.
    #[inline]
    #[track_caller]
    pub fn push_mut(&mut self) -> (usize, &mut T) {
        let len = self.len_mut();

        if len >= self.capacity_mut() {
            unsafe { self.grow_one_mut() };
        }

        *self.inner.len.get_mut() = len + 1;

        // SAFETY: We made sure the index is in bounds above. The mutable reference synchronizes
        // with setting the capacity, making sure that the newly committed memory is visible here.
        // The constructor of `RawVec` must ensure that `T` is zeroable.
        let slot = unsafe { &mut *self.as_mut_ptr().add(len) };

        (len, slot)
    }

    #[cold]
    #[inline(never)]
    #[track_caller]
    unsafe fn grow_one_mut(&mut self) {
        unsafe { self.inner.grow_one_mut(size_of::<T>()) }
    }

    /// Reserves capacity for at least `additional` more elements.
    ///
    /// Not to be confused with [reserving virtual memory]; this method is named so as to match the
    /// standard library vector.
    ///
    /// The new capacity is at least `self.len() + additional`. If this capacity is below the one
    /// calculated using the [growth strategy], the latter is used. Does nothing if the capacity is
    /// already sufficient.
    ///
    /// # Panics
    ///
    /// - Panics if `self.len() + additional` would exceed `self.max_capacity()`.
    /// - Panics if [committing] the new capacity fails.
    ///
    /// [reserving virtual memory]: crate#reserving
    /// [growth strategy]: GrowthStrategy
    /// [committing]: crate#committing
    #[track_caller]
    pub fn reserve(&self, additional: usize) {
        unsafe { self.inner.reserve(additional, size_of::<T>()) };
    }

    /// Reserves the minimum capacity required for `additional` more elements.
    ///
    /// Not to be confused with [reserving virtual memory]; this method is named so as to match the
    /// standard library vector.
    ///
    /// The new capacity is at least `self.len() + additional`. The [growth strategy] is ignored,
    /// but the new capacity can still be greater due to the alignment to the [page size]. Does
    /// nothing if the capacity is already sufficient.
    ///
    /// # Panics
    ///
    /// - Panics if `self.len() + additional` would exceed `self.max_capacity()`.
    /// - Panics if [committing] the new capacity fails.
    ///
    /// [reserving virtual memory]: crate#reserving
    /// [growth strategy]: GrowthStrategy
    /// [page size]: crate#pages
    /// [committing]: crate#committing
    #[track_caller]
    pub fn reserve_exact(&self, additional: usize) {
        unsafe { self.inner.reserve_exact(additional, size_of::<T>()) };
    }

    /// Tries to reserve capacity for at least `additional` more elements, returning an error on
    /// failure.
    ///
    /// Not to be confused with [reserving virtual memory]; this method is named so as to match the
    /// standard library vector.
    ///
    /// The new capacity is at least `self.len() + additional`. If this capacity is below the one
    /// calculated using the [growth strategy], the latter is used. Does nothing if the capacity is
    /// already sufficient.
    ///
    /// # Errors
    ///
    /// - Returns an error if `self.len() + additional` would exceed `self.max_capacity()`.
    /// - Returns an error if [committing] the new capacity fails.
    ///
    /// [reserving virtual memory]: crate#reserving
    /// [growth strategy]: GrowthStrategy
    /// [committing]: crate#committing
    pub fn try_reserve(&self, additional: usize) -> Result<(), TryReserveError> {
        unsafe { self.inner.try_reserve(additional, size_of::<T>()) }
    }

    /// Tries to reserve the minimum capacity required for `additional` more elements, returning an
    /// error on failure.
    ///
    /// Not to be confused with [reserving virtual memory]; this method is named so as to match the
    /// standard library vector.
    ///
    /// The new capacity is at least `self.len() + additional`. The [growth strategy] is ignored,
    /// but the new capacity can still be greater due to the alignment to the [page size]. Does
    /// nothing if the capacity is already sufficient.
    ///
    /// # Errors
    ///
    /// - Returns an error if `self.len() + additional` would exceed `self.max_capacity()`.
    /// - Returns an error if [committing] the new capacity fails.
    ///
    /// [reserving virtual memory]: crate#reserving
    /// [growth strategy]: GrowthStrategy
    /// [page size]: crate#pages
    /// [committing]: crate#committing
    pub fn try_reserve_exact(&self, additional: usize) -> Result<(), TryReserveError> {
        unsafe { self.inner.try_reserve_exact(additional, size_of::<T>()) }
    }
}

impl RawVecInner {
    unsafe fn new(
        max_capacity: usize,
        capacity: usize,
        growth_strategy: GrowthStrategy,
        header_layout: Layout,
        elem_size: usize,
        elem_align: usize,
    ) -> Result<Self, TryReserveError> {
        let size = max_capacity
            .checked_mul(elem_size)
            .ok_or(CapacityOverflow)?;

        #[allow(clippy::cast_possible_wrap)]
        if size > isize::MAX as usize || capacity > max_capacity {
            return Err(CapacityOverflow.into());
        }

        if size == 0 && header_layout.size() == 0 {
            let allocation = Allocation::dangling(elem_align);

            return Ok(RawVecInner {
                elements: allocation.ptr().cast(),
                capacity: AtomicUsize::new(max_capacity),
                len: AtomicUsize::new(0),
                max_capacity,
                growth_strategy,
                allocation,
            });
        }

        // This can't overflow because `Layout`'s size can't exceed `isize::MAX`.
        let elements_offset = align_up(header_layout.size(), elem_align);

        // This can't overflow because `elements_offset` can be at most `1 << 63` and `size` can be
        // at most `isize::MAX`, totaling `usize::MAX`.
        let size = elements_offset + size;

        let page_size = page_size();
        let size = align_up(size, page_size);

        if size == 0 {
            return Err(CapacityOverflow.into());
        }

        let align = cmp::max(header_layout.align(), elem_align);

        // The minimum additional size required to fulfill the alignment requirement of the header
        // and element. The virtual memory allocation is only guaranteed to be aligned to the page
        // size, so if the alignment is greater than the page size, we must pad the allocation.
        let align_size = cmp::max(align, page_size) - page_size;

        let size = align_size.checked_add(size).ok_or(CapacityOverflow)?;

        let allocation = Allocation::new(size).map_err(AllocError)?;
        let aligned_ptr = allocation.ptr().map_addr(|addr| align_up(addr, align));

        // This can't overflow because the size is already allocated.
        let initial_size = align_up(elements_offset + capacity * elem_size, page_size);

        if initial_size != 0 {
            allocation
                .commit(aligned_ptr, initial_size)
                .map_err(AllocError)?;
        }

        let elements = aligned_ptr.wrapping_add(elements_offset).cast();

        let capacity = if elem_size == 0 {
            max_capacity
        } else {
            (initial_size - elements_offset) / elem_size
        };

        Ok(RawVecInner {
            elements,
            capacity: AtomicUsize::new(capacity),
            len: AtomicUsize::new(0),
            max_capacity,
            growth_strategy,
            allocation,
        })
    }

    #[inline]
    const fn dangling(elem_align: usize) -> Self {
        let allocation = Allocation::dangling(elem_align);

        RawVecInner {
            elements: allocation.ptr().cast(),
            capacity: AtomicUsize::new(0),
            len: AtomicUsize::new(0),
            max_capacity: 0,
            growth_strategy: GrowthStrategy::new(),
            allocation,
        }
    }

    #[inline]
    #[track_caller]
    unsafe fn reserve(&self, additional: usize, elem_size: usize) {
        let len = self.len.load(Relaxed);

        if self.needs_to_grow(len, additional) {
            unsafe { self.reserve_slow(len, additional, elem_size) };
        }
    }

    #[cold]
    #[track_caller]
    unsafe fn reserve_slow(&self, len: usize, additional: usize, elem_size: usize) {
        if let Err(err) = unsafe { self.grow(len, additional, elem_size) } {
            handle_error(err);
        }
    }

    #[track_caller]
    unsafe fn reserve_exact(&self, additional: usize, elem_size: usize) {
        if let Err(err) = unsafe { self.try_reserve_exact(additional, elem_size) } {
            handle_error(err);
        }
    }

    unsafe fn try_reserve(
        &self,
        additional: usize,
        elem_size: usize,
    ) -> Result<(), TryReserveError> {
        let len = self.len.load(Relaxed);

        if self.needs_to_grow(len, additional) {
            unsafe { self.grow(len, additional, elem_size) }
        } else {
            Ok(())
        }
    }

    unsafe fn try_reserve_exact(
        &self,
        additional: usize,
        elem_size: usize,
    ) -> Result<(), TryReserveError> {
        let len = self.len.load(Relaxed);

        if self.needs_to_grow(len, additional) {
            unsafe { self.grow_exact(len, additional, elem_size) }
        } else {
            Ok(())
        }
    }

    #[inline]
    fn needs_to_grow(&self, len: usize, additional: usize) -> bool {
        let capacity = self.capacity.load(Relaxed);
        let len = cmp::min(len, capacity);

        additional > capacity - len
    }

    #[track_caller]
    unsafe fn grow_one(&self, len: usize, elem_size: usize) {
        if let Err(err) = unsafe { self.grow(len, 1, elem_size) } {
            if len >= self.max_capacity {
                // This can't overflow because `grow_one` must be called after the length was
                // incremented. It is sound to decrement because it's impossible for an element to
                // be initialized while the length exceeds `self.max_capacity`. Note that this is
                // *not* the case when `grow` fails in general: it can happen that committing more
                // memory fails on this thread but succeeds on another, resulting in us
                // decrementing the length while it is below `self.capacity`, which would lead to
                // two threads getting the same index in `push`. That's why we must not decrement
                // the length unless it overshot `self.max_capacity`. We decrement the length in
                // order to prevent an overflow in `push`.
                self.len.fetch_sub(1, Relaxed);
            }

            handle_error(err);
        }
    }

    #[track_caller]
    unsafe fn grow_one_mut(&mut self, elem_size: usize) {
        let len = *self.len.get_mut();

        if let Err(err) = unsafe { self.grow(len, 1, elem_size) } {
            handle_error(err);
        }
    }

    unsafe fn grow(
        &self,
        len: usize,
        additional: usize,
        elem_size: usize,
    ) -> Result<(), TryReserveError> {
        unsafe { self.grow_inner(len, additional, false, elem_size) }
    }

    unsafe fn grow_exact(
        &self,
        len: usize,
        additional: usize,
        elem_size: usize,
    ) -> Result<(), TryReserveError> {
        unsafe { self.grow_inner(len, additional, true, elem_size) }
    }

    unsafe fn grow_inner(
        &self,
        len: usize,
        additional: usize,
        exact: bool,
        elem_size: usize,
    ) -> Result<(), TryReserveError> {
        debug_assert!(additional > 0);

        if elem_size == 0 {
            return Err(CapacityOverflow.into());
        }

        let required_capacity = len.checked_add(additional).ok_or(CapacityOverflow)?;

        if required_capacity > self.max_capacity {
            return Err(CapacityOverflow.into());
        }

        let old_capacity = self.capacity.load(Acquire);

        if old_capacity >= required_capacity {
            // Another thread beat us to it.
            return Ok(());
        }

        let mut new_capacity = required_capacity;

        if !exact {
            new_capacity = cmp::max(new_capacity, self.growth_strategy.grow(old_capacity));
            new_capacity = cmp::min(new_capacity, self.max_capacity);
        }

        let elements_offset = self.elements.addr() - self.allocation.ptr().addr();

        let page_size = page_size();

        // These can't overflow because the size is already allocated.
        let old_size = align_up(elements_offset + old_capacity * elem_size, page_size);
        let new_size = align_up(elements_offset + new_capacity * elem_size, page_size);

        let ptr = self.allocation.ptr().wrapping_add(old_size);
        let size = new_size - old_size;

        self.allocation.commit(ptr, size).map_err(AllocError)?;

        let new_capacity = (new_size - elements_offset) / elem_size;
        let new_capacity = cmp::min(new_capacity, self.max_capacity);

        if let Err(capacity) =
            self.capacity
                .compare_exchange(old_capacity, new_capacity, Release, Acquire)
        {
            // We lost the race, but the winner must have updated the capacity like we wanted to.
            debug_assert!(capacity >= new_capacity);
        }

        Ok(())
    }
}

impl<T> AsRef<RawVec<T>> for RawVec<T> {
    #[inline]
    fn as_ref(&self) -> &RawVec<T> {
        self
    }
}

impl<T> AsMut<RawVec<T>> for RawVec<T> {
    #[inline]
    fn as_mut(&mut self) -> &mut RawVec<T> {
        self
    }
}

impl<T> AsRef<[T]> for RawVec<T> {
    #[inline]
    fn as_ref(&self) -> &[T] {
        self
    }
}

impl<T> AsMut<[T]> for RawVec<T> {
    #[inline]
    fn as_mut(&mut self) -> &mut [T] {
        self
    }
}

impl<T> Borrow<[T]> for RawVec<T> {
    #[inline]
    fn borrow(&self) -> &[T] {
        self
    }
}

impl<T> BorrowMut<[T]> for RawVec<T> {
    #[inline]
    fn borrow_mut(&mut self) -> &mut [T] {
        self
    }
}

impl<T: fmt::Debug> fmt::Debug for RawVec<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&**self, f)
    }
}

impl<T> Deref for RawVec<T> {
    type Target = [T];

    /// This does the same thing as [`RawVec::as_slice`].
    #[inline]
    fn deref(&self) -> &Self::Target {
        self.as_slice()
    }
}

impl<T> DerefMut for RawVec<T> {
    /// This does the same thing as [`RawVec::as_mut_slice`].
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.as_mut_slice()
    }
}

impl<T> Drop for RawVec<T> {
    fn drop(&mut self) {
        let len = cmp::min(self.len_mut(), self.capacity_mut());
        let elements = ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), len);

        // SAFETY: We own the collection, and it is being dropped, which ensures that the elements
        // can't be accessed again.
        unsafe { elements.drop_in_place() };
    }
}

impl<T: PartialEq<U>, U> PartialEq<RawVec<U>> for RawVec<T> {
    #[inline]
    fn eq(&self, other: &RawVec<U>) -> bool {
        **self == **other
    }
}

impl<T: PartialEq<U>, U> PartialEq<&[U]> for RawVec<T> {
    #[inline]
    fn eq(&self, other: &&[U]) -> bool {
        **self == **other
    }
}

impl<T: PartialEq<U>, U> PartialEq<&mut [U]> for RawVec<T> {
    #[inline]
    fn eq(&self, other: &&mut [U]) -> bool {
        **self == **other
    }
}

impl<T: PartialEq<U>, U> PartialEq<RawVec<U>> for &[T] {
    #[inline]
    fn eq(&self, other: &RawVec<U>) -> bool {
        **self == **other
    }
}

impl<T: PartialEq<U>, U> PartialEq<RawVec<U>> for &mut [T] {
    #[inline]
    fn eq(&self, other: &RawVec<U>) -> bool {
        **self == **other
    }
}

impl<T: PartialEq<U>, U> PartialEq<[U]> for RawVec<T> {
    #[inline]
    fn eq(&self, other: &[U]) -> bool {
        **self == *other
    }
}

impl<T: PartialEq<U>, U> PartialEq<RawVec<U>> for [T] {
    #[inline]
    fn eq(&self, other: &RawVec<U>) -> bool {
        *self == **other
    }
}

#[cfg(feature = "alloc")]
impl<T: PartialEq<U> + Clone, U> PartialEq<RawVec<U>> for alloc::borrow::Cow<'_, [T]> {
    #[inline]
    fn eq(&self, other: &RawVec<U>) -> bool {
        **self == **other
    }
}

impl<T: PartialEq<U>, U, const N: usize> PartialEq<[U; N]> for RawVec<T> {
    #[inline]
    fn eq(&self, other: &[U; N]) -> bool {
        **self == *other
    }
}

impl<T: PartialEq<U>, U, const N: usize> PartialEq<&[U; N]> for RawVec<T> {
    #[inline]
    fn eq(&self, other: &&[U; N]) -> bool {
        **self == **other
    }
}

impl<T: Eq> Eq for RawVec<T> {}

impl<T> Extend<T> for RawVec<T> {
    #[inline]
    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
        for elem in iter {
            let (_, slot) = self.push_mut();
            *slot = elem;
        }
    }
}

impl<'a, T: Copy> Extend<&'a T> for RawVec<T> {
    #[inline]
    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
        for &elem in iter {
            let (_, slot) = self.push_mut();
            *slot = elem;
        }
    }
}

impl<T: Hash> Hash for RawVec<T> {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        Hash::hash(&**self, state);
    }
}

impl<T, I: SliceIndex<[T]>> Index<I> for RawVec<T> {
    type Output = I::Output;

    #[inline]
    fn index(&self, index: I) -> &Self::Output {
        Index::index(&**self, index)
    }
}

impl<T, I: SliceIndex<[T]>> IndexMut<I> for RawVec<T> {
    #[inline]
    fn index_mut(&mut self, index: I) -> &mut Self::Output {
        IndexMut::index_mut(&mut **self, index)
    }
}

impl<'a, T> IntoIterator for &'a RawVec<T> {
    type Item = &'a T;

    type IntoIter = slice::Iter<'a, T>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a, T> IntoIterator for &'a mut RawVec<T> {
    type Item = &'a mut T;

    type IntoIter = slice::IterMut<'a, T>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.iter_mut()
    }
}

impl<T> IntoIterator for RawVec<T> {
    type Item = T;

    type IntoIter = raw::IntoIter<T>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        raw::IntoIter::new(self)
    }
}

impl<T: PartialOrd> PartialOrd for RawVec<T> {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
        PartialOrd::partial_cmp(&**self, &**other)
    }
}

impl<T: Ord> Ord for RawVec<T> {
    #[inline]
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        Ord::cmp(&**self, &**other)
    }
}