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
//! This module contains the implementation of a [wavelet matrix].
//! The wavelet matrix is a data structure that encodes a sequence of `n` `k`-bit words
//! into a matrix of bit vectors, allowing for fast rank and select queries on the encoded sequence.
//!
//! This implementation further supports quantile queries, and range-predecessor and -successor queries.
//! All operations are `O(k)` time complexity.
//!
//! See the struct documentation for more information.
//!
//! [wavelet matrix]: WaveletMatrix

use crate::util::impl_vector_iterator;
use crate::{BitVec, RsVec};
use std::mem;
use std::ops::Range;

/// A wavelet matrix implementation implemented as described in
/// [Navarro and Claude, 2021](http://dx.doi.org/10.1007/978-3-642-34109-0_18).
/// The implementation is designed to allow for extremely large alphabet sizes, without
/// sacrificing performance for small alphabets.
///
/// There are two constructor algorithms available:
/// - [`from_bit_vec`] and [`from_slice`] construct the wavelet matrix by repeatedly sorting the elements.
///   These constructors have linear space overhead and run in `O(kn * log n)` time complexity.
/// - [`from_bit_vec_pc`] and [`from_slice_pc`] construct the wavelet matrix by counting the
///   prefixes of the elements. These constructors have a space complexity of `O(2^k)` and run
///   in `O(kn)`, which makes this constructor preferable for large sequences over small alphabets.
///
/// They encode a sequence of `n` `k`-bit words into a wavelet matrix which supports constant-time
/// rank and select queries on elements of its `k`-bit alphabet.
/// All query functions are mirrored for both `BitVec` and `u64` query elements, so
/// if `k <= 64`, no heap allocation is needed for the query element.
///
/// Other than rank and select queries, the matrix also supports quantile queries (range select i), and
/// range-predecessor and -successor queries, all of which are loosely based on
/// [Külekci and Thankachan](https://doi.org/10.1016/j.jda.2017.01.002) with better time complexity.
///
/// All operations implemented on the matrix are `O(k)` time complexity.
/// The space complexity of the wavelet matrix is `O(n * k)` with a small linear overhead
/// (see [`RsVec`]).
///
/// # Examples
/// ```
/// use vers_vecs::{BitVec, WaveletMatrix};
///
/// // pack elements from a 3-bit alphabet into a bit vector and construct a wavelet matrix from them
/// let bit_vec = BitVec::pack_sequence_u8(&[1, 4, 4, 1, 2, 7], 3);
/// let wavelet_matrix = WaveletMatrix::from_bit_vec(&bit_vec, 3);
///
/// // query the wavelet matrix
/// assert_eq!(wavelet_matrix.get_u64(0), Some(1));
/// assert_eq!(wavelet_matrix.get_u64(1), Some(4));
///
// // rank and select queries
/// assert_eq!(wavelet_matrix.rank_u64(3, 4), Some(2));
/// assert_eq!(wavelet_matrix.rank_u64(3, 1), Some(1));
/// assert_eq!(wavelet_matrix.select_u64(0, 7), Some(5));
///
/// // statistics
/// assert_eq!(wavelet_matrix.range_median_u64(0..3), Some(4));
/// assert_eq!(wavelet_matrix.predecessor_u64(0..6, 3), Some(2));
/// ```
///
/// [`RsVec`]: RsVec
#[derive(Clone, Debug)]
pub struct WaveletMatrix {
    data: Box<[RsVec]>,
    bits_per_element: u16,
}

impl WaveletMatrix {
    /// Generic constructor that constructs the wavelet matrix by repeatedly sorting the elements.
    /// The runtime complexity is `O(kn * log n)`.
    ///
    /// # Parameters
    /// - `bits_per_element`: The number of bits in each word. Cannot exceed 1 << 16.
    /// - `num_elements`: The number of elements in the sequence.
    /// - `bit_lookup`: A closure that returns the `bit`-th bit of the `element`-th word.
    #[inline(always)] // should get rid of closures in favor of static calls
    fn permutation_sorting<LOOKUP: Fn(usize, usize) -> u64>(
        bits_per_element: u16,
        num_elements: usize,
        bit_lookup: LOOKUP,
    ) -> Self {
        let element_len = bits_per_element as usize;

        let mut data = vec![BitVec::from_zeros(num_elements); element_len];

        // insert the first bit of each word into the first bit vector
        // for each following level, insert the next bit of each word into the next bit vector
        // sorted stably by the previous bit vector
        let mut permutation = (0..num_elements).collect::<Vec<_>>();
        let mut next_permutation = vec![0; num_elements];

        for (level, data) in data.iter_mut().enumerate() {
            let mut total_zeros = 0;
            for i in 0..num_elements {
                if bit_lookup(permutation[i], element_len - level - 1) == 0 {
                    total_zeros += 1;
                } else {
                    data.set(i, 1).unwrap();
                }
            }

            // scan through the generated bit array and move the elements to the correct position
            // for the next permutation
            if level < element_len - 1 {
                let mut zero_boundary = 0;
                let mut one_boundary = total_zeros;
                for i in 0..num_elements {
                    if data.get_unchecked(i) == 0 {
                        next_permutation[zero_boundary] = permutation[i];
                        zero_boundary += 1;
                    } else {
                        next_permutation[one_boundary] = permutation[i];
                        one_boundary += 1;
                    }
                }

                mem::swap(&mut permutation, &mut next_permutation);
            }
        }

        Self {
            data: data.into_iter().map(BitVec::into).collect(),
            bits_per_element,
        }
    }

    /// Create a new wavelet matrix from a sequence of `n` `k`-bit words.
    /// The constructor runs in `O(kn * log n)` time complexity.
    ///
    /// # Parameters
    /// - `bit_vec`: A packed sequence of `n` `k`-bit words. The `i`-th word begins in the
    ///   `bits_per_element * i`-th bit of the bit vector. Words are stored from least to most
    ///    significant bit.
    /// - `bits_per_element`: The number `k` of bits in each word. Cannot exceed 1 << 16.
    ///
    /// # Panics
    /// Panics if the number of bits in the bit vector is not a multiple of the number of bits per element.
    #[must_use]
    pub fn from_bit_vec(bit_vec: &BitVec, bits_per_element: u16) -> Self {
        assert_eq!(bit_vec.len() % bits_per_element as usize, 0, "The number of bits in the bit vector must be a multiple of the number of bits per element.");
        let num_elements = bit_vec.len() / bits_per_element as usize;
        Self::permutation_sorting(bits_per_element, num_elements, |element, bit| {
            bit_vec.get_unchecked(element * bits_per_element as usize + bit)
        })
    }

    /// Create a new wavelet matrix from a sequence of `n` `k`-bit words.
    /// The constructor runs in `O(kn * log n)` time complexity.
    ///
    /// # Parameters
    /// - `sequence`: A slice of `n` u64 values, each encoding a `k`-bit word.
    /// - `bits_per_element`: The number `k` of bits in each word. Cannot exceed 64.
    ///
    /// # Panics
    /// Panics if the number of bits per element exceeds 64.
    #[must_use]
    pub fn from_slice(sequence: &[u64], bits_per_element: u16) -> Self {
        assert!(
            bits_per_element <= 64,
            "The number of bits per element cannot exceed 64."
        );
        Self::permutation_sorting(bits_per_element, sequence.len(), |element, bit| {
            (sequence[element] >> bit) & 1
        })
    }

    /// Generic constructor that constructs the wavelet matrix by counting the prefixes of the elements.
    /// The runtime complexity is `O(kn)`.
    /// This constructor is only recommended for small alphabets.
    ///
    /// # Parameters
    /// - `bits_per_element`: The number of bits in each word. Cannot exceed 64.
    /// - `num_elements`: The number of elements in the sequence.
    /// - `bit_lookup`: A closure that returns the `bit`-th bit of the `element`-th word.
    /// - `element_lookup`: A closure that returns the `element`-th word.
    #[inline(always)] // should get rid of closures in favor of static calls
    fn prefix_counting<LOOKUP: Fn(usize, usize) -> u64, ELEMENT: Fn(usize) -> u64>(
        bits_per_element: u16,
        num_elements: usize,
        bit_lookup: LOOKUP,
        element_lookup: ELEMENT,
    ) -> Self {
        let element_len = bits_per_element as usize;
        let mut histogram = vec![0usize; 1 << bits_per_element];
        let mut borders = vec![0usize; 1 << bits_per_element];
        let mut data = vec![BitVec::from_zeros(num_elements); element_len];

        for i in 0..num_elements {
            histogram[element_lookup(i) as usize] += 1;
            data[0].set_unchecked(i, bit_lookup(i, element_len - 1));
        }

        for level in (1..element_len).rev() {
            // combine histograms of prefixes
            for h in 0..1 << level {
                histogram[h] = histogram[2 * h] + histogram[2 * h + 1];
            }

            // compute borders of current level, using bit reverse patterns because of the weird
            // node ordering in wavelet matrices
            borders[0] = 0;
            for h in 1usize..1 << level {
                let h_minus_1 = (h - 1).reverse_bits() >> (64 - level);
                borders[h.reverse_bits() >> (64 - level)] =
                    borders[h_minus_1] + histogram[h_minus_1];
            }

            for i in 0..num_elements {
                let bit = bit_lookup(i, element_len - level - 1);
                data[level].set_unchecked(
                    borders[element_lookup(i) as usize >> (element_len - level)],
                    bit,
                );
                borders[element_lookup(i) as usize >> (element_len - level)] += 1;
            }
        }

        Self {
            data: data.into_iter().map(BitVec::into).collect(),
            bits_per_element,
        }
    }

    /// Create a new wavelet matrix from a sequence of `n` `k`-bit words using the prefix counting
    /// algorithm [Dinklage et al.](https://doi.org/10.1145/3457197)
    /// The constructor runs in `O(kn)` time complexity but requires `O(2^k)` space during construction,
    /// so it is only recommended for small alphabets.
    /// Use the [`from_bit_vec`] or [`from_slice`] constructors for larger alphabets.
    ///
    /// # Parameters
    /// - `bit_vec`: A packed sequence of `n` `k`-bit words. The `i`-th word begins in the
    ///   `bits_per_element * i`-th bit of the bit vector. Words are stored from least to most
    ///   significant bit.
    /// - `bits_per_element`: The number `k` of bits in each word. Cannot exceed 1 << 16.
    ///
    /// # Panics
    /// Panics if the number of bits in the bit vector is not a multiple of the number of bits per element,
    /// or if the number of bits per element exceeds 64.
    ///
    /// [`from_bit_vec`]: WaveletMatrix::from_bit_vec
    /// [`from_slice`]: WaveletMatrix::from_slice
    #[must_use]
    pub fn from_bit_vec_pc(bit_vec: &BitVec, bits_per_element: u16) -> Self {
        assert_eq!(bit_vec.len() % bits_per_element as usize, 0, "The number of bits in the bit vector must be a multiple of the number of bits per element.");
        assert!(
            bits_per_element <= 64,
            "The number of bits per element cannot exceed 64."
        );
        let num_elements = bit_vec.len() / bits_per_element as usize;
        Self::prefix_counting(
            bits_per_element,
            num_elements,
            |element, bit| bit_vec.get_unchecked(element * bits_per_element as usize + bit),
            |element| {
                bit_vec.get_bits_unchecked(
                    element * bits_per_element as usize,
                    bits_per_element as usize,
                )
            },
        )
    }

    /// Create a new wavelet matrix from a sequence of `n` `k`-bit words using the prefix counting
    /// algorithm [Dinklage et al.](https://doi.org/10.1145/3457197)
    /// The constructor runs in `O(kn)` time complexity but requires `O(2^k)` space during construction,
    /// so it is only recommended for small alphabets.
    /// Use the [`from_bit_vec`] or [`from_slice`] constructors for larger alphabets.
    ///
    /// # Parameters
    /// - `sequence`: A slice of `n` u64 values, each encoding a `k`-bit word.
    /// - `bits_per_element`: The number `k` of bits in each word. Cannot exceed 64.
    ///
    /// # Panics
    /// Panics if the number of bits per element exceeds 64.
    ///
    /// [`from_bit_vec`]: WaveletMatrix::from_bit_vec
    /// [`from_slice`]: WaveletMatrix::from_slice
    #[must_use]
    pub fn from_slice_pc(sequence: &[u64], bits_per_element: u16) -> Self {
        assert!(
            bits_per_element <= 64,
            "The number of bits per element cannot exceed 64."
        );
        Self::prefix_counting(
            bits_per_element,
            sequence.len(),
            |element, bit| (sequence[element] >> bit) & 1,
            |element| sequence[element],
        )
    }

    /// Generic function to read a value from the wavelet matrix and consume it with a closure.
    /// The function is used by the `get_value` and `get_u64` functions, deduplicating code.
    #[inline(always)]
    fn reconstruct_value_unchecked<F: FnMut(u64)>(&self, mut i: usize, mut target_func: F) {
        for level in 0..self.bits_per_element as usize {
            let bit = self.data[level].get_unchecked(i);
            target_func(bit);
            if bit == 0 {
                i = self.data[level].rank0(i);
            } else {
                i = self.data[level].rank0 + self.data[level].rank1(i);
            }
        }
    }

    /// Get the `i`-th element of the encoded sequence in a `k`-bit word.
    /// The `k`-bit word is returned as a `BitVec`.
    /// The first element of the bit vector is the least significant bit.
    ///
    /// Returns `None` if the index is out of bounds.
    ///
    /// # Example
    /// ```
    /// use vers_vecs::{BitVec, WaveletMatrix};
    ///
    /// let bit_vec = BitVec::pack_sequence_u8(&[1, 4, 4, 1, 2, 7], 3);
    /// let wavelet_matrix = WaveletMatrix::from_bit_vec(&bit_vec, 3);
    ///
    /// assert_eq!(wavelet_matrix.get_value(0), Some(BitVec::pack_sequence_u8(&[1], 3)));
    /// assert_eq!(wavelet_matrix.get_value(1), Some(BitVec::pack_sequence_u8(&[4], 3)));
    /// assert_eq!(wavelet_matrix.get_value(100), None);
    /// ```
    #[must_use]
    pub fn get_value(&self, i: usize) -> Option<BitVec> {
        if self.data.is_empty() || i >= self.data[0].len() {
            None
        } else {
            Some(self.get_value_unchecked(i))
        }
    }

    /// Get the `i`-th element of the encoded sequence in a `k`-bit word.
    /// The `k`-bit word is returned as a `BitVec`.
    /// The first element of the bit vector is the least significant bit.
    /// This function does not perform bounds checking.
    /// Use [`get_value`] for a checked version.
    ///
    /// # Panics
    /// May panic if the index is out of bounds. May instead return an empty bit vector.
    ///
    /// [`get_value`]: WaveletMatrix::get_value
    #[must_use]
    pub fn get_value_unchecked(&self, i: usize) -> BitVec {
        let mut value = BitVec::from_zeros(self.bits_per_element as usize);
        let mut level = self.bits_per_element - 1;
        self.reconstruct_value_unchecked(i, |bit| {
            value.set_unchecked(level as usize, bit);
            level = level.saturating_sub(1);
        });
        value
    }

    /// Get the `i`-th element of the encoded sequence as a `u64`.
    /// The `u64` is constructed from the `k`-bit word stored in the wavelet matrix.
    ///
    /// Returns `None` if the index is out of bounds, or if the number of bits per element exceeds 64.
    ///
    /// # Example
    /// ```
    /// use vers_vecs::{BitVec, WaveletMatrix};
    ///
    /// let bit_vec = BitVec::pack_sequence_u8(&[1, 4, 4, 1, 2, 7], 3);
    /// let wavelet_matrix = WaveletMatrix::from_bit_vec(&bit_vec, 3);
    ///
    /// assert_eq!(wavelet_matrix.get_u64(0), Some(1));
    /// assert_eq!(wavelet_matrix.get_u64(1), Some(4));
    /// assert_eq!(wavelet_matrix.get_u64(100), None);
    /// ```
    #[must_use]
    pub fn get_u64(&self, i: usize) -> Option<u64> {
        if self.bits_per_element > 64 || self.data.is_empty() || i >= self.data[0].len() {
            None
        } else {
            Some(self.get_u64_unchecked(i))
        }
    }

    /// Get the `i`-th element of the encoded sequence as a `u64` numeral.
    /// The element is encoded in the lowest `k` bits of the numeral.
    /// If the number of bits per element exceeds 64, the value is truncated.
    /// This function does not perform bounds checking.
    /// Use [`get_u64`] for a checked version.
    ///
    /// # Panic
    /// May panic if the value of `i` is out of bounds. May instead return 0.
    ///
    /// [`get_u64`]: WaveletMatrix::get_u64
    #[must_use]
    pub fn get_u64_unchecked(&self, i: usize) -> u64 {
        let mut value = 0;
        self.reconstruct_value_unchecked(i, |bit| {
            value <<= 1;
            value |= bit;
        });
        value
    }

    /// Get the number of occurrences of the given `symbol` in the encoded sequence in the `range`.
    /// The `symbol` is a `k`-bit word encoded in a [`BitVec`],
    /// where the least significant bit is the first element, and `k` is the number of bits per element
    /// in the wavelet matrix.
    ///
    /// This method does not perform bounds checking, nor does it check if the `symbol` is a valid
    /// `k`-bit word.
    /// Use [`rank_range`] for a checked version.
    ///
    /// # Panics
    /// May panic if the `range` is out of bounds,
    /// or if the number of bits in `symbol` is lower than `k`.
    /// May instead return 0.
    ///
    /// [`BitVec`]: BitVec
    /// [`rank_range`]: WaveletMatrix::rank_range
    #[must_use]
    pub fn rank_range_unchecked(&self, mut range: Range<usize>, symbol: &BitVec) -> usize {
        for (level, data) in self.data.iter().enumerate() {
            if symbol.get_unchecked((self.bits_per_element - 1) as usize - level) == 0 {
                range.start = data.rank0(range.start);
                range.end = data.rank0(range.end);
            } else {
                range.start = data.rank0 + data.rank1(range.start);
                range.end = data.rank0 + data.rank1(range.end);
            }
        }

        range.end - range.start
    }

    /// Get the number of occurrences of the given `symbol` in the encoded sequence in the `range`.
    /// The `symbol` is a `k`-bit word encoded in a [`BitVec`],
    /// where the least significant bit is the first element, and `k` is the number of bits per element
    /// in the wavelet matrix.
    ///
    /// Returns `None` if the `range` is out of bounds (greater than the length of the encoded sequence,
    /// but since it is exclusive, it may be equal to the length),
    /// or if the number of bits in `symbol` is not equal to `k`.
    ///
    /// # Example
    /// ```
    /// use vers_vecs::{BitVec, WaveletMatrix};
    ///
    /// let bit_vec = BitVec::pack_sequence_u8(&[1, 4, 4, 1, 2, 7], 3);
    /// let wavelet_matrix = WaveletMatrix::from_bit_vec(&bit_vec, 3);
    ///
    /// assert_eq!(wavelet_matrix.rank_range(0..3, &BitVec::pack_sequence_u8(&[4], 3)), Some(2));
    /// assert_eq!(wavelet_matrix.rank_range(2..4, &BitVec::pack_sequence_u8(&[4], 3)), Some(1));
    /// ```
    ///
    /// [`BitVec`]: BitVec
    #[must_use]
    pub fn rank_range(&self, range: Range<usize>, symbol: &BitVec) -> Option<usize> {
        if range.start >= self.len()
            || range.end > self.len()
            || symbol.len() != self.bits_per_element as usize
        {
            None
        } else {
            Some(self.rank_range_unchecked(range, symbol))
        }
    }

    /// Get the number of occurrences of the given `symbol` in the encoded sequence in the `range`.
    /// The `symbol` is a `k`-bit word encoded in a u64 numeral,
    /// where k is less than or equal to 64.
    /// The interval is half-open, meaning `rank_range_u64(0..0, symbol)` returns 0.
    ///
    /// This method does not perform bounds checking, nor does it check if the elements of the
    /// wavelet matrix can be represented in a u64 numeral.
    /// Use [`rank_range_u64`] for a checked version.
    ///
    /// # Panics
    /// May panic if the `range` is out of bounds.
    /// May instead return 0.
    /// If the number of bits in wavelet matrix elements exceed `64`, the behavior is
    /// platform-dependent.
    ///
    /// [`rank_range_u64`]: WaveletMatrix::rank_range_u64
    #[must_use]
    pub fn rank_range_u64_unchecked(&self, mut range: Range<usize>, symbol: u64) -> usize {
        for (level, data) in self.data.iter().enumerate() {
            if (symbol >> ((self.bits_per_element - 1) as usize - level)) & 1 == 0 {
                range.start = data.rank0(range.start);
                range.end = data.rank0(range.end);
            } else {
                range.start = data.rank0 + data.rank1(range.start);
                range.end = data.rank0 + data.rank1(range.end);
            }
        }

        range.end - range.start
    }

    /// Get the number of occurrences of the given `symbol` in the encoded sequence in the `range`.
    /// The `symbol` is a `k`-bit word encoded in a u64 numeral,
    /// where k is less than or equal to 64.
    /// The interval is half-open, meaning `rank_range_u64(0..0, symbol)` returns 0.
    ///
    /// Returns `None` if the `range` is out of bounds (greater than the length of the encoded sequence,
    /// but since it is exclusive, it may be equal to the length),
    /// or if the number of bits in the wavelet matrix elements exceed `64`.
    ///
    /// # Example
    /// ```
    /// use vers_vecs::{BitVec, WaveletMatrix};
    ///
    /// let bit_vec = BitVec::pack_sequence_u8(&[1, 4, 4, 1, 2, 7], 3);
    /// let wavelet_matrix = WaveletMatrix::from_bit_vec(&bit_vec, 3);
    ///
    /// assert_eq!(wavelet_matrix.rank_range_u64(0..3, 4), Some(2));
    /// assert_eq!(wavelet_matrix.rank_range_u64(2..4, 4), Some(1));
    /// ```
    #[must_use]
    pub fn rank_range_u64(&self, range: Range<usize>, symbol: u64) -> Option<usize> {
        if range.start >= self.len() || range.end > self.len() || self.bits_per_element > 64 {
            None
        } else {
            Some(self.rank_range_u64_unchecked(range, symbol))
        }
    }

    /// Get the number of occurrences of the given `symbol` in the encoded sequence between the
    /// `offset`-th and `i`-th element (exclusive).
    /// This is equivalent to ```rank_range_unchecked(offset..i, symbol)```.
    /// The interval is half-open, meaning ```rank_offset_unchecked(0, 0, symbol)``` returns 0.
    ///
    /// The `symbol` is a `k`-bit word encoded in a [`BitVec`],
    /// where the least significant bit is the first element, and `k` is the number of bits per element
    /// in the wavelet matrix.
    ///
    /// This method does not perform bounds checking, nor does it check if the `symbol` is a valid
    /// `k`-bit word.
    /// Use [`rank_offset`] for a checked version.
    ///
    /// # Panics
    /// May panic if `offset` is out of bounds,
    /// or if `offset + i` is larger than the length of the encoded sequence,
    /// or if `offset` is greater than `i`,
    /// or if the number of bits in `symbol` is lower than `k`.
    /// May instead return 0.
    ///
    /// [`BitVec`]: BitVec
    /// [`rank_offset`]: WaveletMatrix::rank_offset
    #[must_use]
    pub fn rank_offset_unchecked(&self, offset: usize, i: usize, symbol: &BitVec) -> usize {
        self.rank_range_unchecked(offset..i, symbol)
    }

    /// Get the number of occurrences of the given `symbol` in the encoded sequence between the
    /// `offset`-th and `i`-th element (exclusive).
    /// This is equivalent to ``rank_range(offset..i, symbol)``.
    /// The interval is half-open, meaning ``rank_offset(0, 0, symbol)`` returns 0,
    /// because the interval is empty.
    ///
    /// The `symbol` is a `k`-bit word encoded in a [`BitVec`],
    /// where the least significant bit is the first element, and `k` is the number of bits per element
    /// in the wavelet matrix.
    ///
    /// Returns `None` if `offset` is out of bounds,
    /// or if `i` is larger than the length of the encoded sequence,
    /// or if `offset` is greater than `i`,
    /// or if the number of bits in `symbol` is not equal to `k`.
    /// `i` may equal the length of the encoded sequence,
    /// which will return the number of occurrences of the symbol up to the end of the sequence.
    ///
    /// # Example
    /// ```
    /// use vers_vecs::{BitVec, WaveletMatrix};
    ///
    /// let bit_vec = BitVec::pack_sequence_u8(&[1, 4, 4, 1, 2, 7], 3);
    /// let wavelet_matrix = WaveletMatrix::from_bit_vec(&bit_vec, 3);
    ///
    /// assert_eq!(wavelet_matrix.rank_offset(0, 3, &BitVec::pack_sequence_u8(&[4], 3)), Some(2));
    /// assert_eq!(wavelet_matrix.rank_offset(2, 4, &BitVec::pack_sequence_u8(&[4], 3)), Some(1));
    /// ```
    ///
    /// [`BitVec`]: BitVec
    #[must_use]
    pub fn rank_offset(&self, offset: usize, i: usize, symbol: &BitVec) -> Option<usize> {
        if offset > i
            || offset >= self.len()
            || i > self.len()
            || symbol.len() != self.bits_per_element as usize
        {
            None
        } else {
            Some(self.rank_offset_unchecked(offset, i, symbol))
        }
    }

    /// Get the number of occurrences of the given `symbol` in the encoded sequence between the
    /// `offset`-th and `i`-th element (exclusive).
    /// This is equivalent to ``rank_range(offset..i, symbol)``.
    /// The interval is half-open, meaning ``rank_offset(0, 0, symbol)`` returns 0.
    ///
    /// The `symbol` is a `k`-bit word encoded in a u64 numeral,
    /// where k is less than or equal to 64.
    ///
    /// This method does not perform bounds checking, nor does it check if the elements of the
    /// wavelet matrix can be represented in a u64 numeral.
    /// Use [`rank_offset_u64`] for a checked version.
    ///
    /// # Panics
    /// May panic if `offset` is out of bounds,
    /// or if `i` is larger than the length of the encoded sequence,
    /// or if `offset` is greater than `i`,
    /// or if the number of bits in wavelet matrix elements exceed `64`.
    /// May instead return 0.
    ///
    /// [`rank_offset_u64`]: WaveletMatrix::rank_offset_u64
    #[must_use]
    pub fn rank_offset_u64_unchecked(&self, offset: usize, i: usize, symbol: u64) -> usize {
        self.rank_range_u64_unchecked(offset..i, symbol)
    }

    /// Get the number of occurrences of the given `symbol` in the encoded sequence between the
    /// `offset`-th and `i`-th element (exclusive).
    /// This is equivalent to ``rank_range(offset..i, symbol)``.
    /// The interval is half-open, meaning ``rank_offset(0, 0, symbol)`` returns 0.
    ///
    /// The `symbol` is a `k`-bit word encoded in a u64 numeral,
    /// where k is less than or equal to 64.
    ///
    /// Returns `None` if `offset` is out of bounds,
    /// or if `i` is larger than the length of the encoded sequence,
    /// or if `offset` is greater than `i`,
    /// or if the number of bits in the wavelet matrix elements exceed `64`.
    /// `i` may equal the length of the encoded sequence,
    /// which will return the number of occurrences of the symbol up to the end of the sequence.
    ///
    /// # Example
    /// ```
    /// use vers_vecs::{BitVec, WaveletMatrix};
    ///
    /// let bit_vec = BitVec::pack_sequence_u8(&[1, 4, 4, 1, 2, 7], 3);
    /// let wavelet_matrix = WaveletMatrix::from_bit_vec(&bit_vec, 3);
    ///
    /// assert_eq!(wavelet_matrix.rank_offset_u64(0, 3, 4), Some(2));
    /// assert_eq!(wavelet_matrix.rank_offset_u64(2, 4, 4), Some(1));
    /// ```
    #[must_use]
    pub fn rank_offset_u64(&self, offset: usize, i: usize, symbol: u64) -> Option<usize> {
        if offset > i || offset >= self.len() || i > self.len() || self.bits_per_element > 64 {
            None
        } else {
            Some(self.rank_offset_u64_unchecked(offset, i, symbol))
        }
    }

    /// Get the number of occurrences of the given `symbol` in the encoded sequence up to the `i`-th
    /// element (exclusive).
    /// The `symbol` is a `k`-bit word encoded in a [`BitVec`],
    /// where the least significant bit is the first element, and `k` is the number of bits per element
    /// in the wavelet matrix.
    ///
    /// This method does not perform bounds checking, nor does it check if the `symbol` is a valid
    /// `k`-bit word.
    /// Use [`rank`] for a checked version.
    ///
    /// # Panics
    /// May panic if `i` is out of bounds, or if the number of bits in `symbol` is lower than `k`.
    /// May instead return 0.
    /// If the number of bits in `symbol` exceeds `k`, the remaining bits are ignored.
    ///
    /// [`BitVec`]: BitVec
    /// [`rank`]: WaveletMatrix::rank
    #[must_use]
    pub fn rank_unchecked(&self, i: usize, symbol: &BitVec) -> usize {
        self.rank_range_unchecked(0..i, symbol)
    }

    /// Get the number of occurrences of the given `symbol` in the encoded sequence up to the `i`-th
    /// element (exclusive).
    /// The `symbol` is a `k`-bit word encoded in a [`BitVec`],
    /// where the least significant bit is the first element, and `k` is the number of bits per element
    /// in the wavelet matrix.
    ///
    /// Returns `None` if `i` is out of bounds (greater than the length of the encoded sequence, but
    /// since it is exclusive, it may be equal to the length),
    /// or if the number of bits in `symbol` is not equal to `k`.
    ///
    /// # Example
    /// ```
    /// use vers_vecs::{BitVec, WaveletMatrix};
    ///
    /// let bit_vec = BitVec::pack_sequence_u8(&[1, 4, 4, 1, 2, 7], 3);
    /// let wavelet_matrix = WaveletMatrix::from_bit_vec(&bit_vec, 3);
    ///
    /// assert_eq!(wavelet_matrix.rank(3, &BitVec::pack_sequence_u8(&[4], 3)), Some(2));
    /// assert_eq!(wavelet_matrix.rank(3, &BitVec::pack_sequence_u8(&[1], 3)), Some(1));
    /// ```
    ///
    /// [`BitVec`]: BitVec
    #[must_use]
    pub fn rank(&self, i: usize, symbol: &BitVec) -> Option<usize> {
        if i > self.len() || symbol.len() != self.bits_per_element as usize {
            None
        } else {
            Some(self.rank_range_unchecked(0..i, symbol))
        }
    }

    /// Get the number of occurrences of the given `symbol` in the encoded sequence up to the `i`-th
    /// element (exclusive).
    /// The `symbol` is a `k`-bit word encoded in a u64 numeral,
    /// where k is less than or equal to 64.
    ///
    /// This method does not perform bounds checking, nor does it check if the elements of the
    /// wavelet matrix can be represented in a u64 numeral.
    /// Use [`rank_u64`] for a checked version.
    ///
    /// # Panics
    /// May panic if `i` is out of bounds,
    /// or if the number of bits in wavelet matrix elements exceed `64`.
    /// May instead return 0.
    ///
    /// [`rank_u64`]: WaveletMatrix::rank_u64
    #[must_use]
    pub fn rank_u64_unchecked(&self, i: usize, symbol: u64) -> usize {
        self.rank_range_u64_unchecked(0..i, symbol)
    }

    /// Get the number of occurrences of the given `symbol` in the encoded sequence up to the `i`-th
    /// element (exclusive).
    /// The `symbol` is a `k`-bit word encoded in a u64 numeral,
    /// where k is less than or equal to 64.
    ///
    /// Returns `None` if `i` is out of bounds (greater than the length of the encoded sequence, but
    /// since it is exclusive, it may be equal to the length),
    /// or if the number of bits in the wavelet matrix elements exceed `64`.
    ///
    /// # Example
    /// ```
    /// use vers_vecs::{BitVec, WaveletMatrix};
    ///
    /// let bit_vec = BitVec::pack_sequence_u8(&[1, 4, 4, 1, 2, 7], 3);
    /// let wavelet_matrix = WaveletMatrix::from_bit_vec(&bit_vec, 3);
    ///
    /// assert_eq!(wavelet_matrix.rank_u64(3, 4), Some(2));
    /// assert_eq!(wavelet_matrix.rank_u64(3, 1), Some(1));
    /// ```
    #[must_use]
    pub fn rank_u64(&self, i: usize, symbol: u64) -> Option<usize> {
        if i > self.len() || self.bits_per_element > 64 {
            None
        } else {
            Some(self.rank_range_u64_unchecked(0..i, symbol))
        }
    }

    /// Get the index of the `rank`-th occurrence of the given `symbol` in the encoded sequence,
    /// starting from the `offset`-th element.
    /// The `symbol` is a `k`-bit word encoded in a [`BitVec`],
    /// where the least significant bit is the first element, and `k` is the number of bits per element
    /// in the wavelet matrix.
    ///
    /// This method does not perform bounds checking, nor does it check if the `symbol` is a valid
    /// `k`-bit word.
    /// Use [`select_offset`] for a checked version.
    ///
    /// Returns the index of the `rank`-th occurrence of the `symbol` in the encoded sequence,
    /// or the length of the encoded sequence if the `rank`-th occurrence does not exist.
    ///
    /// # Panics
    /// May panic if the `offset` is out of bounds,
    /// or if the number of bits in `symbol` is lower than `k`.
    /// May instead return the length of the encoded sequence.
    ///
    /// [`BitVec`]: BitVec
    /// [`select_offset`]: WaveletMatrix::select_offset
    #[must_use]
    pub fn select_offset_unchecked(&self, offset: usize, rank: usize, symbol: &BitVec) -> usize {
        let mut range_start = offset;

        for (level, data) in self.data.iter().enumerate() {
            if symbol.get_unchecked((self.bits_per_element - 1) as usize - level) == 0 {
                range_start = data.rank0(range_start);
            } else {
                range_start = data.rank0 + data.rank1(range_start);
            }
        }

        let mut range_end = range_start + rank;

        for (level, data) in self.data.iter().enumerate().rev() {
            if symbol.get_unchecked((self.bits_per_element - 1) as usize - level) == 0 {
                range_end = data.select0(range_end);
            } else {
                range_end = data.select1(range_end - data.rank0);
            }
        }

        range_end
    }

    /// Get the index of the `rank`-th occurrence of the given `symbol` in the encoded sequence,
    /// starting from the `offset`-th element.
    /// The `symbol` is a `k`-bit word encoded in a [`BitVec`],
    /// where the least significant bit is the first element, and `k` is the number of bits per element
    /// in the wavelet matrix.
    ///
    /// Returns `None` if `offset` is out of bounds, or if the number of bits in `symbol` is not equal to `k`,
    /// or if the `rank`-th occurrence of the `symbol` does not exist.
    ///
    /// # Example
    /// ```
    /// use vers_vecs::{BitVec, WaveletMatrix};
    ///
    /// let bit_vec = BitVec::pack_sequence_u8(&[1, 4, 4, 1, 2, 7], 3);
    /// let wavelet_matrix = WaveletMatrix::from_bit_vec(&bit_vec, 3);
    ///
    /// assert_eq!(wavelet_matrix.select_offset(0, 0, &BitVec::pack_sequence_u8(&[4], 3)), Some(1));
    /// assert_eq!(wavelet_matrix.select_offset(0, 1, &BitVec::pack_sequence_u8(&[4], 3)), Some(2));
    /// assert_eq!(wavelet_matrix.select_offset(2, 0, &BitVec::pack_sequence_u8(&[4], 3)), Some(2));
    /// assert_eq!(wavelet_matrix.select_offset(2, 1, &BitVec::pack_sequence_u8(&[4], 3)), None);
    /// ```
    ///
    /// [`BitVec`]: BitVec
    #[must_use]
    pub fn select_offset(&self, offset: usize, rank: usize, symbol: &BitVec) -> Option<usize> {
        if offset >= self.len() || symbol.len() != self.bits_per_element as usize {
            None
        } else {
            let idx = self.select_offset_unchecked(offset, rank, symbol);
            if idx < self.len() {
                Some(idx)
            } else {
                None
            }
        }
    }

    /// Get the index of the `rank`-th occurrence of the given `symbol` in the encoded sequence,
    /// starting from the `offset`-th element.
    /// The `symbol` is a `k`-bit word encoded in a u64 numeral,
    /// where k is less than or equal to 64.
    ///
    /// This method does not perform bounds checking, nor does it check if the elements of the
    /// wavelet matrix can be represented in a u64 numeral.
    /// Use [`select_offset_u64`] for a checked version.
    ///
    /// Returns the index of the `rank`-th occurrence of the `symbol` in the encoded sequence,
    /// or the length of the encoded sequence if the `rank`-th occurrence does not exist.
    ///
    /// # Panics
    /// May panic if the `offset` is out of bounds,
    /// or if the number of bits in wavelet matrix elements exceed `64`.
    /// May instead return the length of the encoded sequence.
    ///
    /// [`select_offset_u64`]: WaveletMatrix::select_offset_u64
    #[must_use]
    pub fn select_offset_u64_unchecked(&self, offset: usize, rank: usize, symbol: u64) -> usize {
        let mut range_start = offset;

        for (level, data) in self.data.iter().enumerate() {
            if (symbol >> ((self.bits_per_element - 1) as usize - level)) & 1 == 0 {
                range_start = data.rank0(range_start);
            } else {
                range_start = data.rank0 + data.rank1(range_start);
            }
        }

        let mut range_end = range_start + rank;

        for (level, data) in self.data.iter().enumerate().rev() {
            if (symbol >> ((self.bits_per_element - 1) as usize - level)) & 1 == 0 {
                range_end = data.select0(range_end);
            } else {
                range_end = data.select1(range_end - data.rank0);
            }
        }

        range_end
    }

    /// Get the index of the `rank`-th occurrence of the given `symbol` in the encoded sequence,
    /// starting from the `offset`-th element.
    /// The `symbol` is a `k`-bit word encoded in a u64 numeral,
    /// where k is less than or equal to 64.
    ///
    /// Returns `None` if `offset` is out of bounds, or if the number of bits in the wavelet matrix
    /// elements exceed `64`, or if the `rank`-th occurrence of the `symbol` does not exist.
    ///
    /// # Example
    /// ```
    /// use vers_vecs::{BitVec, WaveletMatrix};
    ///
    /// let bit_vec = BitVec::pack_sequence_u8(&[1, 4, 4, 1, 2, 7], 3);
    /// let wavelet_matrix = WaveletMatrix::from_bit_vec(&bit_vec, 3);
    ///
    /// assert_eq!(wavelet_matrix.select_offset_u64(0, 0, 4), Some(1));
    /// assert_eq!(wavelet_matrix.select_offset_u64(0, 1, 4), Some(2));
    /// assert_eq!(wavelet_matrix.select_offset_u64(2, 0, 4), Some(2));
    /// assert_eq!(wavelet_matrix.select_offset_u64(2, 1, 4), None);
    /// ```
    #[must_use]
    pub fn select_offset_u64(&self, offset: usize, rank: usize, symbol: u64) -> Option<usize> {
        if offset >= self.len() || self.bits_per_element > 64 {
            None
        } else {
            let idx = self.select_offset_u64_unchecked(offset, rank, symbol);
            if idx < self.len() {
                Some(idx)
            } else {
                None
            }
        }
    }

    /// Get the index of the `rank`-th occurrence of the given `symbol` in the encoded sequence.
    /// The `symbol` is a `k`-bit word encoded in a [`BitVec`],
    /// where the least significant bit is the first element, and `k` is the number of bits per element
    /// in the wavelet matrix.
    ///
    /// This method does not perform bounds checking, nor does it check if the `symbol` is a valid
    /// `k`-bit word.
    /// Use [`select`] for a checked version.
    ///
    /// Returns the index of the `rank`-th occurrence of the `symbol` in the encoded sequence,
    /// or the length of the encoded sequence if the `rank`-th occurrence does not exist.
    ///
    /// # Panics
    /// May panic if the number of bits in `symbol` is not equal to `k`.
    /// May instead return the length of the encoded sequence.
    ///
    /// [`BitVec`]: BitVec
    /// [`select`]: WaveletMatrix::select
    #[must_use]
    pub fn select_unchecked(&self, rank: usize, symbol: &BitVec) -> usize {
        self.select_offset_unchecked(0, rank, symbol)
    }

    /// Get the index of the `rank`-th occurrence of the given `symbol` in the encoded sequence.
    /// The `symbol` is a `k`-bit word encoded in a [`BitVec`],
    /// where the least significant bit is the first element, and `k` is the number of bits per element
    /// in the wavelet matrix.
    ///
    /// Returns `None` if the number of bits in `symbol` is not equal to `k`,
    /// or if the `rank`-th occurrence of the `symbol` does not exist.
    ///
    /// # Example
    /// ```
    /// use vers_vecs::{BitVec, WaveletMatrix};
    ///
    /// let bit_vec = BitVec::pack_sequence_u8(&[1, 4, 4, 1, 2, 7], 3);
    /// let wavelet_matrix = WaveletMatrix::from_bit_vec(&bit_vec, 3);
    ///
    /// assert_eq!(wavelet_matrix.select(0, &BitVec::pack_sequence_u8(&[4], 3)), Some(1));
    /// assert_eq!(wavelet_matrix.select(1, &BitVec::pack_sequence_u8(&[4], 3)), Some(2));
    /// ```
    ///
    /// [`BitVec`]: BitVec
    #[must_use]
    pub fn select(&self, rank: usize, symbol: &BitVec) -> Option<usize> {
        if symbol.len() == self.bits_per_element as usize {
            let idx = self.select_unchecked(rank, symbol);
            if idx < self.len() {
                Some(idx)
            } else {
                None
            }
        } else {
            None
        }
    }

    /// Get the index of the `rank`-th occurrence of the given `symbol` in the encoded sequence.
    /// The `symbol` is a `k`-bit word encoded in a u64 numeral,
    /// where k is less than or equal to 64.
    ///
    /// This method does not perform bounds checking, nor does it check if the elements of the
    /// wavelet matrix can be represented in a u64 numeral.
    /// Use [`select_u64`] for a checked version.
    ///
    /// Returns the index of the `rank`-th occurrence of the `symbol` in the encoded sequence,
    /// or the length of the encoded sequence if the `rank`-th occurrence does not exist.
    ///
    /// # Panics
    /// May panic if the number of bits in wavelet matrix elements exceed `64`.
    /// May instead return the length of the encoded sequence.
    ///
    /// [`select_u64`]: WaveletMatrix::select_u64
    #[must_use]
    pub fn select_u64_unchecked(&self, rank: usize, symbol: u64) -> usize {
        self.select_offset_u64_unchecked(0, rank, symbol)
    }

    /// Get the index of the `rank`-th occurrence of the given `symbol` in the encoded sequence.
    /// The `symbol` is a `k`-bit word encoded in a u64 numeral,
    /// where k is less than or equal to 64.
    ///
    /// Returns `None` if the number of bits in the wavelet matrix elements exceed `64`,
    /// or if the `rank`-th occurrence of the `symbol` does not exist.
    ///
    /// # Example
    /// ```
    /// use vers_vecs::{BitVec, WaveletMatrix};
    ///
    /// let bit_vec = BitVec::pack_sequence_u8(&[1, 4, 4, 1, 2, 7], 3);
    /// let wavelet_matrix = WaveletMatrix::from_bit_vec(&bit_vec, 3);
    ///
    /// assert_eq!(wavelet_matrix.select_u64(0, 4), Some(1));
    /// assert_eq!(wavelet_matrix.select_u64(1, 4), Some(2));
    /// ```
    #[must_use]
    pub fn select_u64(&self, rank: usize, symbol: u64) -> Option<usize> {
        if self.bits_per_element > 64 {
            None
        } else {
            let idx = self.select_u64_unchecked(rank, symbol);
            if idx < self.len() {
                Some(idx)
            } else {
                None
            }
        }
    }

    /// Get the `k`-th smallest element in the encoded sequence in the specified `range`,
    /// where `k = 0` returns the smallest element.
    /// The `range` is a half-open interval, meaning that the `end` index is exclusive.
    /// The `k`-th smallest element is returned as a `BitVec`,
    /// where the least significant bit is the first element.
    ///
    /// This method does not perform bounds checking.
    /// It returns a nonsensical result if the `k` is greater than the size of the range.
    /// Use [`quantile`] for a checked version.
    ///
    /// # Panics
    /// May panic if the `range` is out of bounds. May instead return an empty bit vector.
    ///
    /// [`quantile`]: WaveletMatrix::quantile
    #[must_use]
    pub fn quantile_unchecked(&self, range: Range<usize>, k: usize) -> BitVec {
        let result = BitVec::from_zeros(self.bits_per_element as usize);

        self.partial_quantile_search_unchecked(range, k, 0, result)
    }

    /// Internal function to reuse the quantile code for the predecessor and successor search.
    /// This function performs the quantile search starting at the given level with the given prefix.
    ///
    /// The function does not perform any checks, so the caller must ensure that the range is valid,
    /// and that the prefix is a valid prefix for the given level.
    #[inline(always)]
    fn partial_quantile_search_unchecked(
        &self,
        mut range: Range<usize>,
        mut k: usize,
        start_level: usize,
        mut prefix: BitVec,
    ) -> BitVec {
        debug_assert!(prefix.len() == self.bits_per_element as usize);
        debug_assert!(!range.is_empty());
        debug_assert!(range.end <= self.len());

        for (level, data) in self.data.iter().enumerate().skip(start_level) {
            let zeros_start = data.rank0(range.start);
            let zeros_end = data.rank0(range.end);
            let zeros = zeros_end - zeros_start;

            // if k < zeros, the element is among the zeros
            if k < zeros {
                range.start = zeros_start;
                range.end = zeros_end;
            } else {
                // the element is among the ones, so we set the bit to 1, and move the range
                // into the 1-partition of the next level
                prefix.set_unchecked((self.bits_per_element - 1) as usize - level, 1);
                k -= zeros;
                range.start = data.rank0 + (range.start - zeros_start); // range.start - zeros_start is the rank1 of range.start
                range.end = data.rank0 + (range.end - zeros_end); // same here
            }
        }

        prefix
    }

    /// Get the `k`-th smallest element in the encoded sequence in the specified `range`,
    /// where `k = 0` returns the smallest element.
    /// The `range` is a half-open interval, meaning that the `end` index is exclusive.
    /// The `k`-th smallest element is returned as a `BitVec`,
    /// where the least significant bit is the first element.
    ///
    /// Returns `None` if the `range` is out of bounds, or if `k` is greater than the size of the range.
    ///
    /// # Example
    /// ```
    /// use vers_vecs::{BitVec, WaveletMatrix};
    ///
    /// let bit_vec = BitVec::pack_sequence_u8(&[1, 4, 4, 1, 2, 7], 3);
    /// let wavelet_matrix = WaveletMatrix::from_bit_vec(&bit_vec, 3);
    ///
    /// assert_eq!(wavelet_matrix.quantile(0..3, 0), Some(BitVec::pack_sequence_u8(&[1], 3)));
    /// assert_eq!(wavelet_matrix.quantile(0..3, 1), Some(BitVec::pack_sequence_u8(&[4], 3)));
    /// assert_eq!(wavelet_matrix.quantile(1..4, 0), Some(BitVec::pack_sequence_u8(&[1], 3)));
    /// ```
    #[must_use]
    pub fn quantile(&self, range: Range<usize>, k: usize) -> Option<BitVec> {
        if range.start >= self.len() || range.end > self.len() || k >= range.end - range.start {
            None
        } else {
            Some(self.quantile_unchecked(range, k))
        }
    }

    /// Get the `i`-th smallest element in the entire wavelet matrix.
    /// The `i`-th smallest element is returned as a `BitVec`,
    /// where the least significant bit is the first element.
    ///
    /// This method does not perform bounds checking.
    /// Use [`get_sorted`] for a checked version.
    ///
    /// # Panics
    /// May panic if the `i` is out of bounds, or returns an empty bit vector.
    #[must_use]
    pub fn get_sorted_unchecked(&self, i: usize) -> BitVec {
        self.quantile_unchecked(0..self.len(), i)
    }

    /// Get the `i`-th smallest element in the wavelet matrix.
    /// The `i`-th smallest element is returned as a `BitVec`,
    /// where the least significant bit is the first element.
    /// This method call is equivalent to `self.quantile(0..self.len(), i)`.
    ///
    /// Returns `None` if the `i` is out of bounds.
    ///
    /// # Example
    /// ```
    /// use vers_vecs::{BitVec, WaveletMatrix};
    ///
    /// let bit_vec = BitVec::pack_sequence_u8(&[1, 4, 4, 1, 2, 7], 3);
    /// let wavelet_matrix = WaveletMatrix::from_bit_vec(&bit_vec, 3);
    ///
    /// assert_eq!(wavelet_matrix.get_sorted(0), Some(BitVec::pack_sequence_u8(&[1], 3)));
    /// assert_eq!(wavelet_matrix.get_sorted(1), Some(BitVec::pack_sequence_u8(&[1], 3)));
    /// assert_eq!(wavelet_matrix.get_sorted(2), Some(BitVec::pack_sequence_u8(&[2], 3)));
    /// ```
    #[must_use]
    pub fn get_sorted(&self, i: usize) -> Option<BitVec> {
        if i >= self.len() {
            None
        } else {
            Some(self.get_sorted_unchecked(i))
        }
    }

    /// Get the `k`-th smallest element in the encoded sequence in the specified `range`,
    /// where `k = 0` returns the smallest element.
    /// The `range` is a half-open interval, meaning that the `end` index is exclusive.
    /// The `k`-th smallest element is returned as a `u64` numeral.
    /// If the number of bits per element exceeds 64, the value is truncated.
    ///
    /// This method does not perform bounds checking.
    /// It returns a nonsensical result if the `k` is greater than the size of the range.
    /// Use [`quantile_u64`] for a checked version.
    ///
    /// # Panics
    /// May panic if the `range` is out of bounds.
    /// May instead return 0.
    ///
    /// [`quantile_u64`]: WaveletMatrix::quantile_u64
    #[must_use]
    pub fn quantile_u64_unchecked(&self, range: Range<usize>, k: usize) -> u64 {
        self.partial_quantile_search_u64_unchecked(range, k, 0, 0)
    }

    /// Internal function to reuse the quantile code for the predecessor and successor search.
    /// This function performs the quantile search starting at the given level with the given prefix.
    ///
    /// The function does not perform any checks, so the caller must ensure that the range is valid,
    /// and that the prefix is a valid prefix for the given level (i.e. the prefix is not shifted
    /// to another level).
    #[inline(always)]
    fn partial_quantile_search_u64_unchecked(
        &self,
        mut range: Range<usize>,
        mut k: usize,
        start_level: usize,
        mut prefix: u64,
    ) -> u64 {
        debug_assert!(self.bits_per_element <= 64);
        debug_assert!(!range.is_empty());
        debug_assert!(range.end <= self.len());

        for data in self.data.iter().skip(start_level) {
            prefix <<= 1;
            let zeros_start = data.rank0(range.start);
            let zeros_end = data.rank0(range.end);
            let zeros = zeros_end - zeros_start;

            if k < zeros {
                range.start = zeros_start;
                range.end = zeros_end;
            } else {
                prefix |= 1;
                k -= zeros;
                range.start = data.rank0 + (range.start - zeros_start);
                range.end = data.rank0 + (range.end - zeros_end);
            }
        }

        prefix
    }

    /// Get the `k`-th smallest element in the encoded sequence in the specified `range`,
    /// where `k = 0` returns the smallest element.
    /// The `range` is a half-open interval, meaning that the `end` index is exclusive.
    /// The `k`-th smallest element is returned as a `u64` numeral.
    ///
    /// Returns `None` if the `range` is out of bounds, or if the number of bits per element exceeds 64,
    /// or if `k` is greater than the size of the range.
    ///
    /// # Example
    /// ```
    /// use vers_vecs::{BitVec, WaveletMatrix};
    ///
    /// let bit_vec = BitVec::pack_sequence_u8(&[1, 4, 4, 1, 2, 7], 3);
    /// let wavelet_matrix = WaveletMatrix::from_bit_vec(&bit_vec, 3);
    ///
    /// assert_eq!(wavelet_matrix.quantile_u64(0..3, 0), Some(1));
    /// assert_eq!(wavelet_matrix.quantile_u64(0..3, 1), Some(4));
    /// assert_eq!(wavelet_matrix.quantile_u64(1..4, 0), Some(1));
    /// ```
    #[must_use]
    pub fn quantile_u64(&self, range: Range<usize>, k: usize) -> Option<u64> {
        if range.start >= self.len()
            || range.end > self.len()
            || self.bits_per_element > 64
            || k >= range.end - range.start
        {
            None
        } else {
            Some(self.quantile_u64_unchecked(range, k))
        }
    }

    /// Get the `i`-th smallest element in the wavelet matrix.
    /// The `i`-th smallest element is returned as a u64 numeral.
    ///
    /// If the number of bits per element exceeds 64, the value is truncated.
    ///
    /// This method does not perform bounds checking.
    /// Use [`get_sorted_u64`] for a checked version.
    ///
    /// # Panics
    /// May panic if the `i` is out of bounds, or returns an empty bit vector.
    ///
    /// [`get_sorted_u64`]: WaveletMatrix::get_sorted_u64
    #[must_use]
    pub fn get_sorted_u64_unchecked(&self, i: usize) -> u64 {
        self.quantile_u64_unchecked(0..self.len(), i)
    }

    /// Get the `i`-th smallest element in the entire wavelet matrix.
    /// The `i`-th smallest element is returned as a u64 numeral.
    ///
    /// Returns `None` if the `i` is out of bounds, or if the number of bits per element exceeds 64.
    ///
    /// # Example
    /// ```
    /// use vers_vecs::{BitVec, WaveletMatrix};
    ///
    /// let bit_vec = BitVec::pack_sequence_u8(&[1, 4, 4, 1, 2, 7], 3);
    /// let wavelet_matrix = WaveletMatrix::from_bit_vec(&bit_vec, 3);
    ///
    /// assert_eq!(wavelet_matrix.get_sorted_u64(0), Some(1));
    /// assert_eq!(wavelet_matrix.get_sorted_u64(1), Some(1));
    /// assert_eq!(wavelet_matrix.get_sorted_u64(2), Some(2));
    /// ```
    #[must_use]
    pub fn get_sorted_u64(&self, i: usize) -> Option<u64> {
        if i >= self.len() || self.bits_per_element > 64 {
            None
        } else {
            Some(self.get_sorted_u64_unchecked(i))
        }
    }

    /// Get the smallest element in the encoded sequence in the specified `range`.
    /// The range is a half-open interval, meaning that the `end` index is exclusive.
    /// The smallest element is returned as a `BitVec`,
    ///
    /// This method does not perform bounds checking.
    /// Use [`range_min`] for a checked version.
    ///
    /// # Panics
    /// May panic if the `range` is out of bounds or if the range is empty.
    /// May instead return an empty bit vector.
    ///
    /// [`range_min`]: WaveletMatrix::range_min
    #[must_use]
    pub fn range_min_unchecked(&self, range: Range<usize>) -> BitVec {
        self.quantile_unchecked(range, 0)
    }

    /// Get the smallest element in the encoded sequence in the specified `range`.
    /// The range is a half-open interval, meaning that the `end` index is exclusive.
    /// The smallest element is returned as a `BitVec`,
    ///
    /// Returns `None` if the `range` is out of bounds or if the range is empty.
    ///
    /// # Example
    /// ```
    /// use vers_vecs::{BitVec, WaveletMatrix};
    ///
    /// let bit_vec = BitVec::pack_sequence_u8(&[1, 4, 4, 1, 2, 7], 3);
    /// let wavelet_matrix = WaveletMatrix::from_bit_vec(&bit_vec, 3);
    ///
    /// assert_eq!(wavelet_matrix.range_min(0..3), Some(BitVec::pack_sequence_u8(&[1], 3)));
    /// assert_eq!(wavelet_matrix.range_min(1..4), Some(BitVec::pack_sequence_u8(&[1], 3)));
    /// assert_eq!(wavelet_matrix.range_min(1..3), Some(BitVec::pack_sequence_u8(&[4], 3)));
    /// ```
    #[must_use]
    pub fn range_min(&self, range: Range<usize>) -> Option<BitVec> {
        self.quantile(range, 0)
    }

    /// Get the smallest element in the encoded sequence in the specified `range`.
    /// The range is a half-open interval, meaning that the `end` index is exclusive.
    /// The smallest element is returned as a `u64` numeral.
    /// If the number of bits per element exceeds 64, the value is truncated.
    ///
    /// This method does not perform bounds checking.
    /// Use [`range_min_u64`] for a checked version.
    ///
    /// # Panics
    /// May panic if the `range` is out of bounds or if the range is empty.
    /// May instead return 0.
    ///
    /// [`range_min_u64`]: WaveletMatrix::range_min_u64
    #[must_use]
    pub fn range_min_u64_unchecked(&self, range: Range<usize>) -> u64 {
        self.quantile_u64_unchecked(range, 0)
    }

    /// Get the smallest element in the encoded sequence in the specified `range`.
    /// The range is a half-open interval, meaning that the `end` index is exclusive.
    /// The smallest element is returned as a `u64` numeral.
    ///
    /// Returns `None` if the `range` is out of bounds, if the range is empty, or if the number of bits
    /// per element exceeds 64.
    ///
    /// # Example
    /// ```
    /// use vers_vecs::{BitVec, WaveletMatrix};
    ///
    /// let bit_vec = BitVec::pack_sequence_u8(&[1, 4, 4, 1, 2, 7], 3);
    /// let wavelet_matrix = WaveletMatrix::from_bit_vec(&bit_vec, 3);
    ///
    /// assert_eq!(wavelet_matrix.range_min_u64(0..3), Some(1));
    /// assert_eq!(wavelet_matrix.range_min_u64(1..4), Some(1));
    /// assert_eq!(wavelet_matrix.range_min_u64(1..3), Some(4));
    /// ```
    #[must_use]
    pub fn range_min_u64(&self, range: Range<usize>) -> Option<u64> {
        self.quantile_u64(range, 0)
    }

    /// Get the largest element in the encoded sequence in the specified `range`.
    /// The range is a half-open interval, meaning that the `end` index is exclusive.
    /// The largest element is returned as a `BitVec`,
    /// where the least significant bit is the first element.
    ///
    /// This method does not perform bounds checking.
    /// Use [`range_max`] for a checked version.
    ///
    /// # Panics
    /// May panic if the `range` is out of bounds or if the range is empty.
    /// May instead return an empty bit vector.
    ///
    /// [`range_max`]: WaveletMatrix::range_max
    #[must_use]
    pub fn range_max_unchecked(&self, range: Range<usize>) -> BitVec {
        let k = range.end - range.start - 1;
        self.quantile_unchecked(range, k)
    }

    /// Get the largest element in the encoded sequence in the specified `range`.
    /// The range is a half-open interval, meaning that the `end` index is exclusive.
    /// The largest element is returned as a `BitVec`,
    /// where the least significant bit is the first element.
    ///
    /// Returns `None` if the `range` is out of bounds or if the range is empty.
    ///
    /// # Example
    /// ```
    /// use vers_vecs::{BitVec, WaveletMatrix};
    ///
    /// let bit_vec = BitVec::pack_sequence_u8(&[1, 4, 4, 1, 2, 7], 3);
    /// let wavelet_matrix = WaveletMatrix::from_bit_vec(&bit_vec, 3);
    ///
    /// assert_eq!(wavelet_matrix.range_max(0..3), Some(BitVec::pack_sequence_u8(&[4], 3)));
    /// assert_eq!(wavelet_matrix.range_max(3..6), Some(BitVec::pack_sequence_u8(&[7], 3)));
    /// ```
    #[must_use]
    pub fn range_max(&self, range: Range<usize>) -> Option<BitVec> {
        if range.is_empty() {
            None
        } else {
            let k = range.end - range.start - 1;
            self.quantile(range, k)
        }
    }

    /// Get the largest element in the encoded sequence in the specified `range`.
    /// The range is a half-open interval, meaning that the `end` index is exclusive.
    /// The largest element is returned as a `u64` numeral.
    /// If the number of bits per element exceeds 64, the value is truncated.
    ///
    /// This method does not perform bounds checking.
    /// Use [`range_max_u64`] for a checked version.
    ///
    /// # Panics
    /// May panic if the `range` is out of bounds or if the range is empty.
    /// May instead return 0.
    ///
    /// [`range_max_u64`]: WaveletMatrix::range_max_u64
    #[must_use]
    pub fn range_max_u64_unchecked(&self, range: Range<usize>) -> u64 {
        let k = range.end - range.start - 1;
        self.quantile_u64_unchecked(range, k)
    }

    /// Get the largest element in the encoded sequence in the specified `range`.
    /// The range is a half-open interval, meaning that the `end` index is exclusive.
    /// The largest element is returned as a `u64` numeral.
    ///
    /// Returns `None` if the `range` is out of bounds, if the range is empty, or if the number of bits
    /// per element exceeds 64.
    ///
    /// # Example
    /// ```
    /// use vers_vecs::{BitVec, WaveletMatrix};
    ///
    /// let bit_vec = BitVec::pack_sequence_u8(&[1, 4, 4, 1, 2, 7], 3);
    /// let wavelet_matrix = WaveletMatrix::from_bit_vec(&bit_vec, 3);
    ///
    /// assert_eq!(wavelet_matrix.range_max_u64(0..3), Some(4));
    /// assert_eq!(wavelet_matrix.range_max_u64(3..6), Some(7));
    /// ```
    #[must_use]
    pub fn range_max_u64(&self, range: Range<usize>) -> Option<u64> {
        if range.is_empty() {
            None
        } else {
            let k = range.end - range.start - 1;
            self.quantile_u64(range, k)
        }
    }

    /// Get the median element in the encoded sequence in the specified `range`.
    /// The range is a half-open interval, meaning that the `end` index is exclusive.
    /// The median element is returned as a `BitVec`,
    /// where the least significant bit is the first element.
    ///
    /// If the range does not contain an odd number of elements, the position is rounded down.
    ///
    /// This method does not perform bounds checking.
    /// Use [`range_median`] for a checked version.
    ///
    /// # Panics
    /// May panic if the `range` is out of bounds or if the range is empty.
    /// May instead return an empty bit vector.
    ///
    /// [`range_median`]: WaveletMatrix::range_median
    #[must_use]
    pub fn range_median_unchecked(&self, range: Range<usize>) -> BitVec {
        let k = (range.end - 1 - range.start) / 2;
        self.quantile_unchecked(range, k)
    }

    /// Get the median element in the encoded sequence in the specified `range`.
    /// The range is a half-open interval, meaning that the `end` index is exclusive.
    /// The median element is returned as a `BitVec`,
    /// where the least significant bit is the first element.
    ///
    /// If the range does not contain an odd number of elements, the position is rounded down.
    ///
    /// Returns `None` if the `range` is out of bounds or if the range is empty.
    ///
    /// # Example
    /// ```
    /// use vers_vecs::{BitVec, WaveletMatrix};
    ///
    /// let bit_vec = BitVec::pack_sequence_u8(&[1, 4, 4, 1, 2, 7], 3);
    /// let wavelet_matrix = WaveletMatrix::from_bit_vec(&bit_vec, 3);
    ///
    /// assert_eq!(wavelet_matrix.range_median(0..3), Some(BitVec::pack_sequence_u8(&[4], 3)));
    /// assert_eq!(wavelet_matrix.range_median(1..4), Some(BitVec::pack_sequence_u8(&[4], 3)));
    /// assert_eq!(wavelet_matrix.range_median(0..6), Some(BitVec::pack_sequence_u8(&[2], 3)));
    /// ```
    #[must_use]
    pub fn range_median(&self, range: Range<usize>) -> Option<BitVec> {
        if range.is_empty() {
            None
        } else {
            let k = (range.end - 1 - range.start) / 2;
            self.quantile(range, k)
        }
    }

    /// Get the median element in the encoded sequence in the specified `range`.
    /// The range is a half-open interval, meaning that the `end` index is exclusive.
    /// The median element is returned as a `u64` numeral.
    /// If the number of bits per element exceeds 64, the value is truncated.
    ///
    /// If the range does not contain an odd number of elements, the position is rounded down.
    ///
    /// This method does not perform bounds checking.
    /// Use [`range_median_u64`] for a checked version.
    ///
    /// # Panics
    /// May panic if the `range` is out of bounds or if the range is empty.
    /// May instead return 0.
    ///
    /// [`range_median_u64`]: WaveletMatrix::range_median_u64
    #[must_use]
    pub fn range_median_u64_unchecked(&self, range: Range<usize>) -> u64 {
        let k = (range.end - 1 - range.start) / 2;
        self.quantile_u64_unchecked(range, k)
    }

    /// Get the median element in the encoded sequence in the specified `range`.
    /// The range is a half-open interval, meaning that the `end` index is exclusive.
    /// The median element is returned as a `u64` numeral.
    ///
    /// If the range does not contain an odd number of elements, the position is rounded down.
    ///
    /// Returns `None` if the `range` is out of bounds, if the range is empty, or if the number of bits
    /// per element exceeds 64.
    ///
    /// # Example
    /// ```
    /// use vers_vecs::{BitVec, WaveletMatrix};
    ///
    /// let bit_vec = BitVec::pack_sequence_u8(&[1, 4, 4, 1, 2, 7], 3);
    /// let wavelet_matrix = WaveletMatrix::from_bit_vec(&bit_vec, 3);
    ///
    /// assert_eq!(wavelet_matrix.range_median_u64(0..3), Some(4));
    /// assert_eq!(wavelet_matrix.range_median_u64(1..4), Some(4));
    /// assert_eq!(wavelet_matrix.range_median_u64(0..6), Some(2));
    /// ```
    #[must_use]
    pub fn range_median_u64(&self, range: Range<usize>) -> Option<u64> {
        if range.is_empty() || self.bits_per_element > 64 || range.end > self.len() {
            None
        } else {
            let k = (range.end - 1 - range.start) / 2;
            self.quantile_u64(range, k)
        }
    }

    /// Get the predecessor of the given `symbol` in the given `range`.
    /// This is a private generic helper function to implement the public `predecessor` functions.
    ///
    /// The read and write access to the query and result values are abstracted by the `Reader` and `Writer` closures.
    #[inline(always)] // even though the function is pretty large, inlining probably gets rid of the closure calls in favor of static calls
    fn predecessor_generic_unchecked<
        T: Clone,
        Reader: Fn(usize, &T) -> u64,
        Writer: Fn(u64, usize, &mut T),
        Quantile: Fn(&Self, Range<usize>, usize, usize, T) -> T,
    >(
        &self,
        mut range: Range<usize>,
        symbol: &T,
        mut result_value: T,
        bit_reader: Reader,
        result_writer: Writer,
        quantile_search: Quantile,
    ) -> Option<T> {
        // the bit-prefix at the last node where we could go to an interval with smaller elements,
        // i.e. where we need to go if the current prefix has no elements smaller than the query
        let mut last_smaller_prefix = result_value.clone();
        // the level of the last node where we could go to an interval with smaller elements
        let mut last_one_level: Option<usize> = None;
        // the range of the last node where we could go to an interval with smaller elements
        let mut next_smaller_range: Option<Range<usize>> = None;

        for (level, data) in self.data.iter().enumerate() {
            let query_bit = bit_reader(level, symbol);

            // read the amount of elements with the current result-prefix plus one 0 bit.
            // if the query_bit is 1, we can calculate the amount of elements with the result-prefix
            // plus one 1 from there
            let zeros_start = data.rank0(range.start);
            let zeros_end = data.rank0(range.end);
            let elements_zero = zeros_end - zeros_start;

            if query_bit == 0 {
                if elements_zero == 0 {
                    // if our query bit is zero in this level and suddenly our new interval is empty,
                    // all elements that were in the previous interval are bigger than the query element,
                    // because they all have a 1 in the current level.
                    // this means the predecessor is the largest element in the last smaller interval,
                    // i.e. the interval that has a 0 bit at the last level where our prefix had a 1 bit.

                    return next_smaller_range.map(|r| {
                        let idx = r.end - r.start - 1;
                        result_writer(0, last_one_level.unwrap(), &mut last_smaller_prefix);
                        quantile_search(
                            self,
                            r,
                            idx,
                            last_one_level.unwrap() + 1,
                            last_smaller_prefix,
                        )
                    });
                }

                // update the prefix
                result_writer(0, level, &mut result_value);

                // update the range to the interval of the new prefix
                range.start = zeros_start;
                range.end = zeros_end;
            } else {
                if elements_zero == range.end - range.start {
                    // if our query element is 1 in this level and suddenly our new interval is empty,
                    // all elements that were in the previous interval are smaller than the query element,
                    // because they all have a 0 in the current level.
                    // this means the predecessor is the largest element in the last level's interval.

                    let idx = range.end - range.start - 1;
                    return Some(quantile_search(self, range, idx, level, result_value));
                }

                // if the other interval is not empty, we update the last smaller interval to the last interval where we can switch to a 0 prefix
                if !(zeros_start..zeros_end).is_empty() {
                    last_one_level = Some(level);
                    next_smaller_range = Some(zeros_start..zeros_end);
                    last_smaller_prefix = result_value.clone();
                }

                // update the prefix
                result_writer(1, level, &mut result_value);

                // update the range to the interval of the new prefix
                range.start = data.rank0 + (range.start - zeros_start);
                range.end = data.rank0 + (range.end - zeros_end);
            }
        }

        Some(result_value)
    }

    /// Get the predecessor of the given `symbol` in the given `range`.
    /// The `symbol` is a `k`-bit word encoded in a [`BitVec`],
    /// where the least significant bit is the first element, and `k` is the number of bits per element
    /// in the wavelet matrix.
    /// The `symbol` does not have to be in the encoded sequence.
    /// The predecessor is the largest element in the `range` that is smaller than or equal
    /// to the `symbol`.
    ///
    /// Returns `None` if the number of bits in the `symbol` is not equal to `k`,
    /// if the range is empty, if the wavelet matrix is empty, if the range is out of bounds,
    /// or if the `symbol` is smaller than all elements in the range.
    ///
    /// # Example
    /// ```
    /// use vers_vecs::{BitVec, WaveletMatrix};
    ///
    /// let bit_vec = BitVec::pack_sequence_u8(&[1, 4, 4, 1, 2, 7], 3);
    /// let wavelet_matrix = WaveletMatrix::from_bit_vec(&bit_vec, 3);
    ///
    /// assert_eq!(wavelet_matrix.predecessor(0..3, &BitVec::pack_sequence_u8(&[7], 3)), Some(BitVec::pack_sequence_u8(&[4], 3)));
    /// assert_eq!(wavelet_matrix.predecessor(0..3, &BitVec::pack_sequence_u8(&[4], 3)), Some(BitVec::pack_sequence_u8(&[4], 3)));
    /// assert_eq!(wavelet_matrix.predecessor(0..6, &BitVec::pack_sequence_u8(&[7], 3)), Some(BitVec::pack_sequence_u8(&[7], 3)));
    /// ```
    ///
    /// [`BitVec`]: BitVec
    #[must_use]
    pub fn predecessor(&self, range: Range<usize>, symbol: &BitVec) -> Option<BitVec> {
        if symbol.len() != self.bits_per_element as usize
            || range.is_empty()
            || self.is_empty()
            || range.end > self.len()
        {
            return None;
        }

        self.predecessor_generic_unchecked(
            range,
            symbol,
            BitVec::from_zeros(self.bits_per_element as usize),
            |level, symbol| symbol.get_unchecked((self.bits_per_element - 1) as usize - level),
            |bit, level, result| {
                result.set_unchecked((self.bits_per_element - 1) as usize - level, bit);
            },
            Self::partial_quantile_search_unchecked,
        )
    }

    /// Get the predecessor of the given `symbol` in the given `range`.
    /// The `symbol` is a `k`-bit word encoded in a `u64` numeral,
    /// where k is less than or equal to 64.
    /// The `symbol` does not have to be in the encoded sequence.
    /// The predecessor is the largest element in the `range` that is smaller than or equal
    /// to the `symbol`.
    ///
    /// Returns `None` if the number of bits in the matrix is greater than 64,
    /// if the range is empty, if the wavelet matrix is empty, if the range is out of bounds,
    /// or if the `symbol` is smaller than all elements in the range.
    ///
    /// # Example
    /// ```
    /// use vers_vecs::{BitVec, WaveletMatrix};
    ///
    /// let bit_vec = BitVec::pack_sequence_u8(&[1, 4, 4, 1, 2, 7], 3);
    /// let wavelet_matrix = WaveletMatrix::from_bit_vec(&bit_vec, 3);
    ///
    /// assert_eq!(wavelet_matrix.predecessor_u64(0..3, 7), Some(4));
    /// assert_eq!(wavelet_matrix.predecessor_u64(0..3, 4), Some(4));
    /// assert_eq!(wavelet_matrix.predecessor_u64(0..6, 7), Some(7));
    /// ```
    #[must_use]
    pub fn predecessor_u64(&self, range: Range<usize>, symbol: u64) -> Option<u64> {
        if self.bits_per_element > 64
            || range.is_empty()
            || self.is_empty()
            || range.end > self.len()
        {
            return None;
        }

        self.predecessor_generic_unchecked(
            range,
            &symbol,
            0,
            |level, symbol| symbol >> ((self.bits_per_element - 1) as usize - level) & 1,
            |bit, _level, result| {
                // we ignore the level here, and instead rely on the fact that the bits are set in order.
                // we have to do that, because the quantile_search_u64 does the same.
                *result <<= 1;
                *result |= bit;
            },
            Self::partial_quantile_search_u64_unchecked,
        )
    }

    #[inline(always)]
    fn successor_generic_unchecked<
        T: Clone,
        Reader: Fn(usize, &T) -> u64,
        Writer: Fn(u64, usize, &mut T),
        Quantile: Fn(&Self, Range<usize>, usize, usize, T) -> T,
    >(
        &self,
        mut range: Range<usize>,
        symbol: &T,
        mut result_value: T,
        bit_reader: Reader,
        result_writer: Writer,
        quantile_search: Quantile,
    ) -> Option<T> {
        // the bit-prefix at the last node where we could go to an interval with larger elements,
        // i.e. where we need to go if the current prefix has no elements larger than the query
        let mut last_larger_prefix = result_value.clone();
        // the level of the last node where we could go to an interval with larger elements
        let mut last_zero_level: Option<usize> = None;
        // the range of the last node where we could go to an interval with larger elements
        let mut next_larger_range: Option<Range<usize>> = None;

        for (level, data) in self.data.iter().enumerate() {
            let query_bit = bit_reader(level, symbol);

            // read the amount of elements with the current result-prefix plus one 0 bit.
            // if the query_bit is 1, we can calculate the amount of elements with the result-prefix
            // plus one 1 from there
            let zeros_start = data.rank0(range.start);
            let zeros_end = data.rank0(range.end);
            let elements_zero = zeros_end - zeros_start;

            if query_bit == 0 {
                if elements_zero == 0 {
                    // if our query element is 0 in this level and suddenly our new interval is empty,
                    // all elements that were in the previous interval are larger than the query element,
                    // because they all have a 1 in the current level.
                    // this means the successor is the smallest element in the last level's interval.

                    return Some(quantile_search(self, range, 0, level, result_value));
                }

                // if the other interval is not empty, we update the last interval where we can switch to a prefix with a 1
                if !(data.rank0 + (range.start - zeros_start)..data.rank0 + (range.end - zeros_end))
                    .is_empty()
                {
                    last_zero_level = Some(level);
                    next_larger_range = Some(
                        data.rank0 + (range.start - zeros_start)
                            ..data.rank0 + (range.end - zeros_end),
                    );
                    last_larger_prefix = result_value.clone();
                }

                // update the prefix
                result_writer(0, level, &mut result_value);

                // update the range to the interval of the new prefix
                range.start = zeros_start;
                range.end = zeros_end;
            } else {
                if elements_zero == range.end - range.start {
                    // if our query bit is 1 in this level and suddenly our new interval is empty,
                    // all elements that were in the previous interval are smaller than the query element,
                    // because they all have a 0 in the current level.
                    // this means the successor is the smallest element in the last interval with a larger prefix,
                    // i.e. the interval that has a 1 bit at the last level where our prefix had a 0 bit.

                    return next_larger_range.map(|r| {
                        result_writer(1, last_zero_level.unwrap(), &mut last_larger_prefix);
                        quantile_search(
                            self,
                            r,
                            0,
                            last_zero_level.unwrap() + 1,
                            last_larger_prefix,
                        )
                    });
                }

                // update the prefix
                result_writer(1, level, &mut result_value);

                // update the range to the interval of the new prefix
                range.start = data.rank0 + (range.start - zeros_start);
                range.end = data.rank0 + (range.end - zeros_end);
            }
        }

        Some(result_value)
    }

    /// Get the successor of the given `symbol` in the given range.
    /// The `symbol` is a `k`-bit word encoded in a [`BitVec`],
    /// where the least significant bit is the first element, and `k` is the number of bits per element
    /// in the wavelet matrix.
    /// The `symbol` does not have to be in the encoded sequence.
    /// The successor is the smallest element in the range that is greater than or equal
    /// to the `symbol`.
    ///
    /// Returns `None` if the number of bits in the `symbol` is not equal to `k`,
    /// if the range is empty, if the wavelet matrix is empty, if the range is out of bounds,
    /// or if the `symbol` is greater than all elements in the range.
    ///
    /// # Example
    /// ```
    /// use vers_vecs::{BitVec, WaveletMatrix};
    ///
    /// let bit_vec = BitVec::pack_sequence_u8(&[1, 4, 4, 1, 2, 7], 3);
    /// let wavelet_matrix = WaveletMatrix::from_bit_vec(&bit_vec, 3);
    ///
    /// assert_eq!(wavelet_matrix.successor(0..3, &BitVec::pack_sequence_u8(&[2], 3)), Some(BitVec::pack_sequence_u8(&[4], 3)));
    /// assert_eq!(wavelet_matrix.successor(0..3, &BitVec::pack_sequence_u8(&[5], 3)), None);
    /// assert_eq!(wavelet_matrix.successor(0..6, &BitVec::pack_sequence_u8(&[2], 3)), Some(BitVec::pack_sequence_u8(&[2], 3)));
    /// ```
    ///
    /// [`BitVec`]: BitVec
    #[must_use]
    pub fn successor(&self, range: Range<usize>, symbol: &BitVec) -> Option<BitVec> {
        if symbol.len() != self.bits_per_element as usize
            || range.is_empty()
            || self.is_empty()
            || range.end > self.len()
        {
            return None;
        }

        self.successor_generic_unchecked(
            range,
            symbol,
            BitVec::from_zeros(self.bits_per_element as usize),
            |level, symbol| symbol.get_unchecked((self.bits_per_element - 1) as usize - level),
            |bit, level, result| {
                result.set_unchecked((self.bits_per_element - 1) as usize - level, bit);
            },
            Self::partial_quantile_search_unchecked,
        )
    }

    /// Get the successor of the given `symbol` in the given range.
    /// The `symbol` is a `k`-bit word encoded in a `u64` numeral,
    /// where k is less than or equal to 64.
    /// The `symbol` does not have to be in the encoded sequence.
    /// The successor is the smallest element in the range that is greater than or equal
    /// to the `symbol`.
    ///
    /// Returns `None` if the number of bits in the matrix is greater than 64,
    /// if the range is empty, if the wavelet matrix is empty, if the range is out of bounds,
    /// or if the `symbol` is greater than all elements in the range.
    ///
    /// # Example
    /// ```
    /// use vers_vecs::{BitVec, WaveletMatrix};
    ///
    /// let bit_vec = BitVec::pack_sequence_u8(&[1, 4, 4, 1, 2, 7], 3);
    /// let wavelet_matrix = WaveletMatrix::from_bit_vec(&bit_vec, 3);
    ///
    /// assert_eq!(wavelet_matrix.successor_u64(0..3, 2), Some(4));
    /// assert_eq!(wavelet_matrix.successor_u64(0..3, 5), None);
    /// assert_eq!(wavelet_matrix.successor_u64(0..6, 2), Some(2));
    /// ```
    #[must_use]
    pub fn successor_u64(&self, range: Range<usize>, symbol: u64) -> Option<u64> {
        if self.bits_per_element > 64
            || range.is_empty()
            || self.is_empty()
            || range.end > self.len()
        {
            return None;
        }

        self.successor_generic_unchecked(
            range,
            &symbol,
            0,
            |level, symbol| symbol >> ((self.bits_per_element - 1) as usize - level) & 1,
            |bit, _level, result| {
                // we ignore the level here, and instead rely on the fact that the bits are set in order.
                // we have to do that, because the quantile_search_u64 does the same.
                *result <<= 1;
                *result |= bit;
            },
            Self::partial_quantile_search_u64_unchecked,
        )
    }

    /// Get an iterator over the elements of the encoded sequence.
    /// The iterator yields `u64` elements.
    /// If the number of bits per element exceeds 64, `None` is returned.
    ///
    /// # Example
    /// ```
    /// use vers_vecs::{BitVec, WaveletMatrix};
    ///
    /// let bit_vec = BitVec::pack_sequence_u8(&[1, 4, 4, 1, 2, 7], 3);
    /// let wavelet_matrix = WaveletMatrix::from_bit_vec(&bit_vec, 3);
    ///
    /// let mut iter = wavelet_matrix.iter_u64().unwrap();
    /// assert_eq!(iter.collect::<Vec<_>>(), vec![1, 4, 4, 1, 2, 7]);
    /// ```
    #[must_use]
    pub fn iter_u64(&self) -> Option<WaveletNumRefIter> {
        if self.bits_per_element > 64 {
            None
        } else {
            Some(WaveletNumRefIter::new(self))
        }
    }

    /// Turn the encoded sequence into an iterator.
    /// The iterator yields `u64` elements.
    /// If the number of bits per element exceeds 64, `None` is returned.
    #[must_use]
    pub fn into_iter_u64(self) -> Option<WaveletNumIter> {
        if self.bits_per_element > 64 {
            None
        } else {
            Some(WaveletNumIter::new(self))
        }
    }

    /// Get an iterator over the sorted elements of the encoded sequence.
    /// The iterator yields `BitVec` elements.
    ///
    /// See also [`iter_sorted_u64`] for an iterator that yields `u64` elements.
    #[must_use]
    pub fn iter_sorted(&self) -> WaveletSortedRefIter {
        WaveletSortedRefIter::new(self)
    }

    /// Turn the encoded sequence into an iterator over the sorted sequence.
    /// The iterator yields `BitVec` elements.
    #[must_use]
    pub fn into_iter_sorted(self) -> WaveletSortedIter {
        WaveletSortedIter::new(self)
    }

    /// Get an iterator over the sorted elements of the encoded sequence.
    /// The iterator yields `u64` elements.
    /// If the number of bits per element exceeds 64, `None` is returned.
    ///
    /// # Example
    /// ```
    /// use vers_vecs::{BitVec, WaveletMatrix};
    ///
    /// let bit_vec = BitVec::pack_sequence_u8(&[1, 4, 4, 1, 2, 7], 3);
    /// let wavelet_matrix = WaveletMatrix::from_bit_vec(&bit_vec, 3);
    ///
    /// let mut iter = wavelet_matrix.iter_sorted_u64().unwrap();
    /// assert_eq!(iter.collect::<Vec<_>>(), vec![1, 1, 2, 4, 4, 7]);
    /// ```
    #[must_use]
    pub fn iter_sorted_u64(&self) -> Option<WaveletSortedNumRefIter> {
        if self.bits_per_element > 64 {
            None
        } else {
            Some(WaveletSortedNumRefIter::new(self))
        }
    }

    /// Turn the encoded sequence into an iterator over the sorted sequence.
    /// The iterator yields `u64` elements.
    /// If the number of bits per element exceeds 64, `None` is returned.
    #[must_use]
    pub fn into_iter_sorted_u64(self) -> Option<WaveletSortedNumIter> {
        if self.bits_per_element > 64 {
            None
        } else {
            Some(WaveletSortedNumIter::new(self))
        }
    }

    /// Get the number of bits per element in the alphabet of the encoded sequence.
    #[must_use]
    pub fn bit_len(&self) -> u16 {
        self.bits_per_element
    }

    /// Get the number of elements stored in the encoded sequence.
    #[must_use]
    pub fn len(&self) -> usize {
        if self.data.is_empty() {
            0
        } else {
            self.data[0].len()
        }
    }

    /// Check if the wavelet matrix is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Get the number of bytes allocated on the heap for the wavelet matrix.
    /// This does not include memory that is allocated but unused due to allocation policies of
    /// internal data structures.
    #[must_use]
    pub fn heap_size(&self) -> usize {
        self.data.iter().map(RsVec::heap_size).sum::<usize>()
    }
}

impl_vector_iterator!(
    WaveletMatrix,
    WaveletIter,
    WaveletRefIter,
    get_value_unchecked,
    get_value,
    BitVec
);

impl_vector_iterator!(
    WaveletMatrix,
    WaveletNumIter,
    WaveletNumRefIter,
    get_u64_unchecked,
    get_u64,
    u64,
    special
);

impl_vector_iterator!(
    WaveletMatrix,
    WaveletSortedIter,
    WaveletSortedRefIter,
    get_sorted_unchecked,
    get_sorted,
    BitVec,
    special
);

impl_vector_iterator!(
    WaveletMatrix,
    WaveletSortedNumIter,
    WaveletSortedNumRefIter,
    get_sorted_u64_unchecked,
    get_sorted_u64,
    u64,
    special
);

#[cfg(test)]
mod tests;