commonware-utils 2026.3.0

Leverage common functionality across multiple primitives.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
//! Bitmap implementation
//!
//! The bitmap is a compact representation of a sequence of bits, using chunks of bytes for a
//! more-efficient memory layout than doing [`Vec<bool>`].

#[cfg(not(feature = "std"))]
use alloc::{collections::VecDeque, vec::Vec};
use bytes::{Buf, BufMut};
use commonware_codec::{util::at_least, EncodeSize, Error as CodecError, Read, ReadExt, Write};
use core::{
    fmt::{self, Formatter, Write as _},
    iter,
    ops::{BitAnd, BitOr, BitXor, Index, Range},
};
#[cfg(feature = "std")]
use std::collections::VecDeque;

mod prunable;
pub use prunable::Prunable;

pub mod historical;

/// The default [BitMap] chunk size in bytes.
pub const DEFAULT_CHUNK_SIZE: usize = 8;

/// A bitmap that stores data in chunks of N bytes.
///
/// # Panics
///
/// Operations panic if `bit / CHUNK_SIZE_BITS > usize::MAX`. On 32-bit systems
/// with N=32, this occurs at bit >= 1,099,511,627,776.
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct BitMap<const N: usize = DEFAULT_CHUNK_SIZE> {
    /// The bitmap itself, in chunks of size N bytes. Within each byte, lowest order bits are
    /// treated as coming before higher order bits in the bit ordering.
    ///
    /// Invariant: `chunks.len() == len.div_ceil(CHUNK_SIZE_BITS)`
    /// Invariant: All bits at index `i` where `i >= len` must be 0.
    chunks: VecDeque<[u8; N]>,

    /// The total number of bits stored in the bitmap.
    len: u64,
}

impl<const N: usize> BitMap<N> {
    const _CHUNK_SIZE_NON_ZERO_ASSERT: () = assert!(N > 0, "chunk size must be > 0");

    /// The size of a chunk in bits.
    pub const CHUNK_SIZE_BITS: u64 = (N * 8) as u64;

    /// A chunk of all 0s.
    const EMPTY_CHUNK: [u8; N] = [0u8; N];

    /// A chunk of all 1s.
    const FULL_CHUNK: [u8; N] = [u8::MAX; N];

    /* Constructors */

    /// Create a new empty bitmap.
    pub const fn new() -> Self {
        #[allow(path_statements)]
        Self::_CHUNK_SIZE_NON_ZERO_ASSERT; // Prevent compilation for N == 0

        Self {
            chunks: VecDeque::new(),
            len: 0,
        }
    }

    // Create a new empty bitmap with the capacity to hold `size` bits without reallocating.
    pub fn with_capacity(size: u64) -> Self {
        #[allow(path_statements)]
        Self::_CHUNK_SIZE_NON_ZERO_ASSERT; // Prevent compilation for N == 0

        Self {
            chunks: VecDeque::with_capacity(size.div_ceil(Self::CHUNK_SIZE_BITS) as usize),
            len: 0,
        }
    }

    /// Create a new bitmap with `size` bits, with all bits set to 0.
    pub fn zeroes(size: u64) -> Self {
        #[allow(path_statements)]
        Self::_CHUNK_SIZE_NON_ZERO_ASSERT; // Prevent compilation for N == 0

        let num_chunks = size.div_ceil(Self::CHUNK_SIZE_BITS) as usize;
        let mut chunks = VecDeque::with_capacity(num_chunks);
        for _ in 0..num_chunks {
            chunks.push_back(Self::EMPTY_CHUNK);
        }
        Self { chunks, len: size }
    }

    /// Create a new bitmap with `size` bits, with all bits set to 1.
    pub fn ones(size: u64) -> Self {
        #[allow(path_statements)]
        Self::_CHUNK_SIZE_NON_ZERO_ASSERT; // Prevent compilation for N == 0

        let num_chunks = size.div_ceil(Self::CHUNK_SIZE_BITS) as usize;
        let mut chunks = VecDeque::with_capacity(num_chunks);
        for _ in 0..num_chunks {
            chunks.push_back(Self::FULL_CHUNK);
        }
        let mut result = Self { chunks, len: size };
        // Clear trailing bits to maintain invariant
        result.clear_trailing_bits();
        result
    }

    /* Length */

    /// Return the number of bits currently stored in the bitmap.
    #[inline]
    pub const fn len(&self) -> u64 {
        self.len
    }

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

    /// Returns true if the bitmap length is aligned to a chunk boundary.
    #[inline]
    pub const fn is_chunk_aligned(&self) -> bool {
        self.len.is_multiple_of(Self::CHUNK_SIZE_BITS)
    }

    // Get the number of chunks currently in the bitmap.
    fn chunks_len(&self) -> usize {
        self.chunks.len()
    }

    /* Getters */

    /// Get the value of the bit at the given index.
    ///
    /// # Warning
    ///
    /// Panics if the bit doesn't exist.
    #[inline]
    pub fn get(&self, bit: u64) -> bool {
        let chunk = self.get_chunk_containing(bit);
        Self::get_bit_from_chunk(chunk, bit)
    }

    /// Returns the bitmap chunk containing the given bit.
    ///
    /// # Warning
    ///
    /// Panics if the bit doesn't exist.
    #[inline]
    fn get_chunk_containing(&self, bit: u64) -> &[u8; N] {
        assert!(
            bit < self.len(),
            "bit {} out of bounds (len: {})",
            bit,
            self.len()
        );
        &self.chunks[Self::to_chunk_index(bit)]
    }

    /// Get a reference to a chunk by its index in the current bitmap.
    /// Note this is an index into the chunks, not a bit.
    ///
    /// # Warning
    ///
    /// Panics if the `chunk` is out of bounds.
    #[inline]
    pub(super) fn get_chunk(&self, chunk: usize) -> &[u8; N] {
        assert!(
            chunk < self.chunks.len(),
            "chunk {} out of bounds (chunks: {})",
            chunk,
            self.chunks.len()
        );
        &self.chunks[chunk]
    }

    /// Get the value at the given `bit` from the `chunk`.
    /// `bit` is an index into the entire bitmap, not just the chunk.
    #[inline]
    pub const fn get_bit_from_chunk(chunk: &[u8; N], bit: u64) -> bool {
        let byte = Self::chunk_byte_offset(bit);
        let byte = chunk[byte];
        let mask = Self::chunk_byte_bitmask(bit);
        (byte & mask) != 0
    }

    /// Return the last chunk of the bitmap and its size in bits.
    ///
    /// # Panics
    ///
    /// Panics if bitmap is empty.
    #[inline]
    fn last_chunk(&self) -> (&[u8; N], u64) {
        let rem = self.len % Self::CHUNK_SIZE_BITS;
        let bits_in_last_chunk = if rem == 0 { Self::CHUNK_SIZE_BITS } else { rem };
        (self.chunks.back().unwrap(), bits_in_last_chunk)
    }

    /* Setters */

    /// Add a single bit to the bitmap.
    pub fn push(&mut self, bit: bool) {
        // Check if we need a new chunk
        if self.is_chunk_aligned() {
            self.chunks.push_back(Self::EMPTY_CHUNK);
        }

        // Append to the last chunk
        if bit {
            let last_chunk = self.chunks.back_mut().unwrap();
            let chunk_byte = Self::chunk_byte_offset(self.len);
            last_chunk[chunk_byte] |= Self::chunk_byte_bitmask(self.len);
        }
        // If bit is false, just advance len -- the bit is already 0
        self.len += 1;
    }

    /// Remove and return the last bit from the bitmap.
    ///
    /// # Warning
    ///
    /// Panics if the bitmap is empty.
    pub fn pop(&mut self) -> bool {
        assert!(!self.is_empty(), "Cannot pop from empty bitmap");

        // Get the bit value at the last position
        let last_bit_pos = self.len - 1;
        let bit = Self::get_bit_from_chunk(self.chunks.back().unwrap(), last_bit_pos);

        // Decrement length
        self.len -= 1;

        // Clear the bit we just popped to maintain invariant (if it was 1)
        if bit {
            let chunk_byte = Self::chunk_byte_offset(last_bit_pos);
            let mask = Self::chunk_byte_bitmask(last_bit_pos);
            self.chunks.back_mut().unwrap()[chunk_byte] &= !mask;
        }

        // Remove the last chunk if it's now empty
        if self.is_chunk_aligned() {
            self.chunks.pop_back();
        }

        bit
    }

    /// Remove and return the last complete chunk from the bitmap.
    ///
    /// # Warning
    ///
    /// Panics if the bitmap has fewer than `CHUNK_SIZE_BITS` bits or if not chunk-aligned.
    pub(super) fn pop_chunk(&mut self) -> [u8; N] {
        assert!(
            self.len() >= Self::CHUNK_SIZE_BITS,
            "cannot pop chunk: bitmap has fewer than CHUNK_SIZE_BITS bits"
        );
        assert!(
            self.is_chunk_aligned(),
            "cannot pop chunk when not chunk aligned"
        );

        // Remove and return the last data chunk
        let chunk = self.chunks.pop_back().expect("chunk must exist");
        self.len -= Self::CHUNK_SIZE_BITS;
        chunk
    }

    /// Flips the given bit.
    ///
    /// # Panics
    ///
    /// Panics if `bit` is out of bounds.
    #[inline]
    pub fn flip(&mut self, bit: u64) {
        self.assert_bit(bit);
        let chunk = Self::to_chunk_index(bit);
        let byte = Self::chunk_byte_offset(bit);
        let mask = Self::chunk_byte_bitmask(bit);
        self.chunks[chunk][byte] ^= mask;
    }

    /// Flips all bits (1s become 0s and vice versa).
    pub fn flip_all(&mut self) {
        for chunk in &mut self.chunks {
            for byte in chunk {
                *byte = !*byte;
            }
        }
        // Clear trailing bits to maintain invariant
        self.clear_trailing_bits();
    }

    /// Set the value of the referenced bit.
    ///
    /// # Warning
    ///
    /// Panics if the bit doesn't exist.
    pub fn set(&mut self, bit: u64, value: bool) {
        assert!(
            bit < self.len(),
            "bit {} out of bounds (len: {})",
            bit,
            self.len()
        );

        let chunk = &mut self.chunks[Self::to_chunk_index(bit)];
        let byte = Self::chunk_byte_offset(bit);
        let mask = Self::chunk_byte_bitmask(bit);
        if value {
            chunk[byte] |= mask;
        } else {
            chunk[byte] &= !mask;
        }
    }

    /// Sets all bits to the specified value.
    #[inline]
    pub fn set_all(&mut self, bit: bool) {
        let value = if bit { u8::MAX } else { 0 };
        for chunk in &mut self.chunks {
            chunk.fill(value);
        }
        // Clear trailing bits to maintain invariant
        if bit {
            self.clear_trailing_bits();
        }
    }

    // Add a byte's worth of bits to the bitmap.
    //
    // # Warning
    //
    // Panics if self.len is not byte aligned.
    fn push_byte(&mut self, byte: u8) {
        assert!(
            self.len.is_multiple_of(8),
            "cannot add byte when not byte aligned"
        );

        // Check if we need a new chunk
        if self.is_chunk_aligned() {
            self.chunks.push_back(Self::EMPTY_CHUNK);
        }

        let chunk_byte = Self::chunk_byte_offset(self.len);
        self.chunks.back_mut().unwrap()[chunk_byte] = byte;
        self.len += 8;
    }

    /// Add a chunk of bits to the bitmap.
    ///
    /// # Warning
    ///
    /// Panics if self.len is not chunk aligned.
    pub fn push_chunk(&mut self, chunk: &[u8; N]) {
        assert!(
            self.is_chunk_aligned(),
            "cannot add chunk when not chunk aligned"
        );
        self.chunks.push_back(*chunk);
        self.len += Self::CHUNK_SIZE_BITS;
    }

    /* Invariant Maintenance */

    /// Clear all bits in the last chunk that are >= self.len to maintain the invariant.
    /// Returns true if any bits were flipped from 1 to 0.
    fn clear_trailing_bits(&mut self) -> bool {
        if self.chunks.is_empty() {
            return false;
        }

        let pos_in_chunk = self.len % Self::CHUNK_SIZE_BITS;
        if pos_in_chunk == 0 {
            // Chunk is full -- there are no trailing bits to clear.
            return false;
        }

        let mut flipped_any = false;
        let last_chunk = self.chunks.back_mut().unwrap();

        // Clear whole bytes after the last valid bit
        let last_byte_index = ((pos_in_chunk - 1) / 8) as usize;
        for byte in last_chunk.iter_mut().skip(last_byte_index + 1) {
            if *byte != 0 {
                flipped_any = true;
                *byte = 0;
            }
        }

        // Clear the trailing bits in the last partial byte
        let bits_in_last_byte = pos_in_chunk % 8;
        if bits_in_last_byte != 0 {
            let mask = (1u8 << bits_in_last_byte) - 1;
            let old_byte = last_chunk[last_byte_index];
            let new_byte = old_byte & mask;
            if old_byte != new_byte {
                flipped_any = true;
                last_chunk[last_byte_index] = new_byte;
            }
        }

        flipped_any
    }

    /* Pruning */

    /// Remove the first `chunks` chunks from the bitmap.
    ///
    /// # Warning
    ///
    /// Panics if trying to prune more chunks than exist.
    fn prune_chunks(&mut self, chunks: usize) {
        assert!(
            chunks <= self.chunks.len(),
            "cannot prune {chunks} chunks, only {} available",
            self.chunks.len()
        );
        self.chunks.drain(..chunks);
        // Update len to reflect the removed chunks
        let bits_removed = (chunks as u64) * Self::CHUNK_SIZE_BITS;
        self.len = self.len.saturating_sub(bits_removed);
    }

    /// Prepend a chunk to the beginning of the bitmap.
    pub(super) fn prepend_chunk(&mut self, chunk: &[u8; N]) {
        self.chunks.push_front(*chunk);
        self.len += Self::CHUNK_SIZE_BITS;
    }

    /// Overwrite a chunk's data at the given index.
    ///
    /// Replaces the entire chunk data, including any bits beyond `len()` in the last chunk.
    /// The caller is responsible for ensuring `chunk_data` has the correct bit pattern
    /// (e.g., zeros beyond the valid length if this is a partial last chunk).
    ///
    /// # Panics
    ///
    /// Panics if chunk_index is out of bounds.
    pub(super) fn set_chunk_by_index(&mut self, chunk_index: usize, chunk_data: &[u8; N]) {
        assert!(
            chunk_index < self.chunks.len(),
            "chunk index {chunk_index} out of bounds (chunks_len: {})",
            self.chunks.len()
        );
        self.chunks[chunk_index].copy_from_slice(chunk_data);
    }

    /* Counting */

    /// Returns the number of bits set to 1.
    #[inline]
    pub fn count_ones(&self) -> u64 {
        // Thanks to the invariant that trailing bits are always 0,
        // we can simply count all set bits in all chunks.
        // Iterate over both contiguous deque segments and count 64-bit words first.
        let (front, back) = self.chunks.as_slices();
        Self::count_ones_in_chunk_slice(front) + Self::count_ones_in_chunk_slice(back)
    }

    #[inline]
    fn count_ones_in_chunk_slice(chunks: &[[u8; N]]) -> u64 {
        let mut total = 0u64;
        let mut words = chunks.as_flattened().chunks_exact(8);
        for word in &mut words {
            total += u64::from_le_bytes(word.try_into().unwrap()).count_ones() as u64;
        }
        for byte in words.remainder() {
            total += byte.count_ones() as u64;
        }
        total
    }

    /// Returns the number of bits set to 0.
    #[inline]
    pub fn count_zeros(&self) -> u64 {
        self.len() - self.count_ones()
    }

    /* Indexing Helpers */

    /// Convert a bit offset into a bitmask for the byte containing that bit.
    #[inline]
    pub(super) const fn chunk_byte_bitmask(bit: u64) -> u8 {
        1 << (bit % 8)
    }

    /// Convert a bit into the index of the byte within a chunk containing the bit.
    #[inline]
    pub(super) const fn chunk_byte_offset(bit: u64) -> usize {
        ((bit / 8) % N as u64) as usize
    }

    /// Convert a bit into the index of the chunk it belongs to.
    ///
    /// # Panics
    ///
    /// Panics if the chunk index overflows `usize`.
    #[inline]
    pub(super) fn to_chunk_index(bit: u64) -> usize {
        let chunk = bit / Self::CHUNK_SIZE_BITS;
        assert!(
            chunk <= usize::MAX as u64,
            "chunk overflow: {chunk} exceeds usize::MAX",
        );
        chunk as usize
    }

    /* Iterator */

    /// Creates an iterator over the bits.
    pub const fn iter(&self) -> Iterator<'_, N> {
        Iterator {
            bitmap: self,
            pos: 0,
        }
    }

    /* Bitwise Operations */

    /// Helper for binary operations
    #[inline]
    fn binary_op<F: Fn(u8, u8) -> u8>(&mut self, other: &Self, op: F) {
        self.assert_eq_len(other);
        for (a_chunk, b_chunk) in self.chunks.iter_mut().zip(other.chunks.iter()) {
            for (a_byte, b_byte) in a_chunk.iter_mut().zip(b_chunk.iter()) {
                *a_byte = op(*a_byte, *b_byte);
            }
        }
        // Clear trailing bits to maintain invariant
        self.clear_trailing_bits();
    }

    /// Performs a bitwise AND with another BitMap.
    ///
    /// # Panics
    ///
    /// Panics if the lengths don't match.
    pub fn and(&mut self, other: &Self) {
        self.binary_op(other, |a, b| a & b);
    }

    /// Performs a bitwise OR with another BitMap.
    ///
    /// # Panics
    ///
    /// Panics if the lengths don't match.
    pub fn or(&mut self, other: &Self) {
        self.binary_op(other, |a, b| a | b);
    }

    /// Performs a bitwise XOR with another BitMap.
    ///
    /// # Panics
    ///
    /// Panics if the lengths don't match.
    pub fn xor(&mut self, other: &Self) {
        self.binary_op(other, |a, b| a ^ b);
    }

    /* Assertions */

    /// Asserts that the bit is within bounds.
    #[inline(always)]
    fn assert_bit(&self, bit: u64) {
        assert!(
            bit < self.len(),
            "bit {} out of bounds (len: {})",
            bit,
            self.len()
        );
    }

    /// Asserts that the lengths of two [BitMap]s match.
    #[inline(always)]
    fn assert_eq_len(&self, other: &Self) {
        assert_eq!(
            self.len(),
            other.len(),
            "BitMap lengths don't match: {} vs {}",
            self.len(),
            other.len()
        );
    }

    /// Check if all the bits in a given range are 0.
    ///
    /// Returns `true` if every index in the range is unset (i.e.
    /// [`Self::get`] returns `false`). Returns `true` if the range
    /// is empty.
    ///
    /// # Panics
    ///
    /// Panics if `range.end` exceeds the length of the bitmap.
    ///
    /// # Examples
    ///
    /// ```
    /// use commonware_utils::bitmap::BitMap;
    ///
    /// let mut bitmap = BitMap::<8>::zeroes(128);
    /// assert!(bitmap.is_unset(0..128));
    ///
    /// bitmap.set(64, true);
    /// assert!(bitmap.is_unset(0..64));
    /// assert!(!bitmap.is_unset(0..65));
    /// ```
    pub fn is_unset(&self, range: Range<u64>) -> bool {
        assert!(
            range.end <= self.len(),
            "range end {} out of bounds (len: {})",
            range.end,
            self.len()
        );
        if range.start >= range.end {
            return true;
        }
        let start = range.start;
        let end = range.end;

        // We know this can't underflow, because start < end.
        //
        // We now want "end" to represent the last bit we want to consider.
        let end = end - 1;

        // Get the chunks containing the start and end bits.
        let first_chunk = Self::to_chunk_index(start);
        let last_chunk = Self::to_chunk_index(end);

        // All of these chunks require all of their bits to be checked.
        // If first_chunk == last_chunk, we skip the loop.
        let zero = [0u8; N];
        for full_chunk in (first_chunk + 1)..last_chunk {
            if self.chunks[full_chunk] != zero {
                return false;
            }
        }

        // Check first chunk tail (or whole range if first_chunk == last_chunk).
        let start_byte = Self::chunk_byte_offset(start);
        let end_byte = Self::chunk_byte_offset(end);
        let start_mask = (0xFFu16 << ((start & 0b111) as u32)) as u8;
        let end_mask = (0xFFu16 >> (7 - ((end & 0b111) as u32))) as u8;
        let first = &self.chunks[first_chunk];
        let first_end_byte = if first_chunk == last_chunk {
            end_byte
        } else {
            N - 1
        };
        for (i, &byte) in first
            .iter()
            .enumerate()
            .take(first_end_byte + 1)
            .skip(start_byte)
        {
            let mut mask = 0xFFu8;
            if i == start_byte {
                mask &= start_mask;
            }
            if first_chunk == last_chunk && i == end_byte {
                mask &= end_mask;
            }
            if (byte & mask) != 0 {
                return false;
            }
        }
        if first_chunk == last_chunk {
            return true;
        }

        // Check last chunk head.
        let last = &self.chunks[last_chunk];
        for (i, &byte) in last.iter().enumerate().take(end_byte + 1) {
            let mask = if i == end_byte { end_mask } else { 0xFF };
            if (byte & mask) != 0 {
                return false;
            }
        }

        true
    }
}

impl<const N: usize> Default for BitMap<N> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: AsRef<[bool]>, const N: usize> From<T> for BitMap<N> {
    fn from(t: T) -> Self {
        let bools = t.as_ref();
        let mut bv = Self::with_capacity(bools.len() as u64);
        for &b in bools {
            bv.push(b);
        }
        bv
    }
}

impl<const N: usize> From<BitMap<N>> for Vec<bool> {
    fn from(bv: BitMap<N>) -> Self {
        bv.iter().collect()
    }
}

impl<const N: usize> fmt::Debug for BitMap<N> {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        // For very large BitMaps, only show a preview
        const MAX_DISPLAY: u64 = 64;
        const HALF_DISPLAY: u64 = MAX_DISPLAY / 2;

        // Closure for writing a bit
        let write_bit = |formatter: &mut Formatter<'_>, bit: u64| -> core::fmt::Result {
            formatter.write_char(if self.get(bit) { '1' } else { '0' })
        };

        f.write_str("BitMap[")?;
        let len = self.len();
        if len <= MAX_DISPLAY {
            // Show all bits
            for i in 0..len {
                write_bit(f, i)?;
            }
        } else {
            // Show first and last bits with ellipsis
            for i in 0..HALF_DISPLAY {
                write_bit(f, i)?;
            }

            f.write_str("...")?;

            for i in (len - HALF_DISPLAY)..len {
                write_bit(f, i)?;
            }
        }
        f.write_str("]")
    }
}

impl<const N: usize> Index<u64> for BitMap<N> {
    type Output = bool;

    /// Allows accessing bits using the `[]` operator.
    ///
    /// Panics if out of bounds.
    #[inline]
    fn index(&self, bit: u64) -> &Self::Output {
        self.assert_bit(bit);
        let value = self.get(bit);
        if value {
            &true
        } else {
            &false
        }
    }
}

impl<const N: usize> BitAnd for &BitMap<N> {
    type Output = BitMap<N>;

    fn bitand(self, rhs: Self) -> Self::Output {
        self.assert_eq_len(rhs);
        let mut result = self.clone();
        result.and(rhs);
        result
    }
}

impl<const N: usize> BitOr for &BitMap<N> {
    type Output = BitMap<N>;

    fn bitor(self, rhs: Self) -> Self::Output {
        self.assert_eq_len(rhs);
        let mut result = self.clone();
        result.or(rhs);
        result
    }
}

impl<const N: usize> BitXor for &BitMap<N> {
    type Output = BitMap<N>;

    fn bitxor(self, rhs: Self) -> Self::Output {
        self.assert_eq_len(rhs);
        let mut result = self.clone();
        result.xor(rhs);
        result
    }
}

impl<const N: usize> Write for BitMap<N> {
    fn write(&self, buf: &mut impl BufMut) {
        // Prefix with the number of bits
        self.len().write(buf);

        // Write all chunks
        for chunk in &self.chunks {
            for &byte in chunk {
                byte.write(buf);
            }
        }
    }
}

impl<const N: usize> Read for BitMap<N> {
    type Cfg = u64; // Max bitmap length

    fn read_cfg(buf: &mut impl Buf, max_len: &Self::Cfg) -> Result<Self, CodecError> {
        // Parse length in bits
        let len = u64::read(buf)?;
        if len > *max_len {
            return Err(CodecError::InvalidLength(len as usize));
        }

        // Calculate how many chunks we need to read
        let num_chunks = len.div_ceil(Self::CHUNK_SIZE_BITS) as usize;

        // Parse chunks
        let mut chunks = VecDeque::with_capacity(num_chunks);
        for _ in 0..num_chunks {
            at_least(buf, N)?;
            let mut chunk = [0u8; N];
            buf.copy_to_slice(&mut chunk);
            chunks.push_back(chunk);
        }

        let mut result = Self { chunks, len };

        // Verify trailing bits are zero (maintain invariant)
        if result.clear_trailing_bits() {
            return Err(CodecError::Invalid(
                "BitMap",
                "Invalid trailing bits in encoded data",
            ));
        }

        Ok(result)
    }
}

impl<const N: usize> EncodeSize for BitMap<N> {
    fn encode_size(&self) -> usize {
        // Size of length prefix + all chunks
        self.len().encode_size() + (self.chunks.len() * N)
    }
}

/// Iterator over bits in a [BitMap].
pub struct Iterator<'a, const N: usize> {
    /// Reference to the BitMap being iterated over
    bitmap: &'a BitMap<N>,

    /// Current index in the BitMap
    pos: u64,
}

impl<const N: usize> iter::Iterator for Iterator<'_, N> {
    type Item = bool;

    fn next(&mut self) -> Option<Self::Item> {
        if self.pos >= self.bitmap.len() {
            return None;
        }

        let bit = self.bitmap.get(self.pos);
        self.pos += 1;
        Some(bit)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.bitmap.len().saturating_sub(self.pos);
        let capped = remaining.min(usize::MAX as u64) as usize;
        (capped, Some(capped))
    }
}

impl<const N: usize> ExactSizeIterator for Iterator<'_, N> {}

#[cfg(feature = "arbitrary")]
impl<const N: usize> arbitrary::Arbitrary<'_> for BitMap<N> {
    fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
        let size = u.int_in_range(0..=1024)?;
        let mut bits = Self::with_capacity(size);
        for _ in 0..size {
            bits.push(u.arbitrary::<bool>()?);
        }
        Ok(bits)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::hex;
    use bytes::BytesMut;
    use commonware_codec::{Decode, Encode};

    #[test]
    fn test_constructors() {
        // Test new()
        let bv: BitMap<4> = BitMap::new();
        assert_eq!(bv.len(), 0);
        assert!(bv.is_empty());

        // Test default()
        let bv: BitMap<4> = Default::default();
        assert_eq!(bv.len(), 0);
        assert!(bv.is_empty());

        // Test with_capacity()
        let bv: BitMap<4> = BitMap::with_capacity(0);
        assert_eq!(bv.len(), 0);
        assert!(bv.is_empty());

        let bv: BitMap<4> = BitMap::with_capacity(10);
        assert_eq!(bv.len(), 0);
        assert!(bv.is_empty());
    }

    #[test]
    fn test_zeroes() {
        let bv: BitMap<1> = BitMap::zeroes(0);
        assert_eq!(bv.len(), 0);
        assert!(bv.is_empty());
        assert_eq!(bv.count_ones(), 0);
        assert_eq!(bv.count_zeros(), 0);

        let bv: BitMap<1> = BitMap::zeroes(1);
        assert_eq!(bv.len(), 1);
        assert!(!bv.is_empty());
        assert_eq!(bv.len(), 1);
        assert!(!bv.get(0));
        assert_eq!(bv.count_ones(), 0);
        assert_eq!(bv.count_zeros(), 1);

        let bv: BitMap<1> = BitMap::zeroes(10);
        assert_eq!(bv.len(), 10);
        assert!(!bv.is_empty());
        assert_eq!(bv.len(), 10);
        for i in 0..10 {
            assert!(!bv.get(i as u64));
        }
        assert_eq!(bv.count_ones(), 0);
        assert_eq!(bv.count_zeros(), 10);
    }

    #[test]
    fn test_ones() {
        let bv: BitMap<1> = BitMap::ones(0);
        assert_eq!(bv.len(), 0);
        assert!(bv.is_empty());
        assert_eq!(bv.count_ones(), 0);
        assert_eq!(bv.count_zeros(), 0);

        let bv: BitMap<1> = BitMap::ones(1);
        assert_eq!(bv.len(), 1);
        assert!(!bv.is_empty());
        assert_eq!(bv.len(), 1);
        assert!(bv.get(0));
        assert_eq!(bv.count_ones(), 1);
        assert_eq!(bv.count_zeros(), 0);

        let bv: BitMap<1> = BitMap::ones(10);
        assert_eq!(bv.len(), 10);
        assert!(!bv.is_empty());
        assert_eq!(bv.len(), 10);
        for i in 0..10 {
            assert!(bv.get(i as u64));
        }
        assert_eq!(bv.count_ones(), 10);
        assert_eq!(bv.count_zeros(), 0);
    }

    #[test]
    fn test_invariant_trailing_bits_are_zero() {
        // Helper function to check the invariant
        fn check_trailing_bits_zero<const N: usize>(bitmap: &BitMap<N>) {
            let (last_chunk, next_bit) = bitmap.last_chunk();

            // Check that all bits >= next_bit in the last chunk are 0
            for bit_idx in next_bit..((N * 8) as u64) {
                let byte_idx = (bit_idx / 8) as usize;
                let bit_in_byte = bit_idx % 8;
                let mask = 1u8 << bit_in_byte;
                assert_eq!(last_chunk[byte_idx] & mask, 0);
            }
        }

        // Test ones() constructor
        let bv: BitMap<4> = BitMap::ones(15);
        check_trailing_bits_zero(&bv);

        let bv: BitMap<4> = BitMap::ones(33);
        check_trailing_bits_zero(&bv);

        // Test after push operations
        let mut bv: BitMap<4> = BitMap::new();
        for i in 0..37 {
            bv.push(i % 2 == 0);
            check_trailing_bits_zero(&bv);
        }

        // Test after pop operations
        let mut bv: BitMap<4> = BitMap::ones(40);
        check_trailing_bits_zero(&bv);
        for _ in 0..15 {
            bv.pop();
            check_trailing_bits_zero(&bv);
        }

        // Test after flip_all
        let mut bv: BitMap<4> = BitMap::ones(25);
        bv.flip_all();
        check_trailing_bits_zero(&bv);

        // Test after binary operations
        let bv1: BitMap<4> = BitMap::ones(20);
        let bv2: BitMap<4> = BitMap::zeroes(20);

        let mut bv_and = bv1.clone();
        bv_and.and(&bv2);
        check_trailing_bits_zero(&bv_and);

        let mut bv_or = bv1.clone();
        bv_or.or(&bv2);
        check_trailing_bits_zero(&bv_or);

        let mut bv_xor = bv1;
        bv_xor.xor(&bv2);
        check_trailing_bits_zero(&bv_xor);

        // Test after deserialization
        let original: BitMap<4> = BitMap::ones(27);
        let encoded = original.encode();
        let decoded: BitMap<4> =
            BitMap::decode_cfg(&mut encoded.as_ref(), &(usize::MAX as u64)).unwrap();
        check_trailing_bits_zero(&decoded);

        // Test clear_trailing_bits return value
        let mut bv_clean: BitMap<4> = BitMap::ones(20);
        // Should return false since ones() already clears trailing bits
        assert!(!bv_clean.clear_trailing_bits());

        // Create a bitmap with invalid trailing bits by manually setting them
        let mut bv_dirty: BitMap<4> = BitMap::ones(20);
        // Manually corrupt the last chunk to have trailing bits set
        let last_chunk = bv_dirty.chunks.back_mut().unwrap();
        last_chunk[3] |= 0xF0; // Set some high bits in the last byte
                               // Should return true since we had invalid trailing bits
        assert!(bv_dirty.clear_trailing_bits());
        // After clearing, should return false
        assert!(!bv_dirty.clear_trailing_bits());
        check_trailing_bits_zero(&bv_dirty);
    }

    #[test]
    fn test_get_set() {
        let mut bv: BitMap<4> = BitMap::new();

        // Test initial state
        assert_eq!(bv.len(), 0);
        assert!(bv.is_empty());

        // Test push
        bv.push(true);
        bv.push(false);
        bv.push(true);
        assert_eq!(bv.len(), 3);
        assert!(!bv.is_empty());

        // Test get
        assert!(bv.get(0));
        assert!(!bv.get(1));
        assert!(bv.get(2));

        bv.set(1, true);
        assert!(bv.get(1));
        bv.set(2, false);
        assert!(!bv.get(2));

        // Test flip
        bv.flip(0); // true -> false
        assert!(!bv.get(0));
        bv.flip(0); // false -> true
        assert!(bv.get(0));
    }

    #[test]
    fn test_chunk_operations() {
        let mut bv: BitMap<4> = BitMap::new();
        let test_chunk = hex!("0xABCDEF12");

        // Test push_chunk
        bv.push_chunk(&test_chunk);
        assert_eq!(bv.len(), 32); // 4 bytes * 8 bits

        // Test get_chunk
        let chunk = bv.get_chunk(0);
        assert_eq!(chunk, &test_chunk);

        // Test get_chunk_containing
        let chunk = bv.get_chunk_containing(0);
        assert_eq!(chunk, &test_chunk);

        // Test last_chunk
        let (last_chunk, next_bit) = bv.last_chunk();
        assert_eq!(next_bit, BitMap::<4>::CHUNK_SIZE_BITS); // Should be at chunk boundary
        assert_eq!(last_chunk, &test_chunk); // The chunk we just pushed
    }

    #[test]
    fn test_pop() {
        let mut bv: BitMap<3> = BitMap::new();
        bv.push(true);
        assert!(bv.pop());
        assert_eq!(bv.len(), 0);

        bv.push(false);
        assert!(!bv.pop());
        assert_eq!(bv.len(), 0);

        bv.push(true);
        bv.push(false);
        bv.push(true);
        assert!(bv.pop());
        assert_eq!(bv.len(), 2);
        assert!(!bv.pop());
        assert_eq!(bv.len(), 1);
        assert!(bv.pop());
        assert_eq!(bv.len(), 0);

        for i in 0..100 {
            bv.push(i % 2 == 0);
        }
        assert_eq!(bv.len(), 100);
        for i in (0..100).rev() {
            assert_eq!(bv.pop(), i % 2 == 0);
        }
        assert_eq!(bv.len(), 0);
        assert!(bv.is_empty());
    }

    #[test]
    fn test_pop_chunk() {
        let mut bv: BitMap<3> = BitMap::new();
        const CHUNK_SIZE: u64 = BitMap::<3>::CHUNK_SIZE_BITS;

        // Test 1: Pop a single chunk and verify it returns the correct data
        let chunk1 = hex!("0xAABBCC");
        bv.push_chunk(&chunk1);
        assert_eq!(bv.len(), CHUNK_SIZE);
        let popped = bv.pop_chunk();
        assert_eq!(popped, chunk1);
        assert_eq!(bv.len(), 0);
        assert!(bv.is_empty());

        // Test 2: Pop multiple chunks in reverse order
        let chunk2 = hex!("0x112233");
        let chunk3 = hex!("0x445566");
        let chunk4 = hex!("0x778899");

        bv.push_chunk(&chunk2);
        bv.push_chunk(&chunk3);
        bv.push_chunk(&chunk4);
        assert_eq!(bv.len(), CHUNK_SIZE * 3);

        assert_eq!(bv.pop_chunk(), chunk4);
        assert_eq!(bv.len(), CHUNK_SIZE * 2);

        assert_eq!(bv.pop_chunk(), chunk3);
        assert_eq!(bv.len(), CHUNK_SIZE);

        assert_eq!(bv.pop_chunk(), chunk2);
        assert_eq!(bv.len(), 0);

        // Test 3: Verify data integrity when popping chunks
        let first_chunk = hex!("0xAABBCC");
        let second_chunk = hex!("0x112233");
        bv.push_chunk(&first_chunk);
        bv.push_chunk(&second_chunk);

        // Pop the second chunk, verify it and that first chunk is intact
        assert_eq!(bv.pop_chunk(), second_chunk);
        assert_eq!(bv.len(), CHUNK_SIZE);

        for i in 0..CHUNK_SIZE {
            let byte_idx = (i / 8) as usize;
            let bit_idx = i % 8;
            let expected = (first_chunk[byte_idx] >> bit_idx) & 1 == 1;
            assert_eq!(bv.get(i), expected);
        }

        assert_eq!(bv.pop_chunk(), first_chunk);
        assert_eq!(bv.len(), 0);
    }

    #[test]
    #[should_panic(expected = "cannot pop chunk when not chunk aligned")]
    fn test_pop_chunk_not_aligned() {
        let mut bv: BitMap<3> = BitMap::new();

        // Push a full chunk plus one bit
        bv.push_chunk(&[0xFF; 3]);
        bv.push(true);

        // Should panic because not chunk-aligned
        bv.pop_chunk();
    }

    #[test]
    #[should_panic(expected = "cannot pop chunk: bitmap has fewer than CHUNK_SIZE_BITS bits")]
    fn test_pop_chunk_insufficient_bits() {
        let mut bv: BitMap<3> = BitMap::new();

        // Push only a few bits (less than a full chunk)
        bv.push(true);
        bv.push(false);

        // Should panic because we don't have a full chunk to pop
        bv.pop_chunk();
    }

    #[test]
    fn test_byte_operations() {
        let mut bv: BitMap<4> = BitMap::new();

        // Test push_byte
        bv.push_byte(0xFF);
        assert_eq!(bv.len(), 8);

        // All bits in the byte should be set
        for i in 0..8 {
            assert!(bv.get(i as u64));
        }

        bv.push_byte(0x00);
        assert_eq!(bv.len(), 16);

        // All bits in the second byte should be clear
        for i in 8..16 {
            assert!(!bv.get(i as u64));
        }
    }

    #[test]
    fn test_count_operations() {
        let mut bv: BitMap<4> = BitMap::new();

        // Empty bitmap
        assert_eq!(bv.count_ones(), 0);
        assert_eq!(bv.count_zeros(), 0);

        // Add some bits
        bv.push(true);
        bv.push(false);
        bv.push(true);
        bv.push(true);
        bv.push(false);

        assert_eq!(bv.count_ones(), 3);
        assert_eq!(bv.count_zeros(), 2);
        assert_eq!(bv.len(), 5);

        // Test with full bytes
        let mut bv2: BitMap<4> = BitMap::new();
        bv2.push_byte(0xFF); // 8 ones
        bv2.push_byte(0x00); // 8 zeros
        bv2.push_byte(0xAA); // 4 ones, 4 zeros (10101010)

        assert_eq!(bv2.count_ones(), 12);
        assert_eq!(bv2.count_zeros(), 12);
        assert_eq!(bv2.len(), 24);
    }

    #[test]
    fn test_set_all() {
        let mut bv: BitMap<1> = BitMap::new();

        // Add some bits
        bv.push(true);
        bv.push(false);
        bv.push(true);
        bv.push(false);
        bv.push(true);
        bv.push(false);
        bv.push(true);
        bv.push(false);
        bv.push(true);
        bv.push(false);

        assert_eq!(bv.len(), 10);
        assert_eq!(bv.count_ones(), 5);
        assert_eq!(bv.count_zeros(), 5);

        // Test set_all(true)
        bv.set_all(true);
        assert_eq!(bv.len(), 10);
        assert_eq!(bv.count_ones(), 10);
        assert_eq!(bv.count_zeros(), 0);

        // Test set_all(false)
        bv.set_all(false);
        assert_eq!(bv.len(), 10);
        assert_eq!(bv.count_ones(), 0);
        assert_eq!(bv.count_zeros(), 10);
    }

    #[test]
    fn test_flip_all() {
        let mut bv: BitMap<4> = BitMap::new();

        bv.push(true);
        bv.push(false);
        bv.push(true);
        bv.push(false);
        bv.push(true);

        let original_ones = bv.count_ones();
        let original_zeros = bv.count_zeros();
        let original_len = bv.len();

        bv.flip_all();

        // Length should not change
        assert_eq!(bv.len(), original_len);

        // Ones and zeros should be swapped
        assert_eq!(bv.count_ones(), original_zeros);
        assert_eq!(bv.count_zeros(), original_ones);

        // Check bits
        assert!(!bv.get(0));
        assert!(bv.get(1));
        assert!(!bv.get(2));
        assert!(bv.get(3));
        assert!(!bv.get(4));
    }

    #[test]
    fn test_bitwise_and() {
        let mut bv1: BitMap<4> = BitMap::new();
        let mut bv2: BitMap<4> = BitMap::new();

        // Create test patterns: 10110 & 11010 = 10010
        let pattern1 = [true, false, true, true, false];
        let pattern2 = [true, true, false, true, false];
        let expected = [true, false, false, true, false];

        for &bit in &pattern1 {
            bv1.push(bit);
        }
        for &bit in &pattern2 {
            bv2.push(bit);
        }

        bv1.and(&bv2);

        assert_eq!(bv1.len(), 5);
        for (i, &expected_bit) in expected.iter().enumerate() {
            assert_eq!(bv1.get(i as u64), expected_bit);
        }
    }

    #[test]
    fn test_bitwise_or() {
        let mut bv1: BitMap<4> = BitMap::new();
        let mut bv2: BitMap<4> = BitMap::new();

        // Create test patterns: 10110 | 11010 = 11110
        let pattern1 = [true, false, true, true, false];
        let pattern2 = [true, true, false, true, false];
        let expected = [true, true, true, true, false];

        for &bit in &pattern1 {
            bv1.push(bit);
        }
        for &bit in &pattern2 {
            bv2.push(bit);
        }

        bv1.or(&bv2);

        assert_eq!(bv1.len(), 5);
        for (i, &expected_bit) in expected.iter().enumerate() {
            assert_eq!(bv1.get(i as u64), expected_bit);
        }
    }

    #[test]
    fn test_bitwise_xor() {
        let mut bv1: BitMap<4> = BitMap::new();
        let mut bv2: BitMap<4> = BitMap::new();

        // Create test patterns: 10110 ^ 11010 = 01100
        let pattern1 = [true, false, true, true, false];
        let pattern2 = [true, true, false, true, false];
        let expected = [false, true, true, false, false];

        for &bit in &pattern1 {
            bv1.push(bit);
        }
        for &bit in &pattern2 {
            bv2.push(bit);
        }

        bv1.xor(&bv2);

        assert_eq!(bv1.len(), 5);
        for (i, &expected_bit) in expected.iter().enumerate() {
            assert_eq!(bv1.get(i as u64), expected_bit);
        }
    }

    #[test]
    fn test_multi_chunk_operations() {
        let mut bv1: BitMap<4> = BitMap::new();
        let mut bv2: BitMap<4> = BitMap::new();

        // Fill multiple chunks
        let chunk1 = hex!("0xAABBCCDD"); // 10101010 10111011 11001100 11011101
        let chunk2 = hex!("0x55667788"); // 01010101 01100110 01110111 10001000

        bv1.push_chunk(&chunk1);
        bv1.push_chunk(&chunk1);
        bv2.push_chunk(&chunk2);
        bv2.push_chunk(&chunk2);

        assert_eq!(bv1.len(), 64);
        assert_eq!(bv2.len(), 64);

        // Test AND operation
        let mut bv_and = bv1.clone();
        bv_and.and(&bv2);

        // Test OR operation
        let mut bv_or = bv1.clone();
        bv_or.or(&bv2);

        // Test XOR operation
        let mut bv_xor = bv1.clone();
        bv_xor.xor(&bv2);

        // Verify results make sense
        assert_eq!(bv_and.len(), 64);
        assert_eq!(bv_or.len(), 64);
        assert_eq!(bv_xor.len(), 64);

        // AND should have fewer or equal ones than either operand
        assert!(bv_and.count_ones() <= bv1.count_ones());
        assert!(bv_and.count_ones() <= bv2.count_ones());

        // OR should have more or equal ones than either operand
        assert!(bv_or.count_ones() >= bv1.count_ones());
        assert!(bv_or.count_ones() >= bv2.count_ones());
    }

    #[test]
    fn test_partial_chunk_operations() {
        let mut bv1: BitMap<4> = BitMap::new();
        let mut bv2: BitMap<4> = BitMap::new();

        // Add partial chunks (not aligned to chunk boundaries)
        for i in 0..35 {
            // 35 bits = 4 bytes + 3 bits
            bv1.push(i % 2 == 0);
            bv2.push(i % 3 == 0);
        }

        assert_eq!(bv1.len(), 35);
        assert_eq!(bv2.len(), 35);

        // Test operations with partial chunks
        let mut bv_and = bv1.clone();
        bv_and.and(&bv2);

        let mut bv_or = bv1.clone();
        bv_or.or(&bv2);

        let mut bv_xor = bv1.clone();
        bv_xor.xor(&bv2);

        // All should maintain the same length
        assert_eq!(bv_and.len(), 35);
        assert_eq!(bv_or.len(), 35);
        assert_eq!(bv_xor.len(), 35);

        // Test flip_all with partial chunk
        let mut bv_inv = bv1.clone();
        let original_ones = bv_inv.count_ones();
        let original_zeros = bv_inv.count_zeros();
        bv_inv.flip_all();
        assert_eq!(bv_inv.count_ones(), original_zeros);
        assert_eq!(bv_inv.count_zeros(), original_ones);
    }

    #[test]
    #[should_panic(expected = "bit 1 out of bounds (len: 1)")]
    fn test_flip_out_of_bounds() {
        let mut bv: BitMap<4> = BitMap::new();
        bv.push(true);
        bv.flip(1); // Only bit 0 exists
    }

    #[test]
    #[should_panic(expected = "BitMap lengths don't match: 2 vs 1")]
    fn test_and_length_mismatch() {
        let mut bv1: BitMap<4> = BitMap::new();
        let mut bv2: BitMap<4> = BitMap::new();

        bv1.push(true);
        bv1.push(false);
        bv2.push(true); // Different length

        bv1.and(&bv2);
    }

    #[test]
    #[should_panic(expected = "BitMap lengths don't match: 1 vs 2")]
    fn test_or_length_mismatch() {
        let mut bv1: BitMap<4> = BitMap::new();
        let mut bv2: BitMap<4> = BitMap::new();

        bv1.push(true);
        bv2.push(true);
        bv2.push(false); // Different length

        bv1.or(&bv2);
    }

    #[test]
    #[should_panic(expected = "BitMap lengths don't match: 3 vs 2")]
    fn test_xor_length_mismatch() {
        let mut bv1: BitMap<4> = BitMap::new();
        let mut bv2: BitMap<4> = BitMap::new();

        bv1.push(true);
        bv1.push(false);
        bv1.push(true);
        bv2.push(true);
        bv2.push(false); // Different length

        bv1.xor(&bv2);
    }

    #[test]
    fn test_equality() {
        // Test empty bitmaps
        assert_eq!(BitMap::<4>::new(), BitMap::<4>::new());
        assert_eq!(BitMap::<8>::new(), BitMap::<8>::new());

        // Test non-empty bitmaps from constructors
        let pattern = [true, false, true, true, false, false, true, false, true];
        let bv4: BitMap<4> = pattern.as_ref().into();
        assert_eq!(bv4, BitMap::<4>::from(pattern.as_ref()));
        let bv8: BitMap<8> = pattern.as_ref().into();
        assert_eq!(bv8, BitMap::<8>::from(pattern.as_ref()));

        // Test non-empty bitmaps from push operations
        let mut bv1: BitMap<4> = BitMap::new();
        let mut bv2: BitMap<4> = BitMap::new();
        for i in 0..33 {
            let bit = i % 3 == 0;
            bv1.push(bit);
            bv2.push(bit);
        }
        assert_eq!(bv1, bv2);

        // Test inequality: different lengths
        bv1.push(true);
        assert_ne!(bv1, bv2);
        bv1.pop(); // Restore equality
        assert_eq!(bv1, bv2);

        // Test inequality: different content
        bv1.flip(15);
        assert_ne!(bv1, bv2);
        bv1.flip(15); // Restore equality
        assert_eq!(bv1, bv2);

        // Test equality after operations
        let mut bv_ops1 = BitMap::<16>::ones(25);
        let mut bv_ops2 = BitMap::<16>::ones(25);
        bv_ops1.flip_all();
        bv_ops2.flip_all();
        assert_eq!(bv_ops1, bv_ops2);

        let mask_bits: Vec<bool> = (0..33).map(|i| i % 3 == 0).collect();
        let mask = BitMap::<4>::from(mask_bits);
        bv1.and(&mask);
        bv2.and(&mask);
        assert_eq!(bv1, bv2);
    }

    #[test]
    fn test_different_chunk_sizes() {
        // Test with different chunk sizes
        let mut bv8: BitMap<8> = BitMap::new();
        let mut bv16: BitMap<16> = BitMap::new();
        let mut bv32: BitMap<32> = BitMap::new();

        // Test chunk operations first (must be chunk-aligned)
        let chunk8 = [0xFF; 8];
        let chunk16 = [0xAA; 16];
        let chunk32 = [0x55; 32];

        bv8.push_chunk(&chunk8);
        bv16.push_chunk(&chunk16);
        bv32.push_chunk(&chunk32);

        // Test basic operations work with different sizes
        bv8.push(true);
        bv8.push(false);
        assert_eq!(bv8.len(), 64 + 2);
        assert_eq!(bv8.count_ones(), 64 + 1); // chunk8 is all 0xFF + 1 true bit
        assert_eq!(bv8.count_zeros(), 1);

        bv16.push(true);
        bv16.push(false);
        assert_eq!(bv16.len(), 128 + 2);
        assert_eq!(bv16.count_ones(), 64 + 1); // chunk16 is 0xAA pattern + 1 true bit
        assert_eq!(bv16.count_zeros(), 64 + 1);

        bv32.push(true);
        bv32.push(false);
        assert_eq!(bv32.len(), 256 + 2);
        assert_eq!(bv32.count_ones(), 128 + 1); // chunk32 is 0x55 pattern + 1 true bit
        assert_eq!(bv32.count_zeros(), 128 + 1);
    }

    #[test]
    fn test_iterator() {
        // Test empty iterator
        let bv: BitMap<4> = BitMap::new();
        let mut iter = bv.iter();
        assert_eq!(iter.next(), None);
        assert_eq!(iter.size_hint(), (0, Some(0)));

        // Test iterator with some bits
        let pattern = [true, false, true, false, true];
        let bv: BitMap<4> = pattern.as_ref().into();

        // Collect all bits via iterator
        let collected: Vec<bool> = bv.iter().collect();
        assert_eq!(collected, pattern);

        // Test size_hint
        let mut iter = bv.iter();
        assert_eq!(iter.size_hint(), (5, Some(5)));

        // Consume one element and check size_hint again
        assert_eq!(iter.next(), Some(true));
        assert_eq!(iter.size_hint(), (4, Some(4)));

        // Test ExactSizeIterator
        let iter = bv.iter();
        assert_eq!(iter.len(), 5);

        // Test iterator with larger bitmap
        let mut large_bv: BitMap<8> = BitMap::new();
        for i in 0..100 {
            large_bv.push(i % 3 == 0);
        }

        let collected: Vec<bool> = large_bv.iter().collect();
        assert_eq!(collected.len(), 100);
        for (i, &bit) in collected.iter().enumerate() {
            assert_eq!(bit, i % 3 == 0);
        }
    }

    #[test]
    fn test_iterator_edge_cases() {
        // Test iterator with single bit
        let mut bv: BitMap<4> = BitMap::new();
        bv.push(true);

        let collected: Vec<bool> = bv.iter().collect();
        assert_eq!(collected, vec![true]);

        // Test iterator across chunk boundaries
        let mut bv: BitMap<4> = BitMap::new();
        // Fill exactly one chunk (32 bits)
        for i in 0..32 {
            bv.push(i % 2 == 0);
        }
        // Add a few more bits in the next chunk
        bv.push(true);
        bv.push(false);
        bv.push(true);

        let collected: Vec<bool> = bv.iter().collect();
        assert_eq!(collected.len(), 35);

        // Verify the pattern
        for (i, &bit) in collected.iter().enumerate().take(32) {
            assert_eq!(bit, i % 2 == 0);
        }
        assert!(collected[32]);
        assert!(!collected[33]);
        assert!(collected[34]);
    }

    #[test]
    fn test_codec_roundtrip() {
        // Test empty bitmap
        let original: BitMap<4> = BitMap::new();
        let encoded = original.encode();
        let decoded = BitMap::decode_cfg(&mut encoded.as_ref(), &(usize::MAX as u64)).unwrap();
        assert_eq!(original, decoded);

        // Test small bitmap
        let pattern = [true, false, true, false, true];
        let original: BitMap<4> = pattern.as_ref().into();
        let encoded = original.encode();
        let decoded = BitMap::decode_cfg(&mut encoded.as_ref(), &(usize::MAX as u64)).unwrap();
        assert_eq!(original, decoded);

        // Verify the decoded bitmap has the same bits
        for (i, &expected) in pattern.iter().enumerate() {
            assert_eq!(decoded.get(i as u64), expected);
        }

        // Test larger bitmap across multiple chunks
        let mut large_original: BitMap<8> = BitMap::new();
        for i in 0..100 {
            large_original.push(i % 7 == 0);
        }

        let encoded = large_original.encode();
        let decoded = BitMap::decode_cfg(&mut encoded.as_ref(), &(usize::MAX as u64)).unwrap();
        assert_eq!(large_original, decoded);

        // Verify all bits match
        assert_eq!(decoded.len(), 100);
        for i in 0..100 {
            assert_eq!(decoded.get(i as u64), i % 7 == 0);
        }
    }

    #[test]
    fn test_codec_different_chunk_sizes() {
        let pattern = [true, false, true, true, false, false, true];

        // Test with different chunk sizes
        let bv4: BitMap<4> = pattern.as_ref().into();
        let bv8: BitMap<8> = pattern.as_ref().into();
        let bv16: BitMap<16> = pattern.as_ref().into();

        // Encode and decode each
        let encoded4 = bv4.encode();
        let decoded4 = BitMap::decode_cfg(&mut encoded4.as_ref(), &(usize::MAX as u64)).unwrap();
        assert_eq!(bv4, decoded4);

        let encoded8 = bv8.encode();
        let decoded8 = BitMap::decode_cfg(&mut encoded8.as_ref(), &(usize::MAX as u64)).unwrap();
        assert_eq!(bv8, decoded8);

        let encoded16 = bv16.encode();
        let decoded16 = BitMap::decode_cfg(&mut encoded16.as_ref(), &(usize::MAX as u64)).unwrap();
        assert_eq!(bv16, decoded16);

        // All should have the same logical content
        for (i, &expected) in pattern.iter().enumerate() {
            let i = i as u64;
            assert_eq!(decoded4.get(i), expected);
            assert_eq!(decoded8.get(i), expected);
            assert_eq!(decoded16.get(i), expected);
        }
    }

    #[test]
    fn test_codec_edge_cases() {
        // Test bitmap with exactly one chunk filled
        let mut bv: BitMap<4> = BitMap::new();
        for i in 0..32 {
            bv.push(i % 2 == 0);
        }

        let encoded = bv.encode();
        let decoded = BitMap::decode_cfg(&mut encoded.as_ref(), &(usize::MAX as u64)).unwrap();
        assert_eq!(bv, decoded);
        assert_eq!(decoded.len(), 32);

        // Test bitmap with partial chunk
        let mut bv2: BitMap<4> = BitMap::new();
        for i in 0..35 {
            // 32 + 3 bits
            bv2.push(i % 3 == 0);
        }

        let encoded2 = bv2.encode();
        let decoded2 = BitMap::decode_cfg(&mut encoded2.as_ref(), &(usize::MAX as u64)).unwrap();
        assert_eq!(bv2, decoded2);
        assert_eq!(decoded2.len(), 35);
    }

    #[test]
    fn test_encode_size() {
        // Test encode size calculation
        let bv: BitMap<4> = BitMap::new();
        let encoded = bv.encode();
        assert_eq!(bv.encode_size(), encoded.len());

        // Test with some data
        let pattern = [true, false, true, false, true];
        let bv: BitMap<4> = pattern.as_ref().into();
        let encoded = bv.encode();
        assert_eq!(bv.encode_size(), encoded.len());

        // Test with larger data
        let mut large_bv: BitMap<8> = BitMap::new();
        for i in 0..100 {
            large_bv.push(i % 2 == 0);
        }
        let encoded = large_bv.encode();
        assert_eq!(large_bv.encode_size(), encoded.len());
    }

    #[test]
    fn test_codec_empty_chunk_optimization() {
        // Test that empty last chunks are not serialized

        // Case 1: Empty bitmap (omits the only empty chunk)
        let bv_empty: BitMap<4> = BitMap::new();
        let encoded_empty = bv_empty.encode();
        let decoded_empty: BitMap<4> =
            BitMap::decode_cfg(&mut encoded_empty.as_ref(), &(usize::MAX as u64)).unwrap();
        assert_eq!(bv_empty, decoded_empty);
        assert_eq!(bv_empty.len(), decoded_empty.len());
        // Should only encode the length, no chunks
        assert_eq!(encoded_empty.len(), bv_empty.len().encode_size());

        // Case 2: Bitmap ending exactly at chunk boundary (omits empty last chunk)
        let mut bv_exact: BitMap<4> = BitMap::new();
        for _ in 0..32 {
            bv_exact.push(true);
        }
        let encoded_exact = bv_exact.encode();
        let decoded_exact: BitMap<4> =
            BitMap::decode_cfg(&mut encoded_exact.as_ref(), &(usize::MAX as u64)).unwrap();
        assert_eq!(bv_exact, decoded_exact);

        // Case 3: Bitmap with partial last chunk (includes last chunk)
        let mut bv_partial: BitMap<4> = BitMap::new();
        for _ in 0..35 {
            bv_partial.push(true);
        }
        let encoded_partial = bv_partial.encode();
        let decoded_partial: BitMap<4> =
            BitMap::decode_cfg(&mut encoded_partial.as_ref(), &(usize::MAX as u64)).unwrap();
        assert_eq!(bv_partial, decoded_partial);
        assert_eq!(bv_partial.len(), decoded_partial.len());

        // Verify optimization works correctly
        assert!(encoded_exact.len() < encoded_partial.len());
        assert_eq!(encoded_exact.len(), bv_exact.len().encode_size() + 4); // length + 1 chunk
        assert_eq!(encoded_partial.len(), bv_partial.len().encode_size() + 8); // length + 2 chunks
    }

    #[test]
    fn test_codec_error_cases() {
        // Test invalid length with range check
        let mut buf = BytesMut::new();
        100u64.write(&mut buf); // bits length

        // 100 bits requires 4 chunks (3 full + partially filled)
        for _ in 0..4 {
            [0u8; 4].write(&mut buf);
        }

        // Test with a restricted range that excludes 100
        let result = BitMap::<4>::decode_cfg(&mut buf, &99);
        assert!(matches!(result, Err(CodecError::InvalidLength(100))));

        // Test truncated buffer (not enough chunks)
        let mut buf = BytesMut::new();
        100u64.write(&mut buf); // bits length requiring 4 chunks (3 full + partially filled)
                                // Only write 3 chunks
        [0u8; 4].write(&mut buf);
        [0u8; 4].write(&mut buf);
        [0u8; 4].write(&mut buf);

        let result = BitMap::<4>::decode_cfg(&mut buf, &(usize::MAX as u64));
        // Should fail when trying to read missing chunks
        assert!(result.is_err());

        // Test invalid trailing bits

        // Create a valid bitmap and encode it
        let original: BitMap<4> = BitMap::ones(20);
        let mut buf = BytesMut::new();
        original.write(&mut buf);

        // Manually corrupt the encoded data by setting trailing bits
        let corrupted_data = buf.freeze();
        let mut corrupted_bytes = corrupted_data.to_vec();

        // The last byte should have some trailing bits set to 1
        // For 20 bits with 4-byte chunks: 20 bits = 2.5 bytes, so last byte should have 4 valid bits
        // Set the high 4 bits of the last byte to 1 (these should be 0)
        let last_byte_idx = corrupted_bytes.len() - 1;
        corrupted_bytes[last_byte_idx] |= 0xF0;

        // Read should fail
        let result = BitMap::<4>::read_cfg(&mut corrupted_bytes.as_slice(), &(usize::MAX as u64));
        assert!(matches!(
            result,
            Err(CodecError::Invalid(
                "BitMap",
                "Invalid trailing bits in encoded data"
            ))
        ));
    }

    #[test]
    fn test_codec_range_config() {
        // Test RangeCfg validation in read_cfg

        // Create a bitmap with 100 bits
        let mut original: BitMap<4> = BitMap::new();
        for i in 0..100 {
            original.push(i % 3 == 0);
        }

        // Write to a buffer
        let mut buf = BytesMut::new();
        original.write(&mut buf);

        // Test with max length < actual size (should fail)
        let result = BitMap::<4>::decode_cfg(&mut buf.as_ref(), &50);
        assert!(matches!(result, Err(CodecError::InvalidLength(100))));

        // Test with max length == actual size (should succeed)
        let decoded = BitMap::<4>::decode_cfg(&mut buf.as_ref(), &100).unwrap();
        assert_eq!(decoded.len(), 100);
        assert_eq!(decoded, original);

        // Test with max length > actual size (should succeed)
        let decoded = BitMap::<4>::decode_cfg(&mut buf.as_ref(), &101).unwrap();
        assert_eq!(decoded.len(), 100);
        assert_eq!(decoded, original);

        // Test empty bitmap
        let empty = BitMap::<4>::new();
        let mut buf = BytesMut::new();
        empty.write(&mut buf);

        // Empty bitmap should work with max length 0
        let decoded = BitMap::<4>::decode_cfg(&mut buf.as_ref(), &0).unwrap();
        assert_eq!(decoded.len(), 0);
        assert!(decoded.is_empty());

        // Empty bitmap should work with max length > 0
        let decoded = BitMap::<4>::decode_cfg(&mut buf.as_ref(), &1).unwrap();
        assert_eq!(decoded.len(), 0);
        assert!(decoded.is_empty());
    }

    #[test]
    fn test_from() {
        // Test From trait with different input types

        // Test with Vec<bool>
        let vec_bool = vec![true, false, true, false, true];
        let bv: BitMap<4> = vec_bool.into();
        assert_eq!(bv.len(), 5);
        assert_eq!(bv.count_ones(), 3);
        assert_eq!(bv.count_zeros(), 2);
        for (i, &expected) in [true, false, true, false, true].iter().enumerate() {
            assert_eq!(bv.get(i as u64), expected);
        }

        // Test with array slice
        let array = [false, true, true, false];
        let bv: BitMap<4> = (&array).into();
        assert_eq!(bv.len(), 4);
        assert_eq!(bv.count_ones(), 2);
        assert_eq!(bv.count_zeros(), 2);
        for (i, &expected) in array.iter().enumerate() {
            assert_eq!(bv.get(i as u64), expected);
        }

        // Test with empty slice
        let empty: Vec<bool> = vec![];
        let bv: BitMap<4> = empty.into();
        assert_eq!(bv.len(), 0);
        assert!(bv.is_empty());

        // Test with large slice
        let large: Vec<bool> = (0..100).map(|i| i % 3 == 0).collect();
        let bv: BitMap<8> = large.clone().into();
        assert_eq!(bv.len(), 100);
        for (i, &expected) in large.iter().enumerate() {
            assert_eq!(bv.get(i as u64), expected);
        }
    }

    #[test]
    fn test_debug_formatting() {
        // Test Debug formatting for different sizes

        // Test empty bitmap
        let bv: BitMap<4> = BitMap::new();
        let debug_str = format!("{bv:?}");
        assert_eq!(debug_str, "BitMap[]");

        // Test small bitmap (should show all bits)
        let bv: BitMap<4> = [true, false, true, false, true].as_ref().into();
        let debug_str = format!("{bv:?}");
        assert_eq!(debug_str, "BitMap[10101]");

        // Test bitmap at the display limit (64 bits)
        let pattern: Vec<bool> = (0..64).map(|i| i % 2 == 0).collect();
        let bv: BitMap<8> = pattern.into();
        let debug_str = format!("{bv:?}");
        let expected_pattern = "1010".repeat(16); // 64 bits alternating
        assert_eq!(debug_str, format!("BitMap[{expected_pattern}]"));

        // Test large bitmap (should show ellipsis)
        let large_pattern: Vec<bool> = (0..100).map(|i| i % 2 == 0).collect();
        let bv: BitMap<16> = large_pattern.into();
        let debug_str = format!("{bv:?}");

        // Should show first 32 bits + "..." + last 32 bits
        let first_32 = "10".repeat(16); // First 32 bits: 1010...
        let last_32 = "10".repeat(16); // Last 32 bits: ...1010
        let expected = format!("BitMap[{first_32}...{last_32}]");
        assert_eq!(debug_str, expected);

        // Test single bit
        let bv: BitMap<4> = [true].as_ref().into();
        assert_eq!(format!("{bv:?}"), "BitMap[1]");

        let bv: BitMap<4> = [false].as_ref().into();
        assert_eq!(format!("{bv:?}"), "BitMap[0]");

        // Test exactly at boundary (65 bits - should show ellipsis)
        let pattern: Vec<bool> = (0..65).map(|i| i == 0 || i == 64).collect(); // First and last bits are true
        let bv: BitMap<16> = pattern.into();
        let debug_str = format!("{bv:?}");

        // Should show first 32 bits (100000...) + "..." + last 32 bits (...000001)
        let first_32 = "1".to_string() + &"0".repeat(31);
        let last_32 = "0".repeat(31) + "1";
        let expected = format!("BitMap[{first_32}...{last_32}]");
        assert_eq!(debug_str, expected);
    }

    #[test]
    fn test_from_different_chunk_sizes() {
        // Test From trait works with different chunk sizes
        let pattern = [true, false, true, true, false, false, true];

        let bv4: BitMap<4> = pattern.as_ref().into();
        let bv8: BitMap<8> = pattern.as_ref().into();
        let bv16: BitMap<16> = pattern.as_ref().into();

        // All should have the same content regardless of chunk size
        // Test each bitmap separately since they have different types
        for bv in [&bv4] {
            assert_eq!(bv.len(), 7);
            assert_eq!(bv.count_ones(), 4);
            assert_eq!(bv.count_zeros(), 3);
            for (i, &expected) in pattern.iter().enumerate() {
                assert_eq!(bv.get(i as u64), expected);
            }
        }

        assert_eq!(bv8.len(), 7);
        assert_eq!(bv8.count_ones(), 4);
        assert_eq!(bv8.count_zeros(), 3);
        for (i, &expected) in pattern.iter().enumerate() {
            assert_eq!(bv8.get(i as u64), expected);
        }

        assert_eq!(bv16.len(), 7);
        assert_eq!(bv16.count_ones(), 4);
        assert_eq!(bv16.count_zeros(), 3);
        for (i, &expected) in pattern.iter().enumerate() {
            assert_eq!(bv16.get(i as u64), expected);
        }
    }

    #[test]
    fn test_prune_chunks() {
        let mut bv: BitMap<4> = BitMap::new();
        bv.push_chunk(&[1, 2, 3, 4]);
        bv.push_chunk(&[5, 6, 7, 8]);
        bv.push_chunk(&[9, 10, 11, 12]);

        assert_eq!(bv.len(), 96);
        assert_eq!(bv.get_chunk(0), &[1, 2, 3, 4]);

        // Prune first chunk
        bv.prune_chunks(1);
        assert_eq!(bv.len(), 64);
        assert_eq!(bv.get_chunk(0), &[5, 6, 7, 8]);
        assert_eq!(bv.get_chunk(1), &[9, 10, 11, 12]);

        // Prune another chunk
        bv.prune_chunks(1);
        assert_eq!(bv.len(), 32);
        assert_eq!(bv.get_chunk(0), &[9, 10, 11, 12]);
    }

    #[test]
    #[should_panic(expected = "cannot prune")]
    fn test_prune_too_many_chunks() {
        let mut bv: BitMap<4> = BitMap::new();
        bv.push_chunk(&[1, 2, 3, 4]);
        bv.push_chunk(&[5, 6, 7, 8]);
        bv.push(true);

        // Try to prune 4 chunks when only 3 are available
        bv.prune_chunks(4);
    }

    #[test]
    fn test_prune_with_partial_last_chunk() {
        let mut bv: BitMap<4> = BitMap::new();
        bv.push_chunk(&[1, 2, 3, 4]);
        bv.push_chunk(&[5, 6, 7, 8]);
        bv.push(true);
        bv.push(false);

        assert_eq!(bv.len(), 66);

        // Can prune first chunk
        bv.prune_chunks(1);
        assert_eq!(bv.len(), 34);
        assert_eq!(bv.get_chunk(0), &[5, 6, 7, 8]);

        // Last partial chunk still has the appended bits
        assert!(bv.get(32));
        assert!(!bv.get(33));
    }

    #[test]
    fn test_prune_all_chunks_resets_next_bit() {
        let mut bv: BitMap<4> = BitMap::new();
        bv.push_chunk(&[1, 2, 3, 4]);
        bv.push_chunk(&[5, 6, 7, 8]);
        bv.push(true);
        bv.push(false);
        bv.push(true);

        // Bitmap has 2 full chunks + 3 bits in partial chunk
        assert_eq!(bv.len(), 67);

        // Prune all chunks (this leaves chunks empty, triggering the reset path)
        bv.prune_chunks(3);

        // Regression test: len() should be 0, not the old next_bit value (3)
        assert_eq!(bv.len(), 0);
        assert!(bv.is_empty());

        // Bitmap should behave as freshly created
        bv.push(true);
        assert_eq!(bv.len(), 1);
        assert!(bv.get(0));
    }

    #[test]
    fn test_is_chunk_aligned() {
        // Empty bitmap is chunk aligned
        let bv: BitMap<4> = BitMap::new();
        assert!(bv.is_chunk_aligned());

        // Test with various chunk sizes
        let mut bv4: BitMap<4> = BitMap::new();
        assert!(bv4.is_chunk_aligned());

        // Add bits one at a time and check alignment
        for i in 1..=32 {
            bv4.push(i % 2 == 0);
            if i == 32 {
                assert!(bv4.is_chunk_aligned()); // Exactly one chunk
            } else {
                assert!(!bv4.is_chunk_aligned()); // Partial chunk
            }
        }

        // Add more bits
        for i in 33..=64 {
            bv4.push(i % 2 == 0);
            if i == 64 {
                assert!(bv4.is_chunk_aligned()); // Exactly two chunks
            } else {
                assert!(!bv4.is_chunk_aligned()); // Partial chunk
            }
        }

        // Test with push_chunk
        let mut bv: BitMap<8> = BitMap::new();
        assert!(bv.is_chunk_aligned());
        bv.push_chunk(&[0xFF; 8]);
        assert!(bv.is_chunk_aligned()); // 64 bits = 1 chunk for N=8
        bv.push_chunk(&[0xAA; 8]);
        assert!(bv.is_chunk_aligned()); // 128 bits = 2 chunks
        bv.push(true);
        assert!(!bv.is_chunk_aligned()); // 129 bits = partial chunk

        // Test with push_byte
        let mut bv: BitMap<4> = BitMap::new();
        for _ in 0..4 {
            bv.push_byte(0xFF);
        }
        assert!(bv.is_chunk_aligned()); // 32 bits = 1 chunk for N=4

        // Test after pop
        bv.pop();
        assert!(!bv.is_chunk_aligned()); // 31 bits = partial chunk

        // Test with zeroes and ones constructors
        let bv_zeroes: BitMap<4> = BitMap::zeroes(64);
        assert!(bv_zeroes.is_chunk_aligned());

        let bv_ones: BitMap<4> = BitMap::ones(96);
        assert!(bv_ones.is_chunk_aligned());

        let bv_partial: BitMap<4> = BitMap::zeroes(65);
        assert!(!bv_partial.is_chunk_aligned());
    }

    #[test]
    fn test_unprune_restores_length() {
        let mut prunable: Prunable<4> = Prunable::new_with_pruned_chunks(1).unwrap();
        assert_eq!(prunable.len(), Prunable::<4>::CHUNK_SIZE_BITS);
        assert_eq!(prunable.pruned_chunks(), 1);
        let chunk = [0xDE, 0xAD, 0xBE, 0xEF];

        prunable.unprune_chunks(&[chunk]);

        assert_eq!(prunable.pruned_chunks(), 0);
        assert_eq!(prunable.len(), Prunable::<4>::CHUNK_SIZE_BITS);
        assert_eq!(prunable.get_chunk_containing(0), &chunk);
    }

    mod proptests {
        use super::*;
        use proptest::prelude::*;

        proptest! {
            #[test]
            fn is_unset_matches_naive(
                bits in prop::collection::vec(any::<bool>(), 1..=512usize),
                start in 0u64..=512,
                end in 0u64..=512,
            ) {
                let bitmap: BitMap = BitMap::from(bits.as_slice());
                let len = bitmap.len();
                let start = start.min(len);
                let end = end.max(start).min(len);
                let range = start..end;

                let expected = range.clone().all(|i| !bitmap.get(i));

                prop_assert_eq!(bitmap.is_unset(range), expected);
            }
        }
    }

    #[test]
    fn is_unset_all_zeros() {
        let bitmap = BitMap::<8>::zeroes(256);
        assert!(bitmap.is_unset(0..256));
    }

    #[test]
    fn is_unset_all_ones() {
        let bitmap = BitMap::<8>::ones(256);
        assert!(!bitmap.is_unset(0..256));
    }

    #[test]
    fn is_unset_single_bit() {
        let mut bitmap = BitMap::<8>::zeroes(64);
        bitmap.set(31, true);
        assert!(bitmap.is_unset(0..31));
        assert!(!bitmap.is_unset(0..32));
        assert!(!bitmap.is_unset(31..32));
        assert!(bitmap.is_unset(32..64));
    }

    #[test]
    fn is_unset_empty_range() {
        let bitmap = BitMap::<8>::ones(64);
        assert!(bitmap.is_unset(0..0));
        assert!(bitmap.is_unset(32..32));
        assert!(bitmap.is_unset(64..64));
    }

    #[test]
    fn is_unset_chunk_boundaries() {
        // N=1 means 8 bits per chunk, so boundaries are more frequent
        let mut bitmap = BitMap::<1>::zeroes(32);
        bitmap.set(7, true);
        assert!(bitmap.is_unset(0..7));
        assert!(!bitmap.is_unset(0..8));
        assert!(bitmap.is_unset(8..32));
    }

    #[test]
    fn is_unset_small_chunk_multi_span() {
        // N=4 means 32 bits per chunk, test spanning 3 chunks
        let mut bitmap = BitMap::<4>::zeroes(128);
        bitmap.set(96, true);
        assert!(bitmap.is_unset(0..96));
        assert!(!bitmap.is_unset(0..97));
        assert!(bitmap.is_unset(97..128));
    }

    #[test]
    #[should_panic(expected = "out of bounds")]
    fn is_unset_out_of_bounds() {
        let bitmap = BitMap::<8>::zeroes(64);
        bitmap.is_unset(0..65);
    }

    #[cfg(feature = "arbitrary")]
    mod conformance {
        use super::*;
        use commonware_codec::conformance::CodecConformance;

        commonware_conformance::conformance_tests! {
            CodecConformance<BitMap>
        }
    }
}