qudit-core 0.3.4

Accelerated and Extensible Quantum Library
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
use super::LimitedSizeVec;
use super::storage::CompactStorage;
use serde::{Deserialize, Serialize};
use std::any::TypeId;
use std::hash::Hash;

const INLINE_CAPACITY: usize = 7;

/// A space-efficient vector that stores small collections inline and transitions to heap allocation when needed.
///
/// `CompactVec` optimizes memory usage by storing up to INLINE_CAPACITY elements directly inline without heap allocation,
/// automatically transitioning to heap storage when the capacity is exceeded or when inline storage
/// cannot represent certain values.
///
/// # Examples
///
/// ```
/// # use qudit_core::CompactVec;
/// let mut vec: CompactVec<i8> = CompactVec::new();
/// vec.push(1);
/// vec.push(2);
/// vec.push(3);
/// assert_eq!(vec.len(), 3);
/// assert!(vec.is_inline());
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum CompactVec<T: CompactStorage> {
    /// Inline storage for up to INLINE_CAPACITY elements.
    Inline([T::InlineType; INLINE_CAPACITY], u8),

    /// Heap storage for more than INLINE_CAPACITY elements.
    Heap(LimitedSizeVec<T>),
}

impl<T: CompactStorage> CompactVec<T> {
    /// Creates a new empty `CompactVec` using inline storage.
    ///
    /// The vector starts with inline storage and can hold up to INLINE_CAPACITY elements
    /// before transitioning to heap allocation.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::CompactVec;
    /// let vec: CompactVec<i8> = CompactVec::new();
    /// assert_eq!(vec.len(), 0);
    /// assert!(vec.is_inline());
    /// ```
    #[inline]
    pub fn new() -> Self {
        CompactVec::Inline([T::InlineType::default(); INLINE_CAPACITY], 0)
    }

    /// Transitions the vector from inline storage to heap storage.
    ///
    /// This method converts all inline-stored elements to their full representation
    /// and moves them to a heap-allocated vector. It's called automatically when
    /// inline storage is insufficient (either due to capacity or representation limits).
    ///
    /// Returns a mutable reference to the heap vector for immediate use.
    #[inline]
    fn transition_to_heap(&mut self) -> &mut LimitedSizeVec<T> {
        match self {
            CompactVec::Inline(storage, length) => {
                let mut heap_vec = LimitedSizeVec::new();
                for i in 0..*length {
                    heap_vec.push(T::from_inline(storage[i as usize]));
                }
                *self = CompactVec::Heap(heap_vec);
                match self {
                    CompactVec::Heap(vec) => vec,
                    _ => unreachable!(),
                }
            }
            CompactVec::Heap(vec) => vec,
        }
    }

    /// Fast push for types where conversion is infallible (i8, u8)
    /// Appends an element to the back of the collection without checking conversion validity.
    ///
    /// This method provides optimal performance for types with infallible inline conversions
    /// (such as `i8` and `u8`) by skipping runtime conversion checks.
    ///
    /// # Safety
    ///
    /// This method should only be used with types where `T::CONVERSION_INFALLIBLE` is true.
    /// Using it with other types may cause debug assertions to fail.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::CompactVec;
    /// let mut vec: CompactVec<i8> = CompactVec::new();
    /// vec.push_unchecked(42);
    /// vec.push_unchecked(-10);
    /// assert_eq!(vec.len(), 2);
    /// ```
    #[inline]
    pub fn push_unchecked(&mut self, value: T) {
        debug_assert!(
            T::CONVERSION_INFALLIBLE,
            "push_unchecked only valid for infallible types"
        );

        match self {
            CompactVec::Inline(storage, length) => {
                if (*length as usize) < INLINE_CAPACITY {
                    storage[*length as usize] = T::to_inline_unchecked(value);
                    *length += 1;
                } else {
                    self.transition_to_heap().push(value);
                }
            }
            CompactVec::Heap(vec) => {
                vec.push(value);
            }
        }
    }

    /// Appends an element to the back of the collection.
    ///
    /// If the vector is using inline storage and has capacity, the element is stored inline.
    /// If inline storage cannot represent the value or is full, the vector transitions to heap storage.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::CompactVec;
    /// let mut vec: CompactVec<i8> = CompactVec::new();
    /// vec.push(1);
    /// vec.push(2);
    /// assert_eq!(vec.len(), 2);
    /// ```
    #[inline]
    pub fn push(&mut self, value: T) {
        // Fast path for infallible conversions
        if T::CONVERSION_INFALLIBLE {
            self.push_unchecked(value);
            return;
        }

        match self {
            CompactVec::Inline(storage, length) => {
                if (*length as usize) < INLINE_CAPACITY {
                    match T::to_inline(value) {
                        Ok(inline_value) => {
                            storage[*length as usize] = inline_value;
                            *length += 1;
                        }
                        Err(original_value) => {
                            self.transition_to_heap().push(original_value);
                        }
                    }
                } else {
                    self.transition_to_heap().push(value);
                }
            }
            CompactVec::Heap(vec) => {
                vec.push(value);
            }
        }
    }

    /// Removes the last element from the vector and returns it, or `None` if empty.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::CompactVec;
    /// let mut vec: CompactVec<i8> = CompactVec::new();
    /// vec.push(1);
    /// vec.push(2);
    /// assert_eq!(vec.pop(), Some(2));
    /// assert_eq!(vec.pop(), Some(1));
    /// assert_eq!(vec.pop(), None);
    /// ```
    #[inline]
    pub fn pop(&mut self) -> Option<T> {
        match self {
            CompactVec::Inline(storage, length) => {
                if *length > 0 {
                    *length -= 1;
                    Some(T::from_inline(storage[*length as usize]))
                } else {
                    None
                }
            }
            CompactVec::Heap(vec) => vec.pop(),
        }
    }

    /// Returns the number of elements in the vector.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::CompactVec;
    /// let mut vec: CompactVec<i8> = CompactVec::new();
    /// assert_eq!(vec.len(), 0);
    /// vec.push(1);
    /// assert_eq!(vec.len(), 1);
    /// ```
    #[inline]
    pub fn len(&self) -> usize {
        match self {
            CompactVec::Inline(_, length) => *length as usize,
            CompactVec::Heap(vec) => vec.len(),
        }
    }

    /// Returns `true` if the vector contains no elements.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::CompactVec;
    /// let mut vec: CompactVec<i8> = CompactVec::new();
    /// assert!(vec.is_empty());
    /// vec.push(1);
    /// assert!(!vec.is_empty());
    /// ```
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns a copy of the element at the given index, or `None` if the index is out of bounds.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::CompactVec;
    /// let mut vec: CompactVec<i8> = CompactVec::new();
    /// vec.push(10);
    /// vec.push(20);
    /// assert_eq!(vec.get(0), Some(10));
    /// assert_eq!(vec.get(1), Some(20));
    /// assert_eq!(vec.get(2), None);
    /// ```
    #[inline]
    pub fn get(&self, index: usize) -> Option<T> {
        match self {
            CompactVec::Inline(storage, length) => {
                if index < *length as usize {
                    Some(T::from_inline(storage[index]))
                } else {
                    None
                }
            }
            CompactVec::Heap(vec) => vec.get(index).copied(),
        }
    }

    /// Returns a copy of the element at the given index without bounds checking.
    ///
    /// This provides optimal performance when the caller can guarantee the index is valid.
    ///
    /// # Safety
    ///
    /// Calling this method with an out-of-bounds index is undefined behavior,
    /// even with a safe type `T`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::CompactVec;
    /// let mut vec: CompactVec<i8> = CompactVec::new();
    /// vec.push(42);
    /// unsafe {
    ///     assert_eq!(vec.get_unchecked(0), 42);
    /// }
    /// ```
    #[inline]
    pub unsafe fn get_unchecked(&self, index: usize) -> T {
        unsafe {
            match self {
                CompactVec::Inline(storage, _) => T::from_inline(*storage.get_unchecked(index)),
                CompactVec::Heap(vec) => *vec.get_unchecked(index),
            }
        }
    }

    /// Returns `true` if the vector is currently using inline storage.
    ///
    /// This can be useful for performance-sensitive code that needs to know
    /// whether operations will involve heap allocation or inline array access.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::CompactVec;
    /// let mut vec: CompactVec<i8> = CompactVec::new();
    /// assert!(vec.is_inline());
    ///
    /// // Still inline after adding elements
    /// for i in 0..7 {
    ///     vec.push(i);
    /// }
    /// assert!(vec.is_inline());
    ///
    /// // Transitions to heap when capacity is exceeded
    /// vec.push(7);
    /// assert!(!vec.is_inline());
    /// ```
    #[inline]
    pub fn is_inline(&self) -> bool {
        matches!(self, CompactVec::Inline(_, _))
    }

    /// Returns the total capacity of the vector.
    ///
    /// For inline storage, this is always INLINE_CAPACITY. For heap storage, this returns
    /// the current heap capacity which may be larger than the length.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::CompactVec;
    /// let vec: CompactVec<i8> = CompactVec::new();
    /// assert_eq!(vec.capacity(), 7);
    ///
    /// let mut vec: CompactVec<i8> = CompactVec::new();
    /// for i in 0..8 {  // Force transition to heap
    ///     vec.push(i);
    /// }
    /// assert!(vec.capacity() >= 8);  // Heap capacity may be larger
    /// ```
    #[inline]
    pub fn capacity(&self) -> usize {
        match self {
            CompactVec::Inline(_, _) => INLINE_CAPACITY,
            CompactVec::Heap(vec) => vec.capacity(),
        }
    }

    /// Returns the vector's contents as a slice.
    ///
    /// This method provides zero-cost slice access for types where `T` and `T::InlineType`
    /// are the same (such as `i8` and `u8`). For other types, it panics since the
    /// inline storage cannot be directly interpreted as a slice of `T`.
    ///
    /// # Panics
    ///
    /// Panics if `T` and `T::InlineType` are different types, as conversion would be required.
    /// Use `iter()` instead for such types.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::CompactVec;
    /// let mut vec: CompactVec<i8> = CompactVec::new();
    /// vec.push(1);
    /// vec.push(2);
    /// vec.push(3);
    /// let slice = vec.as_slice();
    /// assert_eq!(slice, &[1, 2, 3]);
    /// ```
    #[inline]
    pub fn as_slice(&self) -> &[T] {
        // Check if T and T::InlineType are the same type (zero-cost conversion)
        if TypeId::of::<T>() == TypeId::of::<T::InlineType>() {
            match self {
                CompactVec::Inline(storage, length) => {
                    unsafe {
                        // Safe because T == T::InlineType
                        let ptr = storage.as_ptr() as *const T;
                        std::slice::from_raw_parts(ptr, *length as usize)
                    }
                }
                CompactVec::Heap(vec) => vec.as_slice(),
            }
        } else {
            // TODO: transition to HEAP, then return slice
            panic!(
                "Cannot get slice from inline storage for non-zero-cost types - use iter() instead"
            )
        }
    }

    /// Removes and returns the element at position `index`, shifting all elements after it to the left.
    ///
    /// # Panics
    /// Panics if `index` is out of bounds.
    #[inline]
    pub fn remove(&mut self, index: usize) -> T {
        if index >= self.len() {
            panic!(
                "removal index (is {}) should be < len (is {})",
                index,
                self.len()
            );
        }

        match self {
            CompactVec::Inline(storage, length) => {
                let result = T::from_inline(storage[index]);
                // Shift elements left
                for i in index..(*length as usize - 1) {
                    storage[i] = storage[i + 1];
                }
                *length -= 1;
                result
            }
            CompactVec::Heap(vec) => vec.remove(index),
        }
    }

    /// Inserts an element at position `index`, shifting all elements after it to the right.
    ///
    /// # Panics
    /// Panics if `index > len`.
    #[inline]
    pub fn insert(&mut self, index: usize, element: T) {
        if index > self.len() {
            panic!(
                "insertion index (is {}) should be <= len (is {})",
                index,
                self.len()
            );
        }

        match self {
            CompactVec::Inline(storage, length) => {
                if (*length as usize) >= INLINE_CAPACITY || T::to_inline(element).is_err() {
                    self.transition_to_heap().insert(index, element);
                } else {
                    // Shift elements right
                    for i in (index..*length as usize).rev() {
                        storage[i + 1] = storage[i];
                    }
                    storage[index] = T::to_inline(element).unwrap_or_else(|_| unreachable!());
                    *length += 1;
                }
            }
            CompactVec::Heap(vec) => vec.insert(index, element),
        }
    }

    /// Shortens the vector, keeping the first `len` elements and dropping the rest.
    ///
    /// If `len` is greater than the vector's current length, this has no effect.
    #[inline]
    pub fn truncate(&mut self, len: usize) {
        match self {
            CompactVec::Inline(_, length) => {
                if len < *length as usize {
                    *length = len as u8;
                }
            }
            CompactVec::Heap(vec) => vec.truncate(len),
        }
    }

    /// Resizes the vector to the given length.
    ///
    /// If `new_len` is greater than `len`, the vector is extended with clones of `value`.
    /// If `new_len` is less than `len`, the vector is truncated.
    #[inline]
    pub fn resize(&mut self, new_len: usize, value: T) {
        let current_len = self.len();
        if new_len > current_len {
            for _ in current_len..new_len {
                self.push(value);
            }
        } else {
            self.truncate(new_len);
        }
    }

    /// Extends the vector by cloning elements from a slice.
    ///
    /// All elements from the slice are appended to the vector in order.
    /// If the vector is using inline storage and the additional elements
    /// cause it to exceed capacity or cannot be represented inline,
    /// it will transition to heap storage automatically.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::CompactVec;
    /// let mut vec: CompactVec<i8> = CompactVec::new();
    /// vec.extend_from_slice(&[1, 2, 3]);
    /// assert_eq!(vec.len(), 3);
    ///
    /// vec.extend_from_slice(&[4, 5]);
    /// assert_eq!(vec.len(), 5);
    /// ```
    #[inline]
    pub fn extend_from_slice(&mut self, other: &[T]) {
        for item in other {
            self.push(*item);
        }
    }

    /// Reserves capacity for at least `additional` more elements.
    ///
    /// For inline storage, this will transition to heap if the requested
    /// additional capacity would exceed the inline capacity of INLINE_CAPACITY elements.
    /// For heap storage, this forwards the call to the underlying vector's
    /// reserve method.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::CompactVec;
    /// let mut vec: CompactVec<i8> = CompactVec::new();
    /// vec.reserve(10);  // This will transition to heap since 10 > INLINE_CAPACITY
    /// assert!(!vec.is_inline());
    /// assert!(vec.capacity() >= 10);
    /// ```
    #[inline]
    pub fn reserve(&mut self, additional: usize) {
        match self {
            CompactVec::Inline(_, _) => {
                let new_capacity = self.len() + additional;

                if self.capacity() >= new_capacity {
                    return;
                }

                if new_capacity > INLINE_CAPACITY {
                    self.transition_to_heap().reserve(additional);
                }
            }
            CompactVec::Heap(vec) => vec.reserve(additional),
        }
    }

    /// Clears the vector, removing all elements but keeping allocated capacity.
    ///
    /// For inline storage, this resets the length to 0 without changing the storage mode.
    /// For heap storage, this forwards the call to the underlying vector, which clears
    /// all elements but preserves the allocated heap capacity.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::CompactVec;
    /// let mut vec: CompactVec<i8> = CompactVec::new();
    /// vec.push(1);
    /// vec.push(2);
    /// vec.push(3);
    /// assert_eq!(vec.len(), 3);
    ///
    /// vec.clear();
    /// assert_eq!(vec.len(), 0);
    /// assert!(vec.is_empty());
    /// ```
    #[inline]
    pub fn clear(&mut self) {
        match self {
            CompactVec::Inline(_, length) => *length = 0,
            CompactVec::Heap(vec) => vec.clear(),
        }
    }

    /// Returns `true` if the vector contains an element equal to `value`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::CompactVec;
    /// let mut vec: CompactVec<i8> = CompactVec::new();
    /// vec.push(1);
    /// vec.push(2);
    /// vec.push(3);
    ///
    /// assert!(vec.contains(&1));
    /// assert!(!vec.contains(&4));
    /// ```
    #[inline]
    pub fn contains(&self, value: &T) -> bool
    where
        T: PartialEq,
    {
        match self {
            CompactVec::Inline(storage, length) => {
                for i in 0..*length as usize {
                    if T::from_inline(storage[i]) == *value {
                        return true;
                    }
                }
                false
            }
            CompactVec::Heap(vec) => vec.contains(value),
        }
    }

    /// Sorts the vector in-place using the natural ordering of elements.
    ///
    /// This uses insertion sort for inline storage (which is efficient for small arrays)
    /// and delegates to the underlying vector's sort method for heap storage.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::CompactVec;
    /// let mut vec: CompactVec<i8> = CompactVec::new();
    /// vec.extend_from_slice(&[3, 1, 4, 1, 5]);
    /// vec.sort();
    /// assert_eq!(vec.as_slice(), &[1, 1, 3, 4, 5]);
    /// ```
    #[inline]
    pub fn sort(&mut self)
    where
        T: Ord,
    {
        match self {
            CompactVec::Inline(storage, length) => {
                if *length <= 1 {
                    return;
                }

                for i in 1..*length {
                    let mut j = i as usize;
                    while j > 0 && T::from_inline(storage[j - 1]) > T::from_inline(storage[j]) {
                        storage.swap(j - 1, j);
                        j -= 1;
                    }
                }
            }
            CompactVec::Heap(vec) => vec.sort(),
        }
    }

    /// Takes ownership of the vector's contents, leaving the original empty.
    ///
    /// This is equivalent to `std::mem::replace(self, CompactVec::new())` but more explicit.
    /// The original vector is left in a new, empty state (using inline storage).
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::CompactVec;
    /// let mut vec: CompactVec<i8> = CompactVec::new();
    /// vec.extend_from_slice(&[1, 2, 3]);
    ///
    /// let taken = vec.take();
    /// assert_eq!(taken.len(), 3);
    /// assert_eq!(vec.len(), 0);
    /// assert!(vec.is_empty());
    /// ```
    #[inline]
    pub fn take(&mut self) -> Self {
        std::mem::take(self)
    }

    /// Returns a mutable reference to the element at the given index, or `None` if out of bounds.
    ///
    /// For inline storage with non-zero-cost type conversions, this method will transition
    /// the vector to heap storage to provide mutable access. For zero-cost conversions
    /// (where `T` and `T::InlineType` are the same), it provides direct mutable access
    /// to the inline storage.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::CompactVec;
    /// let mut vec: CompactVec<i8> = CompactVec::new();
    /// vec.push(10);
    /// vec.push(20);
    ///
    /// if let Some(elem) = vec.get_mut(1) {
    ///     *elem = 25;
    /// }
    /// assert_eq!(vec.get(1), Some(25));
    /// ```
    #[inline]
    pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
        // Check if T and T::InlineType are the same type (zero-cost conversion)
        match self {
            CompactVec::Inline(storage, length) => {
                if index < *length as usize {
                    if TypeId::of::<T>() == TypeId::of::<T::InlineType>() {
                        unsafe {
                            // Safe because T == T::InlineType
                            let ptr = storage.as_mut_ptr() as *mut T;
                            Some(&mut *ptr.add(index))
                        }
                    } else {
                        // We need to transition to heap for mutable access
                        self.transition_to_heap().get_mut(index)
                    }
                } else {
                    None
                }
            }
            CompactVec::Heap(vec) => vec.get_mut(index),
        }
    }

    /// Returns a mutable reference to an element without bounds checking.
    ///
    /// For inline storage with non-zero-cost type conversions, this method will transition
    /// the vector to heap storage to provide mutable access. For zero-cost conversions,
    /// it provides direct unsafe mutable access to the inline storage.
    ///
    /// # Safety
    ///
    /// Calling this method with an out-of-bounds index is undefined behavior,
    /// even with a safe type `T`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::CompactVec;
    /// let mut vec: CompactVec<i8> = CompactVec::new();
    /// vec.push(42);
    /// unsafe {
    ///     *vec.get_mut_unchecked(0) = 100;
    ///     assert_eq!(vec.get(0), Some(100));
    /// }
    /// ```
    #[inline]
    pub unsafe fn get_mut_unchecked(&mut self, index: usize) -> &mut T {
        unsafe {
            // Check if T and T::InlineType are the same type (zero-cost conversion)
            match self {
                CompactVec::Inline(storage, _) => {
                    if TypeId::of::<T>() == TypeId::of::<T::InlineType>() {
                        // Safe because T == T::InlineType and caller guarantees bounds
                        let ptr = storage.as_mut_ptr() as *mut T;
                        &mut *ptr.add(index)
                    } else {
                        self.transition_to_heap().get_mut_unchecked(index)
                    }
                }
                CompactVec::Heap(vec) => vec.get_mut_unchecked(index),
            }
        }
    }

    /// Returns the vector's contents as a mutable slice.
    ///
    /// For inline storage with non-zero-cost type conversions, this method will transition
    /// the vector to heap storage to provide mutable slice access. For zero-cost conversions
    /// (where `T` and `T::InlineType` are the same), it provides direct mutable access
    /// to the inline storage as a slice.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::CompactVec;
    /// let mut vec: CompactVec<i8> = CompactVec::new();
    /// vec.extend_from_slice(&[1, 2, 3]);
    ///
    /// let slice = vec.as_slice_mut();
    /// slice[1] = 10;
    /// assert_eq!(vec.get(1), Some(10));
    /// ```
    #[inline]
    pub fn as_slice_mut(&mut self) -> &mut [T] {
        // Check if T and T::InlineType are the same type (zero-cost conversion)
        match self {
            CompactVec::Inline(storage, length) => {
                if TypeId::of::<T>() == TypeId::of::<T::InlineType>() {
                    unsafe {
                        // Safe because T == T::InlineType
                        let ptr = storage.as_mut_ptr() as *mut T;
                        std::slice::from_raw_parts_mut(ptr, *length as usize)
                    }
                } else {
                    self.transition_to_heap().as_mut()
                }
            }
            CompactVec::Heap(vec) => vec.as_mut(),
        }
    }

    /// Returns an iterator over the vector's elements.
    ///
    /// This iterator is optimized for inline storage, avoiding heap allocations
    /// and providing efficient element access for small collections.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::CompactVec;
    /// let mut vec: CompactVec<i8> = CompactVec::new();
    /// vec.extend_from_slice(&[1, 2, 3]);
    ///
    /// let sum: i8 = vec.iter().sum();
    /// assert_eq!(sum, 6);
    ///
    /// for (i, value) in vec.iter().enumerate() {
    ///     println!("Element {}: {}", i, value);
    /// }
    /// ```
    #[inline]
    pub fn iter(&self) -> CompactVecIter<'_, T> {
        match self {
            CompactVec::Inline(storage, length) => CompactVecIter::Inline(storage, 0, *length),
            CompactVec::Heap(vec) => CompactVecIter::Heap(vec.iter()),
        }
    }
}

impl<T: CompactStorage> Default for CompactVec<T> {
    /// Creates an empty `CompactVec<T>`.
    ///
    /// This is equivalent to `CompactVec::new()`.
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

/// An iterator over the elements of a `CompactVec`.
///
/// This iterator is optimized to handle both inline and heap storage modes efficiently.
/// It's created by calling `iter()` on a `CompactVec`.
#[derive(Debug, Clone)]
pub enum CompactVecIter<'a, T: CompactStorage> {
    /// Iterator over inline storage elements.
    ///
    /// Contains: (storage reference, current index, total length)
    Inline(&'a [T::InlineType; INLINE_CAPACITY], u8, u8),
    /// Iterator over heap storage elements.
    Heap(std::slice::Iter<'a, T>),
}

impl<'a, T: CompactStorage> Iterator for CompactVecIter<'a, T> {
    type Item = T;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        match self {
            CompactVecIter::Inline(storage, index, length) => {
                if *index < *length {
                    let result = T::from_inline(storage[*index as usize]);
                    *index += 1;
                    Some(result)
                } else {
                    None
                }
            }
            CompactVecIter::Heap(iter) => iter.next().copied(),
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        match self {
            CompactVecIter::Inline(_, index, length) => {
                let remaining = (*length - *index) as usize;
                (remaining, Some(remaining))
            }
            CompactVecIter::Heap(iter) => iter.size_hint(),
        }
    }
}

impl<'a, T: CompactStorage> ExactSizeIterator for CompactVecIter<'a, T> {}

impl<T> AsMut<[T]> for CompactVec<T>
where
    T: CompactStorage,
{
    /// Returns a mutable slice of the vector's contents.
    ///
    /// This delegates to `as_slice_mut()`.
    #[inline]
    fn as_mut(&mut self) -> &mut [T] {
        self.as_slice_mut()
    }
}

/// Enables converting a `Vec<T>` into a `CompactVec<T>`.
impl<T> From<Vec<T>> for CompactVec<T>
where
    T: CompactStorage,
{
    /// Creates a `CompactVec` from a standard `Vec`.
    ///
    /// All elements are moved from the source vector. If the vector has INLINE_CAPACITY or fewer
    /// elements and they can all be represented inline, the result will use inline storage.
    /// Otherwise, it will use heap storage.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::CompactVec;
    /// let vec = vec![1i8, 2, 3];
    /// let compact: CompactVec<i8> = vec.into();
    /// assert_eq!(compact.len(), 3);
    /// assert!(compact.is_inline());
    /// ```
    #[inline]
    fn from(vec: Vec<T>) -> Self {
        if vec.len() > INLINE_CAPACITY {
            Self::Heap(LimitedSizeVec::from(vec))
        } else {
            let mut compact_vec = Self::new();
            for item in vec {
                compact_vec.push(item);
            }
            compact_vec
        }
    }
}

/// Enables converting a fixed-size array `[T; N]` into a `CompactVec<T>`.
impl<T, const N: usize> From<[T; N]> for CompactVec<T>
where
    T: CompactStorage,
{
    /// Creates a `CompactVec` from a fixed-size array.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::CompactVec;
    /// let array = [1i8, 2, 3, 4, 5];
    /// let compact: CompactVec<i8> = array.into();
    /// assert_eq!(compact.len(), 5);
    /// ```
    #[inline]
    fn from(array: [T; N]) -> Self {
        let mut compact_vec = Self::new();
        for item in array {
            compact_vec.push(item);
        }
        compact_vec
    }
}

/// Enables converting a fixed-size array `[T; N]` into a `CompactVec<T>`.
impl<T, const N: usize> From<&[T; N]> for CompactVec<T>
where
    T: CompactStorage,
{
    /// Creates a `CompactVec` from a fixed-size array.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::CompactVec;
    /// let array = [1i8, 2, 3, 4, 5];
    /// let compact: CompactVec<i8> = array.into();
    /// assert_eq!(compact.len(), 5);
    /// ```
    #[inline]
    fn from(array: &[T; N]) -> Self {
        let mut compact_vec = Self::new();
        for item in array {
            compact_vec.push(*item);
        }
        compact_vec
    }
}

/// Enables converting a slice `&[T]` into a `CompactVec<T>`.
impl<T> From<&[T]> for CompactVec<T>
where
    T: CompactStorage + Clone,
{
    /// Creates a `CompactVec` from a slice by cloning all elements.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::CompactVec;
    /// let slice = &[1i8, 2, 3];
    /// let compact: CompactVec<i8> = slice.into();
    /// assert_eq!(compact.len(), 3);
    /// ```
    #[inline]
    fn from(slice: &[T]) -> Self {
        let mut compact_vec = Self::new();
        for item in slice {
            compact_vec.push(*item);
        }
        compact_vec
    }
}

/// Enables converting a `&Vec<T>` into a `CompactVec<T>`.
impl<T> From<&Vec<T>> for CompactVec<T>
where
    T: CompactStorage + Clone,
{
    /// Creates a `CompactVec` from a vector reference by cloning all elements.
    ///
    /// This delegates to the `&[T]` implementation.
    #[inline]
    fn from(vec: &Vec<T>) -> Self {
        Self::from(vec.as_slice())
    }
}

/// Enables converting a `CompactVec<T>` into a standard `Vec<T>`.
impl<T> From<CompactVec<T>> for Vec<T>
where
    T: CompactStorage,
{
    /// Creates a standard `Vec` from a `CompactVec`.
    ///
    /// For inline storage, a new vector is allocated and all elements are copied.
    /// For heap storage, the underlying vector is returned directly when possible.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::CompactVec;
    /// let mut compact: CompactVec<i8> = CompactVec::new();
    /// compact.extend_from_slice(&[1, 2, 3]);
    ///
    /// let vec: Vec<i8> = compact.into();
    /// assert_eq!(vec, vec![1, 2, 3]);
    /// ```
    #[inline]
    fn from(compact_vec: CompactVec<T>) -> Self {
        match compact_vec {
            CompactVec::Inline(storage, length) => {
                let mut vec = Vec::with_capacity(length as usize);
                for i in 0..length {
                    vec.push(T::from_inline(storage[i as usize]));
                }
                vec
            }
            CompactVec::Heap(vec) => vec.into(),
        }
    }
}

impl<T: CompactStorage + Hash> Hash for CompactVec<T> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        for item in self.iter() {
            item.hash(state);
        }
    }
}

impl<T: CompactStorage + PartialEq> PartialEq for CompactVec<T> {
    fn eq(&self, other: &Self) -> bool {
        if self.len() != other.len() {
            return false;
        }

        self.iter().zip(other.iter()).all(|(a, b)| a == b)
    }
}

impl<T: CompactStorage + Eq> Eq for CompactVec<T> {}

/// An owning iterator over the elements of a `CompactVec`.
///
/// This iterator moves elements out of the vector, consuming it in the process.
/// It's created by calling `into_iter()` on a `CompactVec` or by using a `for` loop.
/// Like `CompactVecIter`, it's optimized to handle both inline and heap storage modes.
pub enum CompactVecIntoIter<T: CompactStorage> {
    /// Iterator that moves out of inline storage elements.
    ///
    /// Contains: (storage array, current index, total length)
    Inline([T::InlineType; INLINE_CAPACITY], u8, u8),
    /// Iterator that moves out of heap storage elements.
    Heap(<LimitedSizeVec<T> as IntoIterator>::IntoIter),
}

impl<T: CompactStorage> Iterator for CompactVecIntoIter<T> {
    type Item = T;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        match self {
            CompactVecIntoIter::Inline(storage, index, length) => {
                if *index < *length {
                    let result = T::from_inline(storage[*index as usize]);
                    *index += 1;
                    Some(result)
                } else {
                    None
                }
            }
            CompactVecIntoIter::Heap(iter) => iter.next(),
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        match self {
            CompactVecIntoIter::Inline(_, index, length) => {
                let remaining = (*length - *index) as usize;
                (remaining, Some(remaining))
            }
            CompactVecIntoIter::Heap(iter) => iter.size_hint(),
        }
    }
}

impl<T: CompactStorage> ExactSizeIterator for CompactVecIntoIter<T> {}

impl<T: CompactStorage> FromIterator<T> for CompactVec<T> {
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        let iter = iter.into_iter();
        let (min_len, max_len) = iter.size_hint();

        if let Some(len) = max_len {
            if len <= INLINE_CAPACITY {
                // If the known size fits within inline capacity:
                // For types with infallible inline conversions (e.g., i8, u8),
                // we can directly populate the inline array for maximum performance.
                if T::CONVERSION_INFALLIBLE {
                    let mut storage = [T::InlineType::default(); INLINE_CAPACITY];
                    let mut i = 0;
                    for next in iter {
                        storage[i] = T::to_inline_unchecked(next);
                        i += 1;
                    }
                    return CompactVec::Inline(storage, i as u8);
                }
                // For types with fallible inline conversions, even if the size fits,
                // we cannot pre-populate without checking each item. In this case,
                // we fall through to the general `push` loop, which handles conversions
                // and potential transitions to heap as needed.
            } else {
                // If the known size exceeds inline capacity, it will definitely be a heap-allocated vector.
                // We collect all elements directly into a LimitedSizeVec, leveraging its FromIterator
                // implementation which uses the size hint for efficient allocation.
                return CompactVec::Heap(iter.collect::<LimitedSizeVec<T>>());
            }
        } else {
            // If the exact size is unknown, but the lower bound suggests it's likely to be large,
            // we start with a heap-allocated vector to avoid multiple reallocations during inline-to-heap transition.
            if min_len > INLINE_CAPACITY {
                // Collect into a LimitedSizeVec. Its FromIterator will use min_len for initial capacity.
                return CompactVec::Heap(iter.collect::<LimitedSizeVec<T>>());
            }
        }

        // Default path: This covers cases where a specialized path wasn't taken,
        let mut compact_vec = Self::new();
        for item in iter {
            compact_vec.push(item);
        }
        compact_vec
    }
}

/// Enables using `CompactVec` as a mutable slice through the `AsMut` trait.
impl<T> IntoIterator for CompactVec<T>
where
    T: CompactStorage,
{
    type Item = T;
    type IntoIter = CompactVecIntoIter<T>;

    /// Creates an owning iterator that consumes the vector.
    ///
    /// # Examples
    ///
    /// ```
    /// # use qudit_core::CompactVec;
    /// let mut vec: CompactVec<i8> = CompactVec::new();
    /// vec.extend_from_slice(&[1, 2, 3]);
    ///
    /// let doubled: Vec<i8> = vec.into_iter().map(|x| x * 2).collect();
    /// assert_eq!(doubled, vec![2, 4, 6]);
    /// ```
    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        match self {
            CompactVec::Inline(storage, length) => CompactVecIntoIter::Inline(storage, 0, length),
            CompactVec::Heap(vec) => CompactVecIntoIter::Heap(vec.into_iter()),
        }
    }
}

impl<'a, T> IntoIterator for &'a CompactVec<T>
where
    T: CompactStorage,
{
    type Item = T;
    type IntoIter = CompactVecIter<'a, T>;

    /// Creates an iterator over references to the vector's elements.
    ///
    /// This delegates to `iter()`.
    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a, T> IntoIterator for &'a mut CompactVec<T>
where
    T: CompactStorage,
{
    type Item = &'a mut T;
    type IntoIter = std::slice::IterMut<'a, T>;

    /// Creates an iterator over mutable references to the vector's elements.
    ///
    /// For inline storage with non-zero-cost conversions, this will transition
    /// the vector to heap storage.
    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.as_slice_mut().iter_mut()
    }
}

// Specialized implementations for zero-cost conversions (T == T::InlineType)
// These provide optimal performance for i8 and u8 types.
/// Enables treating `CompactVec<i8>` as a slice through the `Deref` trait.
///
/// This implementation is only available for `i8` because it has zero-cost
/// conversion with its inline type.
impl std::ops::Deref for CompactVec<i8> {
    type Target = [i8];

    /// Returns a slice view of the vector's contents.
    ///
    /// This provides zero-cost access to the underlying storage.
    #[inline]
    fn deref(&self) -> &Self::Target {
        match self {
            CompactVec::Inline(storage, length) => unsafe {
                std::slice::from_raw_parts(storage.as_ptr(), *length as usize)
            },
            CompactVec::Heap(vec) => vec.as_slice(),
        }
    }
}

/// Enables treating `CompactVec<u8>` as a slice through the `Deref` trait.
///
/// This implementation is only available for `u8` because it has zero-cost
/// conversion with its inline type.
impl std::ops::Deref for CompactVec<u8> {
    type Target = [u8];

    /// Returns a slice view of the vector's contents.
    ///
    /// This provides zero-cost access to the underlying storage.
    #[inline]
    fn deref(&self) -> &Self::Target {
        match self {
            CompactVec::Inline(storage, length) => unsafe {
                std::slice::from_raw_parts(storage.as_ptr(), *length as usize)
            },
            CompactVec::Heap(vec) => vec.as_slice(),
        }
    }
}

/// Enables indexing `CompactVec<i8>` with `[]` syntax.
impl std::ops::Index<usize> for CompactVec<i8> {
    type Output = i8;

    /// Returns a reference to the element at the given index.
    ///
    /// # Panics
    ///
    /// Panics if the index is out of bounds.
    #[inline]
    fn index(&self, index: usize) -> &Self::Output {
        match self {
            CompactVec::Inline(storage, length) => {
                if index >= *length as usize {
                    panic!(
                        "index out of bounds: the len is {} but the index is {}",
                        *length, index
                    );
                }
                &storage[index]
            }
            CompactVec::Heap(vec) => &vec[index],
        }
    }
}

/// Enables indexing `CompactVec<u8>` with `[]` syntax.
impl std::ops::Index<usize> for CompactVec<u8> {
    type Output = u8;

    /// Returns a reference to the element at the given index.
    ///
    /// # Panics
    ///
    /// Panics if the index is out of bounds.
    #[inline]
    fn index(&self, index: usize) -> &Self::Output {
        match self {
            CompactVec::Inline(storage, length) => {
                if index >= *length as usize {
                    panic!(
                        "index out of bounds: the len is {} but the index is {}",
                        *length, index
                    );
                }
                &storage[index]
            }
            CompactVec::Heap(vec) => &vec[index],
        }
    }
}

/// Enables using `CompactVec<i8>` where `&[i8]` is expected.
impl AsRef<[i8]> for CompactVec<i8> {
    /// Returns a slice view of the vector's contents.
    #[inline]
    fn as_ref(&self) -> &[i8] {
        self.as_slice()
    }
}

/// Enables using `CompactVec<u8>` where `&[u8]` is expected.
impl AsRef<[u8]> for CompactVec<u8> {
    /// Returns a slice view of the vector's contents.
    #[inline]
    fn as_ref(&self) -> &[u8] {
        self.as_slice()
    }
}

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

    // Helper function to create a test CompactVec with known elements
    fn test_vec_with_elements<T: CompactStorage + Clone>(elements: &[T]) -> CompactVec<T> {
        let mut vec: CompactVec<T> = CompactVec::new();
        for elem in elements {
            vec.push(*elem);
        }
        vec
    }

    #[test]
    fn test_new() {
        let vec: CompactVec<i8> = CompactVec::new();
        assert_eq!(vec.len(), 0);
        assert!(vec.is_empty());
        assert!(vec.is_inline());
        assert_eq!(vec.capacity(), INLINE_CAPACITY);
    }

    #[test]
    fn test_default() {
        let vec: CompactVec<i8> = CompactVec::default();
        assert_eq!(vec.len(), 0);
        assert!(vec.is_empty());
        assert!(vec.is_inline());
    }

    #[test]
    fn test_push_inline() {
        let mut vec: CompactVec<i8> = CompactVec::new();

        // Test pushing elements within inline capacity
        for i in 0..INLINE_CAPACITY as i8 {
            vec.push(i);
            assert_eq!(vec.len(), (i + 1) as usize);
            assert!(vec.is_inline());
            assert_eq!(vec.get(i as usize), Some(i));
        }

        assert_eq!(vec.len(), INLINE_CAPACITY);
        assert!(vec.is_inline());
    }

    #[test]
    fn test_push_transition_to_heap() {
        let mut vec: CompactVec<i8> = CompactVec::new();

        // Fill inline storage
        for i in 0..INLINE_CAPACITY as i8 {
            vec.push(i);
        }
        assert!(vec.is_inline());

        // This should trigger transition to heap
        vec.push(INLINE_CAPACITY as i8);
        assert!(!vec.is_inline());
        assert_eq!(vec.len(), INLINE_CAPACITY + 1);
        assert!(vec.capacity() > INLINE_CAPACITY);

        // Verify all elements are still accessible
        for i in 0..=INLINE_CAPACITY as i8 {
            assert_eq!(vec.get(i as usize), Some(i));
        }
    }

    #[test]
    fn test_push_unchecked() {
        let mut vec: CompactVec<i8> = CompactVec::new();

        vec.push_unchecked(42);
        vec.push_unchecked(-10);

        assert_eq!(vec.len(), 2);
        assert_eq!(vec.get(0), Some(42));
        assert_eq!(vec.get(1), Some(-10));
    }

    #[test]
    fn test_pop() {
        let mut vec: CompactVec<i8> = CompactVec::new();

        // Pop from empty vector
        assert_eq!(vec.pop(), None);

        // Push some elements and pop them
        vec.push(1);
        vec.push(2);
        vec.push(3);

        assert_eq!(vec.pop(), Some(3));
        assert_eq!(vec.len(), 2);
        assert_eq!(vec.pop(), Some(2));
        assert_eq!(vec.pop(), Some(1));
        assert_eq!(vec.len(), 0);
        assert_eq!(vec.pop(), None);
    }

    #[test]
    fn test_get_and_bounds() {
        let vec = test_vec_with_elements(&[1i8, 2, 3]);

        assert_eq!(vec.get(0), Some(1));
        assert_eq!(vec.get(1), Some(2));
        assert_eq!(vec.get(2), Some(3));
        assert_eq!(vec.get(3), None);
        assert_eq!(vec.get(100), None);
    }

    #[test]
    fn test_get_unchecked() {
        let vec = test_vec_with_elements(&[42i8, -10, 100]);

        unsafe {
            assert_eq!(vec.get_unchecked(0), 42);
            assert_eq!(vec.get_unchecked(1), -10);
            assert_eq!(vec.get_unchecked(2), 100);
        }
    }

    #[test]
    fn test_capacity() {
        let mut vec: CompactVec<i8> = CompactVec::new();
        assert_eq!(vec.capacity(), INLINE_CAPACITY);

        // Fill to capacity
        for i in 0..INLINE_CAPACITY as i8 {
            vec.push(i);
        }
        assert_eq!(vec.capacity(), INLINE_CAPACITY);

        // Transition to heap
        vec.push(INLINE_CAPACITY as i8);
        assert!(vec.capacity() > INLINE_CAPACITY);
    }

    #[test]
    fn test_remove() {
        let mut vec = test_vec_with_elements(&[1i8, 2, 3, 4, 5]);

        // Remove from middle
        assert_eq!(vec.remove(2), 3);
        assert_eq!(vec.len(), 4);
        assert_eq!(vec.get(2), Some(4));

        // Remove first element
        assert_eq!(vec.remove(0), 1);
        assert_eq!(vec.len(), 3);
        assert_eq!(vec.get(0), Some(2));

        // Remove last element
        assert_eq!(vec.remove(2), 5);
        assert_eq!(vec.len(), 2);
    }

    #[test]
    #[should_panic(expected = "removal index")]
    fn test_remove_out_of_bounds() {
        let mut vec = test_vec_with_elements(&[1i8, 2, 3]);
        vec.remove(3);
    }

    #[test]
    fn test_insert() {
        let mut vec = test_vec_with_elements(&[1i8, 3, 4]);

        // Insert at middle
        vec.insert(1, 2);
        assert_eq!(vec.len(), 4);
        assert_eq!(vec.get(0), Some(1));
        assert_eq!(vec.get(1), Some(2));
        assert_eq!(vec.get(2), Some(3));
        assert_eq!(vec.get(3), Some(4));

        // Insert at beginning
        vec.insert(0, 0);
        assert_eq!(vec.len(), 5);
        assert_eq!(vec.get(0), Some(0));

        // Insert at end
        vec.insert(5, 5);
        assert_eq!(vec.len(), 6);
        assert_eq!(vec.get(5), Some(5));
    }

    #[test]
    #[should_panic(expected = "insertion index")]
    fn test_insert_out_of_bounds() {
        let mut vec = test_vec_with_elements(&[1i8, 2, 3]);
        vec.insert(4, 42);
    }

    #[test]
    fn test_truncate() {
        let mut vec = test_vec_with_elements(&[1i8, 2, 3, 4, 5]);

        vec.truncate(3);
        assert_eq!(vec.len(), 3);
        assert_eq!(vec.get(2), Some(3));
        assert_eq!(vec.get(3), None);

        // Truncate to larger size should have no effect
        vec.truncate(10);
        assert_eq!(vec.len(), 3);

        // Truncate to 0
        vec.truncate(0);
        assert_eq!(vec.len(), 0);
        assert!(vec.is_empty());
    }

    #[test]
    fn test_resize() {
        let mut vec = test_vec_with_elements(&[1i8, 2, 3]);

        // Resize larger
        vec.resize(5, 42);
        assert_eq!(vec.len(), 5);
        assert_eq!(vec.get(3), Some(42));
        assert_eq!(vec.get(4), Some(42));

        // Resize smaller
        vec.resize(2, 99);
        assert_eq!(vec.len(), 2);
        assert_eq!(vec.get(1), Some(2));
        assert_eq!(vec.get(2), None);
    }

    #[test]
    fn test_extend_from_slice() {
        let mut vec = test_vec_with_elements(&[1i8, 2]);

        vec.extend_from_slice(&[3, 4, 5]);
        assert_eq!(vec.len(), 5);
        assert_eq!(vec.get(2), Some(3));
        assert_eq!(vec.get(3), Some(4));
        assert_eq!(vec.get(4), Some(5));

        // Extend to force heap transition
        vec.extend_from_slice(&[6, 7, 8]);
        assert_eq!(vec.len(), 8);
        assert!(!vec.is_inline());
    }

    #[test]
    fn test_reserve() {
        let mut vec: CompactVec<i8> = CompactVec::new();

        // Reserve within inline capacity
        vec.reserve(5);
        assert!(vec.is_inline());

        // Reserve beyond inline capacity
        vec.reserve(10);
        assert!(!vec.is_inline());
        assert!(vec.capacity() >= 10);
    }

    #[test]
    fn test_clear() {
        let mut vec = test_vec_with_elements(&[1i8, 2, 3, 4, 5]);
        let was_inline = vec.is_inline();

        vec.clear();
        assert_eq!(vec.len(), 0);
        assert!(vec.is_empty());
        assert_eq!(vec.is_inline(), was_inline); // Storage mode should remain the same
    }

    #[test]
    fn test_contains_method() {
        let mut vec: CompactVec<i8> = CompactVec::new();
        vec.push(1);
        vec.push(2);
        vec.push(3);

        assert!(vec.contains(&1));
        assert!(vec.contains(&2));
        assert!(vec.contains(&3));
        assert!(!vec.contains(&4));
        assert!(!vec.contains(&0));
    }

    #[test]
    fn test_sort() {
        let mut vec = test_vec_with_elements(&[3i8, 1, 4, 1, 5]);

        vec.sort();
        assert_eq!(vec.get(0), Some(1));
        assert_eq!(vec.get(1), Some(1));
        assert_eq!(vec.get(2), Some(3));
        assert_eq!(vec.get(3), Some(4));
        assert_eq!(vec.get(4), Some(5));
    }

    #[test]
    fn test_take() {
        let mut vec = test_vec_with_elements(&[1i8, 2, 3]);

        let taken = vec.take();
        assert_eq!(taken.len(), 3);
        assert_eq!(vec.len(), 0);
        assert!(vec.is_empty());
        assert!(vec.is_inline());
    }

    #[test]
    fn test_as_slice_i8() {
        let vec = test_vec_with_elements(&[1i8, 2, 3]);
        let slice = vec.as_slice();
        assert_eq!(slice, &[1, 2, 3]);
    }

    #[test]
    fn test_get_mut_i8() {
        let mut vec = test_vec_with_elements(&[10i8, 20, 30]);

        if let Some(elem) = vec.get_mut(1) {
            *elem = 25;
        }
        assert_eq!(vec.get(1), Some(25));
    }

    #[test]
    fn test_get_mut_unchecked_i8() {
        let mut vec = test_vec_with_elements(&[42i8]);

        unsafe {
            *vec.get_mut_unchecked(0) = 100;
        }
        assert_eq!(vec.get(0), Some(100));
    }

    #[test]
    fn test_as_slice_mut_i8() {
        let mut vec = test_vec_with_elements(&[1i8, 2, 3]);

        let slice = vec.as_slice_mut();
        slice[1] = 10;
        assert_eq!(vec.get(1), Some(10));
    }

    #[test]
    fn test_iter() {
        let vec = test_vec_with_elements(&[1i8, 2, 3, 4, 5]);

        let collected: Vec<i8> = vec.iter().collect();
        assert_eq!(collected, vec![1, 2, 3, 4, 5]);

        let sum: i8 = vec.iter().sum();
        assert_eq!(sum, 15);
    }

    #[test]
    fn test_iter_size_hint() {
        let vec = test_vec_with_elements(&[1i8, 2, 3]);
        let mut iter = vec.iter();

        assert_eq!(iter.size_hint(), (3, Some(3)));
        iter.next();
        assert_eq!(iter.size_hint(), (2, Some(2)));
    }

    #[test]
    fn test_into_iter() {
        let vec = test_vec_with_elements(&[1i8, 2, 3]);

        let collected: Vec<i8> = vec.into_iter().collect();
        assert_eq!(collected, vec![1, 2, 3]);
    }

    #[test]
    fn test_into_iter_ref() {
        let vec = test_vec_with_elements(&[1i8, 2, 3]);

        let collected: Vec<i8> = (&vec).into_iter().collect();
        assert_eq!(collected, vec![1, 2, 3]);
        assert_eq!(vec.len(), 3); // Original should still exist
    }

    #[test]
    fn test_into_iter_mut() {
        let mut vec = test_vec_with_elements(&[1i8, 2, 3]);

        for elem in &mut vec {
            *elem *= 2;
        }

        assert_eq!(vec.get(0), Some(2));
        assert_eq!(vec.get(1), Some(4));
        assert_eq!(vec.get(2), Some(6));
    }

    #[test]
    fn test_from_vec() {
        let vec = vec![1i8, 2, 3, 4, 5];
        let compact: CompactVec<i8> = vec.into();

        assert_eq!(compact.len(), 5);
        assert!(compact.is_inline());
        assert_eq!(compact.get(0), Some(1));
        assert_eq!(compact.get(4), Some(5));
    }

    #[test]
    fn test_from_array() {
        let array = [1i8, 2, 3, 4, 5];
        let compact: CompactVec<i8> = array.into();

        assert_eq!(compact.len(), 5);
        assert_eq!(compact.get(0), Some(1));
        assert_eq!(compact.get(4), Some(5));
    }

    #[test]
    fn test_from_array_ref() {
        let array = [1i8, 2, 3, 4, 5];
        let compact: CompactVec<i8> = (&array).into();

        assert_eq!(compact.len(), 5);
        assert_eq!(compact.get(0), Some(1));
        assert_eq!(compact.get(4), Some(5));
    }

    #[test]
    fn test_from_slice() {
        let slice = &[1i8, 2, 3];
        let compact: CompactVec<i8> = slice.into();

        assert_eq!(compact.len(), 3);
        assert_eq!(compact.get(0), Some(1));
        assert_eq!(compact.get(2), Some(3));
    }

    #[test]
    fn test_into_vec() {
        let compact = test_vec_with_elements(&[1i8, 2, 3]);
        let vec: Vec<i8> = compact.into();

        assert_eq!(vec, vec![1, 2, 3]);
    }

    #[test]
    fn test_deref_i8() {
        let vec = test_vec_with_elements(&[1i8, 2, 3]);
        let slice: &[i8] = &vec; // Uses Deref

        assert_eq!(slice, &[1, 2, 3]);
    }

    #[test]
    fn test_index_i8() {
        let vec = test_vec_with_elements(&[10i8, 20, 30]);

        assert_eq!(vec[0], 10);
        assert_eq!(vec[1], 20);
        assert_eq!(vec[2], 30);
    }

    #[test]
    #[should_panic(expected = "index out of bounds")]
    fn test_index_out_of_bounds() {
        let vec = test_vec_with_elements(&[1i8, 2, 3]);
        let _ = vec[3];
    }

    #[test]
    fn test_as_ref_i8() {
        let vec = test_vec_with_elements(&[1i8, 2, 3]);
        let slice: &[i8] = vec.as_ref();

        assert_eq!(slice, &[1, 2, 3]);
    }

    #[test]
    fn test_as_mut_trait() {
        let mut vec = test_vec_with_elements(&[1i8, 2, 3]);
        let slice: &mut [i8] = vec.as_mut();

        slice[1] = 42;
        assert_eq!(vec.get(1), Some(42));
    }

    #[test]
    fn test_heap_operations() {
        let mut vec: CompactVec<i8> = CompactVec::new();

        // Fill beyond inline capacity to force heap
        for i in 0..10 {
            vec.push(i);
        }

        assert!(!vec.is_inline());
        assert_eq!(vec.len(), 10);

        // Test operations on heap storage
        assert_eq!(vec.pop(), Some(9));
        assert_eq!(vec.get(5), Some(5));

        vec.insert(5, 42);
        assert_eq!(vec.get(5), Some(42));

        let removed = vec.remove(5);
        assert_eq!(removed, 42);
    }

    #[test]
    fn test_empty_operations() {
        let mut vec: CompactVec<i8> = CompactVec::new();

        assert_eq!(vec.pop(), None);
        assert_eq!(vec.get(0), None);
        assert!(vec.is_empty());
        assert_eq!(vec.len(), 0);

        let iter_count = vec.iter().count();
        assert_eq!(iter_count, 0);
    }

    #[test]
    fn test_clone() {
        let vec = test_vec_with_elements(&[1i8, 2, 3]);
        let cloned = vec.clone();

        assert_eq!(vec.len(), cloned.len());
        assert_eq!(vec.is_inline(), cloned.is_inline());

        for i in 0..vec.len() {
            assert_eq!(vec.get(i), cloned.get(i));
        }
    }

    #[test]
    fn test_u8_specialization() {
        let mut vec: CompactVec<u8> = CompactVec::new();
        vec.extend_from_slice(&[1u8, 2, 3]);

        // Test u8 specific deref
        let slice: &[u8] = &vec;
        assert_eq!(slice, &[1u8, 2, 3]);

        // Test u8 indexing
        assert_eq!(vec[1], 2u8);

        // Test u8 as_ref
        let slice: &[u8] = vec.as_ref();
        assert_eq!(slice, &[1u8, 2, 3]);
    }

    #[test]
    fn test_debug() {
        let vec = test_vec_with_elements(&[1i8, 2, 3]);
        let debug_str = format!("{:?}", vec);

        // Just ensure it doesn't panic and produces some output
        assert!(!debug_str.is_empty());
    }

    #[test]
    fn test_from_iterator() {
        let iter = 0..5;
        let vec: CompactVec<i8> = iter.collect();
        assert_eq!(vec.len(), 5);
        assert_eq!(vec.as_slice(), &[0, 1, 2, 3, 4]);

        let empty_iter: std::vec::IntoIter<i8> = Vec::new().into_iter();
        let empty_vec: CompactVec<i8> = empty_iter.collect();
        assert_eq!(empty_vec.len(), 0);
    }

    #[test]
    fn test_transition_preserves_order() {
        let mut vec: CompactVec<i8> = CompactVec::new();

        // Add elements that will fill inline storage
        for i in 0..INLINE_CAPACITY {
            vec.push((i * 10) as i8);
        }
        assert!(vec.is_inline());

        // Force transition to heap
        vec.push((INLINE_CAPACITY * 10) as i8);
        assert!(!vec.is_inline());

        // Verify all elements are in correct order
        for i in 0..=INLINE_CAPACITY {
            assert_eq!(vec.get(i), Some((i as i8) * 10));
        }
    }
}