astack 0.3.5

astack offers a Stack data structure with fixed capacity capable of fast LIFO operations.
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
//! `astack` offers a [`Stack`] data structure with fixed capacity capable of
//! fast LIFO operations.
//!
//! The crate contains:
//! * A [`Stack`] struct, the main object used to perform TOS operations.
//! * A [`stack`] macro, used to conveniently construct a new [`Stack`].
//! * A [`StackError`] used by the [`Stack`] to signal an invalid operation has occurred.
//! * A [`StackIntoIter`] struct used to iterate over the values of a [`Stack`].
//!
//! `astack` may be used in both std and non-std environments, and is therefore
//! considered platform-agnostic. The crate does not require an allocator at all!
//!
//! You can optionally enable the `std` feature to use some additional features,
//! such as the `std::error::Error` implementation for [`StackError`].
//!
//! # Examples
//!
//! ## Creating an empty `Stack`
//!
//! ```
//! use astack::{stack, Stack};
//!
//! // Through the Stack::new() method
//! let stack = Stack::<u64, 10>::new();
//!
//! // Through the stack! macro
//! let stack = stack![u64; 10];
//! ```
//!
//! ## Creating a `Stack` with already some items inside
//!
//! ```
//! use astack::stack;
//!
//! // Through the stack! macro
//! let stack = stack! {
//!     [u64; 10] = [1, 2, 3]
//! };
//! ```
//!
//! ## Creating a `Stack` filled with items
//!
//! ```
//! use astack::Stack;
//!
//! // A Stack filled with one single Copy item.
//! let stack_of_44 = Stack::<u64, 10>::fill_with_copy(44);
//!
//! // A Stack filled with the Default implementation of u64.
//! let stack_of_default = Stack::<u64, 10>::fill_with_default();
//!
//! // A Stack filled with a value based on the result of a function.
//! let stack = Stack::<String, 10>::fill_with_fn(|i| {
//!     format!("Value n. {}", i)
//! });
//! ```
//!
//! ## Common `Stack` operations
//!
//! ```
//! use astack::stack;
//!
//! // Create a new Stack.
//! let mut stack = stack! {
//!     [i32; 4] = [10, 20, 30]
//! };
//!
//! // Add an item as TOS. This returns Err if the stack if full.
//! stack.push(40).unwrap();
//!
//! // Pop TOS. This returns None if the stack is empty.
//! let last_value = stack.pop().unwrap();
//!
//! // Get a reference to TOS. This returns None if the stack is empty.
//! assert_eq!(stack.tos(), Some(&30));
//! ```

#![warn(rust_2018_idioms, rust_2024_compatibility)]
#![deny(
    missing_docs,
    missing_debug_implementations,
    unsafe_op_in_unsafe_fn,
    clippy::missing_safety_doc,
    clippy::missing_errors_doc,
    clippy::missing_inline_in_public_items,
    clippy::missing_const_for_fn,
    rustdoc::missing_crate_level_docs
)]
#![doc(html_playground_url = "https://play.rust-lang.org")]
#![no_std]

// https://doc.rust-lang.org/nightly/cargo/reference/features.html#feature-unification
#[cfg(feature = "std")]
extern crate std;

mod iter;

use core::{fmt, hash, mem, ptr};
pub use iter::StackIntoIter;

#[doc(hidden)]
#[macro_export(local_inner_macros)]
macro_rules! count_args {
    ($_:expr,) => { 1 };
    ($_:expr, $($others:expr,)+) => {
        count_args!($_,) + count_args!($($others,)*)
    }
}

/// A macro for conveniently creating a [`Stack`].
///
/// [`stack`] is used for 2 purposes:
/// * Create an empty [`Stack`].
/// * Create a [`Stack`] and push some items onto it.
///
/// The syntax is similar to one used to declare an array. If you wanted to create
/// an array of `i32` (filled with `0`s) you'd have to go like this:
/// ```
/// let arr: [i32; 10] = [0; 10];
/// ```
///
/// To create an empty [`Stack`], you can just declare your `T` and `N` in the macro
/// like this:
/// ```
/// use astack::stack;
/// let stack = stack![i32; 10];
/// ```
///
/// or, if you want to both create and push some values at the same time, you can
/// use the same array syntax:
/// ```
/// use astack::stack;
/// let stack = stack! {
///     [i32; 10] = [1, 2, 3]
/// };
/// ```
///
/// Note that in the last scenario [`stack`] checks at compile time if the number
/// of values passed to the macro exceeds the capacity specified.
///
/// # Macro expansion
///
/// The code
/// ```ignore
/// let stack = stack![i32; 10];
/// ```
///
/// expands to
/// ```ignore
/// let stack = Stack::<i32, 10>::new();
/// ```
///
/// On the other hand, the code
/// ```ignore
/// let stack = stack! {
///     [i32; 10] = [1, 2, 3]
/// };
/// ```
///
/// roughly expands to
/// ```ignore
/// let stack = unsafe {
///     let mut stack = Stack::<i32, 10>::new();
///     stack.push_unchecked(1);
///     stack.push_unchecked(2);
///     stack.push_unchecked(3);
///     stack
/// };
/// ```
#[macro_export(local_inner_macros)]
macro_rules! stack {
    ($T:ty; $N:expr) => {
        $crate::Stack::<$T, $N>::new()
    };
    ([$T:ty; $N:expr] = [$($expr:expr),+ $(,)?]) => {{
        // Compile-time error rather than runtime error
        const _: () = core::prelude::rust_2021::assert!(
            count_args!($($expr,)*) <= $N,
            core::prelude::rust_2021::concat!(
                "The number of items exceeds the capacity specified, which is ",
                $N
            )
        );

        let mut stack = stack![$T; $N];

        // SAFETY: we have asserted before that we have enouch capacity
        $( unsafe { stack.push_unchecked($expr) }; )*
        stack
    }};
}

/// The type returned by [`Stack`]'s checked operations if they fail.
///
/// # The `std` feature
///
/// If the `std` feature is enable, [`StackError`] implements `std::error::Error`.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum StackError {
    /// Stack overflow occurs when there is not enough capacity to perform a stack
    /// operation. Examples of that are [`push`][Stack::push] and [`extend`][Stack::extend].
    Overflow,
    /// Stack underflow occurs when there are not enough items to perform a stack
    /// operation. Examples of that are [`rotate_tos`][Stack::rotate_tos] and
    /// [`swap_tos`][Stack::swap_tos].
    ///
    /// From Wikipedia: For integers, the term "integer underflow" typically refers to a
    /// special kind of integer overflow or integer wraparound condition whereby the result
    /// of subtraction would result in a value less than the minimum allowed for a given
    /// integer type.
    Underflow,
}

impl fmt::Display for StackError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}

/// This implementation is only available when the `std` feature is
/// enabled.
#[cfg(feature = "std")]
impl std::error::Error for StackError {}

/// A data structure with fixed capacity aimed at fast LIFO operations.
///
/// The [`Stack`] excels in working with the TOS, also known as the top of the stack.
/// It is generic over any type `T`, and offers some implementations, such
/// as [`Clone`], [`Debug`], [`PartialEq`] and [`Hash`] if `T` supports it as well.
///
/// The [`Stack`] offers three ways to manipulate data:
/// * Checked methods, such as [`push`][Stack::push] and [`pop`][Stack::pop], which
/// return an [`Option`] or a [`Result`]. A bit slower but *much* safer. 👍
/// * `_panicking` methods, such as [`push_panicking`][Stack::push_panicking]
/// and [`pop_panicking`][Stack::pop_panicking], which panic if the operation fails.
/// * `_unchecked` methods, such as [`push_unchecked`][Stack::push_unchecked]
/// and [`pop_unchecked`][Stack::pop_unchecked] which cause [undefined behavior]
/// if the operation fails. The fastest choice but the unsafest! ⚠️
///
/// # How it works
///
/// A [`Stack`] is no more than a fixed size array of [`MaybeUninit`] and an [`usize`]
/// that keeps track of the items count and is in charge of bound checking.
/// The usage of [`MaybeUninit`] enhances the performance of the data structure,
/// as it only allocates when needed. The [`Stack`] makes usage of [`unsafe`] code
/// internally to handle data through raw pointers, and further increase the
/// speed of read/write/swap operations.
///
/// # Safety
///
/// Users are recommended to rely on the checked methods or the `_panicking` ones,
/// even though the second category should be used for testing and teaching purposes,
/// as it does not allow for proper error handling by panicking on error.
/// If deemed necessary, `_unchecked` (but faster) versions of the safe methods
/// are available. These ones skip the safety checks, but will result in
/// *[undefined behavior]* if the user does not respect the [safety contract].
///
/// If the user is certain that the safety contract is guaranteed to be respected,
/// the `_unchecked` versions are available for use. However, as mentioned in the
/// beginning of this paragraph, most of the time users will be happy enough to
/// rely on the safe counterparts and trade off a bit of performance to avoid UB.
///
/// # Examples
///
/// ## Creating an empty `Stack`
///
/// ```
/// use astack::{stack, Stack};
///
/// // Through the Stack::new() method
/// let stack = Stack::<u64, 10>::new();
///
/// // Through the stack! macro
/// let stack = stack![u64; 10];
/// ```
///
/// ## Creating a `Stack` with already some items inside
///
/// ```
/// use astack::stack;
///
/// // Through the stack! macro
/// let stack = stack! {
///     [u64; 10] = [1, 2, 3]
/// };
/// ```
///
/// ## Creating a `Stack` filled with items
///
/// ```
/// use astack::Stack;
///
/// // A Stack filled with one single Copy item.
/// let stack_of_44 = Stack::<u64, 10>::fill_with_copy(44);
///
/// // A Stack filled with the Default implementation of `T`.
/// let stack_of_default = Stack::<u64, 10>::fill_with_default();
///
/// // A Stack filled with a value based on the result of a function.
/// let stack = Stack::<String, 10>::fill_with_fn(|i| {
///     format!("Value n. {}", i)
/// });
/// ```
///
/// ## List of all checked `Stack` operations
/// | Name | Description |
/// |---|---|
/// | [`push`][Stack::push] | Push an item |
/// | [`extend`][Stack::extend] | Push many items |
/// | [`extend_array`][Stack::extend_array] | Push many items from an array |
/// | [`pop`][Stack::pop] | Pop and return an item |
/// | [`cut`][Stack::cut] | Pop and return many items |
/// | [`tos`][Stack::tos] | Get a reference to TOS |
/// | [`tos_mut`][Stack::tos_mut] | Get a mutable reference to TOS |
/// | [`truncate`][Stack::truncate] | Pop and discard many items |
/// | [`swap_tos`][Stack::swap_tos] | Replace TOS with an item |
/// | [`rotate_tos`][Stack::rotate_tos] | Swap TOS with TOS - 1: |
///
/// [`MaybeUninit`]: core::mem::MaybeUninit
/// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
/// [safety contract]: https://doc.rust-lang.org/std/keyword.unsafe.html
/// [`Debug`]: core::fmt::Debug
/// [`Hash`]: core::hash::Hash
/// [`unsafe`]: https://doc.rust-lang.org/book/ch19-01-unsafe-rust.html
pub struct Stack<T, const N: usize> {
    items: [mem::MaybeUninit<T>; N],
    len: usize,
}

impl<T, const N: usize> Stack<T, N> {
    /// Returns a new empty [`Stack`] with its items uninitialized.
    ///
    /// * If you want to get a [`Stack`] filled with [`Copy`] items, see
    /// [`fill_with_copy`][Stack::fill_with_copy].
    /// * If you want to get a [`Stack`] filled with [`Default`] items, see
    /// [`fill_with_default`][Stack::fill_with_default].
    /// * If you want to get a [`Stack`] filled with the value returned by a function,
    /// see [`fill_with_fn`][Stack::fill_with_fn].
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::{Stack, stack};
    /// // Create an empty Stack which can hold up to 10 String.
    /// let stack1 = Stack::<String, 10>::new();
    ///
    /// // You can achieve the same result with the stack! macro.
    /// let same_as_stack1 = stack![String; 10];
    ///
    /// // Both stacks do not have initialized items.
    /// assert!(stack1.is_empty() && same_as_stack1.is_empty());
    /// ```
    #[inline]
    pub const fn new() -> Self {
        Self {
            // SAFETY: The `assume_init` is safe because the type we are claiming
            // to have initialized here is a bunch of `MaybeUninit`s, which do not
            // require initialization.
            // https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html#initializing-an-array-element-by-element
            items: unsafe { mem::MaybeUninit::uninit().assume_init() },
            len: 0,
        }
    }

    /// Returns a [`Stack`] filled with `item`. Only works if `item` implements [`Copy`].
    /// This is optimized for types which implement [`Copy`].
    ///
    /// * If you want to get a [`Stack`] filled with [`Default`] items, see
    /// [`fill_with_default`][Stack::fill_with_default].
    /// * If you want to get a [`Stack`] filled with the value returned by a function,
    /// see [`fill_with_fn`][Stack::fill_with_fn].
    ///
    /// # Examples
    /// ```
    /// use astack::Stack;
    ///
    /// // A stack full of 42.
    /// let stack_of_42 = Stack::<u8, 50>::fill_with_copy(42);
    /// assert!(stack_of_42.is_full());
    /// assert_eq!(stack_of_42.tos(), Some(&42));
    ///
    /// ```
    ///
    /// [this link]: https://doc.rust-lang.org/std/primitive.array.html
    #[inline]
    pub const fn fill_with_copy(item: T) -> Self
    where
        T: Copy,
    {
        Self {
            items: [mem::MaybeUninit::new(item); N],
            len: N,
        }
    }

    /// Returns a [`Stack`] filled with the item returned by `f`. This is useful
    /// to create a [`Stack`] out of non-[`Copy`] and non-[`Default`] items.
    /// The `f` takes as input a [`usize`] which is the i-th index
    ///
    /// * If you want to get a [`Stack`] filled with [`Copy`] items, see
    /// [`fill_with_copy`][Stack::fill_with_copy].
    /// * If you want to get a [`Stack`] filled with [`Default`] items, see
    /// [`fill_with_default`][Stack::fill_with_default].
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::Stack;
    ///
    /// fn long_computation(i: usize) -> String {
    ///     // Perform a long and heavy computation...
    ///     format!("Item n. {}", i)
    /// }
    ///
    /// let stack = Stack::<String, 32>::fill_with_fn(long_computation);
    /// assert!(stack.is_full());
    /// assert_eq!(stack.tos(), Some(&String::from("Item n. 31")));
    /// ```
    #[inline]
    pub fn fill_with_fn<F>(mut f: F) -> Self
    where
        F: FnMut(usize) -> T,
    {
        Self {
            items: core::array::from_fn(|i| mem::MaybeUninit::new(f(i))),
            len: N,
        }
    }

    /// Returns a [`Stack`] filled with the default value for `T`.
    ///
    /// * If you want to get a [`Stack`] filled with [`Copy`] items, see
    /// [`fill_with_copy`][Stack::fill_with_copy].
    /// * If you want to get a [`Stack`] filled with the value returned by a function,
    /// see [`fill_with_fn`][Stack::fill_with_fn].
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::Stack;
    ///
    /// // A Stack filled with empty Strings
    /// let stack = Stack::<String, 4>::fill_with_default();
    /// assert!(stack.is_full());
    /// assert_eq!(stack.tos(), Some(&String::default()));
    /// ```
    #[inline]
    pub fn fill_with_default() -> Self
    where
        T: Default,
    {
        Self::fill_with_fn(|_| T::default())
    }

    /// Builds a [`Stack`] from an array of [`MaybeUninit`] and a `len`,
    /// representing the count of initialized items.
    ///
    /// # Safety
    ///
    /// Building a [`Stack`] using [`from_raw_parts`][Stack::from_raw_parts] is
    /// *[undefined behavior]* if one of the following occurs:
    /// * `len` is greater than the maximum number of items the stack is allowed to hold.
    ///
    /// * `items[..len]` is composed of uninitialized [`MaybeUninit`].
    ///
    /// # Leaking
    ///
    /// Building a [`Stack`] using [`from_raw_parts`][Stack::from_raw_parts]
    /// will cause a memory leak if both conditions are met:
    ///
    /// * `items[len..N]` is composed of one or more already initialized [`MaybeUninit`].
    ///
    /// * `T` does not implement [`Copy`].
    ///
    /// # Examples
    ///
    /// ```
    /// use std::mem;
    /// use astack::{Stack, stack};
    ///
    /// // Create a stack from raw parts.
    /// // [3, 2, 1, (uninit)]
    /// let items = [
    ///     mem::MaybeUninit::new(3),
    ///     mem::MaybeUninit::new(2),
    ///     mem::MaybeUninit::new(1),
    ///     mem::MaybeUninit::uninit(),
    /// ];
    /// let len = 3;
    ///
    /// // Safety: the items have been initialized in the correct way.
    /// // Safety: len correctly represents the count of initialized items.
    ///
    /// let stack = unsafe { Stack::from_raw_parts(items, len) };
    /// assert_eq!(stack.len(), 3);
    /// assert_eq!(stack.tos(), Some(&1));
    /// assert_eq!(stack, stack! {
    ///     [i32; 4] = [3, 2, 1]
    /// });
    /// ```
    ///
    /// [`MaybeUninit`]: core::mem::MaybeUninit
    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
    #[inline]
    pub const unsafe fn from_raw_parts(items: [mem::MaybeUninit<T>; N], len: usize) -> Self {
        debug_assert!(len <= N);
        Self { items, len }
    }

    /// Returns `true` if the stack does not have initialized items, and is therefore
    /// considered empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::stack;
    ///
    /// // Create an empty stack
    /// let mut stack = stack![i32; 16];
    /// assert!(stack.is_empty());
    ///
    /// // Add items
    /// stack.push_panicking(42);
    /// stack.push_panicking(69);
    ///
    /// // Not the stack is not empty anymore!
    /// assert!(!stack.is_empty());
    /// ```
    #[inline]
    pub const fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Returns `true` if the stack contains only initialized items, and is therefore
    /// considered full.
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::stack;
    ///
    /// // Create a stack full of custom items.
    /// let mut stack = stack! {
    ///     [i64; 4] = [567, 212, 890, 90]
    /// };
    /// assert!(stack.is_full());
    ///
    /// // Remove an item.
    /// stack.pop_panicking();
    ///
    /// // Not the stack is not full anymore, even if there are
    /// // still three items inside!
    /// assert!(!stack.is_full());
    /// ```
    #[inline]
    pub const fn is_full(&self) -> bool {
        self.len >= N
    }

    /// Returns the number of initialized items in the stack, also referred to
    /// as its 'len'.
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::stack;
    ///
    /// let stack = stack! {
    ///     [bool; 10] = [false, true, false]
    /// };
    /// assert_eq!(stack.len(), 3);
    /// ```
    #[inline]
    pub const fn len(&self) -> usize {
        self.len
    }

    /// Returns the capacity of the stack. Remember that a [`Stack`] has a fixed
    /// capacity!
    ///
    /// This does not return the *remaining* capacity, but rather the total capacity
    /// that was given as input when the [`Stack`] was created, i.e., the number of
    /// items that the stack is able to hold.
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::stack;
    ///
    /// let mut stack = stack![i32; 10];
    /// assert_eq!(stack.capacity(), 10);
    ///
    /// // Even if we push some items, the capacity remains the same.
    /// stack.push_panicking(50);
    /// stack.push_panicking(150);
    ///
    /// assert_eq!(stack.len(), 2);
    /// assert_eq!(stack.capacity(), 10);
    /// ```
    #[inline]
    pub const fn capacity(&self) -> usize {
        N
    }

    /// Returns the number of items the stack can push before becoming full.
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::stack;
    ///
    /// let mut stack = stack![i32; 5];
    /// // The stack is empty now.
    /// assert_eq!(stack.capacity_remaining(), 5);
    ///
    /// // Add some items.
    /// stack.extend_array_panicking([7, 8, 9]);
    ///
    /// assert_eq!(stack.capacity_remaining(), 2);
    /// ```
    #[inline]
    pub const fn capacity_remaining(&self) -> usize {
        N - self.len
    }

    /// Returns a reference to the top of the stack or [`None`] if it is empty.
    /// This does not remove TOS from the stack.
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::stack;
    ///
    /// let mut stack = stack! {
    ///     [&str; 3] = ["my", "body!"]
    /// };
    ///
    /// // The top of the stack is the last inserted one!
    /// let tos = stack.tos();
    /// assert_eq!(tos, Some(&"body!"));
    ///
    /// // Remove all items
    /// stack.clear();
    ///
    /// assert_eq!(stack.tos(), None);
    /// ```
    #[inline]
    pub const fn tos(&self) -> Option<&T> {
        if self.is_empty() {
            None
        } else {
            Some(unsafe { self.tos_unchecked() })
        }
    }

    /// Returns a reference to the top of the stack. This does not remove TOS from
    /// the stack.
    /// # Panics
    ///
    /// Panics if the stack is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::stack;
    ///
    /// // An empty stack has no TOS!
    /// let mut stack = stack![i32; 100];
    /// stack.push_panicking(80);
    ///
    /// // This example would panic if there was no TOS.
    /// assert_eq!(stack.tos_panicking(), &80);
    /// ```
    #[inline]
    pub const fn tos_panicking(&self) -> &T {
        assert!(
            !self.is_empty(),
            "Called Stack::tos_panicking on an empty stack"
        );
        unsafe { self.tos_unchecked() }
    }

    /// Returns a reference to the top of the stack without checking whether
    /// the latter is empty or not. For a safe alternative see [`tos`][Stack::tos]
    /// or [`tos_panicking`][Stack::tos_panicking]. This does not remove TOS from
    /// the stack.
    ///
    /// # Safety
    ///
    /// Calling this method on an empty stack is *[undefined behavior]*
    /// even if the resulting reference is not used.
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::stack;
    ///
    /// let mut stack = stack! {
    ///     [&str; 3] = ["my", "body!"]
    /// };
    ///
    /// // We know that the tos exists, so we use the unchecked version.
    /// let tos = unsafe { stack.tos_unchecked() };
    /// assert_eq!(tos, &"body!");
    ///
    /// // Remove all items
    /// stack.clear();
    ///
    /// // The following line will cause undefined behavior
    /// // if commented out!
    /// // let tos = unsafe { stack.tos_unchecked() };
    /// ```
    ///
    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
    #[inline]
    pub const unsafe fn tos_unchecked(&self) -> &T {
        debug_assert!(!self.is_empty());

        // SAFETY: the caller must uphold the safety requirements
        // (self.len must be > 0)
        //
        // The following is the same as SliceIndex::get_unchecked with usize
        // By not using the trait method, we can make this function const
        unsafe { (*self.items.as_ptr().add(self.len - 1)).assume_init_ref() }
    }

    /// Returns a mutable reference to the top of the stack or [`None`]
    /// if it is empty. This does not remove TOS from the stack.
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::stack;
    ///
    /// // A stack with one item: the number 0.
    /// let mut stack = stack! {
    ///     [i32; 8] = [0]
    /// };
    /// assert_eq!(stack.tos(), Some(&0));
    ///
    /// // Increment tos by 10
    /// if let Some(tos) = stack.tos_mut() {
    ///     *tos += 10;
    /// }
    ///
    /// assert_eq!(stack.tos(), Some(&10));
    /// ```
    #[inline]
    pub fn tos_mut(&mut self) -> Option<&mut T> {
        if self.is_empty() {
            None
        } else {
            Some(unsafe { self.tos_mut_unchecked() })
        }
    }

    /// Returns a mutable reference to the top of the stack. This does not remove TOS from
    /// the stack.
    ///
    /// # Panics
    ///
    /// Panics if the stack is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::stack;
    ///
    /// // A stack with one item: the number 0.
    /// let mut stack = stack! {
    ///     [i32; 8] = [0]
    /// };
    ///
    /// // The following like would cause a panic if the stack was empty!
    /// let mut tos = stack.tos_mut_panicking();
    /// assert_eq!(tos, &mut 0);
    ///
    /// // Increment tos by 10
    /// *tos += 10;
    ///
    /// assert_eq!(stack.tos_mut_panicking(), &mut 10);
    /// ```
    #[inline]
    pub fn tos_mut_panicking(&mut self) -> &mut T {
        assert!(
            !self.is_empty(),
            "Called Stack::tos_mut_panicking on an empty stack"
        );
        unsafe { self.tos_mut_unchecked() }
    }

    /// Returns a mutable reference to the top of the stack without checking
    /// whether the latter is empty or not. For a safe alternative see
    /// [`tos_mut`][Stack::tos_mut] or [`tos_mut_panicking`][Stack::tos_mut_panicking].
    /// This does not remove TOS from the stack.
    ///
    /// # Safety
    ///
    /// Calling this method on an empty stack is *[undefined behavior]*
    /// even if the resulting reference is not used.
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::stack;
    ///
    /// let mut stack = stack! {
    ///     [char; 10] = ['a', 'b']
    /// };
    ///
    /// // We know that there must be a tos
    /// // Increment tos ascii value by one
    /// let tos = unsafe { stack.tos_mut_unchecked() };
    /// *tos = (*tos as u8 + 1) as char;
    ///
    /// assert_eq!(stack.tos(), Some(&'c'));
    /// ```
    ///
    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
    #[inline]
    pub unsafe fn tos_mut_unchecked(&mut self) -> &mut T {
        debug_assert!(!self.is_empty());

        // SAFETY: the caller must uphold the safety requirements
        // (self.len must be > 0)
        //
        // The following is the same as SliceIndex::get_unchecked with usize
        // By not using the trait method, we can make this function const (not yet!)
        unsafe { (*self.items.as_mut_ptr().add(self.len - 1)).assume_init_mut() }
    }

    /// Pushes an item at the top of the stack.
    ///
    /// # Errors
    ///
    /// Returns [`StackError`] if the stack is full.
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::{Stack, StackError};
    ///
    /// // Create a full stack.
    /// let mut stack = Stack::<i16, 20>::fill_with_copy(100);
    ///
    /// // Try to push `my_lucky_num`.
    /// let my_lucky_num = 16;
    /// assert_eq!(stack.push(my_lucky_num), Err(StackError::Overflow));
    ///
    /// // Make some space for `my_lucky_num`.
    /// stack.clear();
    ///
    /// assert_eq!(stack.push(my_lucky_num), Ok(()));
    /// ```
    #[inline]
    pub fn push(&mut self, item: T) -> Result<(), StackError> {
        if self.is_full() {
            Err(StackError::Overflow)
        } else {
            unsafe { self.push_unchecked(item) };
            Ok(())
        }
    }

    /// Pushes an item at the top of the stack
    ///
    /// # Panics
    ///
    /// Panics if the stack is full.
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::{Stack, StackError};
    ///
    /// // Create a full stack.
    /// let mut stack = Stack::<i16, 20>::fill_with_copy(100);
    ///
    /// // Try to push `my_lucky_num`.
    /// let my_lucky_num = 16;
    ///
    /// // The following line, if commented out, would cause a panic!
    /// // assert_eq!(stack.push(my_lucky_num), Err(StackError::Overflow));
    ///
    /// // Make some space for `my_lucky_num`.
    /// stack.clear();
    ///
    /// // Now it is safe to push_panicking.
    /// stack.push_panicking(my_lucky_num);
    /// assert_eq!(stack.tos(), Some(&16));
    /// ```
    #[inline]
    pub fn push_panicking(&mut self, item: T) {
        assert!(
            !self.is_full(),
            "Called Stack::push_panicking but the stack is full"
        );
        unsafe { self.push_unchecked(item) };
    }

    /// Pushes an item at the top of the stack, without checking whether the latter
    /// is full or not. For a safe alternative, see [`push`][Stack::push] or
    /// [`push_panicking`][Stack::push_panicking].
    ///
    /// # Safety
    ///
    /// Calling this method if the stack is full is *[undefined behavior]*.
    ///
    /// # Examples
    /// ```
    /// use astack::stack;
    ///
    /// let mut my_stack1 = stack![i32; 10];
    ///
    /// // Fill the stack manually.
    /// for i in 0..10 {
    ///     unsafe {
    ///         my_stack1.push_unchecked(i);
    ///     }
    /// }
    ///
    /// // The following line if commented out, would result in undefined behavior!
    /// // unsafe { my_stack1.push_unchecked(11); }
    /// ```
    ///
    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
    #[inline]
    pub unsafe fn push_unchecked(&mut self, item: T) {
        debug_assert!(!self.is_full());

        // SAFETY: the caller must uphold the safety requirements (self.len < N).
        //
        // This is similar to Vec::push
        unsafe {
            let end = self.items.as_mut_ptr().add(self.len);
            ptr::write(end, mem::MaybeUninit::new(item));
        }
        self.len += 1;
    }

    /// Removes the top of the stack and returns it, or [`None`] if the stack
    /// is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::stack;
    ///
    /// let mut stack = stack!{
    ///     [i32; 16] = [10, 20, 30]
    /// };
    ///
    /// assert_eq!(stack.pop(), Some(30));
    /// assert_eq!(stack.pop(), Some(20));
    /// assert_eq!(stack.pop(), Some(10));
    /// assert_eq!(stack.pop(), None);
    /// ```
    #[inline]
    pub fn pop(&mut self) -> Option<T> {
        if self.is_empty() {
            None
        } else {
            Some(unsafe { self.pop_unchecked() })
        }
    }

    /// Removes the top of the stack and returns it
    ///
    /// # Panics
    ///
    /// Panics if the stack is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::stack;
    ///
    /// let mut stack = stack!{
    ///     [i32; 16] = [10, 20, 30]
    /// };
    ///
    /// // Cannot pop_unchecked more than 3 times, otherwise a panic occurs!
    /// assert_eq!(stack.pop_panicking(), 30);
    /// assert_eq!(stack.pop_panicking(), 20);
    /// assert_eq!(stack.pop_panicking(), 10);
    /// ```
    #[inline]
    pub fn pop_panicking(&mut self) -> T {
        assert!(
            !self.is_empty(),
            "Called Stack::pop_panicking but the stack is empty"
        );
        unsafe { self.pop_unchecked() }
    }

    /// Removes the top of the stack and returns it, without checking whether
    /// the latter is empty or not. For a safe alternative, see [`pop`][Stack::pop]
    /// or [`pop_panicking`][Stack::pop_panicking].
    ///
    /// # Safety
    ///
    /// Calling this method if the stack is empty is *[undefined behavior]*.
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::stack;
    ///
    /// let mut stack = stack! {
    ///     [char; 4] = ['a', 'b']
    /// };
    ///
    /// // We know there are exactly 2 items at this point, so it is safe to use
    /// // the unchecked version.
    /// unsafe {
    ///     assert_eq!(stack.pop_unchecked(), 'b');
    ///     assert_eq!(stack.pop_unchecked(), 'a');
    /// }
    ///
    /// // If commented out, the following line results in undefined behavior!
    /// // unsafe { stack.pop_unchecked(); };
    /// ```
    ///
    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
    #[inline]
    pub unsafe fn pop_unchecked(&mut self) -> T {
        debug_assert!(!self.is_empty());

        // SAFETY: the caller must uphold the safety requirements
        // (self.len > 0)
        // (self.items.as_ptr().add(self.len) must be in an initialized state)
        //
        // This is similar to Vec::pop
        self.len -= 1;
        unsafe { ptr::read(self.items.as_ptr().add(self.len)).assume_init() }
    }

    /// Pushes items of an array of length `M` on the stack. This is optimized
    /// for arrays, and should be preferred before [`extend`][Stack::extend]
    /// if you have an array of elements.
    ///
    /// # Errors
    ///
    /// Returns [`StackError`] if the stack cannot hold `M` more items
    /// (`stack.len() + M > stack.capacity()`).
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::{stack, StackError};
    ///
    /// let mut stack = stack! {
    ///     [i32; 5] = [1, 2, 3]
    /// };
    ///
    /// // Extend the stack
    /// stack.extend_array([4, 5]).unwrap();
    /// assert_eq!(stack.tos(), Some(&5));
    /// assert_eq!(stack, [1, 2, 3, 4, 5]);
    ///
    /// // The stack is full: cannot push more items!
    /// assert_eq!(stack.extend_array([6, 7, 8]), Err(StackError::Overflow));
    /// ```
    #[inline]
    pub fn extend_array<const M: usize>(&mut self, arr: [T; M]) -> Result<(), StackError> {
        if self.len + M > N {
            Err(StackError::Overflow)
        } else {
            unsafe { self.extend_array_unchecked(arr) };
            Ok(())
        }
    }

    /// Pushes items of an array of length `M` on the stack. This is optimized
    /// for arrays, and should be preferred before [`extend_panicking`][Stack::extend_panicking]
    /// if you have an array of elements.
    ///
    /// # Panics
    ///
    /// Panics if the stack cannot hold `M` more items
    /// (`stack.len() + M > stack.capacity()`).
    ///
    /// # Examples
    ///
    /// ```should_panic
    /// use astack::stack;
    ///
    /// let mut characters = stack![char; 4];
    ///
    /// // Extend operations
    /// characters.extend_array_panicking(['x', 'y']);
    /// characters.extend_array_panicking(['z', '_']);
    /// assert_eq!(characters, ['x', 'y', 'z', '_']);
    ///
    /// // The following line makes the program crash!
    /// characters.extend_array_panicking(['a', 'b']);
    /// ```
    #[inline]
    pub fn extend_array_panicking<const M: usize>(&mut self, arr: [T; M]) {
        assert!(
            self.len + M <= N,
            "Called Stack::push_array_panicking but self.len + M > N"
        );
        unsafe { self.extend_array_unchecked(arr) };
    }

    /// Pushes items of an array of length `M` on the stack. This is optimized
    /// for arrays, and should be preferred before [`extend_panicking`][Stack::extend_panicking]
    /// if you have an array of elements.
    ///
    /// # Safety
    ///
    /// Calling this method if `stack.len() + M > stack.capacity()` is
    /// *[undefined behavior]*.
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::stack;
    ///
    /// let mut characters = stack![char; 4];
    ///
    /// // SAFETY: we know that at this point the stack can hold exactly 4 characters
    /// // and therefore it is safe to pass an array of 4 chars.
    /// unsafe {
    ///     characters.extend_array_unchecked(['7', '8', '9', '0']);   
    /// }
    /// assert_eq!(characters, ['7', '8', '9', '0']);
    ///
    /// // The following line, if uncommented, causes undefined behavior.
    /// // characters.extend_array_unchecked(['a', 'b']);
    /// ```
    ///
    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
    #[inline]
    pub unsafe fn extend_array_unchecked<const M: usize>(&mut self, arr: [T; M]) {
        debug_assert!(self.len + M <= N);
        let mut arr = arr.map(|item| mem::MaybeUninit::new(item));

        // SAFETY: this is similar to slice::swap_with_slice. The slices cannot
        // overlap because mutable references are exclusive.
        unsafe {
            ptr::swap_nonoverlapping(
                self.items[self.len..(self.len + M)].as_mut_ptr(),
                arr[..].as_mut_ptr(),
                M,
            );
        }
        self.len += M;
    }

    /// Moves items of an [`IntoIterator`] onto the stack. This is the equivalent of calling
    /// [`push`][Stack::push] for each item of the [`IntoIterator`]. If you want to push
    /// items of an array, see [`extend_array`][Stack::extend_array].
    ///
    /// # Errors
    ///
    /// Returns [`StackError`] if the stack runs out of capacity while inserting
    /// the items.
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::{stack, StackError};
    ///
    /// let mut stack = stack![u8; 7];
    ///
    /// // This works!
    /// stack.extend(0..2).unwrap();
    /// assert_eq!(stack, [0, 1]);
    ///
    /// // All types that support IntoIterator can be used with `extend`.
    /// stack.extend("aa".chars().map(|ch| ch as _)).unwrap();
    /// assert_eq!(stack, [0, 1, 97, 97]);
    ///
    /// // NOT RECOMMENDED: use `extend_array` for that.
    /// stack.extend([4, 5, 6]).unwrap();
    /// assert_eq!(stack.tos(), Some(&6));
    ///
    /// // The stack is at full capacity!
    /// assert_eq!(stack.extend(1..), Err(StackError::Overflow));
    /// ```
    #[inline]
    pub fn extend<I>(&mut self, items: I) -> Result<(), StackError>
    where
        I: IntoIterator<Item = T>,
    {
        items.into_iter().try_for_each(|item| self.push(item))
    }

    /// Moves items of an [`IntoIterator`] onto the stack. This is the equivalent of calling
    /// [`push_panicking`][Stack::push_panicking] for each item of the [`IntoIterator`].
    /// If you want to push items of an array, see
    /// [`extend_array_panicking`][Stack::extend_array_panicking].
    ///
    /// # Panics
    ///
    /// Panics if the stack runs out of capacity while inserting the items.
    ///
    /// # Examples
    ///
    /// ```should_panic
    /// use astack::stack;
    ///
    /// let mut stack = stack![u8; 7];
    ///
    /// // This works!
    /// stack.extend_panicking(0..5);
    /// assert_eq!(stack, [0, 1, 2, 3, 4]);
    ///
    /// // All types that support IntoIterator can be used with `extend_panicking`.
    /// stack.extend_panicking("ee".chars().map(|ch| ch as _));
    /// assert_eq!(stack, [0, 1, 2, 3, 4, 101, 101]);
    /// assert!(stack.is_full());
    ///
    /// // The stack is at full capacity! The program panics at the line below.
    /// stack.extend_panicking(1..);
    /// ```
    #[inline]
    pub fn extend_panicking<I>(&mut self, items: I)
    where
        I: IntoIterator<Item = T>,
    {
        items.into_iter().for_each(|item| self.push_panicking(item));
    }

    /// Moves items of an [`IntoIterator`] onto the stack without checking for overflow.
    /// This is the equivalent of calling [`push_unchecked`][Stack::push_unchecked]
    /// for each item of the [`IntoIterator`]. If you want to push items of an array, see
    /// [`extend_array_unchecked`][Stack::extend_array_unchecked].
    ///
    /// # Safety
    ///
    /// If the [`IntoIterator`] overflows the capacity of the stack, *[undefined behavior]*
    /// occurs.
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::stack;
    ///
    /// let mut stack = stack![char; 4];
    ///
    /// // SAFETY: we know there is enough capacity to do this.
    /// unsafe {
    ///     stack.extend_unchecked("lmao".chars());
    /// }
    /// assert_eq!(stack, ['l', 'm', 'a', 'o']);
    ///
    /// // The following line, if commented out, causes undefined behavior!
    /// // unsafe { stack.extend_unchecked("ub".chars()) };
    /// ```
    ///
    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
    #[inline]
    pub unsafe fn extend_unchecked<I>(&mut self, items: I)
    where
        I: IntoIterator<Item = T>,
    {
        // SAFETY: the safety contract of Stack::push_unchecked applies.
        items
            .into_iter()
            .for_each(|item| unsafe { self.push_unchecked(item) });
    }

    /// Pops `M` items from the stack and returns them as an array (no dynamic
    /// allocation is involved). The order of the items is preserved: the stack
    /// is literally 'cut'.
    ///
    /// # Errors
    ///
    /// Returns [`StackError`] if `M > stack.len`, i.e., the requested number of
    /// items exceeds the number of items available. No item is removed if the
    /// operation is invalid.
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::{stack, StackError};
    ///
    /// let mut greetings = stack! {
    ///     [&str; 5] = ["hello", "ciao", "hola", "salut"]
    /// };
    ///
    /// let arr = greetings.cut::<2>();
    ///
    /// // The order of the items is preserved.
    /// assert_eq!(arr, Ok(["hola", "salut"]));
    /// assert_eq!(greetings, ["hello", "ciao"]);
    /// assert_eq!(greetings.tos(), Some(&"ciao"));
    ///
    /// // Not enough items!
    /// let invalid = greetings.cut::<3>();
    /// assert_eq!(invalid, Err(StackError::Underflow));
    ///
    /// // No item is removed if the operation is invalid.
    /// assert_eq!(greetings, ["hello", "ciao"])
    /// ```
    #[inline]
    #[must_use = "If you want to discard the result, see `Stack::truncate`"]
    pub fn cut<const M: usize>(&mut self) -> Result<[T; M], StackError> {
        if M > self.len {
            Err(StackError::Underflow)
        } else {
            Ok(unsafe { self.cut_unchecked() })
        }
    }

    /// Pops `M` items from the stack and returns them as an array (no dynamic
    /// allocation is involved). The order of the items is preserved: the stack
    /// is literally 'cut'.
    ///
    /// # Panics
    ///
    /// Panics if `M > stack.len`, i.e., the requested number of
    /// items exceeds the number of items available.
    ///
    /// # Examples
    ///
    /// ```should_panic
    /// use astack::stack;
    ///
    /// let mut stack = stack! {
    ///     [String; 3] = ["data1".into(), "data2".into(), "data3".into()]
    /// };
    /// let data = stack.cut_panicking::<2>();
    /// assert_eq!(data, ["data2".to_string(), "data3".to_string()]);
    /// assert_eq!(stack.tos(), Some(&String::from("data1")));
    ///
    /// // The following operation panics at runtime!
    /// let _ = stack.cut_panicking::<2>();
    /// ```
    #[inline]
    #[must_use = "If you want to discard the result, see `Stack::truncate_panicking`"]
    pub fn cut_panicking<const M: usize>(&mut self) -> [T; M] {
        assert!(
            M <= self.len,
            "Called Stack::cut_panicking but M > self.len"
        );
        unsafe { self.cut_unchecked() }
    }

    /// Pops `M` items from the stack and returns them as an array (no dynamic
    /// allocation is involved) without checking if there are enough items.
    /// The order of the items is preserved: the stack is literally 'cut'.
    ///
    /// # Safety
    ///
    /// If `M > stack.len`, i.e., the requested number of
    /// items exceeds the number of items available, *[undefined behavior]* occurs.
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::stack;
    ///
    /// let mut stack = stack! {
    ///     [i64; 8] = [89, 34, 56, 78, 12, 90, 78, 67]
    /// };
    ///
    /// let last_three_numbers = unsafe { stack.cut_unchecked::<3>() };
    /// assert_eq!(last_three_numbers, [90, 78, 67]);
    /// assert_eq!(stack, [89, 34, 56, 78, 12]);
    ///
    /// // The following operation would result in undefined behavior, as there are
    /// // only 5 items remaining in the stack.
    /// // let _ = unsafe { stack.cut_unchecked::<6>() };
    /// ```
    ///
    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
    #[inline]
    #[must_use = "If you want to discard the result, see `Stack::truncate_unchecked`"]
    pub unsafe fn cut_unchecked<const M: usize>(&mut self) -> [T; M] {
        debug_assert!(M <= self.len);

        unsafe {
            // SAFETY: The `assume_init` is safe because the type we are claiming
            // to have initialized here is a bunch of `MaybeUninit`s, which do not
            // require initialization.
            // https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html#initializing-an-array-element-by-element
            let mut arr = mem::MaybeUninit::<[mem::MaybeUninit<T>; M]>::uninit().assume_init();

            // SAFETY: this is similar to slice::swap_with_slice. The slices cannot
            // overlap because mutable references are exclusive.
            ptr::swap_nonoverlapping(
                self.items[(self.len - M)..].as_mut_ptr(),
                arr[..].as_mut_ptr(),
                M,
            );
            self.len -= M;

            // SAFETY: At this point all the items inside arr have been swapped with
            // initialized data.
            arr.map(|item| item.assume_init())
        }
    }

    /// Swaps TOS with `item`, returning the previous TOS.
    ///
    /// # Errors
    ///
    /// If the stack is empty, [`StackError`] is returned instead.
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::stack;
    ///
    /// let mut stack = stack! {
    ///     [&str; 10] = ["praise", "Lamborghini", "supercars!"]
    /// };
    ///
    /// // Replace "supercars" with "tractors".
    /// if let Ok(old_tos) = stack.swap_tos("tractors") {
    ///     println!("The old tos was: {}", old_tos);
    ///     assert_eq!(old_tos, "supercars!");
    /// } else {
    ///     println!("Could not swap tos: empty stack!");
    /// }
    /// ```
    #[inline]
    pub fn swap_tos(&mut self, item: T) -> Result<T, StackError> {
        if self.is_empty() {
            Err(StackError::Underflow)
        } else {
            Ok(unsafe { self.swap_tos_unchecked(item) })
        }
    }

    /// Swaps TOS with `item`, returning the previous TOS.
    ///
    /// # Panics
    ///
    /// Panics if the stack is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::stack;
    ///
    /// let mut stack = stack![i64; 9];
    ///
    /// // SAFETY: We know there's enough space to do it.
    /// unsafe {
    ///     stack.push_unchecked(81);
    ///     stack.push_unchecked(3);
    /// }
    ///
    /// // This will panic if the stack is empty!
    /// assert_eq!(stack.swap_tos_panicking(16), 3);
    /// assert_eq!(stack.swap_tos_panicking(25), 16);
    /// assert_eq!(stack, stack! {
    ///     [i64; 9] = [81, 25]
    /// });
    /// ```
    #[inline]
    pub fn swap_tos_panicking(&mut self, item: T) -> T {
        assert!(
            !self.is_empty(),
            "Called Stack::swap_tos_panicking but the stack is empty"
        );
        unsafe { self.swap_tos_unchecked(item) }
    }

    /// Swaps TOS with `item`, returning the previous TOS without checking whether
    /// the stack is empty or not. For a safe alternative, see [`swap_tos`][Stack::swap_tos]
    /// or [`swap_tos_panicking`][Stack::swap_tos_panicking].
    ///
    /// # Safety
    ///
    /// Calling this method if the stack is empty is *[undefined behavior]*.
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::stack;
    ///
    /// // A stack full of &str.
    /// let mut stack = stack! {
    ///     [&str; 2] = ["yeet", "lmao"]
    /// };
    ///
    /// // SAFETY: we know that the stack is not empty at this point.
    /// let old_tos = unsafe {
    ///     stack.swap_tos_unchecked("lolxd")
    /// };
    ///
    /// assert_eq!(old_tos, "lmao");
    /// assert_eq!(stack.tos(), Some(&"lolxd"));
    /// ```
    ///
    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
    #[inline]
    pub unsafe fn swap_tos_unchecked(&mut self, item: T) -> T {
        debug_assert!(!self.is_empty());

        unsafe {
            // SAFETY: the user has assured us that there is an item to be swapped,
            // and that `item` won't point to garbage.
            let item = ptr::replace(
                self.items.as_mut_ptr().add(self.len - 1),
                mem::MaybeUninit::new(item),
            );

            // SAFETY: the item has been correctly initialized at this point.
            item.assume_init()
        }
    }

    /// Swaps TOS with TOS - 1. In other terms, swaps the topmost item of the stack
    /// with the one immediately below it.
    ///
    /// # Errors
    ///
    /// If the stack contains less than two items, [`StackError`] is
    /// returned.
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::{stack, StackError};
    ///
    /// let mut stack1 = stack! {
    ///     [char; 10] = ['a', 'b']
    /// };
    ///
    /// stack1.rotate_tos().unwrap();
    /// assert_eq!(stack1.tos(), Some(&'a'));
    ///
    /// // Create a stack with no items.
    /// let mut stack2 = stack![i32; 5];
    /// assert_eq!(stack2.rotate_tos(), Err(StackError::Underflow));
    /// ```
    #[inline]
    pub fn rotate_tos(&mut self) -> Result<(), StackError> {
        if self.len < 2 {
            Err(StackError::Underflow)
        } else {
            unsafe { self.rotate_tos_unchecked() };
            Ok(())
        }
    }

    /// Swaps TOS with TOS - 1. In other terms, swaps the topmost item of the stack
    /// with the one immediately below it.
    ///
    /// # Panics
    ///
    /// Panics if the stack contains less than 2 items.
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::stack;
    ///
    /// let mut stack = stack! {
    ///     [isize; 5] = [90, 10, 30]
    /// };
    ///
    /// // This would panic if there were less than 2 items!
    /// stack.rotate_tos_panicking();
    /// assert_eq!(stack.tos(), Some(&10));
    ///
    /// // Rotate again!
    /// stack.rotate_tos_panicking();
    ///
    /// // Now the tos has been swapped twice.
    /// assert_eq!(stack.tos(), Some(&30));
    /// ```
    #[inline]
    pub fn rotate_tos_panicking(&mut self) {
        assert!(
            self.len >= 2,
            "Called Stack::rotate_tos_panicking but the stack contains 1 or 0 items"
        );
        unsafe { self.rotate_tos_unchecked() };
    }

    /// Swaps TOS with TOS - 1. In other terms, swaps the topmost item of the stack
    /// with the one immediately below it, without checking if the stack contains
    /// at least 2 items.
    ///
    /// # Safety
    ///
    /// Calling this method if the stack is contains less than 2 items
    /// is *[undefined behavior]*.
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::stack;
    ///
    /// let mut stack = stack! {
    ///     [char; 80] = ['7', '8', '9']
    /// };
    ///
    /// // SAFETY: we know there are at least 2 items at this point.
    /// unsafe {
    ///     stack.rotate_tos_unchecked();
    /// }
    ///
    /// assert_eq!(stack.tos(), Some(&'8'));
    /// ```
    ///
    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
    #[inline]
    pub unsafe fn rotate_tos_unchecked(&mut self) {
        debug_assert!(self.len >= 2);

        // SAFETY: this is similar to slice::swap_unchecked.
        // Create only 1 single ptr (this is important!)
        let ptr = self.items.as_mut_ptr();
        unsafe {
            ptr::swap(ptr.add(self.len - 1), ptr.add(self.len - 2));
        }
    }

    /// Shortens the stack, keeping the `len` elements and dropping
    /// the rest. If `len == stack.len`, nothing happens.
    ///
    /// # Errors
    ///
    /// Returns a [`StackError`] if `len > stack.len`.
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::{stack, StackError};
    ///
    /// let mut stack = stack! {
    ///     [i8; 5] = [8, 3, 0]
    /// };
    ///
    /// // Remove 2 items, we don't need them!
    ///
    /// assert!(stack.truncate(2).is_ok());
    /// // There are not enough items to truncate!
    /// assert_eq!(stack.truncate(3), Err(StackError::Underflow));
    /// assert_eq!(stack.len(), 2);
    /// ```
    #[inline]
    pub fn truncate(&mut self, new_len: usize) -> Result<(), StackError> {
        if new_len > self.len {
            Err(StackError::Underflow)
        } else {
            unsafe { self.truncate_unchecked(new_len) };
            Ok(())
        }
    }

    /// Shortens the stack, keeping the `len` elements and dropping
    /// the rest. If `len == stack.len`, nothing happens.
    ///
    /// # Panics
    ///
    /// Panics if `len > stack.len`.
    ///
    /// # Examples
    ///
    /// ```should_panic
    /// use astack::stack;
    ///
    /// let mut stack = stack! {
    ///     [i8; 5] = [8, 3, 0]
    /// };
    ///
    /// // Keep 2 items, we don't need them!
    ///
    /// stack.truncate_panicking(2);
    /// // When the following line is executed, the program panics, as there are not
    /// // enough items to remove!
    /// stack.truncate_panicking(3);
    /// ```
    #[inline]
    pub fn truncate_panicking(&mut self, new_len: usize) {
        assert!(
            new_len <= self.len,
            "Called Stack::truncate_panicking but `len` ({}) is greater than stack's len ({})",
            new_len,
            self.len
        );
        unsafe { self.truncate_unchecked(new_len) };
    }

    /// Shortens the stack, keeping the `len` elements and dropping
    /// the rest. If `len == stack.len`, nothing happens. Does not check for the
    /// validity of `len`.
    ///
    /// # Safety
    ///
    /// If `len > stack.len`, *[undefined behavior]* occurs.
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::{stack, Stack};
    ///
    /// // Create a function which removes all items from the stack!
    /// // This uses unsafe code but it is safe.
    ///
    /// fn truncate_all_items<T, const N: usize>(stack: &mut Stack<T, N>) {
    ///     unsafe { stack.truncate_unchecked(0) };
    /// }
    ///
    /// let mut stack = stack! {
    ///     [i32; 8] = [6, 7, 8, 9, 0]
    /// };
    ///
    /// assert_eq!(stack.len(), 5);
    /// truncate_all_items(&mut stack);
    /// assert!(stack.is_empty());
    /// ```
    ///
    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
    #[inline]
    pub unsafe fn truncate_unchecked(&mut self, new_len: usize) {
        debug_assert!(new_len <= self.len);

        // SAFETY: the user gave us a valid len.
        let remaining_len = self.len - new_len;
        unsafe {
            self.drop_items(remaining_len);
        }
        self.len = new_len;
    }

    /// Apply `f` to TOS, returning [`StackError`] if the stack is empty. `f` receives
    /// a mutable reference to TOS, which can be modified accordingly.
    ///
    /// # Errors
    ///
    /// The function returns a [`StackError`] if the stack is empty, because in that
    /// situation you could not apply `f` to TOS.
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::{stack, StackError};
    ///
    /// fn double(x: &mut usize) {
    ///     *x = *x * 2;
    /// }
    ///
    /// let mut stack = stack! {
    ///     [usize; 10] = [7, 8, 9]
    /// };
    ///
    /// assert_eq!(stack.apply_tos(double), Ok(()));
    /// assert_eq!(stack.tos(), Some(&18));
    ///
    /// // Let's try this on an empty stack...
    ///
    /// let mut empty_stack = stack![usize; 10];
    /// assert_eq!(empty_stack.apply_tos(double), Err(StackError::Underflow));
    /// ```
    #[inline]
    pub fn apply_tos<F>(&mut self, f: F) -> Result<(), StackError>
    where
        F: Fn(&mut T),
    {
        let Some(tos) = self.tos_mut() else {
            return Err(StackError::Underflow);
        };

        f(tos);
        Ok(())
    }

    /// Apply `f` to TOS, panicking if the stack is empty. `f` receives
    /// a mutable reference to TOS, which can be modified accordingly.
    ///
    /// # Examples
    ///
    /// ```should_panic
    /// use astack::stack;
    ///
    /// let mut names = stack! {
    ///     [String; 4] = ["Frank".to_string(), "Joe".to_string()]
    /// };
    ///
    /// names.apply_tos_panicking(|name| {
    ///     name.push('!');
    /// });
    /// assert_eq!(names.tos(), Some(&String::from("Joe!")));
    ///
    /// names.clear();
    ///
    /// // The program panics because there is no TOS here!
    /// names.apply_tos_panicking(|name| { name.push('!'); });
    /// ```
    #[inline]
    pub fn apply_tos_panicking<F>(&mut self, f: F)
    where
        F: Fn(&mut T),
    {
        assert!(
            !self.is_empty(),
            "Called Stack::apply_tos_panicking on empty stack"
        );
        unsafe {
            self.apply_tos_unchecked(f);
        }
    }

    /// Apply `f` to TOS, without checking whether the stack is empty or not.
    /// `f` receives a mutable reference to TOS, which can be modified accordingly.
    ///
    /// # Safety
    ///
    /// Calling this method on an empty stack is *[undefined behaviour]*. Refer to
    /// [apply_tos][Stack::apply_tos] and [apply_tos_panicking][Stack::apply_tos_panicking]
    /// for a safe version of this function.
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::Stack;
    ///
    /// fn create_a_non_empty_stack() -> Stack<i32, 16> {
    ///     Stack::fill_with_default()
    /// }
    ///
    /// let mut stack = create_a_non_empty_stack();
    ///
    /// // Safety: we know that the function never returns an empty stack.
    /// // It is therefore safe to call `apply_tos_unchecked` here.
    /// let set_to_max = |num: &mut i32| *num = i32::MAX;
    /// unsafe {
    ///     stack.apply_tos_unchecked(set_to_max);
    /// }
    /// assert_eq!(stack.tos(), Some(&i32::MAX));
    /// ```
    ///
    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
    #[inline]
    pub unsafe fn apply_tos_unchecked<F>(&mut self, f: F)
    where
        F: Fn(&mut T),
    {
        debug_assert!(!self.is_empty());

        // SAFETY: the user is upholding the safety contract here by promising
        // that the stack is not empty.
        f(unsafe { self.tos_mut_unchecked() });
    }

    /// Removes all the initialized items contained in the stack. The `len` becomes
    /// 0.
    ///
    /// # Examples
    ///
    /// ```
    /// use astack::stack;
    ///
    /// let mut stack = stack! {
    ///     [u64; 128] = [7, 8, 9, 10]
    /// };
    /// assert!(!stack.is_empty());
    ///
    /// // Remove all the stack items.
    /// stack.clear();
    /// assert!(stack.is_empty());
    /// ```
    #[inline]
    pub fn clear(&mut self) {
        // SAFETY: the items have been correctly initialized, this SHOULD not
        // result in a double free (unless user-provied incorrect initialization).
        unsafe { self.drop_items(0) };
        self.len = 0;
    }

    /// The implementation of [`Drop::drop`] for [`Stack`].
    #[inline]
    unsafe fn drop_items(&mut self, start: usize) {
        // SAFETY: mem::MaybeUninit<T> has the same memory layout and align as T,
        // as it is #[repr(transparent)]. We assume that self.items[..self.len]
        // have been correctly initialized: if this is not the case, we drop
        // uninit memory, which is bad I suppose. But the user had been warned!
        //
        // We take inspiration from the Drop implementation of Vec<T> and from
        // the link below.
        //
        // https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html#method.slice_assume_init_mut
        unsafe {
            let items = self.init_items_as_mut_ptr(start);
            ptr::drop_in_place(items);
        }
    }

    /// Returns an immutable raw pointer to a slice of initialized items, beginning
    /// from `start`. If `start` is 0, this will return all the initialized items.
    #[inline]
    unsafe fn init_items_as_ptr(&self, start: usize) -> *const [T] {
        debug_assert!(start <= self.len);

        // SAFETY: this is only called internally and we know what we are doing.
        unsafe { self.items.get_unchecked(start..self.len) as *const [mem::MaybeUninit<T>] as _ }
    }

    /// Returns a mutable raw pointer to a slice of initialized items, beginning
    /// from `start`. If `start` is 0, this will return all the initialized items.
    #[inline]
    unsafe fn init_items_as_mut_ptr(&mut self, start: usize) -> *mut [T] {
        debug_assert!(start <= self.len);

        // SAFETY: this is only called internally and we know what we are doing.
        unsafe { self.items.get_unchecked_mut(start..self.len) as *mut [mem::MaybeUninit<T>] as _ }
    }
}

impl<T, const N: usize> Default for Stack<T, N> {
    /// `Stack::<T, N>::default()` is equivalent to `Stack::<T, N>::new()`.
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl<T, const N: usize> Clone for Stack<T, N>
where
    T: Clone,
{
    #[inline]
    fn clone(&self) -> Self {
        // Create an array of uninitialized memory and fill each uninitialized
        // cell with a copy of the corresponding initialized item.
        unsafe {
            let mut items = mem::MaybeUninit::<[mem::MaybeUninit<T>; N]>::uninit().assume_init();
            self.items
                .get_unchecked(..self.len)
                .iter()
                .zip(items.get_unchecked_mut(..self.len))
                .for_each(|(src, dst)| {
                    dst.write(src.assume_init_ref().clone());
                });
            Self {
                items,
                len: self.len,
            }
        }
    }
}

impl<T, U, const N: usize> PartialEq<Stack<U, N>> for Stack<T, N>
where
    T: PartialEq<U>,
{
    #[inline]
    fn eq(&self, other: &Stack<U, N>) -> bool {
        unsafe {
            let items1 = self.init_items_as_ptr(0);
            let items2 = other.init_items_as_ptr(0);

            // SAFETY: the following items should have been correctly initialized
            *items1 == *items2
        }
    }
}

impl<T, U, const N: usize> PartialEq<[U]> for Stack<T, N>
where
    T: PartialEq<U>,
{
    #[inline]
    fn eq(&self, other: &[U]) -> bool {
        unsafe {
            let items = self.init_items_as_ptr(0);
            *items == *other
        }
    }
}

impl<T, U, const N: usize, const M: usize> PartialEq<[U; M]> for Stack<T, N>
where
    T: PartialEq<U>,
{
    #[inline]
    fn eq(&self, other: &[U; M]) -> bool {
        unsafe {
            let items = self.init_items_as_ptr(0);
            *items == *other
        }
    }
}

impl<T, const N: usize> hash::Hash for Stack<T, N>
where
    T: hash::Hash,
{
    #[inline]
    fn hash<H>(&self, state: &mut H)
    where
        H: hash::Hasher,
    {
        ptr::hash(unsafe { self.init_items_as_ptr(0) }, state);
    }
}

impl<T, const N: usize> fmt::Debug for Stack<T, N>
where
    T: fmt::Debug,
{
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Better print output
        struct DebugUninit;
        impl fmt::Debug for DebugUninit {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(f, "(uninit)")
            }
        }

        let mut list = f.debug_list();

        unsafe {
            list.entries(
                self.items
                    .get_unchecked(..self.len)
                    .iter()
                    .map(|item| item.assume_init_ref()),
            );
        }

        list.entries((self.len..N).map(|_| &DebugUninit));

        list.finish()
    }
}

impl<T, const N: usize> Drop for Stack<T, N> {
    #[inline]
    fn drop(&mut self) {
        unsafe { self.drop_items(0) };
    }
}

#[cfg(feature = "std")]
impl<T, const N: usize> From<Stack<T, N>> for std::vec::Vec<T> {
    #[inline]
    fn from(stack: Stack<T, N>) -> Self {
        let mut v = std::vec::Vec::with_capacity(stack.len());
        // We rev because we want the end of the vec to be the top
        // of the stack
        v.extend(stack.into_iter().rev());
        v
    }
}

#[cfg(feature = "std")]
impl<T, const N: usize> TryFrom<std::vec::Vec<T>> for Stack<T, N> {
    type Error = StackError;

    #[inline]
    fn try_from(v: std::vec::Vec<T>) -> Result<Self, Self::Error> {
        try_extend_into_iter(v.len(), v)
    }
}

#[cfg(feature = "std")]
impl<T, const N: usize> TryFrom<std::collections::LinkedList<T>> for Stack<T, N> {
    type Error = StackError;

    #[inline]
    fn try_from(list: std::collections::LinkedList<T>) -> Result<Self, Self::Error> {
        try_extend_into_iter(list.len(), list)
    }
}

#[cfg(feature = "std")]
#[inline]
fn try_extend_into_iter<T, const N: usize>(
    len: usize,
    it: impl IntoIterator<Item = T>,
) -> Result<Stack<T, N>, StackError> {
    if len > N {
        return Err(StackError::Overflow);
    }

    let mut stack = Stack::new();

    // SAFETY: we know that the iterator does not have more items
    // than the stack's remaining capacity
    unsafe {
        stack.extend_unchecked(it);
    }
    Ok(stack)
}

impl<T, const N: usize> IntoIterator for Stack<T, N> {
    type IntoIter = StackIntoIter<T, N>;
    type Item = T;

    #[inline]
    fn into_iter(mut self) -> Self::IntoIter {
        // Replace the items with the default array
        //
        // SAFETY: same as `Stack::new()`
        let items = mem::replace(&mut self.items, unsafe {
            mem::MaybeUninit::uninit().assume_init()
        });

        // Do not forget to reset the length as well otherwise we drop more than we have!
        let top_len = mem::replace(&mut self.len, 0);

        // Safety: `items` and `top_len` are valid as they come from us
        unsafe { StackIntoIter::new(items, top_len) }
    }
}