soavec 0.2.0

A vector-like data structure for conventient growable Struct-of-Arrays creation and manipulation.
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
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

//! A vector-like data-structure for convenient growable Struct-of-Arrays
//! creation and manipulation.
//!
//! The [`SoAVec`] type is recommended for use in places where multiple structs
//! need to be stored on the heap and their access to or iteration of is done
//! mostly field-wise as opposed to all-fields-together.
//!
//! # Basic usage
//!
//! The [`SoAble`] trait can be derived on structs to conveniently split them
//! up into Struct-of-Arrays format field-wise and to generate wrapper types
//! for the [`as_ref`], [`as_mut`], [`as_slice`], and [`as_mut_slice`] methods'
//! return types. For advanced usage, the [`SoAble`] trait can be implemented
//! manually.
//!
//! When deriving the [`SoAble`] trait it is recommended to write the struct
//! definition in order of alignment and size, eg. a `u64` field should come
//! before a `[u32; 3]` field. If the [`SoAble`] trait is implemented manually
//! then the struct's layout ordering does not matter but the chosen
//! [tuple representation] should still uphold this same order. This ensures
//! that the `SoAVec` does not need to add extra padding between field slices.
//!
//! # Example
//!
//! ```rust
//! use soavec::soavec;
//! use soavec_derive::SoAble;
//!
//! #[derive(Clone, SoAble)]
//! struct Basic {
//!   a: Vec<u32>,
//!   b: usize,
//!   c: u16,
//!   d: bool,
//! }
//!
//! let mut vec = soavec![Basic { a: vec![1, 2, 3], b: 55, c: 4, d: false }; 32].unwrap();
//! let BasicSlice {
//!   a,
//!   b,
//!   c,
//!   d,
//! } = vec.as_slice();
//! assert_eq!(a, vec![vec![1, 2, 3]; 32]);
//! assert_eq!(b, vec![55usize; 32]);
//! assert_eq!(c, vec![4u16; 32]);
//! assert_eq!(d, vec![false; 32]);
//! ```
//!
//! [`SoAVec`]: SoAVec
//! [`SoAble`]: SoAble
//! [`as_ref`]: SoAVec::as_ref
//! [`as_mut`]: SoAVec::as_mut
//! [`as_slice`]: SoAVec::as_slice
//! [`as_mut_slice`]: SoAVec::as_mut_slice

mod macros;
mod raw_vec;
mod raw_vec_inner;
mod soable;

use core::marker::PhantomData;
use std::ptr::NonNull;

use raw_vec::RawSoAVec;
use raw_vec_inner::AllocError;
pub use soable::{SoATuple, SoAble};

#[cfg(feature = "derive")]
pub use soavec_derive::*;

/// A contiguous growable Struct-of-Arrays type, written as `SoAVec<T>`, short
/// for ‘Struct-of-Arrays vector’.
///
/// The API and layout is purposefully very similar to a standard library
/// `Vec`, with the exception that the capacity is capped at 32-bit unsigned
/// values.
///
/// # Examples
///
/// ```
/// use soavec::SoAVec;
///
/// let mut vec = SoAVec::new();
/// vec.push((1, 1)).unwrap();
/// vec.push((2, 2)).unwrap();
///
/// assert_eq!(vec.len(), 2);
/// assert_eq!(vec.get(0).unwrap(), (&1, &1));
///
/// assert_eq!(vec.pop(), Some((2, 2)));
/// assert_eq!(vec.len(), 1);
///
/// let m = vec.get_mut(0).unwrap();
/// *m.0 = 7;
/// *m.1 = 7;
/// assert_eq!(vec.get(0).unwrap(), (&7, &7));
/// ```
///
/// The [`soavec!`] macro is provided for convenient initialization:
///
/// ```
/// use soavec::soavec;
///
/// let mut vec1 = soavec![(1, 1), (2, 2), (3, 3)].unwrap();
/// vec1.push((4, 4));
/// ```
///
/// It can also initialize each element of a `Vec<T>` with a given value.
///
/// ```
/// use soavec::soavec;
///
/// let vec = soavec![(0, 0); 5];
/// ```
///
/// For more information, see
/// [Capacity and Reallocation](#capacity-and-reallocation).
///
/// # Indexing
///
/// The `SoAVec` type does not allow access to values by index currently.
///
/// Use [`get`] and [`get_mut`] if you want to access an index in the `SoAVec`.
///
/// # Slicing
///
/// A `SoAVec` can be mutable. On the other hand, slices are read-only objects.
/// To get a [slice][prim@slice], use [`as_slice`] or [`as_mut_slice`]. Note
/// that these methods give out multiple slices, one for each field in the
/// struct. Example:
///
/// ```
/// use soavec::soavec;
///
/// fn read_slice(slice: &[usize]) {
///     // ...
/// }
///
/// let v = soavec![(0, 1), (0, 1)].unwrap();
/// let (zeros_slice, ones_slice) = v.as_slice();
/// read_slice(v.as_slice().0);
/// read_slice(v.as_slice().1);
/// ```
///
/// # Capacity and reallocation
///
/// The capacity of a Struct-of-Arrays vector is the amount of space allocated
/// for any future elements that will be added onto the vector. This is not to
/// be confused with the *length* of a vector, which specifies the number of
/// actual elements within the vector. If a vector's length exceeds its
/// capacity, its capacity will automatically be increased, but its elements
/// will have to be reallocated. The reallocation may also fail due to OOM or
/// other reasons, and these failures are exposed by the APIs. Thus methods
/// such as [`push`] and [`SoAVec::with_capacity`] may fail.
///
/// For example, a vector with capacity 10 and length 0 would be an empty
/// vector with space for 10 more elements. Pushing 10 or fewer elements onto
/// the vector will not change its capacity or cause reallocation to occur.
/// However, if the vector's length is increased to 11, it will have to
/// reallocate, which can be slow. For this reason, it is recommended to use
/// [`SoAVec::with_capacity`] whenever possible to specify how big the vector
/// is expected to get. This is even more important than with a traditional
/// `Vec`, as during reallocation `SoAVec` must also move all element data
/// except for the first fields.
///
/// # Guarantees
///
/// `SoAVec` is guaranteed to be a (pointer, capacity, length) triplet where
/// the capacity and length are 32-bit values regardless of architecture (note:
/// 16-bit systems are not supported but there the capacity and length would be
/// 16-bit values). The order of these fields is completely unspecified, and
/// you should use the appropriate methods to modify these. The pointer will
/// never be null, so this type is null-pointer-optimized.
///
/// However, the pointer might not actually point to allocated memory. In
/// particular, if you construct a `SoAVec` with capacity 0 via
/// [`SoAVec::new`], [`soavec![]`][`soavec!`],
/// [`SoAVec::with_capacity(0)`][`SoAVec::with_capacity`], it will not allocate
/// memory. Similarly, if you store zero-sized types inside a `SoAVec`, it will
/// not allocate space for them. *Note that in this case the `Vec` might not
/// report a [`capacity`] of 0*. `SoAVec` will allocate if and only if
/// <code>[size_of::\<T>]\() * [capacity]\() > 0</code>. In general, `SoAVec`'s
/// allocation details are very subtle indeed --- if you intend to allocate
/// memory using a `SoAVec` and use it for something else (either to pass to
/// unsafe code, or to build your own memory-backed collection), don't.
///
/// If a `SoAVec` *has* allocated memory, then the memory it points to is on
/// the heap (as defined by the allocator Rust is configured to use by
/// default), and its pointer points to a number of field slices determined by
/// the contained type, with each field slice containing [`len`] initialized,
/// contiguous field elements in order (what you would see if you call
/// `as_slice` or `as_mut_slice`), followed by <code>[capacity] - [len]</code>
/// logically uninitialized, contiguous field elements.
///
/// A vector containing two struct elements `'a'` and `'b'` with fields `'x'`
/// and `'y'`, and with capacity 4 can be visualized as below. The top part is
/// the `SoAVec` struct, it contains a pointer to the head of the allocation in
/// the heap, length and capacity. The bottom part is the allocation on the
/// heap, a contiguous memory block.
///
/// ```text
///             ptr      len  capacity
///        +--------+--------+--------+
///        | 0x0123 |      2 |      4 |
///        +--------+--------+--------+
///             |
///             v
/// Heap   +--------+--------+--------+--------+--------+--------+--------+--------+
///        |  'a.x' |  'b.x' | uninit | uninit |  'a.y' |  'b.y' | uninit | uninit |
///        +--------+--------+--------+--------+--------+--------+--------+--------+
/// ```
///
/// - **uninit** represents memory that is not initialized, see [`MaybeUninit`].
/// - Note: the ABI is not stable and `SoAVec` makes no guarantees about its
///   memory layout (including the order of fields).
///
/// `SoAVec` will never perform a "small optimization" where elements are
/// actually stored on the stack.
///
/// `SoAVec` will never automatically shrink itself, even if completely empty.
/// This ensures no unnecessary allocations or deallocations occur. Emptying a
/// `SoAVec` and then filling it back up to the same [`len`] should incur no
/// calls to the allocator.
///
/// [`push`] will never (re)allocate if the reported capacity is sufficient.
/// [`push`] *will* (re)allocate if <code>[len] == [capacity]</code>. That is,
/// the reported capacity is completely accurate. The size of the allocation is
/// not guaranteed to be equal to <code>size_of::\<T>]\() * [capacity]</code>,
/// as padding may be required between field slices.
///
/// `SoAVec` does not guarantee any particular growth strategy when
/// reallocating when full, nor when [`reserve`] is called. The current
/// strategy is basic and it may prove desirable to use a non-constant growth
/// factor. Whatever strategy is used will of course guarantee *O*(1) amortized
/// [`push`].
///
/// It is guaranteed, in order to respect the intentions of the programmer,
/// that all of `soavec![e_1, e_2, ..., e_n]`, `soavec![x; n]`, and
/// [`SoAVec::with_capacity(n)`] produce a `SoAVec` that requests an allocation
/// of the exact size needed for precisely `n` elements from the allocator,
/// and no other size (such as, for example: a size rounded up to the nearest
/// power of 2). The allocator will return an allocation that is at least as
/// large as requested, but it may be larger.
///
/// It is guaranteed that the [`SoAVec::capacity`] method returns a value that
/// is at least the requested capacity and not more than the allocated
/// capacity.
///
/// `SoAVec` will not specifically overwrite any data that is removed from it,
/// but also won't specifically preserve it. Its uninitialized memory is
/// scratch space that it may use however it wants. It will generally just do
/// whatever is most efficient or otherwise easy to implement. Do not rely on
/// removed data to be erased for security purposes. Even if you drop a
/// `SoAVec`, its buffer may simply be reused by another allocation. Even if
/// you zero a `SoAVec`'s memory first, that might not actually happen because
/// the optimizer does not consider this a side-effect that must be preserved.
///
/// Currently, `SoAVec` does not guarantee the order in which elements are
/// dropped.
///
/// [`get`]: SoAVec::get
/// [`get_mut`]: SoAVec::get_mut
/// [capacity]: SoAVec::capacity
/// [`capacity`]: SoAVec::capacity
/// [`SoAVec::capacity`]: SoAVec::capacity
/// [size_of::\<T>]: size_of
/// [len]: SoAVec::len
/// [`len`]: SoAVec::len
/// [`push`]: SoAVec::push
/// [`as_slice`]: SoAVec::as_slice
/// [`as_mut_slice`]: SoAVec::as_mut_slice
/// [`reserve`]: SoAVec::reserve
/// [`Vec::with_capacity(n)`]: SoAVec::with_capacity
/// [`MaybeUninit`]: core::mem::MaybeUninit
#[repr(C)]
pub struct SoAVec<T: SoAble> {
    buf: RawSoAVec<T>,
}

/// The error type for when an index is out of bounds.
#[derive(Clone, Debug)]
pub struct IndexOutOfBoundsError;

/// A union of possible errors that can occur when inserting into a `SoAVec`.
#[derive(Clone, Debug)]
pub enum InsertError {
    IndexOutOfBounds(IndexOutOfBoundsError),
    AllocError(AllocError),
}

impl From<IndexOutOfBoundsError> for InsertError {
    fn from(e: IndexOutOfBoundsError) -> Self {
        InsertError::IndexOutOfBounds(e)
    }
}

impl From<AllocError> for InsertError {
    fn from(e: AllocError) -> Self {
        InsertError::AllocError(e)
    }
}

impl<T: SoAble> SoAVec<T> {
    pub fn new() -> Self {
        SoAVec {
            // SAFETY: 0-capacity vector cannot create an invalid layout.
            buf: unsafe { RawSoAVec::with_capacity(0).unwrap_unchecked() },
        }
    }

    /// Constructs a new, empty `SoAVec<T>` with at least the specified
    /// capacity. Returns an error if an allocator error occurred.
    ///
    /// The Struct-of-Arrays vector will be able to hold at least `capacity`
    /// elements without reallocating. This method is allowed to allocate for
    /// more elements than `capacity`. If `capacity` is zero, the vector will
    /// not allocate.
    ///
    /// It is important to note that although the returned vector has the
    /// minimum *capacity* specified, the vector will have a zero *length*. For
    /// an explanation of the difference between length and capacity, see
    /// *[Capacity and reallocation]*.
    ///
    /// If it is important to know the exact allocated capacity of a `SoAVec`,
    /// always use the [`capacity`] method after construction.
    ///
    /// For `SoAVec<T>` where `T` is a zero-sized type, there will be no
    /// allocation and the capacity will always be `usize::MAX`.
    ///
    /// [Capacity and reallocation]: #capacity-and-reallocation
    /// [`capacity`]: Vec::capacity
    ///
    /// # Panics
    ///
    /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
    ///
    /// # Examples
    ///
    /// ```
    /// use soavec::SoAVec;
    ///
    /// let mut vec = SoAVec::<(u32, u32)>::with_capacity(10).unwrap();
    ///
    /// // The vector contains no items, even though it has capacity for more
    /// assert_eq!(vec.len(), 0);
    /// assert!(vec.capacity() >= 10);
    ///
    /// // These are all done without reallocating...
    /// for i in 0..10 {
    ///     vec.push((i, i));
    /// }
    /// assert_eq!(vec.len(), 10);
    /// assert!(vec.capacity() >= 10);
    ///
    /// // ...but this may make the vector reallocate
    /// vec.push((11, 11));
    /// assert_eq!(vec.len(), 11);
    /// assert!(vec.capacity() >= 11);
    ///
    /// // A vector of a zero-sized type will always over-allocate, since no
    /// // allocation is necessary
    /// let vec_units = SoAVec::<((), ())>::with_capacity(10).unwrap();
    /// assert_eq!(vec_units.capacity(), u32::MAX);
    /// ```
    pub fn with_capacity(cap: u32) -> Result<Self, AllocError> {
        Ok(SoAVec {
            buf: RawSoAVec::with_capacity(cap)?,
        })
    }

    /// Returns the number of elements in the vector, also referred to
    /// as its 'length'.
    ///
    /// # Examples
    ///
    /// ```
    /// use soavec::soavec;
    ///
    /// let mut a = soavec![(0, 0); 3].unwrap();
    /// assert_eq!(a.len(), 3);
    /// ```
    #[inline]
    pub fn len(&self) -> u32 {
        self.buf.len()
    }

    /// Returns `true` if the vector contains no elements.
    ///
    /// # Examples
    ///
    /// ```
    /// use soavec::SoAVec;
    ///
    /// let mut v = SoAVec::new();
    /// assert!(v.is_empty());
    ///
    /// v.push((1, 1));
    /// assert!(!v.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.buf.is_empty()
    }

    /// Returns the total number of elements the vector can hold without
    /// reallocating.
    ///
    /// # Examples
    ///
    /// ```
    /// use soavec::SoAVec;
    ///
    /// let mut vec: SoAVec<(u32, i32)> = SoAVec::with_capacity(10).unwrap();
    /// vec.push((42, 3));
    /// assert!(vec.capacity() >= 10);
    /// ```
    ///
    /// A vector with zero-sized elements will always have a capacity of usize::MAX:
    ///
    /// ```
    /// use soavec::SoAVec;
    ///
    /// assert_eq!(std::mem::size_of::<((), ())>(), 0);
    /// let v = SoAVec::<((), ())>::new();
    /// assert_eq!(v.capacity(), u32::MAX);
    /// ```
    #[inline]
    pub fn capacity(&self) -> u32 {
        self.buf.capacity()
    }

    /// Reserves capacity for at least `additional` more elements to be inserted
    /// in the given `Vec<T>`. The collection may reserve more space to
    /// speculatively avoid frequent reallocations. After calling `reserve`,
    /// capacity will be greater than or equal to `self.len() + additional`.
    /// Does nothing if capacity is already sufficient.
    ///
    /// # Errors
    ///
    /// Returns an error if the new capacity exceeds `isize::MAX` _bytes_.
    ///
    /// # Examples
    ///
    /// ```
    /// use soavec::soavec;
    ///
    /// let mut vec = soavec![(1u32, 1u32)].unwrap();
    /// vec.reserve(10).unwrap();
    /// assert!(vec.capacity() >= 11);
    /// ```
    pub fn reserve(&mut self, additional: u32) -> Result<(), AllocError> {
        self.buf.reserve(additional)
    }

    /// Appends an element to the back of a collection.
    ///
    /// # Errors
    ///
    /// Returns an error if the new capacity exceeds `isize::MAX` _bytes_.
    ///
    /// # Examples
    ///
    /// ```
    /// use soavec::soavec;
    ///
    /// let mut vec = soavec![(1u32, 1u32), (2u32, 2u32)].unwrap();
    /// vec.push((3, 3)).unwrap();
    /// assert_eq!(vec.get(0), Some((&1, &1)));
    /// assert_eq!(vec.get(1), Some((&2, &2)));
    /// assert_eq!(vec.get(2), Some((&3, &3)));
    /// ```
    ///
    /// # Time complexity
    ///
    /// Takes amortized *O*(1) time. If the vector's length would exceed its
    /// capacity after the push, *O*(*capacity*) time is taken to copy the
    /// vector's elements to a larger allocation. This expensive operation is
    /// offset by the *capacity* *O*(1) insertions it allows.
    pub fn push(&mut self, value: T) -> Result<(), AllocError> {
        let len = self.len();
        if len == self.capacity() {
            self.buf.reserve(1)?;
        }

        // SAFETY: sure.
        unsafe {
            T::TupleRepr::write(
                self.buf.as_mut_ptr(),
                T::into_tuple(value),
                len,
                self.capacity(),
            )
        };
        // SAFETY: length cannot overflow due to reserve succeeding.
        unsafe { self.buf.set_len(self.len().unchecked_add(1)) };
        Ok(())
    }

    /// Moves all the elements of `other` into `self`, leaving `other` empty.
    ///
    /// # Errors
    ///
    /// Returns an error if the new capacity exceeds `isize::MAX` _bytes_.
    ///
    /// # Examples
    ///
    /// ```
    /// use soavec::soavec;
    ///
    /// let mut vec1 = soavec![(1, 1), (2, 2)].unwrap();
    /// let mut vec2 = soavec![(3, 3), (4, 4)].unwrap();
    ///
    /// vec1.append(&mut vec2).unwrap();
    ///
    /// assert_eq!(vec1.len(), 4);
    /// assert_eq!(vec2.len(), 0);
    /// assert_eq!(vec1.get(0), Some((&1, &1)));
    /// assert_eq!(vec1.get(1), Some((&2, &2)));
    /// assert_eq!(vec1.get(2), Some((&3, &3)));
    /// assert_eq!(vec1.get(3), Some((&4, &4)));
    /// ```
    ///
    /// # Time complexity
    ///
    /// Takes *O*(*other.len() \* number_of_fields*) time.
    pub fn append(&mut self, other: &mut Self) -> Result<(), AllocError> {
        let other_len = other.len();
        if other_len == 0 {
            return Ok(());
        }

        // Reserve space for the additional elements
        self.reserve(other_len)?;

        let self_len = self.len();
        let self_cap = self.capacity();
        let other_cap = other.capacity();

        // SAFETY: We reserved enough space, so we have capacity for other_len more elements
        unsafe {
            T::TupleRepr::copy(
                T::TupleRepr::get_pointers(other.buf.as_ptr(), 0, other_cap),
                T::TupleRepr::get_pointers(self.buf.as_mut_ptr(), self_len, self_cap),
                other_len,
            );

            self.buf.set_len(self_len + other_len);

            other.buf.set_len(0);
        }

        Ok(())
    }

    /// Copies all elements from a slice and appends them to the `SoAVec`.
    ///
    /// Iterates over the slice, cloning each element and appending it to this
    /// `SoAVec`. The slice is in Array-of-Structs format and will be transposed
    /// into the Struct-of-Arrays layout.
    ///
    /// # Errors
    ///
    /// Returns an error if the new capacity exceeds `isize::MAX` _bytes_.
    ///
    /// # Examples
    ///
    /// ```
    /// use soavec::soavec;
    ///
    /// let mut vec = soavec![(1, 1), (2, 2)].unwrap();
    /// vec.extend_from_slice(&[(3, 3), (4, 4)]).unwrap();
    ///
    /// assert_eq!(vec.len(), 4);
    /// assert_eq!(vec.get(0), Some((&1, &1)));
    /// assert_eq!(vec.get(1), Some((&2, &2)));
    /// assert_eq!(vec.get(2), Some((&3, &3)));
    /// assert_eq!(vec.get(3), Some((&4, &4)));
    /// ```
    ///
    /// # Time complexity
    ///
    /// Takes *O*(*slice.len()*) time.
    pub fn extend_from_slice(&mut self, slice: &[T]) -> Result<(), AllocError>
    where
        T: Clone,
    {
        let slice_len = slice.len() as u32;
        if slice_len == 0 {
            return Ok(());
        }

        // Reserve space for the additional elements
        self.reserve(slice_len)?;

        let mut self_len = self.len();
        let self_cap = self.capacity();

        // SAFETY: We reserved enough space, so we have capacity for slice_len more elements
        for item in slice.iter() {
            unsafe {
                T::TupleRepr::write(
                    self.buf.as_mut_ptr(),
                    T::into_tuple(item.clone()),
                    self_len,
                    self_cap,
                );
            }
            self_len += 1;
        }

        // SAFETY: We wrote exactly slice_len elements
        unsafe {
            self.buf.set_len(self_len);
        }

        Ok(())
    }

    /// Removes the last element from a SoA vector and returns it, or [`None`]
    /// if it is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use soavec::soavec;
    ///
    /// let mut vec = soavec![(1, 1), (2, 2), (3, 3)].unwrap();
    /// assert_eq!(vec.pop(), Some((3, 3)));
    /// assert_eq!(vec.get(0), Some((&1, &1)));
    /// assert_eq!(vec.get(1), Some((&2, &2)));
    /// ```
    ///
    /// # Time complexity
    ///
    /// Takes *O*(1) time.
    #[inline]
    pub fn pop(&mut self) -> Option<T> {
        let len = self.len();
        if len == 0 {
            None
        } else {
            unsafe {
                self.buf.set_len(len - 1);
                core::hint::assert_unchecked(self.len() < self.capacity());
                Some(T::from_tuple(T::TupleRepr::read(
                    self.buf.as_ptr(),
                    self.len(),
                    self.capacity(),
                )))
            }
        }
    }

    /// Returns a reference to each field in T or `None` if out of bounds.
    ///
    /// # Examples
    ///
    /// ```
    /// use soavec::soavec;
    ///
    /// let v = soavec![(10, 10), (40, 40), (30, 30)].unwrap();
    /// assert_eq!(Some((&40, &40)), v.get(1));
    /// assert_eq!(None, v.get(3));
    /// ```
    #[inline]
    #[must_use]
    pub fn get(&self, index: u32) -> Option<T::Ref<'_>> {
        if self.len() <= index {
            // Over-indexing.
            return None;
        }
        let ptrs = unsafe { T::TupleRepr::get_pointers(self.buf.as_ptr(), index, self.capacity()) };
        Some(T::as_ref(PhantomData, ptrs))
    }

    /// Returns a mutable reference to each field in `T` or `None` if the index
    /// is out of bounds.
    ///
    /// # Examples
    ///
    /// ```
    /// use soavec::soavec;
    ///
    /// let x = &mut soavec![(0, 0), (1, 1), (2, 2)].unwrap();
    ///
    /// if let Some((first, second)) = x.get_mut(1) {
    ///     *first = 42;
    ///     *second = 3;
    /// }
    /// assert_eq!(x.as_slice(), ([0, 42, 2].as_slice(), [0, 3, 2].as_slice()));
    /// ```
    #[inline]
    #[must_use]
    pub fn get_mut(&mut self, index: u32) -> Option<T::Mut<'_>> {
        if self.len() <= index {
            // Over-indexing.
            return None;
        }
        let ptrs =
            unsafe { T::TupleRepr::get_pointers(self.buf.as_mut_ptr(), index, self.capacity()) };
        Some(T::as_mut(PhantomData, ptrs))
    }

    /// Extracts a tuple of slices containing the entire vector.
    ///
    /// # Examples
    ///
    /// ```
    /// use soavec::soavec;
    /// use std::io::{self, Write};
    ///
    /// let buffer = soavec![(1, 1), (2, 2), (3, 3), (5, 5), (8, 8)].unwrap();
    /// let (first, second) = buffer.as_slice();
    /// io::sink().write(first).unwrap();
    /// io::sink().write(second).unwrap();
    /// ```
    pub fn as_slice(&self) -> T::Slice<'_> {
        let ptrs = unsafe { T::TupleRepr::get_pointers(self.buf.as_ptr(), 0, self.capacity()) };
        let len = self.len();
        T::as_slice(PhantomData, ptrs, len)
    }

    /// Extracts a mutable slice of the entire vector.
    ///
    /// Equivalent to `&mut s[..]`.
    ///
    /// # Examples
    ///
    /// ```
    /// use soavec::soavec;
    /// use std::io::{self, Read};
    /// let mut buffer = soavec![(0, 0); 3].unwrap();
    /// let (first, second) = buffer.as_mut_slice();
    ///
    /// io::repeat(0b101).read_exact(first).unwrap();
    /// io::repeat(0b010).read_exact(second).unwrap();
    /// ```
    pub fn as_mut_slice(&mut self) -> T::SliceMut<'_> {
        let ptrs = unsafe { T::TupleRepr::get_pointers(self.buf.as_ptr(), 0, self.capacity()) };
        let len = self.len();
        T::as_mut_slice(PhantomData, ptrs, len)
    }

    /// Retains only the elements specified by the predicate, passing a mutable
    /// reference to it.
    ///
    /// In other words, remove all elements `e` such that `f(T::Mut)` returns
    /// `false`. This method operates in place, visiting each element exactly
    /// once in the original order, and preserves the order of the retained
    /// elements.
    ///
    /// # Examples
    ///
    /// ```
    /// use soavec::soavec;
    /// let mut vec = soavec![(1, 1), (2, 2), (3, 3), (4, 4)].unwrap();
    /// vec.retain_mut(|x| if *x.0 <= 3 {
    ///     *x.1 += 1;
    ///     true
    /// } else {
    ///     false
    /// });
    /// assert_eq!(vec.len(), 3);
    /// assert_eq!(vec.get(0), Some((&1, &2)));
    /// assert_eq!(vec.get(1), Some((&2, &3)));
    /// assert_eq!(vec.get(2), Some((&3, &4)));
    /// ```
    pub fn retain_mut<F>(&mut self, mut f: F)
    where
        F: FnMut(T::Mut<'_>) -> bool,
    {
        let original_len = self.len();

        if original_len == 0 {
            // Empty case: explicit return allows better optimization, vs letting compiler infer it
            return;
        }

        // Avoid double drop if the drop guard is not executed,
        // since we may make some holes during the process.
        unsafe { self.buf.set_len(0) };

        // Vec: [Kept, Kept, Hole, Hole, Hole, Hole, Unchecked, Unchecked]
        //      |<-              processed len   ->| ^- next to check
        //                  |<-  deleted cnt     ->|
        //      |<-              original_len                          ->|
        // Kept: Elements which predicate returns true on.
        // Hole: Moved or dropped element slot.
        // Unchecked: Unchecked valid elements.
        //
        // This drop guard will be invoked when predicate or `drop` of element panicked.
        // It shifts unchecked elements to cover holes and `set_len` to the correct length.
        // In cases when predicate and `drop` never panick, it will be optimized out.
        struct BackshiftOnDrop<'a, T: SoAble> {
            v: &'a mut SoAVec<T>,
            processed_len: u32,
            deleted_cnt: u32,
            original_len: u32,
        }

        impl<T: SoAble> Drop for BackshiftOnDrop<'_, T> {
            fn drop(&mut self) {
                if self.deleted_cnt > 0 {
                    let cap = self.v.buf.capacity();
                    // SAFETY: Trailing unchecked items must be valid since we never touch them.
                    unsafe {
                        T::TupleRepr::copy(
                            T::TupleRepr::get_pointers(
                                self.v.buf.as_ptr(),
                                self.processed_len,
                                cap,
                            ),
                            T::TupleRepr::get_pointers(
                                self.v.buf.as_mut_ptr(),
                                self.processed_len - self.deleted_cnt,
                                cap,
                            ),
                            self.original_len - self.processed_len,
                        );
                    }
                }
                // SAFETY: After filling holes, all items are in contiguous memory.
                unsafe {
                    self.v.buf.set_len(self.original_len - self.deleted_cnt);
                }
            }
        }

        let mut g = BackshiftOnDrop {
            v: self,
            processed_len: 0,
            deleted_cnt: 0,
            original_len,
        };

        fn process_loop<F, T: SoAble, const DELETED: bool>(
            original_len: u32,
            f: &mut F,
            g: &mut BackshiftOnDrop<'_, T>,
        ) where
            F: FnMut(T::Mut<'_>) -> bool,
        {
            while g.processed_len != original_len {
                // SAFETY: Unchecked element must be valid.
                let cur_ptrs = unsafe {
                    T::TupleRepr::get_pointers(
                        g.v.buf.as_mut_ptr(),
                        g.processed_len,
                        g.v.capacity(),
                    )
                };
                let cur = T::as_mut(PhantomData, cur_ptrs);
                if !f(cur) {
                    let cur_len = g.processed_len;
                    // Advance early to avoid double drop if `drop_in_place` panicked.
                    g.processed_len += 1;
                    g.deleted_cnt += 1;
                    // SAFETY: We never touch this element again after dropped.
                    if T::MUST_DROP_AS_SELF {
                        // T must be dropped as T; we have to read out each T from the
                        // SoAVec and drop them individually.
                        let ptr = g.v.buf.as_mut_ptr();
                        let cap = g.v.buf.capacity();
                        // SAFETY: cur was moved to f and its backing memory
                        // will never be accessed again.
                        let _ = T::from_tuple(unsafe { T::TupleRepr::read(ptr, cur_len, cap) });
                    } else if const { core::mem::needs_drop::<T::TupleRepr>() } {
                        // SAFETY: cur was moved to f and its backing memory
                        // will never be accessed again.
                        unsafe { T::TupleRepr::drop_in_place(cur_ptrs, 1) };
                    }
                    // We already advanced the counter.
                    if DELETED {
                        continue;
                    } else {
                        break;
                    }
                }
                if DELETED {
                    // SAFETY: `deleted_cnt` > 0, so the hole slot must not overlap with current element.
                    // We use copy for move, and never touch this element again.
                    unsafe {
                        let hole_slot = T::TupleRepr::get_pointers(
                            g.v.buf.as_mut_ptr(),
                            g.processed_len - g.deleted_cnt,
                            g.v.buf.capacity(),
                        );
                        T::TupleRepr::copy(cur_ptrs, hole_slot, 1);
                    }
                }
                g.processed_len += 1;
            }
        }

        // Stage 1: Nothing was deleted.
        process_loop::<F, T, false>(original_len, &mut f, &mut g);

        // Stage 2: Some elements were deleted.
        process_loop::<F, T, true>(original_len, &mut f, &mut g);

        // All item are processed. This can be optimized to `set_len` by LLVM.
        drop(g);
    }

    /// Removes and returns the element at position `index` within the vector,
    /// shifting all elements after it to the left.
    ///
    /// # Examples
    ///
    /// ```
    /// use soavec::soavec;
    ///
    /// let mut v = soavec![('a', 'a'), ('b', 'b'), ('c', 'c')].unwrap();
    /// assert_eq!(v.remove(1).unwrap(), ('b', 'b'));
    /// assert_eq!(v.len(), 2);
    /// ```
    pub fn remove(&mut self, index: u32) -> Result<T, InsertError> {
        let len = self.len();
        if index >= len {
            return Err(IndexOutOfBoundsError.into());
        }

        let cap = self.buf.capacity();
        let ptr = self.buf.as_ptr();

        unsafe {
            // Read the value out before we overwrite its memory.
            let result = T::from_tuple(T::TupleRepr::read(ptr, index, cap));
            // Shift down everything after it.
            if index < len - 1 {
                T::TupleRepr::copy(
                    T::TupleRepr::get_pointers(ptr, index + 1, cap),
                    T::TupleRepr::get_pointers(ptr, index, cap),
                    len - index - 1,
                );
            }
            // Update the length.
            self.buf.set_len(len - 1);

            Ok(result)
        }
    }

    /// Inserts an element at position `index` within the vector, shifting all
    /// elements after it to the right.
    ///
    /// # Examples
    ///
    /// ```
    /// use soavec::soavec;
    ///
    /// let mut vec = soavec![('a', 'b'), ('c', 'd')].unwrap();
    /// vec.insert(1, ('x', 'y')).unwrap();
    /// assert_eq!(vec.len(), 3);
    /// ```
    pub fn insert(&mut self, index: u32, element: T) -> Result<(), InsertError> {
        self.insert_mut(index, element)?;

        Ok(())
    }

    /// Inserts an element at position `index` within the vector, shifting all
    /// elements after it to the right, and returning a reference to the new
    /// element.
    ///
    /// # Examples
    ///
    /// ```
    /// use soavec::soavec;
    ///
    /// let mut vec = soavec![(1, 1), (3, 3), (5, 5), (7, 7), (9, 9)].unwrap();
    /// let (mut x1, _) = vec.insert_mut(3, (6, 6)).unwrap();
    /// *x1 += 1;
    /// assert_eq!(vec.len(), 6);
    /// assert_eq!(vec.get(3), Some((&7, &6)));
    /// ```
    pub fn insert_mut(&mut self, index: u32, element: T) -> Result<T::Mut<'_>, InsertError> {
        let len = self.len();
        if index > len {
            return Err(IndexOutOfBoundsError.into());
        }

        if len == self.capacity() {
            // Make sure we have space to one more element.
            self.buf.reserve(1)?;
        }

        let ptr = self.buf.as_mut_ptr();
        let cap = self.capacity();

        unsafe {
            if index < len {
                // Shift elements to the right.
                let src = T::TupleRepr::get_pointers(ptr, index, cap);
                let dst = T::TupleRepr::get_pointers(ptr, (index) + 1, cap);
                T::TupleRepr::copy(src, dst, len - (index));
            }

            // Write the new element.
            let src = T::into_tuple(element);
            T::TupleRepr::write(ptr, src, index, cap);

            // Update length.
            self.buf.set_len(len + 1);

            let ptrs = T::TupleRepr::get_pointers(ptr, index, cap);
            Ok(T::as_mut(PhantomData, ptrs))
        }
    }

    /// Clears the vector, removing all values.
    ///
    /// Note that this method has no effect on the allocated capacity
    /// of the vector.
    ///
    /// # Examples
    ///
    /// ```
    /// use soavec::soavec;
    ///
    /// let mut vec = soavec![(1, 1), (2, 2), (3, 3)].unwrap();
    /// vec.clear();
    /// assert_eq!(vec.len(), 0);
    /// ```
    pub fn clear(&mut self) {
        let len = self.len();
        if len == 0 {
            return;
        }

        let ptr = self.buf.as_mut_ptr();
        let cap = self.capacity();

        unsafe {
            self.buf.set_len(0);
        };
        self.drop_in_place(ptr, cap, len);
    }

    // Drops the items in place without deallocating the buffer.
    fn drop_in_place(&mut self, ptr: NonNull<u8>, cap: u32, len: u32) {
        if T::MUST_DROP_AS_SELF {
            for i in 0..len {
                // SAFETY: reads each value out without altering the backing
                // memory; using the backing memory may violate memory safety
                // after this but we are about to deallocate it afterwards.
                let _ = T::from_tuple(unsafe { T::TupleRepr::read(ptr, i, cap) });
            }
        } else if const { core::mem::needs_drop::<T::TupleRepr>() } {
            // SAFETY: buffer is still allocated to capacity, contains len
            // items.
            unsafe { T::TupleRepr::drop_in_place(T::TupleRepr::get_pointers(ptr, 0, cap), len) };
        }
    }

    /// Removes an element from the vector and returns it.
    ///
    /// The removed element is replaced by the last element of the vector.
    ///
    /// This does not preserve ordering of the remaining elements, but is *O*(n_fields).
    /// If you need to preserve the element order, use [`remove`] instead.
    ///
    /// [`remove`]: SoAVec::remove
    ///
    /// # Examples
    ///
    /// ```
    /// use soavec::soavec;
    ///
    /// let mut v = soavec![("foo", "foo"), ("bar", "bar"), ("baz", "baz"), ("qux", "qux")].unwrap();
    ///
    /// assert_eq!(v.swap_remove(1).unwrap(), ("bar", "bar"));
    /// assert_eq!(v, soavec![("foo", "foo"), ("qux", "qux"), ("baz", "baz")].unwrap());
    ///
    /// assert_eq!(v.swap_remove(0).unwrap(), ("foo", "foo"));
    /// assert_eq!(v, soavec![("baz", "baz"), ("qux", "qux")].unwrap());
    /// ```
    pub fn swap_remove(&mut self, index: u32) -> Result<T, IndexOutOfBoundsError> {
        let len = self.len();
        if index >= len {
            return Err(IndexOutOfBoundsError);
        }

        let ptr = self.buf.as_mut_ptr();
        let cap = self.capacity();

        unsafe {
            let value = T::from_tuple(T::TupleRepr::read(ptr, index, cap));

            let src = T::TupleRepr::get_pointers(ptr, len - 1, cap);
            let dst = T::TupleRepr::get_pointers(ptr, index, cap);
            T::TupleRepr::copy(src, dst, 1);

            self.buf.set_len(len - 1);

            Ok(value)
        }
    }
}

impl<T: SoAble> Drop for SoAVec<T> {
    fn drop(&mut self) {
        let len = self.len();
        let cap = self.capacity();
        let ptr = self.buf.as_mut_ptr();
        self.drop_in_place(ptr, cap, len);
        // RawSoAVec's Drop impl deallocates the buffer.
    }
}

impl<T> PartialEq for SoAVec<T>
where
    T: SoAble,
    for<'a> T::Slice<'a>: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.len() == other.len() && self.as_slice() == other.as_slice()
    }
}

impl<T> Eq for SoAVec<T>
where
    T: SoAble,
    for<'a> T::Slice<'a>: Eq,
{
}

impl<T: SoAble> core::default::Default for SoAVec<T> {
    #[inline(always)]
    fn default() -> Self {
        Self::new()
    }
}

impl<T: SoAble> core::fmt::Debug for SoAVec<T>
where
    for<'a> T::Slice<'a>: core::fmt::Debug,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        core::fmt::Debug::fmt(&self.as_slice(), f)
    }
}

impl<T: SoAble> AsRef<SoAVec<T>> for SoAVec<T> {
    #[inline(always)]
    fn as_ref(&self) -> &SoAVec<T> {
        self
    }
}

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

#[cfg(test)]
mod tests {
    use core::marker::PhantomData;

    use crate as soavec;
    use crate::{SoATuple, SoAVec, SoAble};

    #[test]
    fn basic_usage() {
        use soavec_derive::SoAble;

        #[repr(C)]
        #[derive(Debug, Clone, Copy, PartialEq, Eq, SoAble)]
        struct Foo {
            a: u64,
            b: u32,
        }

        /// Conceptually; this is what we're doing here.
        const _ARRAY: [Foo; 16] = [Foo { a: 0, b: 1 }; 16];
        const _SOA_ARRAY: ([u64; 16], [u32; 16]) = ([0; 16], [1; 16]);

        let mut foo = SoAVec::<Foo>::with_capacity(16).unwrap();
        foo.push(Foo { a: 0, b: 2 }).unwrap();
        let first = foo.get(0).unwrap();
        assert_eq!(first.a, &0);
        assert_eq!(first.b, &2);

        let first = foo.get_mut(0).unwrap();
        *first.a = 52;
        *first.b = 66;
        assert_eq!(first.a, &52);
        assert_eq!(first.b, &66);

        let first = foo.get(0).unwrap();
        assert_eq!(first.a, &52);
        assert_eq!(first.b, &66);

        foo.reserve(32).unwrap();
        let first = foo.get(0).unwrap();
        assert_eq!(first.a, &52);
        assert_eq!(first.b, &66);

        foo.push(Foo { a: 4, b: 8 }).unwrap();
        let FooSlice {
            a: a_slice,
            b: b_slice,
        } = foo.as_slice();
        assert_eq!(a_slice.len(), b_slice.len());
        assert_eq!(a_slice.len(), 2);
        assert_eq!(a_slice, &[52, 4]);
        assert_eq!(b_slice, &[66, 8]);
        assert_eq!(foo.pop(), Some(Foo { a: 4, b: 8 }));
    }

    #[test]
    fn basic_usage_with_lifetime() {
        use soavec_derive::SoAble;

        #[repr(C)]
        #[derive(Debug, Clone, Copy, SoAble)]
        struct Foo<'a> {
            a: &'a u64,
            b: &'a u32,
        }

        let mut foo = SoAVec::<Foo>::with_capacity(16).unwrap();
        foo.push(Foo { a: &0, b: &2 }).unwrap();
        let first = foo.get(0).unwrap();
        assert_eq!(first.a, &&0);
        assert_eq!(first.b, &&2);

        let first = foo.get_mut(0).unwrap();
        *first.a = &52;
        *first.b = &66;
        assert_eq!(first.a, &&52);
        assert_eq!(first.b, &&66);

        let first = foo.get(0).unwrap();
        assert_eq!(first.a, &&52);
        assert_eq!(first.b, &&66);

        foo.reserve(32).unwrap();
        let first = foo.get(0).unwrap();
        assert_eq!(first.a, &&52);
        assert_eq!(first.b, &&66);

        foo.push(Foo { a: &4, b: &8 }).unwrap();
        let FooSlice {
            a: a_slice,
            b: b_slice,
        } = foo.as_slice();
        assert_eq!(a_slice.len(), b_slice.len());
        assert_eq!(a_slice.len(), 2);
        assert_eq!(a_slice, &[&52, &4]);
        assert_eq!(b_slice, &[&66, &8]);
    }

    #[test]
    fn more_basic_usage() {
        use soavec_derive::SoAble;

        #[repr(C)]
        #[derive(Debug, Clone, Copy, SoAble)]
        struct Bar {
            a: u64,
            b: u32,
            c: u8,
        }

        let mut bar = SoAVec::<Bar>::with_capacity(16).unwrap();
        bar.reserve(32).unwrap();
        bar.push(Bar { a: 0, b: 2, c: 255 }).unwrap();
        let first = bar.get(0).unwrap();
        assert_eq!(first.a, &0);
        assert_eq!(first.b, &2);
        assert_eq!(first.c, &255);
    }

    #[test]
    fn clear_resets_len() {
        use soavec_derive::SoAble;

        #[repr(C)]
        #[derive(SoAble)]
        struct Foo {
            a: u32,
            b: u64,
        }

        let mut foo = SoAVec::<Foo>::with_capacity(5).unwrap();
        foo.push(Foo { a: 2, b: 0 }).unwrap();
        assert_eq!(foo.len(), 1);

        foo.clear();

        assert_eq!(foo.len(), 0);

        foo.push(Foo { a: 3, b: 0 }).unwrap();
        assert_eq!(foo.len(), 1);
    }

    #[test]
    fn clear_does_not_change_capacity() {
        use soavec_derive::SoAble;

        #[repr(C)]
        #[derive(SoAble)]
        struct Foo {
            a: u32,
            b: u64,
        }

        let mut foo = SoAVec::<Foo>::with_capacity(5).unwrap();
        let cap = foo.capacity();
        foo.push(Foo { a: 2, b: 0 }).unwrap();
        assert_eq!(foo.len(), 1);
        assert_eq!(foo.capacity(), cap);

        foo.clear();

        assert_eq!(foo.len(), 0);
        assert_eq!(foo.capacity(), cap);

        foo.push(Foo { a: 3, b: 0 }).unwrap();
        assert_eq!(foo.len(), 1);
        assert_eq!(foo.capacity(), cap);
    }

    #[test]
    fn clears_all_elements() {
        use soavec_derive::SoAble;
        use std::rc::Rc;

        #[repr(C)]
        #[derive(Debug, Clone, SoAble)]
        struct Foo {
            b: Rc<u32>,
            a: u64,
        }

        let rc1 = Rc::new(2u32);

        let mut foo = SoAVec::<Foo>::with_capacity(5).unwrap();
        foo.push(Foo {
            b: rc1.clone(),
            a: 0,
        })
        .unwrap();

        // `rc1` is referenced two times. Once in `rc1` and once in `foo`.
        assert_eq!(Rc::strong_count(&rc1), 2);

        foo.clear();

        assert_eq!(foo.len(), 0);
        // After clearing, `rc1` should only be referenced once in `rc1`.
        assert_eq!(Rc::strong_count(&rc1), 1);
    }

    #[test]
    fn clears_all_elements_with_droppable() {
        #[repr(C)]
        struct LoudDrop {
            a: (),
            b: (),
        }

        static mut DROP_COUNT: usize = 0;

        impl Drop for LoudDrop {
            fn drop(&mut self) {
                println!("LoudDrop");
                // SAFETY: test is entirely single-threaded.
                unsafe {
                    DROP_COUNT += 1;
                }
            }
        }

        // SAFETY: No internal invariants on fields.
        unsafe impl SoAble for LoudDrop {
            type TupleRepr = ((), ());

            const MUST_DROP_AS_SELF: bool = true;

            type Ref<'a>
                = (&'a (), &'a ())
            where
                Self: 'a;

            type Mut<'a>
                = (&'a mut (), &'a mut ())
            where
                Self: 'a;

            type Slice<'a>
                = (&'a [()], &'a [()])
            where
                Self: 'a;

            type SliceMut<'a>
                = (&'a mut [()], &'a mut [()])
            where
                Self: 'a;

            fn into_tuple(value: Self) -> Self::TupleRepr {
                core::mem::forget(value);
                ((), ())
            }

            fn from_tuple(_value: Self::TupleRepr) -> Self {
                Self { a: (), b: () }
            }

            fn as_ref<'a>(
                _: PhantomData<&'a Self>,
                value: <Self::TupleRepr as SoATuple>::Pointers,
            ) -> Self::Ref<'a> {
                unsafe { (value.0.as_ref(), value.1.as_ref()) }
            }

            fn as_mut<'a>(
                _: PhantomData<&'a mut Self>,
                mut value: <Self::TupleRepr as SoATuple>::Pointers,
            ) -> Self::Mut<'a> {
                unsafe { (value.0.as_mut(), value.1.as_mut()) }
            }

            fn as_slice<'a>(
                _: PhantomData<&'a Self>,
                value: <Self::TupleRepr as SoATuple>::Pointers,
                len: u32,
            ) -> Self::Slice<'a> {
                unsafe {
                    (
                        core::slice::from_raw_parts(value.0.as_ptr(), len as usize),
                        core::slice::from_raw_parts(value.1.as_ptr(), len as usize),
                    )
                }
            }

            fn as_mut_slice<'a>(
                _: PhantomData<&'a mut Self>,
                value: <Self::TupleRepr as SoATuple>::Pointers,
                len: u32,
            ) -> Self::SliceMut<'a> {
                unsafe {
                    (
                        core::slice::from_raw_parts_mut(value.0.as_ptr(), len as usize),
                        core::slice::from_raw_parts_mut(value.1.as_ptr(), len as usize),
                    )
                }
            }
        }

        let mut foo = SoAVec::<LoudDrop>::with_capacity(16).unwrap();
        foo.push(LoudDrop { a: (), b: () }).unwrap();
        foo.push(LoudDrop { a: (), b: () }).unwrap();

        assert_eq!(foo.len(), 2);

        foo.clear();

        assert_eq!(foo.len(), 0);
        assert_eq!(unsafe { DROP_COUNT }, 2);
    }

    #[test]
    fn basic_usage_with_bad_alignment() {
        use soavec_derive::SoAble;

        #[repr(C)]
        #[derive(Debug, Clone, Copy, SoAble)]
        struct Foo {
            b: u32,
            a: u64,
        }

        #[repr(C)]
        #[derive(Debug, Clone, Copy, SoAble)]
        struct Bar {
            c: u8,
            b: u32,
            a: u64,
        }

        let mut foo = SoAVec::<Foo>::with_capacity(5).unwrap();
        foo.reserve(9).unwrap();
        foo.push(Foo { b: 2, a: 0 }).unwrap();
        let first = foo.get(0).unwrap();
        assert_eq!(first.b, &2);
        assert_eq!(first.a, &0);
        // let a_0: &u64 = foo.get_a(0);
        // let a_0: &u32 = foo.get_b(0);
        // let a_n: &[u64] = foo.get_all_a();

        let mut bar = SoAVec::<Bar>::with_capacity(7).unwrap();
        bar.reserve(11).unwrap();
        bar.push(Bar { c: 255, b: 2, a: 0 }).unwrap();
        let first = bar.get(0).unwrap();
        assert_eq!(first.c, &255);
        assert_eq!(first.b, &2);
        assert_eq!(first.a, &0);
    }

    #[test]
    fn insert_and_insert_mut() {
        let mut vec = SoAVec::<(u32, u32)>::new();
        vec.push((1, 10)).unwrap();
        vec.push((3, 30)).unwrap();

        let (first, second) = vec.insert_mut(1, (2, 20)).unwrap();
        *first += 10;
        *second += 5;

        vec.insert(0, (0, 0)).unwrap();

        let slice = vec.as_slice();
        assert_eq!(slice.0, &[0, 1, 12, 3]);
        assert_eq!(slice.1, &[0, 10, 25, 30]);
    }

    #[test]
    fn insert_grows_capacity() {
        let mut vec = SoAVec::<(u32, u32)>::with_capacity(2).unwrap();
        assert_eq!(vec.capacity(), 2);

        vec.push((1, 10)).unwrap();
        vec.push((2, 20)).unwrap();
        assert_eq!(vec.capacity(), 2);

        // Should grow capacity.
        vec.insert(1, (3, 30)).unwrap();
        assert!(vec.capacity() >= 3);

        let slice = vec.as_slice();
        assert_eq!(slice.0, &[1, 3, 2]);
        assert_eq!(slice.1, &[10, 30, 20]);
    }

    #[test]
    fn basic_usage_with_zst() {
        use soavec_derive::SoAble;

        #[repr(C)]
        #[derive(Debug, Clone, Copy, SoAble)]
        struct Foo {
            b: (),
            a: u32,
        }

        #[repr(C)]
        #[derive(Debug, Clone, Copy, SoAble)]
        struct Bar {
            c: u8,
            b: (),
            a: u64,
        }

        #[repr(C)]
        #[derive(Debug, Clone, Copy, SoAble)]
        struct Baz {
            c: (),
            b: (),
            a: (),
        }

        let mut foo = SoAVec::<Foo>::with_capacity(5).unwrap();
        foo.reserve(9).unwrap();
        foo.push(Foo { a: 2, b: () }).unwrap();
        let first = foo.get(0).unwrap();
        assert_eq!(first.b, &());
        assert_eq!(first.a, &2);

        let mut bar = SoAVec::<Bar>::with_capacity(7).unwrap();
        bar.reserve(11).unwrap();
        bar.push(Bar {
            c: 255,
            b: (),
            a: 0,
        })
        .unwrap();
        let first = bar.get(0).unwrap();
        assert_eq!(first.c, &255);
        assert_eq!(first.b, &());
        assert_eq!(first.a, &0);

        let mut baz = SoAVec::<Baz>::with_capacity(7).unwrap();
        baz.reserve(11).unwrap();
        baz.push(Baz {
            a: (),
            b: (),
            c: (),
        })
        .unwrap();
        let first = baz.get(0).unwrap();
        assert_eq!(first.a, &());
        assert_eq!(first.b, &());
        assert_eq!(first.c, &());
    }

    #[test]
    fn droppable_types() {
        use soavec_derive::SoAble;

        #[repr(C)]
        #[derive(Debug, Clone, SoAble)]
        struct Foo {
            a: Vec<u64>,
            b: Box<u32>,
        }

        let mut foo = SoAVec::<Foo>::with_capacity(16).unwrap();
        foo.push(Foo {
            a: vec![0],
            b: Box::new(2),
        })
        .unwrap();
        let first = foo.get(0).unwrap();
        assert_eq!(first.a, &[0]);
        assert_eq!(**first.b, 2);

        let first = foo.get_mut(0).unwrap();
        first.a.push(52);
        *first.b = Box::new(66u32);
        assert_eq!(first.a, &[0, 52]);
        assert_eq!(**first.b, 66u32);

        let first = foo.get(0).unwrap();
        assert_eq!(first.a, &[0, 52]);
        assert_eq!(**first.b, 66u32);

        foo.reserve(32).unwrap();
        let first = foo.get(0).unwrap();
        assert_eq!(first.a, &[0, 52]);
        assert_eq!(**first.b, 66u32);

        foo.push(Foo {
            a: vec![4],
            b: Box::new(8),
        })
        .unwrap();
        let FooSlice {
            a: a_slice,
            b: b_slice,
        } = foo.as_slice();
        assert_eq!(a_slice.len(), b_slice.len());
        assert_eq!(a_slice.len(), 2);
        assert_eq!(a_slice, &[vec![0, 52], vec![4]]);
        assert_eq!(b_slice, &[Box::new(66), Box::new(8)]);
    }

    #[test]
    fn must_drop_as_self_type() {
        #[repr(C)]
        struct LoudDrop {
            a: (),
            b: (),
        }

        static mut DROP_COUNT: usize = 0;

        impl Drop for LoudDrop {
            fn drop(&mut self) {
                println!("LoudDrop");
                // SAFETY: test is entirely single-threaded.
                unsafe {
                    DROP_COUNT += 1;
                }
            }
        }

        // SAFETY: No internal invariants on fields.
        unsafe impl SoAble for LoudDrop {
            type TupleRepr = ((), ());

            const MUST_DROP_AS_SELF: bool = true;

            type Ref<'a>
                = (&'a (), &'a ())
            where
                Self: 'a;

            type Mut<'a>
                = (&'a mut (), &'a mut ())
            where
                Self: 'a;

            type Slice<'a>
                = (&'a [()], &'a [()])
            where
                Self: 'a;

            type SliceMut<'a>
                = (&'a mut [()], &'a mut [()])
            where
                Self: 'a;

            fn into_tuple(value: Self) -> Self::TupleRepr {
                core::mem::forget(value);
                ((), ())
            }

            fn from_tuple(_value: Self::TupleRepr) -> Self {
                Self { a: (), b: () }
            }

            fn as_ref<'a>(
                _: PhantomData<&'a Self>,
                value: <Self::TupleRepr as SoATuple>::Pointers,
            ) -> Self::Ref<'a> {
                unsafe { (value.0.as_ref(), value.1.as_ref()) }
            }

            fn as_mut<'a>(
                _: PhantomData<&'a mut Self>,
                mut value: <Self::TupleRepr as SoATuple>::Pointers,
            ) -> Self::Mut<'a> {
                unsafe { (value.0.as_mut(), value.1.as_mut()) }
            }

            fn as_slice<'a>(
                _: PhantomData<&'a Self>,
                value: <Self::TupleRepr as SoATuple>::Pointers,
                len: u32,
            ) -> Self::Slice<'a> {
                unsafe {
                    (
                        core::slice::from_raw_parts(value.0.as_ptr(), len as usize),
                        core::slice::from_raw_parts(value.1.as_ptr(), len as usize),
                    )
                }
            }

            fn as_mut_slice<'a>(
                _: PhantomData<&'a mut Self>,
                value: <Self::TupleRepr as SoATuple>::Pointers,
                len: u32,
            ) -> Self::SliceMut<'a> {
                unsafe {
                    (
                        core::slice::from_raw_parts_mut(value.0.as_ptr(), len as usize),
                        core::slice::from_raw_parts_mut(value.1.as_ptr(), len as usize),
                    )
                }
            }
        }

        let mut foo = SoAVec::<LoudDrop>::with_capacity(16).unwrap();
        foo.push(LoudDrop { a: (), b: () }).unwrap();
        let _first = foo.get(0).unwrap();
        drop(foo);
        assert_eq!(
            unsafe { DROP_COUNT },
            1,
            "should have dropped a single LoudDrop item"
        );
    }

    #[test]
    fn remove_at_index() {
        use soavec_derive::SoAble;

        #[repr(C)]
        #[derive(Debug, Clone, Copy, PartialEq, Eq, SoAble)]
        struct Foo {
            a: u64,
            b: u32,
        }

        let mut foo = SoAVec::<Foo>::with_capacity(16).unwrap();
        for i in 0..10 {
            foo.push(Foo { a: i, b: i as u32 }).unwrap()
        }

        assert_eq!(foo.len(), 10);

        let removed = foo.remove(4).unwrap();
        assert_eq!(removed, Foo { a: 4, b: 4 });
        assert_eq!(foo.len(), 9);
    }

    #[test]
    fn append_basic() {
        use soavec_derive::SoAble;

        #[repr(C)]
        #[derive(Debug, Clone, Copy, PartialEq, Eq, SoAble)]
        struct Foo {
            a: u64,
            b: u32,
        }

        let mut vec1 = SoAVec::<Foo>::with_capacity(10).unwrap();
        vec1.push(Foo { a: 1, b: 2 }).unwrap();
        vec1.push(Foo { a: 3, b: 4 }).unwrap();

        let mut vec2 = SoAVec::<Foo>::with_capacity(10).unwrap();
        vec2.push(Foo { a: 5, b: 6 }).unwrap();
        vec2.push(Foo { a: 7, b: 8 }).unwrap();
        vec2.push(Foo { a: 9, b: 10 }).unwrap();

        let vec2_cap = vec2.capacity();

        vec1.append(&mut vec2).unwrap();

        assert_eq!(vec1.len(), 5);
        assert_eq!(vec2.len(), 0);
        assert!(vec2.is_empty());
        assert_eq!(vec2.capacity(), vec2_cap);

        let elem0 = vec1.get(0).unwrap();
        assert_eq!(elem0.a, &1);
        assert_eq!(elem0.b, &2);

        let elem1 = vec1.get(1).unwrap();
        assert_eq!(elem1.a, &3);
        assert_eq!(elem1.b, &4);

        let elem2 = vec1.get(2).unwrap();
        assert_eq!(elem2.a, &5);
        assert_eq!(elem2.b, &6);

        let elem3 = vec1.get(3).unwrap();
        assert_eq!(elem3.a, &7);
        assert_eq!(elem3.b, &8);

        let elem4 = vec1.get(4).unwrap();
        assert_eq!(elem4.a, &9);
        assert_eq!(elem4.b, &10);
    }

    #[test]
    fn append_empty_to_non_empty() {
        use soavec_derive::SoAble;

        #[repr(C)]
        #[derive(Debug, Clone, Copy, PartialEq, Eq, SoAble)]
        struct Foo {
            a: u32,
            b: u64,
        }

        let mut vec1 = SoAVec::<Foo>::new();
        vec1.push(Foo { a: 1, b: 2 }).unwrap();

        let mut vec2 = SoAVec::<Foo>::new();

        vec1.append(&mut vec2).unwrap();

        assert_eq!(vec1.len(), 1);
        assert_eq!(vec2.len(), 0);

        let elem0 = vec1.get(0).unwrap();
        assert_eq!(elem0.a, &1);
        assert_eq!(elem0.b, &2);
    }

    #[test]
    fn append_non_empty_to_empty() {
        use soavec_derive::SoAble;

        #[repr(C)]
        #[derive(Debug, Clone, Copy, PartialEq, Eq, SoAble)]
        struct Foo {
            a: u32,
            b: u64,
        }

        let mut vec1 = SoAVec::<Foo>::new();

        let mut vec2 = SoAVec::<Foo>::new();
        vec2.push(Foo { a: 1, b: 2 }).unwrap();
        vec2.push(Foo { a: 3, b: 4 }).unwrap();

        vec1.append(&mut vec2).unwrap();

        assert_eq!(vec1.len(), 2);
        assert_eq!(vec2.len(), 0);

        let elem0 = vec1.get(0).unwrap();
        assert_eq!(elem0.a, &1);
        assert_eq!(elem0.b, &2);

        let elem1 = vec1.get(1).unwrap();
        assert_eq!(elem1.a, &3);
        assert_eq!(elem1.b, &4);
    }

    #[test]
    fn append_with_droppable_types() {
        use soavec_derive::SoAble;
        use std::rc::Rc;

        #[repr(C)]
        #[derive(Debug, Clone, SoAble)]
        struct Foo {
            a: Rc<u64>,
            b: Vec<u32>,
        }

        let mut vec1 = SoAVec::<Foo>::new();
        vec1.push(Foo {
            a: Rc::new(42),
            b: vec![1, 2, 3],
        })
        .unwrap();

        let mut vec2 = SoAVec::<Foo>::new();
        let shared_rc = Rc::new(84);
        vec2.push(Foo {
            a: shared_rc.clone(),
            b: vec![4, 5],
        })
        .unwrap();
        vec2.push(Foo {
            a: Rc::new(168),
            b: vec![6],
        })
        .unwrap();

        assert_eq!(Rc::strong_count(&shared_rc), 2);

        vec1.append(&mut vec2).unwrap();

        assert_eq!(vec1.len(), 3);
        assert_eq!(vec2.len(), 0);
        assert_eq!(Rc::strong_count(&shared_rc), 2);

        let first = vec1.get(0).unwrap();
        assert_eq!(**first.a, 42);
        assert_eq!(first.b, &[1, 2, 3]);

        let second = vec1.get(1).unwrap();
        assert_eq!(**second.a, 84);
        assert_eq!(second.b, &[4, 5]);

        let third = vec1.get(2).unwrap();
        assert_eq!(**third.a, 168);
        assert_eq!(third.b, &[6]);
    }

    #[test]
    fn extend_from_slice_basic() {
        use soavec_derive::SoAble;

        #[repr(C)]
        #[derive(Debug, Clone, Copy, PartialEq, Eq, SoAble)]
        struct Foo {
            a: u64,
            b: u32,
        }

        let mut vec = SoAVec::<Foo>::new();
        vec.push(Foo { a: 1, b: 2 }).unwrap();
        vec.push(Foo { a: 3, b: 4 }).unwrap();

        let slice = &[Foo { a: 5, b: 6 }, Foo { a: 7, b: 8 }, Foo { a: 9, b: 10 }];
        vec.extend_from_slice(slice).unwrap();

        assert_eq!(vec.len(), 5);

        let elem0 = vec.get(0).unwrap();
        assert_eq!(elem0.a, &1);
        assert_eq!(elem0.b, &2);

        let elem1 = vec.get(1).unwrap();
        assert_eq!(elem1.a, &3);
        assert_eq!(elem1.b, &4);

        let elem2 = vec.get(2).unwrap();
        assert_eq!(elem2.a, &5);
        assert_eq!(elem2.b, &6);

        let elem3 = vec.get(3).unwrap();
        assert_eq!(elem3.a, &7);
        assert_eq!(elem3.b, &8);

        let elem4 = vec.get(4).unwrap();
        assert_eq!(elem4.a, &9);
        assert_eq!(elem4.b, &10);
    }

    #[test]
    fn extend_from_slice_empty() {
        use soavec_derive::SoAble;

        #[repr(C)]
        #[derive(Debug, Clone, Copy, PartialEq, Eq, SoAble)]
        struct Foo {
            a: u32,
            b: u64,
        }

        let mut vec = SoAVec::<Foo>::new();
        vec.push(Foo { a: 1, b: 2 }).unwrap();

        let empty_slice: &[Foo] = &[];
        vec.extend_from_slice(empty_slice).unwrap();

        assert_eq!(vec.len(), 1);

        let elem0 = vec.get(0).unwrap();
        assert_eq!(elem0.a, &1);
        assert_eq!(elem0.b, &2);
    }

    #[test]
    fn extend_from_slice_to_empty() {
        use soavec_derive::SoAble;

        #[repr(C)]
        #[derive(Debug, Clone, Copy, PartialEq, Eq, SoAble)]
        struct Foo {
            a: u32,
            b: u64,
        }

        let mut vec = SoAVec::<Foo>::new();

        let slice = &[Foo { a: 1, b: 2 }, Foo { a: 3, b: 4 }];
        vec.extend_from_slice(slice).unwrap();

        assert_eq!(vec.len(), 2);

        let elem0 = vec.get(0).unwrap();
        assert_eq!(elem0.a, &1);
        assert_eq!(elem0.b, &2);

        let elem1 = vec.get(1).unwrap();
        assert_eq!(elem1.a, &3);
        assert_eq!(elem1.b, &4);
    }

    #[test]
    fn extend_from_slice_with_droppable_types() {
        use soavec_derive::SoAble;
        use std::rc::Rc;

        #[repr(C)]
        #[derive(Debug, Clone, SoAble)]
        struct Foo {
            a: Rc<u64>,
            b: Vec<u32>,
        }

        let mut vec = SoAVec::<Foo>::new();
        vec.push(Foo {
            a: Rc::new(42),
            b: vec![1, 2, 3],
        })
        .unwrap();

        let shared_rc = Rc::new(84);
        let slice = &[
            Foo {
                a: shared_rc.clone(),
                b: vec![4, 5],
            },
            Foo {
                a: Rc::new(168),
                b: vec![6],
            },
        ];

        assert_eq!(Rc::strong_count(&shared_rc), 2);

        vec.extend_from_slice(slice).unwrap();

        assert_eq!(vec.len(), 3);
        assert_eq!(Rc::strong_count(&shared_rc), 3); // original + slice + vec

        let first = vec.get(0).unwrap();
        assert_eq!(**first.a, 42);
        assert_eq!(first.b, &[1, 2, 3]);

        let second = vec.get(1).unwrap();
        assert_eq!(**second.a, 84);
        assert_eq!(second.b, &[4, 5]);

        let third = vec.get(2).unwrap();
        assert_eq!(**third.a, 168);
        assert_eq!(third.b, &[6]);
    }
}