tiny-vec 0.10.1

Small vector optimization
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
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
/*  Copyright (C) 2025 Saúl Valdelvira
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, version 3.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <https://www.gnu.org/licenses/>. */

//! Tiny Vec
//!
//! A dynamic array that can store a small amount of elements on the stack.
//!
//! This struct provides a vec-like API, but performs small-vector optimization.
//! This means that a `TinyVec<T, N>` stores up to N elements on the stack.
//! If the vector grows bigger than that, it moves the contents to the heap.
#![cfg_attr(not(feature = "alloc"), doc = "
# WARNING
The `alloc` feature is disabled. This means that a `TinyVec` won't be able to
grow over it's stack capacity.

The following functions from [TinyVec] can cause the program to panic if the vector exceeds its
capacity.
- [with_capacity]
- [from_array](TinyVec::from_array)
- [from_tiny_vec](TinyVec::from_tiny_vec)
- [from_slice_copied](TinyVec::from_slice_copied)
- [repeat](TinyVec::repeat)
- [reserve]
- [reserve_exact]
- [push]
- [push_unchecked](TinyVec::push_unchecked)
- [insert](TinyVec::insert)
- [insert_unchecked](TinyVec::insert_unchecked)
- [insert_slice](TinyVec::insert_slice)
- [insert_slice_copied](TinyVec::insert_slice_copied)
- [insert_iter](TinyVec::insert_iter)
- [resize](TinyVec::resize)
- [reserve](TinyVec::reserve)
- [resize_with](TinyVec::resize_with)
- [resize_zeroed](TinyVec::resize_zeroed)
- [extend_from_slice](TinyVec::extend_from_slice)
- [copy_from_slice](TinyVec::copy_from_slice)
- [extend_from_within](TinyVec::extend_from_within)
- [extend_from_within_copied](TinyVec::extend_from_within_copied)
- [append](TinyVec::append)

## Alternatives
| May Panic | No Panic |
| --------- | -------- |
|  [push]   | [push_within_capacity](TinyVec::push_within_capacity) |
|  [reserve]   | [try_reserve](TinyVec::try_reserve) |
|  [reserve_exact]   | [try_reserve_exact](TinyVec::try_reserve) |
| [with_capacity] | [try_with_capacity](TinyVec::try_with_capacity) |

[push]: TinyVec::push
[reserve]: TinyVec::reserve
[reserve_exact]: TinyVec::reserve_exact
[with_capacity]: TinyVec::with_capacity
")]
//!
//! # Example
//! ```
//! use tiny_vec::TinyVec;
//!
//! let mut tv = TinyVec::<u8, 16>::new();
//!
//! for n in 0..16 {
//!     tv.push(n);
//! }
//!
//! // Up to this point, no heap allocations are needed.
//! // All the elements are stored on the stack.
//!
//! tv.push(123); // This moves the vector to the heap
//!
//! assert_eq!(&tv[..], &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
//!                       10, 11, 12, 13, 14, 15, 123])
//! ```
//!
//! # Memory layout
//! For a TinyVec<T, N>
//!
//! On the stack (length <= N)
//! - [T; N] : Data
//! - usize  : Length
//!
//! On the heap (length > N)
//! - T*    : Data
//! - usize : Capacity
//! - usize : Length
//!
//! If N is equal to `sizeof (T*, usize) / sizeof T`, the
//! TinyVec is the same size as a regular vector \
//! NOTE: The [n_elements_for_stack] function returns the maximun
//! number of elements for a type, such that it doesn't waste extra
//! space when moved to the heap

#![allow(incomplete_features)]
#![cfg_attr(feature = "use-nightly-features", feature(min_specialization, slice_swap_unchecked, generic_const_exprs))]
#![cfg_attr(feature = "use-nightly-features", feature(extend_one, extend_one_unchecked))]
#![cfg_attr(feature = "use-nightly-features", feature(iter_advance_by))]
#![cfg_attr(feature = "use-nightly-features", feature(can_vector, write_all_vectored))]

#![no_std]

#[cfg(feature = "alloc")]
extern crate alloc;
#[cfg(feature = "alloc")]
use alloc::{
    vec::Vec,
    boxed::Box,
    collections::VecDeque,
};
use drain::Drain;
use extract_if::ExtractIf;
#[cfg(feature = "serde")]
use serde::Deserialize;

use core::borrow::{Borrow, BorrowMut};
use core::hash::Hash;
use core::marker::PhantomData;
use core::mem::{self, ManuallyDrop, MaybeUninit};
use core::ops::{Bound, Deref, DerefMut, Range, RangeBounds};
use core::ptr::NonNull;
use core::{fmt, ptr};
use core::slice;

mod raw;
use raw::RawVec;
pub use raw::ResizeError;

mod cow;
pub use cow::Cow;

pub mod iter;
pub mod drain;
pub mod extract_if;

union TinyVecInner<T, const N: usize> {
    stack: ManuallyDrop<[MaybeUninit<T>; N]>,
    raw: RawVec<T>,
}

impl<T, const N: usize> TinyVecInner<T, N> {
    #[inline(always)]
    const unsafe fn as_ptr_stack(&self) -> *const T {
        unsafe { &raw const self.stack as *const T }
    }

    #[inline(always)]
    const unsafe fn as_ptr_stack_mut(&mut self) -> *mut T {
        unsafe { &raw mut self.stack as *mut T }
    }

    #[inline(always)]
    const unsafe fn as_ptr_heap(&self) -> *const T {
        unsafe { self.raw.ptr.as_ptr() }
    }

    #[inline(always)]
    const unsafe fn as_ptr_heap_mut(&mut self) -> *mut T {
        unsafe { self.raw.ptr.as_ptr() }
    }
}

#[repr(transparent)]
struct Length(usize);

impl Length {
    #[inline(always)]
    const fn new_stack(len: usize) -> Self {
        Self(len << 1)
    }

    #[inline(always)]
    #[cfg(feature = "alloc")]
    const fn new_heap(len: usize) -> Self {
        Self(len << 1 | 0b1)
    }

    #[inline(always)]
    const fn is_stack(&self) -> bool {
        (self.0 & 0b1) == 0
    }

    #[inline(always)]
    const fn set_heap(&mut self) {
        self.0 |= 0b1;
    }

    #[inline(always)]
    #[cfg(feature = "alloc")]
    const fn set_stack(&mut self) {
        self.0 &= 0b0;
    }

    #[inline(always)]
    const fn set(&mut self, n: usize) {
        self.0 &= 0b1;
        self.0 |= n << 1;
    }

    #[inline(always)]
    const fn get(&self) -> usize {
        self.0 >> 1
    }

    #[inline(always)]
    const fn add(&mut self, n: usize) {
        self.0 += n << 1;
    }

    #[inline(always)]
    const fn sub(&mut self, n: usize) {
        self.0 -= n << 1;
    }
}

/// Macro to create [TinyVec]s
///
/// # Example
/// ```
/// use tiny_vec::{TinyVec, tinyvec};
///
/// // Create a TinyVec with a list of elements
/// let v: TinyVec<_, 10> = tinyvec![1, 2, 3, 4];
/// assert_eq!(&v[0..4], &[1, 2, 3, 4]);
///
/// // Create a TinyVec with 100 zeroes
/// let v: TinyVec<_, 10> = tinyvec![0; 100];
/// assert_eq!(v[20], 0);
/// ```
#[macro_export]
macro_rules! tinyvec {
    (@one $e:expr) => { 1 };
    () => {
        $crate::TinyVec::new()
    };
    ($elem:expr; $n:expr) => ({
        let mut tv = $crate::TinyVec::new();
        tv.resize($n, $elem);
        tv
    });
    ($($x:expr),+ $(,)?) => ({
        let n = const {
            0 $( + $crate::tinyvec!(@one $x) )+
        };
        let mut vec = $crate::TinyVec::with_capacity(n);
        $(vec.push($x);)+
        vec
    });
}

/// The maximun number of elements that can be stored in the stack
/// for the vector, without incrementing it's size
///
/// This means, that [`n_elements_for_stack`] for T returns the max
/// number of elements, so that when switching to a heap allocated
/// buffer, no stack size is wasted
///
/// # Examples
/// ```
/// use tiny_vec::n_elements_for_stack;
///
/// assert_eq!(n_elements_for_stack::<u8>(), 16);
/// assert_eq!(n_elements_for_stack::<u16>(), 8);
/// assert_eq!(n_elements_for_stack::<i32>(), 4);
/// ```
pub const fn n_elements_for_stack<T>() -> usize {
    n_elements_for_bytes::<T>(mem::size_of::<RawVec<T>>())
}

/// The maximun number of elements of type T, that can be stored on
/// the given byte size
///
/// # Examples
/// ```
/// use tiny_vec::n_elements_for_bytes;
///
/// assert_eq!(n_elements_for_bytes::<u8>(2), 2);
/// assert_eq!(n_elements_for_bytes::<u16>(4), 2);
/// assert_eq!(n_elements_for_bytes::<i32>(17), 4);
/// ```
pub const fn n_elements_for_bytes<T>(n: usize) -> usize {
    let size = mem::size_of::<T>();
    if size == 0 {
        isize::MAX as usize
    } else {
        n / size
    }
}

fn slice_range<R>(range: R, len: usize) -> Range<usize>
where
    R: RangeBounds<usize>
{
    let start = match range.start_bound() {
        Bound::Included(n) => *n,
        Bound::Excluded(n) => *n + 1,
        Bound::Unbounded => 0,
    };

    let end = match range.end_bound() {
        Bound::Included(n) => *n + 1,
        Bound::Excluded(n) => *n,
        Bound::Unbounded => len,
    };

    assert!(start <= end);
    assert!(end <= len);

    Range { start, end }
}

/// A dynamic array that can store a small amount of elements on the stack.
pub struct TinyVec<T,
    #[cfg(not(feature = "use-nightly-features"))]
    const N: usize,

    #[cfg(feature = "use-nightly-features")]
    const N: usize = { n_elements_for_stack::<T>() },
> {
    inner: TinyVecInner<T, N>,
    len: Length,
}

impl<T, const N: usize> TinyVec<T, N> {

    unsafe fn switch_to_heap(&mut self, n: usize, exact: bool) -> Result<(), ResizeError> {
        debug_assert!(self.lives_on_stack());
        debug_assert_ne!(mem::size_of::<T>(), 0);

        let mut vec = RawVec::new();
        if exact {
            vec.try_expand_if_needed_exact(0, self.len.get() + n)?;
        } else {
            vec.try_expand_if_needed(0, self.len.get() + n)?;
        }
        unsafe {
            let src = self.inner.as_ptr_stack();
            let dst = vec.ptr.as_ptr();
            ptr::copy_nonoverlapping(src, dst, self.len());
            self.inner.raw = vec;
        }
        self.len.set_heap();

        Ok(())
    }

    #[cfg(feature = "alloc")]
    unsafe fn switch_to_stack(&mut self) {
        debug_assert!(!self.lives_on_stack());
        debug_assert_ne!(mem::size_of::<T>(), 0,
            "We shouldn't call switch_to_stack, since T is a ZST, and\
            shouldn't be moved to the heap in the first place");

        let mut rv = unsafe { self.inner.raw };

        let mut stack = [const { MaybeUninit::uninit() }; N];

        unsafe {
            let src = rv.ptr.as_ptr();
            let dst = stack.as_mut_ptr() as *mut T;
            ptr::copy_nonoverlapping(src,dst,self.len());
            rv.destroy();
        }

        self.inner.stack =  ManuallyDrop::new(stack);
        self.len.set_stack();
    }

    const fn split_at_spare_mut_with_len(&mut self) -> (&mut [T], &mut [MaybeUninit<T>], &mut Length) {
        unsafe {
            let len = self.len();
            let ptr = self.as_mut_ptr();

            let spare_ptr = ptr.add(len).cast::<MaybeUninit<T>>();
            let spare_len = self.capacity() - len;

            let slice = slice::from_raw_parts_mut(ptr, len);
            let spare_slice = slice::from_raw_parts_mut(spare_ptr, spare_len);

            (slice, spare_slice, &mut self.len)
        }
    }

    #[cfg(feature = "alloc")]
    fn _shrink(&mut self, cap: usize) {
        assert!(!self.lives_on_stack());
        assert!(cap >= self.len.get());

        /* SAFETY: It's safe to assume that we are on the heap,
         * because of the assertion above */
        if cap <= N {
            unsafe { self.switch_to_stack(); }
        } else {
            unsafe { self.inner.raw.shrink_to_fit(cap); };
        }
    }
}

impl<T, const N: usize> TinyVec<T, N> {

    /// Creates a new [TinyVec]
    #[must_use]
    pub const fn new() -> Self {
        let stack = [ const { MaybeUninit::uninit() }; N ];
        Self {
            inner: TinyVecInner { stack: ManuallyDrop::new(stack) },
            len: Length::new_stack(0),
        }
    }

    /// Creates a new [TinyVec] with the specified initial capacity
    #[must_use]
    pub fn with_capacity(cap: usize) -> Self {
        Self::try_with_capacity(cap).unwrap_or_else(|err| err.handle())
    }

    /// Like [with_capacity](Self::with_capacity), but it returns a [Result].
    ///
    /// If an allocation error hapens when reserving the memory, returns
    /// a [ResizeError] unlike [with_capacity](Self::with_capacity), which
    /// panics in such case.
    pub fn try_with_capacity(cap: usize) -> Result<Self,ResizeError> {
        let mut len = Length(0);
        let inner = if cap <= N {
            let s = [const { MaybeUninit::uninit() }; N];
            TinyVecInner {
                stack: ManuallyDrop::new(s)
            }
        } else {
            len.set_heap();
            TinyVecInner {
                raw: RawVec::try_with_capacity(cap)?
            }
        };

        Ok(Self { inner, len })
    }

    /// Creates a new [TinyVec] from the given array
    ///
    /// # Example
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let tv = TinyVec::<i32, 10>::from_array([1, 2, 3, 4]);
    ///
    /// assert_eq!(tv.capacity(), 10);
    /// assert!(tv.lives_on_stack());
    /// ```
    #[must_use]
    pub fn from_array<const M: usize>(arr: [T; M]) -> Self {
        let arr = ManuallyDrop::new(arr);
        let mut tv = Self::with_capacity(M);

        let src = arr.as_ptr();
        let dst = tv.as_mut_ptr();

        unsafe {
            ptr::copy(src, dst, M);
            tv.set_len(M);
        }

        tv
    }

    /// Like [from_array](Self::from_array), but the array's length
    /// and the TinyVec's N are equal, so we can call it on const functions.
    ///
    /// # Example
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let tv = TinyVec::from_array_eq_size([1, 2, 3, 4]);
    ///
    /// assert_eq!(tv.capacity(), 4);
    /// assert!(tv.lives_on_stack());
    /// ```
    #[must_use]
    pub const fn from_array_eq_size(arr: [T; N]) -> Self {
        let mut tv = Self::new();

        let src = arr.as_ptr();
        let dst = tv.as_mut_ptr();

        unsafe {
            ptr::copy(src, dst, N);
            tv.set_len(N);
        }

        mem::forget(arr);
        tv
    }

    /// Creates a new [TinyVec] from the given [Vec]
    ///
    /// # Example
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let vec = vec![1, 2, 3, 4, 5];
    ///
    /// let tv = TinyVec::<i32, 10>::from_vec(vec);
    ///
    /// assert_eq!(tv, &[1, 2, 3, 4, 5]);
    /// ```
    #[cfg(feature = "alloc")]
    #[must_use]
    pub fn from_vec(vec: Vec<T>) -> Self {
        let mut vec = ManuallyDrop::new(vec);

        let ptr = vec.as_mut_ptr();
        let ptr = unsafe { NonNull::new_unchecked(ptr) };

        let len = Length::new_heap(vec.len());
        let cap = vec.capacity();
        let raw = RawVec { cap, ptr };

        let inner = TinyVecInner { raw };
        Self { inner, len }
    }

    /// Creates a TinyVec from a boxed slice of T
    #[cfg(feature = "alloc")]
    #[must_use]
    pub fn from_boxed_slice(boxed: Box<[T]>) -> Self {
        let len = boxed.len();
        let ptr = Box::into_raw(boxed);
        let ptr = unsafe { NonNull::new_unchecked(ptr as *mut T) };

        let raw = RawVec { ptr, cap: len };

        Self {
            inner: TinyVecInner { raw },
            len: Length::new_heap(len)
        }
    }

    /// Builds a TinyVec from a TinyVec with a different capacity generic parameter
    ///
    /// # Example
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let v1 = TinyVec::<i32, 10>::from(&[1, 2, 3, 4]);
    ///
    /// let v2 = TinyVec::<i32, 7>::from_tiny_vec(v1.clone());
    /// assert!(v2.lives_on_stack());
    ///
    /// let v3 = TinyVec::<i32, 2>::from_tiny_vec(v1);
    /// /* v3 must be heap-allocated, since it can only store 2 elements
    ///    on the stack, and v1 has 3*/
    /// assert!(!v3.lives_on_stack());
    /// ```
    #[must_use]
    pub fn from_tiny_vec<const M: usize>(mut vec: TinyVec<T, M>) -> Self {
        let len = vec.len();

        /* When alloc is disabled, it's impossible that the legth
         * of a TinyVec exceeds it's stack-capacity */
        #[cfg(feature = "alloc")]
        if len > N && len > M {
            /* If the buffer must be on the heap on both src and dest,
            * just copy the RawVec from vec to Self */
            let tv = Self {
                len: Length::new_heap(len),
                inner: TinyVecInner {
                    raw: unsafe { vec.inner.raw }
                }
            };
            mem::forget(vec);
            return tv
        }

        let mut tv = Self::with_capacity(len);
        let src = vec.as_ptr();
        let dst = tv.as_mut_ptr();
        unsafe {
            /* SAFETY: src points to vec, and dst to tv. They are two different
             * objects, so their buffers can't overap */
            ptr::copy_nonoverlapping(src, dst, len);
            vec.set_len(0);
            tv.set_len(len);
        }
        tv
    }

    /// Creates a new [TinyVec] from the given slice.
    ///
    /// This function clones the elements in the slice.
    /// If the type T is [Copy], the [from_slice_copied](Self::from_slice_copied)
    /// function is a more optimized alternative
    pub fn from_slice(slice: &[T]) -> Self
    where
        T: Clone
    {
        let mut v = Self::with_capacity(slice.len());
        v.extend_from_slice_impl(slice);
        v
    }

    /// Creates a new [TinyVec] from the given slice.
    ///
    /// This function copies the slice into the buffer, which
    /// is faster that calling [clone](Clone::clone).
    /// That's why it requires T to implement [Copy].
    ///
    /// For a cloning alternative, use [from_slice](Self::from_slice)
    #[must_use]
    pub fn from_slice_copied(slice: &[T]) -> Self
    where
        T: Copy
    {
        let mut v = Self::with_capacity(slice.len());
        v.copy_from_slice(slice);
        v
    }

    /// Creates a new [TinyVec] by copying the given
    /// `slice` `n` times.
    ///
    /// # Example
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let vec = TinyVec::<i32, 10>::repeat(
    ///     &[1, 2, 3, 4],
    ///     3
    /// );
    ///
    /// assert_eq!(vec, &[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]);
    /// ```
    #[must_use]
    pub fn repeat(slice: &[T], n: usize) -> Self
    where
        T: Copy
    {
        let mut s = Self::with_capacity(slice.len() * n);
        let mut dst = s.as_mut_ptr();
        let src = slice.as_ptr();
        let len = slice.len();
        for _ in 0..n {
            unsafe {
                ptr::copy(src, dst, len);
                dst = dst.add(len);
            }
        }
        s.len.set(len * n);
        s
    }

    /// Returns the number of elements inside this vec
    #[inline]
    pub const fn len(&self) -> usize { self.len.get() }

    /// Returns true if the vector is empty
    #[inline]
    pub const fn is_empty(&self) -> bool { self.len.get() == 0 }

    /// Returns the allocated capacity for this vector
    #[inline]
    pub const fn capacity(&self) -> usize {
        if mem::size_of::<T>() == 0 {
            return isize::MAX as usize
        }
        if self.len.is_stack() {
            N
        } else {
            unsafe { self.inner.raw.cap }
        }
    }

    /// Returns true if the vector is currently using stack memory.
    ///
    /// This means that [Self::len] <= `N`
    ///
    /// # Example
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let mut vec = TinyVec::<i32, 5>::new();
    ///
    /// for n in 0..5 {
    ///     vec.push(n)
    /// }
    ///
    /// assert!(vec.lives_on_stack());
    /// vec.push(6);
    /// assert!(!vec.lives_on_stack());
    /// ```
    #[inline]
    pub const fn lives_on_stack(&self) -> bool { self.len.is_stack() }

    /// Gets a const pointer to the vec's buffer
    #[inline]
    pub const fn as_ptr(&self) -> *const T {
        unsafe {
            if self.len.is_stack() {
                self.inner.as_ptr_stack()
            } else {
                self.inner.as_ptr_heap()
            }
        }
    }

    /// Gets a mutable pointer to the vec's buffer
    #[inline]
    pub const fn as_mut_ptr(&mut self) -> *mut T {
        unsafe {
            if self.len.is_stack() {
                self.inner.as_ptr_stack_mut()
            } else {
                self.inner.as_ptr_heap_mut()
            }
        }
    }

    /// Gets a mutable pointer to the vec's buffer as a [NonNull]
    #[inline]
    pub const fn as_non_null(&mut self) -> NonNull<T> {
        debug_assert!(!self.as_mut_ptr().is_null());
        unsafe {
            /* SAFETY: as_mut_ptr should never return a null ptr */
            NonNull::new_unchecked(self.as_mut_ptr())
        }
    }

    /// Gets a slice of the whole vector
    #[inline]
    pub const fn as_slice(&self) -> &[T] {
        unsafe {
            slice::from_raw_parts(self.as_ptr(), self.len.get())
        }
    }

    /// Gets a mutable slice of the whole vector
    #[inline]
    pub const fn as_mut_slice(&mut self) -> &mut [T] {
        unsafe {
            slice::from_raw_parts_mut(self.as_mut_ptr(), self.len.get())
        }
    }

    /// Reserves space for, at least, n elements
    ///
    /// # Panics
    /// If an allocation error happens. For a non-panicking version
    /// see [try_reserve](Self::try_reserve)
    ///
    /// # Example
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let mut vec = TinyVec::<i32, 5>::new();
    ///
    /// assert_eq!(vec.capacity(), 5);
    /// assert!(vec.lives_on_stack());
    /// vec.reserve(10);
    /// assert!(vec.capacity() >= 10);
    /// assert!(!vec.lives_on_stack());
    /// ```
    #[inline]
    pub fn reserve(&mut self, n: usize) {
        self.try_reserve(n).unwrap_or_else(|err| err.handle());
    }

    /// Like [reserve](Self::reserve), but on failure returns an [Err] variant
    /// with a [ResizeError], instead of panicking.
    ///
    /// # Example
    /// ```
    /// use tiny_vec::{TinyVec, ResizeError};
    ///
    /// let mut tv = TinyVec::<u64, 10>::new();
    ///
    /// assert_eq!(
    ///     tv.try_reserve(isize::MAX as usize),
    ///     Err(ResizeError::AllocationExceedsMaximun)
    /// );
    /// ```
    pub fn try_reserve(&mut self, n: usize) -> Result<(), ResizeError> {
        if self.len.is_stack() {
            if self.len.get() + n > self.capacity() {
                unsafe { self.switch_to_heap(n, false)?; }
            }
        } else {
            unsafe {
                self.inner.raw.try_expand_if_needed(self.len.get(), n)?;
            }
        }
        Ok(())
    }

    /// Reserves space for n more elements, but unlike
    /// [reserve](Self::reserve), this function doesn't over-allocate.
    ///
    /// # Panics
    /// If an allocation error happens. For a non-panicking version
    /// see [try_reserve_exact](Self::try_reserve_exact)
    ///
    /// # Example
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let mut vec = TinyVec::<i32, 5>::new();
    ///
    /// assert_eq!(vec.capacity(), 5);
    /// assert!(vec.lives_on_stack());
    /// vec.reserve_exact(10);
    /// assert_eq!(vec.capacity(), 10);
    /// assert!(!vec.lives_on_stack());
    /// ```
    pub fn reserve_exact(&mut self, n: usize) {
        self.try_reserve_exact(n).unwrap_or_else(|err| err.handle())
    }

    /// Like [resize](Self::resize), but on failure returns an [Err] variant
    /// with a [ResizeError], instead of panicking.
    pub fn try_reserve_exact(&mut self, n: usize) -> Result<(), ResizeError> {
        if self.len.is_stack() {
            if self.len.get() + n > self.capacity() {
                unsafe { self.switch_to_heap(n, true)?; }
            }
        } else {
            let vec = unsafe { &mut self.inner.raw };
            let len = self.len.get();
            let new_cap = vec.cap.max(len + n);
            vec.try_expand_if_needed_exact(len, new_cap)?;
        }
        Ok(())
    }

    /// Appends an element to the back of the vector
    /// This operation is O(1), if no resize takes place.
    /// If the buffer needs to be resized, it has an O(n)
    /// time complexity.
    ///
    /// See also: [push_within_capacity](Self::push_within_capacity)
    ///
    /// # Example
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let mut vec = TinyVec::<i32, 5>::from(&[1, 2, 3, 4]);
    ///
    /// vec.push(5); // No resize. O(1)
    /// vec.push(6); // Resize, must realloc. O(n)
    ///
    /// assert_eq!(vec.as_slice(), &[1, 2, 3, 4, 5, 6]);
    /// ```
    #[inline]
    pub fn push(&mut self, elem: T) {
        self.reserve(1);
        unsafe { self.push_unchecked(elem); }
    }

    /// Appends an element to the back of the vector without
    /// checking for space.
    ///
    /// # Safety
    /// The caller must ensure that there's enought capacity
    /// for this element.
    /// This means that [Self::len] < [Self::capacity]
    ///
    /// # Example
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let mut vec = TinyVec::<i32, 10>::with_capacity(10);
    ///
    /// // We've allocated a TinyVec with an initial capacity of 10.
    /// // We can skip the bounds checking, since there will be room
    /// // for all the elements on the iterator
    /// for n in 0..10 {
    ///     unsafe { vec.push_unchecked(n); }
    /// }
    /// assert_eq!(vec.as_slice(), &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    /// ```
    pub unsafe fn push_unchecked(&mut self, elem: T) {
        unsafe {
            let dst = self.as_mut_ptr().add(self.len.get());
            dst.write(elem);
        }
        self.len.add(1);
    }

    /// Try to push an element inside the vector, only if
    /// there's room for it. If the push would've caused a
    /// reallocation of the buffer, returns the value wrapped
    /// on an [Err] variant.
    ///
    /// This operation has O(1) time complexity in all cases.
    ///
    /// # Example
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let mut vec = TinyVec::<i32, 5>::from(&[1, 2, 3, 4]);
    ///
    /// assert!(vec.push_within_capacity(5).is_ok());
    ///
    /// // No room left, the value is returned
    /// assert_eq!(vec.push_within_capacity(6), Err(6));
    /// ```
    pub fn push_within_capacity(&mut self, val: T) -> Result<(),T> {
        if self.len.get() < self.capacity() {
            unsafe { self.push_unchecked(val); }
            Ok(())
        } else {
            Err(val)
        }
    }
    /// Removes the last element of this vector (if present)
    pub const fn pop(&mut self) -> Option<T> {
        if self.len.get() == 0 {
            None
        } else {
            self.len.sub(1);
            let val = unsafe {
                self.as_ptr()
                    .add(self.len.get())
                    .read()
            };
            Some(val)
        }
    }

    /// Removes and returns the last element from a vector if the `predicate`
    /// returns true, or [None] if the predicate returns false or the vector
    /// is empty (the predicate will not be called in that case).
    ///
    /// # Example
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let mut vec = TinyVec::from([1, 2, 3, 4]);
    /// let pred = |x: &mut i32| *x % 2 == 0;
    ///
    /// assert_eq!(vec.pop_if(pred), Some(4));
    /// assert_eq!(vec, [1, 2, 3]);
    /// assert_eq!(vec.pop_if(pred), None);
    /// ```
    pub fn pop_if<F>(&mut self, predicate: F) -> Option<T>
    where
        F: FnOnce(&mut T) -> bool
    {
        let len = self.len();
        if len == 0 { return None }

        unsafe {
            let last = self.as_mut_ptr().add(len - 1);
            predicate(&mut *last).then(|| {
                self.len.sub(1);
                last.read()
            })
        }
    }

    /// Inserts an element in the given index position
    ///
    /// This operation has a worst case time complexity of O(n),
    /// since it needs to move elements on range [index, len) one
    /// position to the right.
    ///
    /// # Example
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let mut vec = TinyVec::<i32, 10>::from(&[1, 2, 3, 4]);
    ///
    /// vec.insert(2, -1);
    /// assert_eq!(vec.as_slice(), &[1, 2, -1, 3, 4]);
    ///
    /// // An insert on vec.len() behaves like a push
    /// vec.insert(vec.len(), 5);
    /// assert_eq!(vec.as_slice(), &[1, 2, -1, 3, 4, 5]);
    /// ```
    pub fn insert(&mut self, index: usize, elem: T) -> Result<(),T> {
        if index > self.len.get() {
            return Err(elem)
        }
        unsafe { self.insert_unchecked(index, elem); }
        Ok(())
    }

    /// Like [insert](Self::insert), but without bounds checking
    ///
    /// # Safety
    /// The index should be <= self.len
    pub unsafe fn insert_unchecked(&mut self, index: usize, elem: T) {
        self.reserve(1);
        unsafe {
            let ptr = self.as_mut_ptr();
            ptr::copy(
                ptr.add(index),
                ptr.add(index + 1),
                self.len.get() - index,
            );
            ptr.add(index).write(elem);
        }
        self.len.add(1);
    }

    /// Inserts all the elements of the given slice into the
    /// vector, at the given index
    ///
    /// This function clones the elements in the slice.
    ///
    /// If the type T is [Copy], the [insert_slice_copied]
    /// function is a more optimized alternative
    ///
    /// # Errors
    /// If the index is out of bounds, returns the slice as an [Err] variant
    ///
    /// # Example
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let mut vec = TinyVec::from(["abc".to_string(), "ghi".to_string()]);
    /// vec.insert_slice(1, &[
    ///     "__".to_string(),
    ///     "def".to_string(),
    ///     "__".to_string(),
    /// ]);
    ///
    /// assert_eq!(vec.as_slice(), &["abc", "__", "def", "__", "ghi"]);
    /// ```
    /// [insert_slice_copied]: Self::insert_slice_copied
    #[inline]
    pub fn insert_slice<'a>(&mut self, index: usize, elems: &'a [T]) -> Result<(), &'a [T]>
    where
        T: Clone
    {
        self.insert_slice_impl(index, elems)
    }

    /// Inserts all the elements of the given slice into the
    /// vector, at the given index
    ///
    /// This function copies the slice into the buffer, which
    /// is faster that calling [clone]
    /// That's why it requires T to implement [Copy].
    ///
    /// For a cloning alternative, use [insert_slice]
    ///
    /// # Example
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let mut vec = TinyVec::from([1, 2, 3, 4]);
    /// vec.insert_slice_copied(2, &[-1, -2, -3]);
    /// assert_eq!(vec.as_slice(), &[1, 2, -1, -2, -3, 3, 4]);
    /// ```
    /// [clone]: Clone::clone
    /// [insert_slice]: Self::insert_slice
    pub fn insert_slice_copied<'a>(&mut self, index: usize, elems: &'a [T]) -> Result<(), &'a [T]>
    where
        T: Copy
    {
        if index > self.len() {
            return Err(elems)
        }

        let len = elems.len();
        self.reserve(len);
        unsafe {
            let ptr = self.as_mut_ptr();
            ptr::copy(
                ptr.add(index),
                ptr.add(index + len),
                self.len.get() - index,
            );
            ptr::copy_nonoverlapping(
                elems.as_ptr(),
                ptr.add(index),
                len
            );
        }
        self.len.add(len);

        Ok(())
    }

    /// Inserts all the elements on the given iterator at the given index
    ///
    /// # Errors
    /// If the index is out of bounds, returns the passed iterator, wrapped
    /// on an [Err] variant.
    ///
    /// # Example
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let mut vec = TinyVec::from([1, 2, 3, 4]);
    ///
    /// vec.insert_iter(2, (-3..-1));
    /// assert_eq!(vec.as_slice(), &[1, 2, -3, -2, 3, 4]);
    /// ```
    pub fn insert_iter<I>(&mut self, index: usize, it: I) -> Result<(), I>
    where
        I: IntoIterator<Item = T>,
        <I as IntoIterator>::IntoIter: ExactSizeIterator,
    {
        if index > self.len() {
            return Err(it);
        }

        let it = it.into_iter();
        let len = it.len();
        self.reserve(len);
        unsafe {
            let ptr = self.as_mut_ptr();
            ptr::copy(
                ptr.add(index),
                ptr.add(index + len),
                self.len.get() - index,
            );
            let mut ptr = ptr.add(index);
            for elem in it {
                ptr.write(elem);
                ptr = ptr.add(1);
                self.len.add(1);
            }
        }
        Ok(())
    }

    /// Resizes the vector, cloning elem to fill any possible new slots
    ///
    /// If new_len < self.len, behaves like [truncate](Self::truncate)
    ///
    /// # Example
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let mut vec = TinyVec::<i32, 5>::new();
    ///
    /// vec.resize(5, 0);
    /// assert_eq!(vec.len(), 5);
    /// assert_eq!(vec.as_slice(), &[0, 0, 0, 0, 0]);
    /// ```
    pub fn resize(&mut self, new_len: usize, elem: T)
    where
        T: Clone
    {
        if new_len < self.len() {
            self.truncate(new_len);
        } else {
            self.resize_impl(new_len, elem);
        }
    }

    /// Resizes the vector, using the given generator closure
    /// to fill any possible new slots
    ///
    /// If new_len < self.len, behaves like [truncate](Self::truncate)
    ///
    /// # Example
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let mut v = TinyVec::<i32, 10>::new();
    ///
    /// let mut n = 0;
    /// v.resize_with(5, || {
    ///     n += 1;
    ///     n
    /// });
    ///
    /// assert_eq!(v.len(), 5);
    /// assert_eq!(v.as_slice(), &[1, 2, 3, 4, 5]);
    /// ```
    pub fn resize_with<F>(&mut self, cap: usize, mut f: F)
    where
        F: FnMut() -> T
    {
        if cap < self.len() {
            self.truncate(cap);
        } else {
            let n = cap - self.len();
            self.reserve(n);

            unsafe {
                let mut ptr = self.as_mut_ptr().add(self.len());
                let len = &mut self.len;

                for _ in 0..n {
                    ptr::write(ptr, f());
                    ptr = ptr.add(1);
                    len.add(1);
                }
            }
        }
    }

    /// Resizes the vector, initializing the new memory to 0
    ///
    /// # Safety
    /// The caller must ensure that an all-zero byte representation
    /// is valid for T.
    ///
    /// If [mem::zeroed] is valid for T, this function is valid too.
    ///
    /// # Example
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let mut v = TinyVec::<_, 10>::from(&[1, 2, 3]);
    ///
    /// /* SAFETY: i32 can be initialized to 0b0 */
    /// unsafe { v.resize_zeroed(8); }
    ///
    /// /* The above is the same as
    ///    v.resize_with(8, || unsafe { core::mem::zeroed() }); */
    ///
    /// assert_eq!(v.len(), 8);
    /// assert_eq!(v.as_slice(), &[1, 2, 3, 0, 0, 0, 0, 0]);
    /// ```
    pub unsafe fn resize_zeroed(&mut self, cap: usize) {
        if cap < self.len() {
            self.truncate(cap);
        } else {
            let n = cap - self.len();
            self.reserve(n);
            unsafe {
                let ptr = self.as_mut_ptr().add(self.len());
                ptr.write_bytes(0, n);
            }
            self.len.add(n);
        }
    }

    /// Like [remove](Self::remove), but without bounds checking
    ///
    /// # Safety
    /// index must be within bounds (less than self.len)
    pub const unsafe fn remove_unchecked(&mut self, index: usize) -> T {
        debug_assert!(index < self.len());

        unsafe {
            self.len.sub(1);
            let result = self.as_mut_ptr().add(index).read();
            ptr::copy(
                self.as_ptr().add(index + 1),
                self.as_mut_ptr().add(index),
                self.len.get() - index,
            );
            result
        }
    }

    /// Removes the element at the given index.
    /// If the index is out of bounds, returns [None]
    #[inline]
    pub const fn remove(&mut self, index: usize) -> Option<T> {
        if index >= self.len.get() { return None }
        /* SAFETY: We've just checked that index is < self.len */
        Some(unsafe { self.remove_unchecked(index) })
    }

    /// Removes and returns the element at the given `index` from a `self`
    /// if the `predicate` returns true, or [None] if the predicate returns
    /// false or the `index` is out of bounds (the predicate will not be called
    /// in that case).
    ///
    /// # Example
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let mut vec = TinyVec::from([1, 2, 3, 4]);
    /// let pred = |x: &mut i32| *x % 2 == 0;
    ///
    /// assert_eq!(vec.remove_if(1, pred), Some(2));
    /// assert_eq!(vec, [1, 3, 4]);
    /// assert_eq!(vec.remove_if(0, pred), None);
    /// ```
    pub fn remove_if<F>(&mut self, index: usize, predicate: F) -> Option<T>
    where
        F: FnOnce(&mut T) -> bool
    {
        let len = self.len.get();
        if index >= len { return None }

        unsafe {
            let ptr = self.as_mut_ptr().add(index);
            predicate(&mut *ptr).then(|| {
                let elem = ptr.read();
                ptr::copy(
                    ptr.add(1),
                    ptr,
                    len - index - 1
                );
                self.len.sub(1);
                elem
            })
        }
    }

    /// Swaps the elements on index a and b
    ///
    /// # Errors
    /// If an index is out of bounds for [0, len),
    /// returns that index inside an [Err] variant.
    pub const fn swap_checked(&mut self, a: usize, b: usize) -> Result<(),usize> {
        if a >= self.len.get() {
            return Err(a)
        };
        if b >= self.len.get() {
            return Err(b)
        };
        /* SAFETY: a and b are in bounds */
        unsafe { self.swap_unchecked(a, b); }
        Ok(())
    }
    /// Swaps the elements on index a and b, without checking bounds
    ///
    /// # Safety
    /// The caller must ensure that both `a` and `b` are in bounds [0, len)
    /// For a checked version of this function, check [swap_checked](Self::swap_checked)
    #[cfg(not(feature = "use-nightly-features"))]
    pub const unsafe fn swap_unchecked(&mut self, a: usize, b: usize) {
        unsafe {
            let ptr = self.as_mut_ptr();
            let ap = ptr.add(a);
            let bp = ptr.add(b);
            ptr::swap(ap, bp);
        }
    }

    #[cfg(feature = "use-nightly-features")]
    #[inline(always)]
    const unsafe fn swap_unchecked(&mut self, a: usize, b: usize) {
        unsafe { self.as_mut_slice().swap_unchecked(a, b); }
    }

    /// Removes the element at the given index by swaping it with the last one
    pub const fn swap_remove(&mut self, index: usize) -> Option<T> {
        if index >= self.len.get() {
            None
        } else if index == self.len.get() - 1 {
            self.pop()
        } else {
            /* SAFETY: index in < self.len */
            unsafe { self.swap_unchecked(index, self.len.get() - 1) }
            self.pop()
        }
    }

    /// Removes consecutive repeated elements in `self` according to the
    /// [`PartialEq`] trait implementation.
    ///
    /// If the vector is sorted, this removes all duplicates.
    ///
    /// # Examples
    /// ```
    /// use tiny_vec::TinyVec;
    /// let mut vec = TinyVec::from([1, 2, 2, 3, 2]);
    /// vec.dedup();
    /// assert_eq!(vec, [1, 2, 3, 2]);
    /// ```
    #[inline]
    pub fn dedup(&mut self)
    where
        T: PartialEq
    {
        self.dedup_by(|a, b| a == b);
    }

    /// Removes all but the first of consecutive elements in the
    /// vector that resolve to the same key.
    ///
    /// If the vector is sorted, this removes all duplicates.
    ///
    /// # Examples
    /// ```
    /// use tiny_vec::TinyVec;
    /// let mut vec = TinyVec::from([10, 20, 21, 30, 20]);
    ///
    /// vec.dedup_by_key(|i| *i / 10);
    /// assert_eq!(vec, [10, 20, 30, 20]);
    /// ```
    #[inline]
    pub fn dedup_by_key<F, K>(&mut self, mut key: F)
    where
        F: FnMut(&mut T) -> K,
        K: PartialEq
    {
        self.dedup_by(|a, b| key(a) == key(b));
    }

    /// Removes all but the first of consecutive elements in `self` satisfying
    /// a given equality relation.
    ///
    /// The `are_equal` function is passed references to two elements from the vector and
    /// must determine if the elements compare equal. The elements are passed in opposite order
    /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed.
    ///
    /// If the vector is sorted, this removes all duplicates.
    ///
    /// # Examples
    /// ```
    /// use tiny_vec::TinyVec;
    /// let mut vec = TinyVec::from(["foo", "bar", "Bar", "baz", "bar"]);
    ///
    /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
    ///
    /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
    /// ```
    pub fn dedup_by<F>(&mut self, mut are_equal: F)
    where
        F: FnMut(&mut T, &mut T) -> bool
    {
        let (ptr, _, len) = self.split_at_spare_mut_with_len();
        let ptr = ptr.as_mut_ptr();

        if len.get() <= 1 {
            return
        }

        let mut first_dup = 1;
        while first_dup != len.get() {
           let is_dup = unsafe {
                let a = ptr.add(first_dup - 1);
                let b = ptr.add(first_dup);
                are_equal(&mut *b, &mut *a)
           };
           if is_dup {
               break
           }
           first_dup += 1;
        }
        if first_dup == len.get() {
            return;
        }

        struct DropGuard<'a, T> {
            len: &'a mut Length,
            ptr: *mut T,
            right: usize,
            left: usize,
        }

        impl<T> Drop for DropGuard<'_, T> {
            fn drop(&mut self) {
                unsafe {
                    let len = self.len.get();

                    let shift = len - self.right;
                    let src = self.ptr.add(self.right);
                    let dst = self.ptr.add(self.left);
                    ptr::copy(src, dst, shift);

                    let deleted = self.right - self.left;
                    self.len.sub(deleted);
                }
            }
        }

        let mut guard = DropGuard { right: first_dup + 1, left: first_dup, ptr, len };
        unsafe { ptr::drop_in_place(ptr.add(first_dup)); }
        while guard.right < guard.len.get() {
            unsafe {
                let a = ptr.add(guard.left - 1);
                let b = ptr.add(guard.right);

                if are_equal(&mut *b, &mut *a) {
                    guard.right += 1;
                    ptr::drop_in_place(b);
                } else {
                    let dst = ptr.add(guard.left);
                    ptr::copy_nonoverlapping(b, dst, 1);
                    guard.left += 1;
                    guard.right += 1;
                }
            }
        }

        guard.len.set(guard.left);
        mem::forget(guard);
    }

    /// Shrinks the capacity of the vector with a lower bound.
    ///
    /// The capacity will remain at least as large as both the length
    /// and the supplied value.
    ///
    /// If the current capacity is less than the lower limit, this is a no-op.
    ///
    /// # Examples
    /// ```
    /// use tiny_vec::TinyVec;
    /// let mut vec = TinyVec::<i32, 4>::with_capacity(10);
    /// vec.extend([1, 2, 3]);
    /// assert!(vec.capacity() >= 10);
    /// vec.shrink_to(4);
    /// assert!(vec.capacity() >= 4);
    /// vec.shrink_to(0);
    /// assert!(vec.capacity() >= 3);
    /// ```
    #[cfg(feature = "alloc")]
    pub fn shrink_to(&mut self, min_capacity: usize) {
        if !self.lives_on_stack() && self.capacity() > min_capacity {
            let new_cap = usize::max(self.len.get(), min_capacity);
            self._shrink(new_cap);
        }
    }

    /// Shrinks the capacity of the vector to fit exactly it's length
    ///
    /// If the vector lives on the heap, but it's length fits inside the
    /// stack-allocated buffer `self.len <= N`, it deallocates the heap
    /// buffer and moves the contents to the stack.
    ///
    /// If you need a function that doesn't move the buffer to the stack,
    /// use the [shrink_to_fit_heap_only](Self::shrink_to_fit_heap_only) function.
    #[cfg(feature = "alloc")]
    pub fn shrink_to_fit(&mut self) {
        if self.len.is_stack() { return }
        self._shrink(self.len.get());
    }

    /// Moves this `TinyVec` to the heap
    #[cfg(feature = "alloc")]
    pub fn move_to_heap(&mut self) {
        self.try_move_to_heap().unwrap_or_else(|err| err.handle());
    }

    /// Like [move_to_heap](Self::move_to_heap), but returns a result
    /// in case the allocation fail
    #[cfg(feature = "alloc")]
    pub fn try_move_to_heap(&mut self) -> Result<(), ResizeError> {
        if self.lives_on_stack() {
            unsafe { self.switch_to_heap(0, false)? };
        }
        Ok(())
    }

    /// Moves this `TinyVec` to the heap, without allocating more
    /// than `self.len` elements
    #[cfg(feature = "alloc")]
    pub fn move_to_heap_exact(&mut self) {
        self.try_move_to_heap_exact().unwrap_or_else(|err| err.handle());
    }

    /// Like [move_to_heap_exact](Self::move_to_heap_exact), but returns a result
    /// in case the allocation fail
    #[cfg(feature = "alloc")]
    pub fn try_move_to_heap_exact(&mut self) -> Result<(), ResizeError> {
        if self.lives_on_stack() {
            unsafe { self.switch_to_heap(0, true)? };
        }
        Ok(())
    }

    /// Shrinks the capacity of the vector to fit exactly it's length.
    ///
    /// Unlike [shrink_to_fit](Self::shrink_to_fit), this function doesn't
    /// move the buffer to the stack, even if the length of `self`, could
    /// fit on the stack space.
    #[cfg(feature = "alloc")]
    pub fn shrink_to_fit_heap_only(&mut self) {
        if !self.len.is_stack() {
            unsafe { self.inner.raw.shrink_to_fit(self.len.get()); };
        }
    }

    /// Clears all the elements of this vector
    ///
    /// # Example
    /// ```
    /// use tiny_vec::{TinyVec, tinyvec};
    ///
    /// let mut vec: TinyVec<_, 5> = tinyvec![1, 2, 3, 4, 5];
    /// vec.clear();
    ///
    /// assert!(vec.is_empty());
    /// assert_eq!(vec.as_slice(), &[]);
    /// ```
    pub fn clear(&mut self) {
        let ptr = self.as_mut_slice() as *mut [T];
        unsafe {
            self.len.set(0);
            ptr::drop_in_place(ptr);
        }
    }

    /// Sets the length of the vector.
    ///
    /// # Safety
    /// The caller must ensure that changing the length doesn't
    /// leave the vector in an inconsistent state. This is:
    ///
    /// - If you reduce de length, you may leak memory, if the type
    ///   stored need to be droped
    /// - If you extend the length, you may access uninitialized memory
    #[inline]
    pub const unsafe fn set_len(&mut self, len: usize) {
        self.len.set(len);
    }

    /// Updates the length of the vector using the given closure.
    ///
    /// This is just the same as getting the len using [Self::len], and
    /// then using [Self::set_len].
    ///
    /// *This is a low level api*. Use it only if you know what you're doing.
    ///
    /// # Safety
    /// Just like [Self::set_len], you need to make sure that changing the
    /// vector length doesn't leave the vector in an inconsistent state, or
    /// leaks memory.
    ///
    /// # Example
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let mut vec = TinyVec::<i32, 10>::with_capacity(10);
    ///
    /// unsafe {
    ///     let mut dst = vec.as_mut_ptr();
    ///     let src = &[1, 2, 3, 4] as *const i32;
    ///     core::ptr::copy(src, dst, 4);
    ///     vec.update_len(|len| *len += 4);
    ///     // Same as:
    ///     // let len = vec.len();
    ///     // len.set_len(len + 4);
    /// }
    /// ```
    pub unsafe fn update_len<F>(&mut self, mut f: F)
    where
        F: FnMut(&mut usize)
    {
        let mut len = self.len.get();
        f(&mut len);
        self.len.set(len);
    }

    /// Reduces the length in the vector, dropping the elements
    /// in range [new_len, old_len)
    ///
    /// If the new_len is >= old_len, this function does nothing.
    ///
    /// # Example
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let mut vec = TinyVec::from([1, 2, 3, 4, 5]);
    /// vec.truncate(3);
    /// assert_eq!(vec.as_slice(), &[1, 2, 3]);
    /// ```
    pub fn truncate(&mut self, len: usize) {
        if len < self.len.get() {
            for e in &mut self[len..] {
                unsafe { ptr::drop_in_place(e) }
            }
            unsafe { self.set_len(len); }
        }
    }

    /// Copies all the elements of the given slice into the vector
    ///
    /// # Example
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let mut vec = TinyVec::<String, 5>::new();
    /// vec.extend_from_slice(&[
    ///     "abc".to_string(),
    ///     "def".to_string(),
    ///     "__".to_string(),
    /// ]);
    ///
    /// assert_eq!(vec.as_slice(), &["abc", "def", "__"]);
    /// ```
    /// [copy_from_slice]: Self::copy_from_slice
    #[inline]
    pub fn extend_from_slice(&mut self, s: &[T])
    where
        T: Clone
    {
        self.extend_from_slice_impl(s);
    }

    /// Copies all the elements of the given slice into the vector
    ///
    /// This function copies the slice into the buffer, which
    /// is faster that calling [clone]
    /// That's why it requires T to implement [Copy].
    ///
    /// For a cloning alternative, use [extend_from_slice]
    ///
    /// # Example
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let mut vec = TinyVec::<i32, 5>::new();
    /// vec.copy_from_slice(&[1, 2, 3, 4]);
    ///
    /// assert_eq!(vec.as_slice(), &[1, 2, 3, 4]);
    /// ```
    /// [clone]: Clone::clone
    /// [extend_from_slice]: Self::extend_from_slice
    #[inline]
    pub fn copy_from_slice(&mut self, s: &[T])
    where
        T: Copy
    {
        let len = s.len();
        self.reserve(len);

        unsafe {
            /* SAFETY: We've just reserved space for `len` elements */
            ptr::copy(
                s.as_ptr(),
                self.as_mut_ptr().add(self.len.get()),
                len
            )
        }

        self.len.add(len);
    }

    /// Copies the slice from the given range to the back
    /// of this vector.
    ///
    /// # Panics
    /// Panics if the range is invalid for [0, self.len)
    ///
    /// # Example
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let mut vec = TinyVec::from([1, 2, 3, 4, 5, 6, 7, 8]);
    ///
    /// vec.extend_from_within(3..=5);
    ///
    /// assert_eq!(vec, &[1, 2, 3, 4, 5, 6, 7, 8, 4, 5, 6]);
    /// ```
    #[inline]
    pub fn extend_from_within<R>(&mut self, range: R)
    where
        T: Clone,
        R: RangeBounds<usize>,
    {
        self.extend_from_within_impl(range);
    }

    /// Like [extend_from_within](Self::extend_from_within),
    /// but optimized for [Copy] types
    pub fn extend_from_within_copied<R>(&mut self, range: R)
    where
        T: Copy,
        R: RangeBounds<usize>,
    {
        let len = self.len();
        let Range { start, end } = slice_range(range, len);

        let new_len = end - start;
        self.reserve(new_len);

        let ptr = self.as_mut_ptr();
        unsafe {
            let src = ptr.add(start);
            let dst = ptr.add(len);
            ptr::copy(src, dst, new_len);
        }
        self.len.add(new_len);
    }

    /// Retains in this vector only the elements that match
    /// the given predicate
    ///
    /// This is the same as calling
    /// `self.extract_if(.., |e| !pred(e)).for_each(|e| drop(e))`
    ///
    /// If you need the predicate to receive a mutable reference,
    /// see [retain_mut](Self::retain_mut)
    ///
    /// # Example
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let mut vec = TinyVec::from([1, 2, 3, 4, 5, 6, 7, 8]);
    /// vec.retain(|&n| n % 2 == 0);
    /// assert_eq!(vec, &[2, 4, 6, 8]);
    /// ```
    #[inline]
    pub fn retain<F>(&mut self, mut pred: F)
    where
        F: FnMut(&T) -> bool
    {
        self.retain_mut(|e| pred(e));
    }

    /// Like [retain](Self::retain), but the predicate receives a
    /// mutable reference to the element.
    ///
    /// # Example
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let mut vec = TinyVec::from([1, 2, 3, 4, 5, 6, 7, 8]);
    /// vec.retain_mut(|n| {
    ///     let is_even = *n % 2 == 0;
    ///     *n *= 2;
    ///     is_even
    /// });
    /// assert_eq!(vec, &[4, 8, 12, 16]);
    /// ```
    pub fn retain_mut<F>(&mut self, mut pred: F)
    where
        F: FnMut(&mut T) -> bool
    {
        /* TODO: We can probably optimize this */
        for e in self.extract_if(.., |e| !pred(e)) {
            drop(e)
        }
    }

    /// Returns vector content as a slice of `T`, along with the remaining spare
    /// capacity of the vector as a slice of `MaybeUninit<T>`.
    ///
    /// The returned spare capacity slice can be used to fill the vector with data
    /// (e.g. by reading from a file) before marking the data as initialized using
    /// the [`set_len`], or [`update_len`] methods.
    ///
    /// [`set_len`]: TinyVec::set_len
    /// [`update_len`]: TinyVec::update_len
    ///
    /// Note that this is a low-level API, which should be used with care for
    /// optimization purposes. If you need to append data to a `Vec`
    /// you can use [`push`], [`extend`], [`extend_from_slice`],
    /// [`extend_from_within`], [`insert`], [`append`], [`resize`] or
    /// [`resize_with`], depending on your exact needs.
    ///
    /// [`push`]: TinyVec::push
    /// [`extend`]: TinyVec::extend
    /// [`extend_from_slice`]: TinyVec::extend_from_slice
    /// [`extend_from_within`]: TinyVec::extend_from_within
    /// [`insert`]: TinyVec::insert
    /// [`append`]: TinyVec::append
    /// [`resize`]: TinyVec::resize
    /// [`resize_with`]: TinyVec::resize_with
    ///
    /// # Examples
    ///
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let mut v = TinyVec::from([1, 1, 2]);
    ///
    /// // Reserve additional space big enough for 10 elements.
    /// v.reserve(10);
    ///
    /// let (init, uninit) = v.split_at_spare_mut();
    /// let sum = init.iter().copied().sum::<u32>();
    ///
    /// // Fill in the next 4 elements.
    /// uninit[0].write(sum);
    /// uninit[1].write(sum * 2);
    /// uninit[2].write(sum * 3);
    /// uninit[3].write(sum * 4);
    ///
    /// // Mark the 4 elements of the vector as being initialized.
    /// unsafe {
    ///     let len = v.len();
    ///     v.set_len(len + 4);
    /// }
    ///
    /// assert_eq!(&v, &[1, 1, 2, 4, 8, 12, 16]);
    /// ```
    pub const fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit<T>]) {
        let (init, uninit, _) = self.split_at_spare_mut_with_len();
        (init, uninit)
    }

    /// Splits the collection into two at the given index.
    ///
    /// Returns a newly allocated vector containing the elements in the range
    /// `[at, len)`. After the call, the original vector will be left containing
    /// the elements `[0, at)` with its previous capacity unchanged.
    ///
    /// - If you want to take ownership of the entire contents and capacity of
    ///   the vector, see [`mem::take`] or [`mem::replace`].
    /// - If you don't need the returned vector at all, see [`TinyVec::truncate`].
    /// - If you want to take ownership of an arbitrary subslice, or you don't
    ///   necessarily want to store the removed items in a vector, see [`TinyVec::drain`].
    ///
    /// # Panics
    ///
    /// Panics if `at > len`.
    ///
    /// # Examples
    ///
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let mut vec = TinyVec::from(['a', 'b', 'c']);
    /// let vec2 = vec.split_off(1);
    /// assert_eq!(vec, ['a']);
    /// assert_eq!(vec2, ['b', 'c']);
    /// ```
    #[must_use = "use `.truncate()` if you don't need the other half"]
    pub fn split_off(&mut self, at: usize) -> TinyVec<T , N>  {
        if at >= self.len() {
            panic!("Index out of bounds");
        }
        let other_len = self.len() - at;
        let mut other = TinyVec::<T, N>::with_capacity(other_len);

        unsafe {
            let src = self.as_ptr().add(at);
            let dst = other.as_mut_ptr();
            ptr::copy_nonoverlapping(src, dst, other_len);
            other.set_len(other_len);
            self.len.sub(other_len);
        }
        other
    }

    /// Consumes and leaks the `TinyVec`, returning a mutable reference to the contents,
    /// `&'a mut [T]`.
    ///
    /// Note that the type `T` must outlive the chosen lifetime `'a`. If the type
    /// has only static references, or none at all, then this may be chosen to be
    /// `'static`.
    ///
    /// This method shrinks the buffer, and moves it to the heap in case it lived
    /// on the stack.
    ///
    /// This function is mainly useful for data that lives for the remainder of
    /// the program's life. Dropping the returned reference will cause a memory
    /// leak.
    ///
    /// # Examples
    ///
    /// ```
    /// let x = tiny_vec::TinyVec::from([1, 2, 3]);
    ///
    /// let static_ref: &'static mut [usize] = x.leak();
    /// static_ref[0] += 1;
    ///
    /// assert_eq!(static_ref, &[2, 2, 3]);
    /// # // FIXME(https://github.com/rust-lang/miri/issues/3670):
    /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak.
    /// # drop(unsafe { Box::from_raw(static_ref) });
    /// ```
    #[cfg(feature = "alloc")]
    pub fn leak<'a>(self) -> &'a mut [T]
    where
        T: 'a
    {
        let mut slf = ManuallyDrop::new(self);
        unsafe {
            let len = slf.len();
            slf.shrink_to_fit_heap_only();
            slf.move_to_heap_exact();
            let ptr = slf.as_mut_ptr();
            slice::from_raw_parts_mut(ptr, len)
        }
    }

    /// Moves all the elements of `other` into `self`, leaving `other` empty.
    ///
    /// # Panics
    ///
    /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
    ///
    /// # Examples
    ///
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let mut vec = TinyVec::from([1, 2, 3]);
    /// let mut vec2 = TinyVec::from([4, 5, 6]);
    /// vec.append(&mut vec2);
    /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
    /// assert_eq!(vec2, []);
    /// ```
    pub fn append<const M: usize>(&mut self, other: &mut TinyVec<T, M>) {
       unsafe {
           let other_len = other.len();
           self.reserve(other_len);

           let src = other.as_slice().as_ptr();
           let dst = self.as_mut_ptr().add(self.len());
           ptr::copy(src, dst, other_len);

           other.set_len(0);
           self.len.add(other_len);
       }
    }

    /// Removes the subslice indicated by the given range from the vector,
    /// returning a double-ended iterator over the removed subslice.
    ///
    /// If the iterator is dropped before being fully consumed,
    /// it drops the remaining removed elements.
    ///
    /// # Panics
    ///
    /// Panics if the starting point is greater than the end point or if
    /// the end point is greater than the length of the vector.
    ///
    /// # Leaking
    ///
    /// If the returned iterator goes out of scope without being dropped (due to
    /// [`mem::forget`], for example), the vector may have lost and leaked
    /// elements arbitrarily, including elements outside the range.
    ///
    /// # Examples
    ///
    /// ```
    /// use tiny_vec::{tinyvec, TinyVec};
    /// let mut v: TinyVec<_, 10> = tinyvec![0, 1, 2, 3, 4, 5, 6];
    /// let mut drain = v.drain(2..=4);
    /// assert_eq!(drain.next(), Some(2));
    /// assert_eq!(drain.next(), Some(3));
    /// assert_eq!(drain.next(), Some(4));
    /// assert_eq!(drain.next(), None);
    /// drop(drain);
    ///
    /// assert_eq!(v, &[0, 1, 5, 6]);
    ///
    /// // A full range clears the vector, like `clear()` does
    /// v.drain(..);
    /// assert_eq!(v, &[]);
    /// ```
    pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, N>
    where
        R: RangeBounds<usize>
    {

        let len = self.len();
        let Range { start, end } = slice_range(range, len);

        unsafe {
            self.set_len(start);

            Drain {
                vec: NonNull::new_unchecked(self as *mut _),
                remaining_start: start,
                remaining_len: end - start,
                tail_start: end,
                tail_len: len - end,
                _marker: PhantomData,
            }
        }
    }

    /// Creates an iterator which uses a closure to determine if the element in the range should be removed.
    ///
    /// If the closure returns true, then the element is removed and yielded.
    /// If the closure returns false, the element will remain in the vector and will not be yielded
    /// by the iterator.
    ///
    /// Only elements that fall in the provided range are considered for extraction, but any elements
    /// after the range will still have to be moved if any element has been extracted.
    ///
    /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating
    /// or the iteration short-circuits, then the remaining elements will be retained. If you want to
    /// remove all elements matching `pred`, you need to exhaust the iterator. Alternativelly, you can
    /// use [retain](Self::retain) with the predicate negated.
    ///
    /// Note that `extract_if` also lets you mutate the elements passed to the filter closure,
    /// regardless of whether you choose to keep or remove them.
    ///
    /// # Panics
    ///
    /// If `range` is out of bounds.
    ///
    /// # Examples
    ///
    /// Splitting an array into evens and odds, reusing the original allocation:
    ///
    /// ```
    /// use tiny_vec::TinyVec;
    /// let mut numbers = TinyVec::<i32, 10>::from(&[1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15]);
    ///
    /// let evens = numbers.extract_if(.., |x| *x % 2 == 0).collect::<TinyVec<_, 8>>();
    /// let odds = numbers;
    ///
    /// assert_eq!(evens, &[2, 4, 6, 8, 14]);
    /// assert_eq!(odds, &[1, 3, 5, 9, 11, 13, 15]);
    /// ```
    ///
    /// Using the range argument to only process a part of the vector:
    ///
    /// ```
    /// use tiny_vec::TinyVec;
    /// let mut items = TinyVec::<i32, 10>::from(&[0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 2, 1, 2]);
    /// let ones = items.extract_if(7.., |x| *x == 1).collect::<TinyVec<_, 4>>();
    /// assert_eq!(items, &[0, 0, 0, 0, 0, 0, 0, 2, 2, 2]);
    /// assert_eq!(ones.len(), 3);
    /// ```
    ///
    /// ## Comparison between [extract_if](Self::extract_if) and [retain](Self::retain)
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let mut vec1 = TinyVec::<i32, 10>::from(&[1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15]);
    /// let mut vec2 = vec1.clone();
    /// let pred = |x: &i32| *x % 2 == 0;
    ///
    /// vec1.extract_if(.., |n| pred(n))
    ///     .for_each(|_| {}); // We need to exhaust the iterator for it to remove all matches
    /// vec2.retain(|n| !pred(n));
    ///
    /// assert_eq!(vec1, vec2);
    /// ```
    #[must_use = "extract_if won't do anything if it's dropped immediately. \
                  Use '.retain' with the predicate negated."]
    pub fn extract_if<R, F>(&mut self, range: R, pred: F) -> ExtractIf<'_, T, N, F>
    where
        R: RangeBounds<usize>,
        F: FnMut(&mut T) -> bool,
    {
        let len = self.len();
        let Range { start, end } = slice_range(range, len);

        unsafe { self.set_len(start) }

        ExtractIf {
            original_len: len,
            deleted: 0,
            next: start,
            last: end,
            vec: self,
            pred,
        }
    }

    /// Converts this [TinyVec] into a boxed slice
    ///
    /// # Example
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let mut v = TinyVec::<_, 10>::from(&[1, 2, 3, 4]);
    /// let b = v.into_boxed_slice();
    ///
    /// assert_eq!(&b[..], [1, 2, 3, 4]);
    /// ```
    #[cfg(feature = "alloc")]
    pub fn into_boxed_slice(self) -> Box<[T]> {
        let mut slf = ManuallyDrop::new(self);

        if slf.lives_on_stack() {
            unsafe { slf.switch_to_heap(0, true).unwrap_or_else(|err| err.handle()) };
        }
        debug_assert!(!slf.lives_on_stack());

        let len = slf.len();
        slf.shrink_to_fit_heap_only();
        debug_assert_eq!(len, slf.capacity());

        let ptr = slf.as_mut_ptr();
        unsafe {
            let slice = slice::from_raw_parts_mut(ptr, len);
            Box::from_raw(slice)
        }
    }

    /// Converts this [TinyVec] into a standard [Vec]
    ///
    /// # Example
    /// ```
    /// use tiny_vec::TinyVec;
    ///
    /// let mut v = TinyVec::from([1, 2, 3, 4]);
    /// let b = v.into_vec();
    ///
    /// assert_eq!(&b[..], &[1, 2, 3, 4]);
    /// ```
    #[cfg(feature = "alloc")]
    pub fn into_vec(self) -> Vec<T> {
        let mut vec = ManuallyDrop::new(self);
        vec.move_to_heap();

        let ptr = vec.as_mut_ptr();
        let len = vec.len();
        let cap = vec.capacity();

        unsafe { Vec::from_raw_parts(ptr, len, cap) }
    }
}

impl<T, const N: usize> Extend<T> for TinyVec<T, N> {
    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
        let iter = iter.into_iter();

        let (lower, _) = iter.size_hint();
        self.reserve(lower);

        for elem in iter {
            self.push(elem);
        }
    }

    #[cfg(feature = "use-nightly-features")]
    #[inline]
    fn extend_one(&mut self, item: T) {
        self.push(item);
    }

    #[cfg(feature = "use-nightly-features")]
    #[inline]
    fn extend_reserve(&mut self, additional: usize) {
        self.reserve(additional);
    }

    #[cfg(feature = "use-nightly-features")]
    #[inline]
    unsafe fn extend_one_unchecked(&mut self, item: T) {
        /* SAFETY: The caller guarantees that self.len < self.capacity */
        unsafe { self.push_unchecked(item); }
    }
}

impl<'a, T: Clone, const N: usize> Extend<&'a T> for TinyVec<T, N> {
    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
        self.extend(iter.into_iter().map(Clone::clone));
    }
}

#[cfg(feature = "use-nightly-features")]
macro_rules! maybe_default {
    ($($t:tt)*) => {
        default $($t)*
    };
}

#[cfg(not(feature = "use-nightly-features"))]
macro_rules! maybe_default {
    ($($t:tt)*) => {
        $($t)*
    };
}

trait CopyOptimization<T> {
    fn extend_from_slice_impl(&mut self, s: &[T]);
    fn insert_slice_impl<'a>(&mut self, index: usize, elems: &'a [T]) -> Result<(), &'a [T]>;
    fn resize_impl(&mut self, new_len: usize, elem: T);
    fn extend_from_within_impl<R>(&mut self, range: R)
    where
        R: RangeBounds<usize>;
}

impl<T: Clone, const N: usize> CopyOptimization<T> for TinyVec<T, N> {
    maybe_default! {
        fn extend_from_slice_impl(&mut self, s: &[T]) {
            self.extend(s.iter().cloned());
        }
    }

    maybe_default! {
        fn insert_slice_impl<'a>(&mut self, index: usize, elems: &'a [T]) -> Result<(), &'a [T]> {
            self.insert_iter(index, elems.iter().cloned()).map_err(|_| elems)
        }
    }

    maybe_default! {
        fn extend_from_within_impl<R>(&mut self, range: R)
        where
            R: RangeBounds<usize>
        {
            let len = self.len();
            let Range { start, end } = slice_range(range, len);

            self.reserve(end - start);

            let (slice, spare, len) = self.split_at_spare_mut_with_len();
            let slice = &slice[start..end];

            for (src, dst) in slice.iter().zip(spare.iter_mut()) {
                dst.write(src.clone());
                len.add(1);
            }
        }
    }

    maybe_default! {
        fn resize_impl(&mut self, new_len: usize, elem: T) {
            let n = new_len - self.len();
            self.reserve(n);

            unsafe {
                let mut ptr = self.as_mut_ptr().add(self.len());
                let len = &mut self.len;

                for _ in 1..n {
                    ptr::write(ptr, elem.clone());
                    ptr = ptr.add(1);
                    len.add(1);
                }

                if n > 0 {
                    ptr::write(ptr, elem);
                    len.add(1);
                }
            }
        }
    }
}

#[cfg(feature = "use-nightly-features")]
impl<T: Copy, const N: usize> CopyOptimization<T> for TinyVec<T, N> {

    #[inline]
    fn extend_from_slice_impl(&mut self, s: &[T]) {
        self.copy_from_slice(s);
    }

    #[inline]
    fn insert_slice_impl<'a>(&mut self, index: usize, elems: &'a [T]) -> Result<(), &'a [T]> {
        self.insert_slice_copied(index, elems)
    }

    #[inline]
    fn extend_from_within_impl<R>(&mut self, range: R)
    where
        R: RangeBounds<usize>
    {
        self.extend_from_within_copied(range);
    }

    #[inline]
    fn resize_impl(&mut self, new_len: usize, elem: T) {
        let n = new_len - self.len();
        self.reserve(n);

        unsafe {
            let mut ptr = self.as_mut_ptr().add(self.len());

            for _ in 0..n {
                ptr::write(ptr, elem);
                ptr = ptr.add(1);
            }

            self.len.add(n);
        }
    }
}

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

impl<T: fmt::Debug, const N: usize> fmt::Debug for TinyVec<T, N> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self.as_slice(), f)
    }
}

impl<T: PartialEq, const N: usize, S> PartialEq<S> for TinyVec<T, N>
where
    S: AsRef<[T]>,
{
    #[inline]
    fn eq(&self, other: &S) -> bool {
        self.as_slice() == other.as_ref()
    }
}

impl<T: PartialOrd, const N: usize> PartialOrd for TinyVec<T, N> {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        self.as_slice().partial_cmp(other.as_slice())
    }
}

impl<T: Ord, const N: usize> Ord for TinyVec<T, N> {
    #[inline]
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        self.as_slice().cmp(other.as_slice())
    }
}

impl<T: PartialEq, const N: usize> Eq for TinyVec<T, N> {}

impl<T: Hash, const N: usize> Hash for TinyVec<T, N> {
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        self.as_slice().hash(state);
    }
}

impl<T, const N: usize> Borrow<[T]> for TinyVec<T, N> {
    #[inline]
    fn borrow(&self) -> &[T] {
        self.as_slice()
    }
}

impl<T, const N: usize> BorrowMut<[T]> for TinyVec<T, N> {
    #[inline]
    fn borrow_mut(&mut self) -> &mut [T] {
        self.as_mut_slice()
    }
}

impl<T, const N: usize> Deref for TinyVec<T, N> {
    type Target = [T];

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.as_slice()
    }
}

impl<T, const N: usize> DerefMut for TinyVec<T, N> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.as_mut_slice()
    }
}

impl<T, const N: usize> Drop for TinyVec<T, N> {
    fn drop(&mut self) {
        if mem::needs_drop::<T>() {
            for e in self.as_mut_slice() {
                unsafe { ptr::drop_in_place(e) };
            }
        }
        if !self.len.is_stack() {
            unsafe { self.inner.raw.destroy(); }
        }
    }
}

macro_rules! impl_from_call {
    ($( $({$($im:tt)*})? $(where { $($w:tt)* })? $t:ty => $c:ident ),* $(,)?) => {
       $(
            impl<T, const N: usize, $($($im)*)?> From<$t> for TinyVec<T, N>
            $(where $($w)* )?
            {
                fn from(value: $t) -> Self {
                    Self:: $c (value)
                }
            }
       )*
    };
}

#[cfg(feature = "alloc")]
impl_from_call! {
    Vec<T> => from_vec,
    Box<[T]> => from_boxed_slice,
}

#[cfg(feature = "alloc")]
impl<T, const N: usize> From<VecDeque<T>> for TinyVec<T, N> {
    fn from(value: VecDeque<T>) -> Self {
        Self::from_vec(Vec::from(value))
    }
}

#[cfg(feature = "alloc")]
impl<T, const N: usize> From<TinyVec<T, N>> for VecDeque<T> {
    fn from(value: TinyVec<T, N>) -> Self {
        VecDeque::from(value.into_vec())
    }
}

impl_from_call! {
    [T; N] => from_array_eq_size,

    where { T: Clone } &[T] => from_slice,
    where { T: Clone } &mut [T] => from_slice,

    { const M: usize } where { T: Clone } &[T; M] => from_slice,
    { const M: usize } where { T: Clone } &mut [T; M] => from_slice,
}

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

impl<'a, T: Clone, const N: usize> FromIterator<&'a T> for TinyVec<T, N> {
    fn from_iter<I: IntoIterator<Item = &'a T>>(iter: I) -> Self {
        let mut s = Self::new();
        s.extend(iter);
        s
    }
}

#[cfg(feature = "alloc")]
impl<T, const N: usize> From<TinyVec<T, N>> for Vec<T> {
    #[inline]
    fn from(value: TinyVec<T, N>) -> Self {
        value.into_vec()
    }
}

impl<T, const N: usize> AsRef<[T]> for TinyVec<T, N> {
    #[inline]
    fn as_ref(&self) -> &[T] {
        self.as_slice()
    }
}

impl<T, const N: usize> AsMut<[T]> for TinyVec<T, N> {
    #[inline]
    fn as_mut(&mut self) -> &mut [T] {
        self.as_mut_slice()
    }
}

impl<T, const N: usize> AsRef<TinyVec<T, N>> for TinyVec<T, N> {
    #[inline]
    fn as_ref(&self) -> &TinyVec<T, N> {
        self
    }
}

impl<T, const N: usize> AsMut<TinyVec<T, N>> for TinyVec<T, N> {
    #[inline]
    fn as_mut(&mut self) -> &mut TinyVec<T, N> {
        self
    }
}

impl<T: Clone, const N: usize> Clone for TinyVec<T, N> {
    fn clone(&self) -> Self {
        Self::from_slice(self.as_slice())
    }

    /// ```
    /// use tiny_vec::{TinyVec, tinyvec};
    ///
    /// let tv = tinyvec![1, 2, 3, 4, 5];
    /// let mut tv2 = TinyVec::<i32, 10>::new();
    /// tv2.clone_from(&tv);
    ///
    /// assert_eq!(tv, tv2);
    /// ```
    fn clone_from(&mut self, source: &Self) {
        self.clear();
        self.reserve(source.len());
        let (_, buf, len) = self.split_at_spare_mut_with_len();
        for (src, dst) in source.as_slice().iter().zip(buf.iter_mut()) {
            dst.write(src.clone());
        }
        len.set(source.len());
    }
}

#[cfg(feature = "std")]
extern crate std;

#[cfg(feature = "std")]
impl<const N: usize> std::io::Write for TinyVec<u8, N> {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.copy_from_slice(buf);
        Ok(buf.len())
    }

    fn write_all(&mut self, buf: &[u8]) -> std::io::Result<()> {
        self.copy_from_slice(buf);
        Ok(())
    }

    fn write_vectored(&mut self, bufs: &[std::io::IoSlice<'_>]) -> std::io::Result<usize> {
        use std::io::{Error, ErrorKind};
        use std::string::ToString;

        let len = bufs.iter().map(|b| b.len()).sum();
        self.try_reserve(len).map_err(|err| {
            Error::new(ErrorKind::OutOfMemory, err.to_string())
        })?;
        for buf in bufs {
            self.copy_from_slice(buf);
        }
        Ok(len)
    }

    #[cfg(feature = "use-nightly-features")]
    fn is_write_vectored(&self) -> bool { true }

    #[cfg(feature = "use-nightly-features")]
    fn write_all_vectored(&mut self, bufs: &mut [std::io::IoSlice<'_>]) -> std::io::Result<()> {
       self.write_vectored(bufs)?;
       Ok(())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

impl<const N: usize> fmt::Write for TinyVec<u8, N> {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        self.copy_from_slice(s.as_bytes());
        Ok(())
    }
}

#[cfg(feature = "serde")]
impl<T: serde::Serialize, const N: usize> serde::Serialize for TinyVec<T, N> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer
    {
        use serde::ser::SerializeSeq;

        let mut seq = serializer.serialize_seq(Some(self.len()))?;
        for elem in self.as_slice() {
            seq.serialize_element(elem)?;
        }
        seq.end()
    }
}

#[cfg(feature = "serde")]
impl<'de, T: Deserialize<'de>, const N: usize> serde::Deserialize<'de> for TinyVec<T, N> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>
    {
        deserializer.deserialize_seq(TinyVecDeserializer(PhantomData))
    }
}

#[cfg(feature = "serde")]
struct TinyVecDeserializer<T, const N: usize>(PhantomData<T>);

#[cfg(feature = "serde")]
impl<'de, T: Deserialize<'de>, const N: usize> serde::de::Visitor<'de> for TinyVecDeserializer<T, N> {
    type Value = TinyVec<T, N>;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "a sequence")
    }

    fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
    where
        A: serde::de::SeqAccess<'de>,
    {
        use serde::de::Error;
        let len = seq.size_hint().unwrap_or(0);
        let mut values = TinyVec::try_with_capacity(len).map_err(A::Error::custom)?;

        while let Some(value) = seq.next_element()? {
            values.push(value);
        }

        Ok(values)
    }
}

#[cfg(test)]
mod test;