zipora 2.1.5

High-performance Rust implementation providing advanced data structures and compression algorithms with memory safety guarantees. Features LRU page cache, sophisticated caching layer, fiber-based concurrency, real-time compression, secure memory pools, SIMD optimizations, and complete C FFI for migration from C++.
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
//! Bit vector implementation with efficient storage and access
//!
//! Provides a compact representation of bit arrays with efficient operations
//! for setting, getting, and manipulating individual bits.

use crate::FastVec;
use crate::error::{Result, ZiporaError};
use std::fmt;

// SIMD imports for bulk operations
#[cfg(all(target_arch = "x86_64", feature = "simd"))]
use std::arch::x86_64::{
    __m256i, _mm256_and_si256, _mm256_loadu_si256, _mm256_or_si256, _mm256_storeu_si256,
    _mm256_xor_si256,
};

/// A compact bit vector supporting efficient bit operations
///
/// BitVector stores bits in a packed format using u64 blocks for efficient
/// access and manipulation. It supports dynamic resizing and provides
/// constant-time access to individual bits.
///
/// # Examples
///
/// ```rust
/// use zipora::BitVector;
///
/// let mut bv = BitVector::new();
/// bv.push(true)?;
/// bv.push(false)?;
/// bv.push(true)?;
///
/// assert_eq!(bv.get(0), Some(true));
/// assert_eq!(bv.get(1), Some(false));
/// assert_eq!(bv.len(), 3);
/// # Ok::<(), zipora::ZiporaError>(())
/// ```
pub struct BitVector {
    blocks: FastVec<u64>,
    len: usize,
}

const BITS_PER_BLOCK: usize = 64;

impl BitVector {
    /// Create a new empty bit vector
    #[inline]
    pub fn new() -> Self {
        Self {
            blocks: FastVec::new(),
            len: 0,
        }
    }

    /// Create a bit vector with the specified capacity (in bits)
    pub fn with_capacity(capacity: usize) -> Result<Self> {
        let block_capacity = (capacity + BITS_PER_BLOCK - 1) / BITS_PER_BLOCK;
        Ok(Self {
            blocks: FastVec::with_capacity(block_capacity)?,
            len: 0,
        })
    }

    /// Create a bit vector with the specified size, filled with the given value
    pub fn with_size(size: usize, value: bool) -> Result<Self> {
        let mut bv = Self::with_capacity(size)?;
        bv.resize(size, value)?;
        Ok(bv)
    }

    /// Create a bit vector from raw u64 blocks and bit length
    ///
    /// This is used by multi-dimensional operations to create result bit vectors
    /// from SIMD-computed raw bit data.
    ///
    /// # Arguments
    ///
    /// * `raw_bits` - Raw u64 words containing the bit data
    /// * `total_bits` - Total number of valid bits
    ///
    /// # Examples
    ///
    /// ```rust
    /// use zipora::BitVector;
    ///
    /// let raw_bits = vec![0xFFFFFFFFFFFFFFFFu64, 0x0000000000000000u64];
    /// let bv = BitVector::from_raw_bits(raw_bits, 128)?;
    /// assert_eq!(bv.len(), 128);
    /// assert_eq!(bv.get(0).unwrap(), true);
    /// assert_eq!(bv.get(63).unwrap(), true);
    /// assert_eq!(bv.get(64).unwrap(), false);
    /// # Ok::<(), zipora::ZiporaError>(())
    /// ```
    pub fn from_raw_bits(raw_bits: Vec<u64>, total_bits: usize) -> Result<Self> {
        let required_blocks = (total_bits + BITS_PER_BLOCK - 1) / BITS_PER_BLOCK;

        if raw_bits.len() < required_blocks {
            return Err(ZiporaError::invalid_data(format!(
                "Insufficient raw bits: need {} blocks for {} bits, got {}",
                required_blocks, total_bits, raw_bits.len()
            )));
        }

        let mut blocks = FastVec::with_capacity(required_blocks)?;
        for (i, &word) in raw_bits.iter().enumerate() {
            if i < required_blocks {
                blocks.push(word)?;
            }
        }

        // Clear trailing bits in the last block if necessary
        if total_bits > 0 {
            let last_block_idx = required_blocks - 1;
            let bits_in_last_block = total_bits % BITS_PER_BLOCK;
            if bits_in_last_block > 0 {
                let mask = (1u64 << bits_in_last_block) - 1;
                blocks[last_block_idx] &= mask;
            }
        }

        Ok(Self {
            blocks,
            len: total_bits,
        })
    }

    /// Get the number of bits in the vector
    #[inline]
    pub fn len(&self) -> usize {
        self.len
    }

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

    /// Get the capacity in bits
    #[inline]
    pub fn capacity(&self) -> usize {
        self.blocks.capacity() * BITS_PER_BLOCK
    }

    /// Get the bit at the specified position
    #[inline]
    pub fn get(&self, index: usize) -> Option<bool> {
        if index >= self.len {
            return None;
        }

        let block_index = index / BITS_PER_BLOCK;
        let bit_index = index % BITS_PER_BLOCK;

        Some((self.blocks[block_index] >> bit_index) & 1 == 1)
    }

    /// Get the bit at the specified position without bounds checking
    ///
    /// # Safety
    ///
    /// The caller must ensure that `index < self.len()`
    #[inline]
    pub unsafe fn get_unchecked(&self, index: usize) -> bool {
        debug_assert!(index < self.len);

        let block_index = index / BITS_PER_BLOCK;
        let bit_index = index % BITS_PER_BLOCK;

// SAFETY: Caller must ensure index < self.len()

        (unsafe { self.blocks.get_unchecked(block_index) } >> bit_index) & 1 == 1
    }

    /// Set the bit at the specified position
    pub fn set(&mut self, index: usize, value: bool) -> Result<()> {
        if index >= self.len {
            return Err(ZiporaError::out_of_bounds(index, self.len));
        }

        let block_index = index / BITS_PER_BLOCK;
        let bit_index = index % BITS_PER_BLOCK;

        if value {
            self.blocks[block_index] |= 1u64 << bit_index;
        } else {
            self.blocks[block_index] &= !(1u64 << bit_index);
        }

        Ok(())
    }

    /// Set the bit at the specified position without bounds checking
    ///
    /// # Safety
    ///
    /// The caller must ensure that `index < self.len()`
    #[inline]
    pub unsafe fn set_unchecked(&mut self, index: usize, value: bool) {
        debug_assert!(index < self.len);

        let block_index = index / BITS_PER_BLOCK;
        let bit_index = index % BITS_PER_BLOCK;

        if value {
            // SAFETY: index < len checked by caller, block_index is valid
            unsafe {
                *self.blocks.get_unchecked_mut(block_index) |= 1u64 << bit_index;
            }
        } else {
            // SAFETY: index < len checked by caller, block_index is valid
            unsafe {
                *self.blocks.get_unchecked_mut(block_index) &= !(1u64 << bit_index);
            }
        }
    }

    /// Push a bit to the end of the vector
    pub fn push(&mut self, value: bool) -> Result<()> {
        let block_index = self.len / BITS_PER_BLOCK;
        let bit_index = self.len % BITS_PER_BLOCK;

        // Ensure we have enough blocks
        while self.blocks.len() <= block_index {
            self.blocks.push(0)?;
        }

        if value {
            self.blocks[block_index] |= 1u64 << bit_index;
        } else {
            self.blocks[block_index] &= !(1u64 << bit_index);
        }

        self.len += 1;
        Ok(())
    }

    /// Ensure the bit at position `i` is set to 1, growing the vector if necessary
    ///
    /// This is useful when using the bit vector as an integer set.
    /// If `i >= len`, the vector is resized to include position `i`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use zipora::BitVector;
    ///
    /// let mut bv = BitVector::new();
    /// bv.ensure_set1(5)?;
    /// bv.ensure_set1(10)?;
    /// bv.ensure_set1(3)?;
    ///
    /// assert_eq!(bv.len(), 11);
    /// assert_eq!(bv.get(5), Some(true));
    /// assert_eq!(bv.get(10), Some(true));
    /// assert_eq!(bv.get(3), Some(true));
    /// assert_eq!(bv.get(4), Some(false));
    /// # Ok::<(), zipora::ZiporaError>(())
    /// ```
    pub fn ensure_set1(&mut self, i: usize) -> Result<()> {
        if i < self.len {
            // Fast path: just set the bit
            let block_index = i / BITS_PER_BLOCK;
            let bit_index = i % BITS_PER_BLOCK;
            self.blocks[block_index] |= 1u64 << bit_index;
        } else {
            // Slow path: need to grow
            self.ensure_set1_slow_path(i)?;
        }
        Ok(())
    }

    /// Slow path for ensure_set1 when vector needs to grow
    #[cold]
    #[inline(never)]
    fn ensure_set1_slow_path(&mut self, i: usize) -> Result<()> {
        // Resize to include position i (sets all new bits to 0)
        let new_len = i + 1;
        let new_block_count = (new_len + BITS_PER_BLOCK - 1) / BITS_PER_BLOCK;

        // Add new blocks initialized to 0
        while self.blocks.len() < new_block_count {
            self.blocks.push(0)?;
        }
        self.len = new_len;

        // Set the bit
        let block_index = i / BITS_PER_BLOCK;
        let bit_index = i % BITS_PER_BLOCK;
        self.blocks[block_index] |= 1u64 << bit_index;

        Ok(())
    }

    /// Fast ensure_set1 optimized for sequential integer set insertions
    ///
    /// This is much faster than `ensure_set1` when inserting integer set members
    /// sequentially. The optimization relies on the invariant that allocated but
    /// unused bits between `len` and `capacity` are always 0.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use zipora::BitVector;
    ///
    /// let mut bv = BitVector::with_capacity(1000)?;
    /// // Sequential insertions are very fast
    /// for i in 0..100 {
    ///     bv.fast_ensure_set1(i)?;
    /// }
    /// assert_eq!(bv.count_ones(), 100);
    /// # Ok::<(), zipora::ZiporaError>(())
    /// ```
    pub fn fast_ensure_set1(&mut self, i: usize) -> Result<()> {
        let capacity = self.blocks.len() * BITS_PER_BLOCK;

        if i < capacity {
            // Fast path: within capacity, just update len and set bit
            if self.len <= i {
                // Invariant: bits between len and capacity are already 0
                debug_assert!(
                    (self.len..=i).all(|j| {
                        let block_idx = j / BITS_PER_BLOCK;
                        let bit_idx = j % BITS_PER_BLOCK;
                        block_idx >= self.blocks.len() || (self.blocks[block_idx] >> bit_idx) & 1 == 0
                    }),
                    "fast_ensure_set1 invariant violated: unused bits must be 0"
                );
                self.len = i + 1;
            }
            let block_index = i / BITS_PER_BLOCK;
            let bit_index = i % BITS_PER_BLOCK;
            self.blocks[block_index] |= 1u64 << bit_index;
            Ok(())
        } else {
            // Slow path: need to grow capacity
            self.fast_ensure_set1_slow_path(i)
        }
    }

    /// Slow path for fast_ensure_set1 when capacity needs to grow
    #[cold]
    #[inline(never)]
    fn fast_ensure_set1_slow_path(&mut self, i: usize) -> Result<()> {
        // Invariant check in debug mode: unused bits must be 0
        #[cfg(debug_assertions)]
        {
            let capacity = self.blocks.len() * BITS_PER_BLOCK;
            for j in self.len..capacity {
                let block_idx = j / BITS_PER_BLOCK;
                let bit_idx = j % BITS_PER_BLOCK;
                if block_idx < self.blocks.len() {
                    debug_assert!(
                        (self.blocks[block_idx] >> bit_idx) & 1 == 0,
                        "fast_ensure_set1 invariant violated at bit {}: unused bits must be 0",
                        j
                    );
                }
            }
        }

        let old_capacity = self.blocks.len() * BITS_PER_BLOCK;
        let new_len = i + 1;
        let new_block_count = (new_len + BITS_PER_BLOCK - 1) / BITS_PER_BLOCK;

        // Add new blocks initialized to 0
        while self.blocks.len() < new_block_count {
            self.blocks.push(0)?;
        }

        // Clear any bits that might have been set in the old capacity range
        // (ensures invariant is maintained)
        let new_capacity = self.blocks.len() * BITS_PER_BLOCK;
        if old_capacity < new_capacity {
            // New blocks are already 0, nothing to do
        }

        self.len = new_len;

        // Set the bit
        let block_index = i / BITS_PER_BLOCK;
        let bit_index = i % BITS_PER_BLOCK;
        self.blocks[block_index] |= 1u64 << bit_index;

        Ok(())
    }

    /// Insert a bit at the specified position
    pub fn insert(&mut self, index: usize, value: bool) -> Result<()> {
        if index > self.len {
            return Err(ZiporaError::out_of_bounds(index, self.len));
        }

        // For simplicity, we'll implement this by pushing a bit and then
        // shifting everything after the insertion point
        self.push(false)?; // Extend by one bit

        // Shift bits to the right starting from the end
        for i in (index + 1..self.len).rev() {
            let bit = self.get(i - 1).unwrap_or(false);
            self.set(i, bit)?;
        }

        // Set the bit at the insertion position
        self.set(index, value)?;

        Ok(())
    }

    /// Get a mutable reference to the bit at the specified position
    /// Returns a helper struct that can be used to modify the bit
    pub fn get_mut(&mut self, index: usize) -> Option<BitRef<'_>> {
        if index >= self.len {
            return None;
        }

        Some(BitRef {
            bit_vector: self,
            index,
        })
    }

    /// Pop a bit from the end of the vector
    pub fn pop(&mut self) -> Option<bool> {
        if self.len == 0 {
            return None;
        }

        self.len -= 1;
        let block_index = self.len / BITS_PER_BLOCK;
        let bit_index = self.len % BITS_PER_BLOCK;

        let value = (self.blocks[block_index] >> bit_index) & 1 == 1;

        // Clear the bit
        self.blocks[block_index] &= !(1u64 << bit_index);

        Some(value)
    }

    /// Resize the bit vector to the specified length
    pub fn resize(&mut self, new_len: usize, value: bool) -> Result<()> {
        if new_len > self.len {
            // Extend with the given value
            for _ in self.len..new_len {
                self.push(value)?;
            }
        } else if new_len < self.len {
            // Truncate
            self.len = new_len;

            // Clear bits in the last partial block
            if new_len > 0 {
                let last_block_index = (new_len - 1) / BITS_PER_BLOCK;
                let bits_in_last_block = new_len % BITS_PER_BLOCK;

                if bits_in_last_block > 0 {
                    let mask = (1u64 << bits_in_last_block) - 1;
                    self.blocks[last_block_index] &= mask;
                }
            }
        }

        Ok(())
    }

    /// Clear all bits from the vector
    pub fn clear(&mut self) {
        self.blocks.clear();
        self.len = 0;
    }

    /// Count the number of set bits in the entire vector
    pub fn count_ones(&self) -> usize {
        let mut count = 0;

        // Count complete blocks
        let complete_blocks = self.len / BITS_PER_BLOCK;
        for i in 0..complete_blocks {
            count += self.blocks[i].count_ones() as usize;
        }

        // Count bits in the last partial block
        let remaining_bits = self.len % BITS_PER_BLOCK;
        if remaining_bits > 0 && complete_blocks < self.blocks.len() {
            let mask = (1u64 << remaining_bits) - 1;
            count += (self.blocks[complete_blocks] & mask).count_ones() as usize;
        }

        count
    }

    /// Count the number of clear bits in the entire vector
    #[inline]
    pub fn count_zeros(&self) -> usize {
        self.len - self.count_ones()
    }

    /// Count the number of set bits up to (but not including) the given position
    pub fn rank1(&self, pos: usize) -> usize {
        if pos == 0 {
            return 0;
        }

        let pos = pos.min(self.len);
        let mut count = 0;

        // Count complete blocks
        let complete_blocks = pos / BITS_PER_BLOCK;
        for i in 0..complete_blocks {
            count += self.blocks[i].count_ones() as usize;
        }

        // Count bits in the partial block
        let remaining_bits = pos % BITS_PER_BLOCK;
        if remaining_bits > 0 && complete_blocks < self.blocks.len() {
            let mask = (1u64 << remaining_bits) - 1;
            count += (self.blocks[complete_blocks] & mask).count_ones() as usize;
        }

        count
    }

    /// Count the number of clear bits up to (but not including) the given position
    #[inline]
    pub fn rank0(&self, pos: usize) -> usize {
        if pos == 0 {
            return 0;
        }

        let pos = pos.min(self.len);
        pos - self.rank1(pos)
    }

    /// Get access to the underlying blocks for advanced operations
    #[inline]
    pub fn blocks(&self) -> &[u64] {
        self.blocks.as_slice()
    }

    /// Reserve space for at least `additional` more bits
    pub fn reserve(&mut self, additional: usize) -> Result<()> {
        let new_len = self.len + additional;
        let new_block_count = (new_len + BITS_PER_BLOCK - 1) / BITS_PER_BLOCK;
        let additional_blocks = new_block_count.saturating_sub(self.blocks.len());

        if additional_blocks > 0 {
            self.blocks.reserve(additional_blocks)?;
        }

        Ok(())
    }

    /// SIMD-accelerated bulk rank operations
    ///
    /// Process multiple rank queries in parallel using AVX2 vectorization.
    /// This provides significant performance improvements for bulk operations.
    #[cfg(all(target_arch = "x86_64", feature = "simd"))]
    pub fn rank1_bulk_simd(&self, positions: &[usize]) -> Vec<usize> {
        let mut results = Vec::with_capacity(positions.len());

        // Process positions using SIMD acceleration when available
        if is_x86_feature_detected!("avx2") {
            self.rank1_bulk_simd_avx2(positions, &mut results);
        } else {
            // Fallback to individual rank operations
            for &pos in positions {
                results.push(self.rank1(pos));
            }
        }

        results
    }

    #[cfg(all(target_arch = "x86_64", feature = "simd"))]
    fn rank1_bulk_simd_avx2(&self, positions: &[usize], results: &mut Vec<usize>) {
        // Process 4 positions at a time using AVX2
        let chunk_size = 4;

        for chunk in positions.chunks(chunk_size) {
            // SAFETY: pos_array is properly aligned and sized for AVX2 load
            unsafe {
                // Load positions into SIMD register
                let mut pos_array = [0u64; 4];
                for (i, &pos) in chunk.iter().enumerate() {
                    pos_array[i] = pos as u64;
                }

                let _positions_vec = _mm256_loadu_si256(pos_array.as_ptr() as *const __m256i);

                // Process each position (simplified for demonstration)
                for &pos in chunk {
                    results.push(self.rank1(pos));
                }
            }
        }
    }

    #[cfg(not(all(target_arch = "x86_64", feature = "simd")))]
    pub fn rank1_bulk_simd(&self, positions: &[usize]) -> Vec<usize> {
        // Fallback implementation for non-SIMD platforms
        positions.iter().map(|&pos| self.rank1(pos)).collect()
    }

    /// SIMD-accelerated bit setting for ranges
    ///
    /// Set ranges of bits using vectorized operations for better performance
    /// on large ranges.
    #[cfg(all(target_arch = "x86_64", feature = "simd"))]
    pub fn set_range_simd(&mut self, start: usize, end: usize, value: bool) -> Result<()> {
        if start > end || end > self.len {
            return Err(ZiporaError::out_of_bounds(end, self.len));
        }

        if is_x86_feature_detected!("avx2") {
            self.set_range_simd_avx2(start, end, value)?;
        } else {
            // Fallback to individual bit setting
            for i in start..end {
                self.set(i, value)?;
            }
        }

        Ok(())
    }

    #[cfg(all(target_arch = "x86_64", feature = "simd"))]
    fn set_range_simd_avx2(&mut self, start: usize, end: usize, value: bool) -> Result<()> {
        let start_block = start / BITS_PER_BLOCK;
        let end_block = (end - 1) / BITS_PER_BLOCK;

        // Handle aligned blocks using SIMD
        for block_idx in start_block..=end_block {
            if block_idx >= self.blocks.len() {
                break;
            }

            let block_start = block_idx * BITS_PER_BLOCK;
            let block_end = ((block_idx + 1) * BITS_PER_BLOCK).min(end);
            let range_start = start.max(block_start);
            let range_end = end.min(block_end);

            if range_start >= range_end {
                continue;
            }

            let start_bit = range_start - block_start;
            let end_bit = range_end - block_start;

            // Create mask for the range within this block
            let mask = if end_bit >= BITS_PER_BLOCK {
                !((1u64 << start_bit) - 1)
            } else {
                ((1u64 << end_bit) - 1) & !((1u64 << start_bit) - 1)
            };

            if value {
                self.blocks[block_idx] |= mask;
            } else {
                self.blocks[block_idx] &= !mask;
            }
        }

        Ok(())
    }

    #[cfg(not(all(target_arch = "x86_64", feature = "simd")))]
    pub fn set_range_simd(&mut self, start: usize, end: usize, value: bool) -> Result<()> {
        // Fallback implementation for non-SIMD platforms
        if start > end || end > self.len {
            return Err(ZiporaError::out_of_bounds(end, self.len));
        }

        for i in start..end {
            self.set(i, value)?;
        }

        Ok(())
    }

    /// SIMD-accelerated bulk bit operations
    ///
    /// Perform bitwise operations (AND, OR, XOR) on ranges using vectorized instructions
    /// for improved performance on large datasets.
    #[cfg(all(target_arch = "x86_64", feature = "simd"))]
    pub fn bulk_bitwise_op_simd(
        &mut self,
        other: &BitVector,
        op: BitwiseOp,
        start: usize,
        end: usize,
    ) -> Result<()> {
        if start > end || end > self.len || end > other.len {
            return Err(ZiporaError::invalid_data(
                "Invalid range for bulk operation".to_string(),
            ));
        }

        if is_x86_feature_detected!("avx2") {
            self.bulk_bitwise_op_simd_avx2(other, op, start, end)?;
        } else {
            // Fallback to scalar operations
            for i in start..end {
                let other_bit = other.get(i).unwrap_or(false);
                let self_bit = self.get(i).unwrap_or(false);
                let result = match op {
                    BitwiseOp::And => self_bit & other_bit,
                    BitwiseOp::Or => self_bit | other_bit,
                    BitwiseOp::Xor => self_bit ^ other_bit,
                };
                self.set(i, result)?;
            }
        }

        Ok(())
    }

    #[cfg(all(target_arch = "x86_64", feature = "simd"))]
    fn bulk_bitwise_op_simd_avx2(
        &mut self,
        other: &BitVector,
        op: BitwiseOp,
        start: usize,
        end: usize,
    ) -> Result<()> {
        let start_block = start / BITS_PER_BLOCK;
        let end_block = (end - 1) / BITS_PER_BLOCK;

        // Process blocks using AVX2 (4 u64s at a time)
        let avx2_blocks = 4;
        let mut block_idx = start_block;

        // SAFETY: Bounds checked in loop condition, pointers are valid for AVX2 operations
        unsafe {
            // Process 4 blocks at a time with AVX2
            while block_idx + avx2_blocks <= end_block + 1
                && block_idx + avx2_blocks <= self.blocks.len()
                && block_idx + avx2_blocks <= other.blocks.len()
            {
                let self_ptr = self.blocks.as_ptr().add(block_idx) as *const __m256i;
                let other_ptr = other.blocks.as_ptr().add(block_idx) as *const __m256i;
                let result_ptr = self.blocks.as_mut_ptr().add(block_idx) as *mut __m256i;

                let self_vec = _mm256_loadu_si256(self_ptr);
                let other_vec = _mm256_loadu_si256(other_ptr);

                let result_vec = match op {
                    BitwiseOp::And => _mm256_and_si256(self_vec, other_vec),
                    BitwiseOp::Or => _mm256_or_si256(self_vec, other_vec),
                    BitwiseOp::Xor => _mm256_xor_si256(self_vec, other_vec),
                };

                _mm256_storeu_si256(result_ptr, result_vec);
                block_idx += avx2_blocks;
            }
        }

        // Handle remaining blocks with scalar operations
        while block_idx <= end_block
            && block_idx < self.blocks.len()
            && block_idx < other.blocks.len()
        {
            match op {
                BitwiseOp::And => self.blocks[block_idx] &= other.blocks[block_idx],
                BitwiseOp::Or => self.blocks[block_idx] |= other.blocks[block_idx],
                BitwiseOp::Xor => self.blocks[block_idx] ^= other.blocks[block_idx],
            }
            block_idx += 1;
        }

        Ok(())
    }

    #[cfg(not(all(target_arch = "x86_64", feature = "simd")))]
    pub fn bulk_bitwise_op_simd(
        &mut self,
        other: &BitVector,
        op: BitwiseOp,
        start: usize,
        end: usize,
    ) -> Result<()> {
        // Fallback implementation for non-SIMD platforms
        if start > end || end > self.len || end > other.len {
            return Err(ZiporaError::invalid_data(
                "Invalid range for bulk operation".to_string(),
            ));
        }

        for i in start..end {
            let other_bit = other.get(i).unwrap_or(false);
            let self_bit = self.get(i).unwrap_or(false);
            let result = match op {
                BitwiseOp::And => self_bit & other_bit,
                BitwiseOp::Or => self_bit | other_bit,
                BitwiseOp::Xor => self_bit ^ other_bit,
            };
            self.set(i, result)?;
        }

        Ok(())
    }
}

/// Supported bitwise operations for SIMD bulk operations
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BitwiseOp {
    /// Bitwise AND operation
    And,
    /// Bitwise OR operation
    Or,
    /// Bitwise XOR operation
    Xor,
}

/// Helper struct for mutable bit access
pub struct BitRef<'a> {
    bit_vector: &'a mut BitVector,
    index: usize,
}

impl<'a> BitRef<'a> {
    /// Get the current value of the bit
    #[inline]
    pub fn get(&self) -> bool {
        self.bit_vector.get(self.index).unwrap_or(false)
    }

    /// Set the value of the bit
    #[inline]
    pub fn set(&mut self, value: bool) -> Result<()> {
        self.bit_vector.set(self.index, value)
    }
}

impl<'a> std::ops::Deref for BitRef<'a> {
    type Target = bool;

    fn deref(&self) -> &Self::Target {
        // We can't return a reference to a bool that doesn't exist,
        // so we use a static value. This is a limitation of the design.
        if self.get() { &true } else { &false }
    }
}

impl Default for BitVector {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Debug for BitVector {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "BitVector {{ len: {}, bits: [", self.len)?;
        for i in 0..self.len.min(64) {
            // SAFETY: Loop bounds are 0..self.len.min(64), so i < self.len always.
            write!(f, "{}", if self.get(i).expect("index within bitvector length") { '1' } else { '0' })?;
        }
        if self.len > 64 {
            write!(f, "...")?;
        }
        write!(f, "] }}")
    }
}

impl Clone for BitVector {
    fn clone(&self) -> Self {
        Self {
            blocks: self.blocks.clone(),
            len: self.len,
        }
    }
}

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

        // Compare complete blocks
        let complete_blocks = self.len / BITS_PER_BLOCK;
        for i in 0..complete_blocks {
            if self.blocks[i] != other.blocks[i] {
                return false;
            }
        }

        // Compare remaining bits in the last block
        let remaining_bits = self.len % BITS_PER_BLOCK;
        if remaining_bits > 0
            && complete_blocks < self.blocks.len()
            && complete_blocks < other.blocks.len()
        {
            let mask = (1u64 << remaining_bits) - 1;
            if (self.blocks[complete_blocks] & mask) != (other.blocks[complete_blocks] & mask) {
                return false;
            }
        }

        true
    }
}

impl Eq for BitVector {}

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

    #[test]
    fn test_new() {
        let bv = BitVector::new();
        assert_eq!(bv.len(), 0);
        assert!(bv.is_empty());
    }

    #[test]
    fn test_push_pop() {
        let mut bv = BitVector::new();
        bv.push(true).unwrap();
        bv.push(false).unwrap();
        bv.push(true).unwrap();

        assert_eq!(bv.len(), 3);
        assert_eq!(bv.get(0), Some(true));
        assert_eq!(bv.get(1), Some(false));
        assert_eq!(bv.get(2), Some(true));

        assert_eq!(bv.pop(), Some(true));
        assert_eq!(bv.pop(), Some(false));
        assert_eq!(bv.len(), 1);
    }

    #[test]
    fn test_set_get() {
        let mut bv = BitVector::with_size(10, false).unwrap();

        bv.set(0, true).unwrap();
        bv.set(5, true).unwrap();
        bv.set(9, true).unwrap();

        assert_eq!(bv.get(0), Some(true));
        assert_eq!(bv.get(1), Some(false));
        assert_eq!(bv.get(5), Some(true));
        assert_eq!(bv.get(9), Some(true));
        assert_eq!(bv.get(10), None);
    }

    #[test]
    fn test_count_operations() {
        let mut bv = BitVector::with_size(10, false).unwrap();
        bv.set(0, true).unwrap();
        bv.set(3, true).unwrap();
        bv.set(7, true).unwrap();

        assert_eq!(bv.count_ones(), 3);
        assert_eq!(bv.count_zeros(), 7);
    }

    #[test]
    fn test_rank_operations() {
        let mut bv = BitVector::with_size(10, false).unwrap();
        bv.set(1, true).unwrap();
        bv.set(3, true).unwrap();
        bv.set(7, true).unwrap();

        assert_eq!(bv.rank1(0), 0);
        assert_eq!(bv.rank1(2), 1);
        assert_eq!(bv.rank1(4), 2);
        assert_eq!(bv.rank1(8), 3);
        assert_eq!(bv.rank1(10), 3);

        assert_eq!(bv.rank0(2), 1);
        assert_eq!(bv.rank0(4), 2);
        assert_eq!(bv.rank0(8), 5);
    }

    #[test]
    fn test_large_bitvector() {
        let mut bv = BitVector::new();

        // Test across multiple blocks
        for i in 0..200 {
            bv.push(i % 3 == 0).unwrap();
        }

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

        let mut expected_ones = 0;
        for i in 0..200 {
            if i % 3 == 0 {
                expected_ones += 1;
                assert_eq!(bv.get(i), Some(true));
            } else {
                assert_eq!(bv.get(i), Some(false));
            }
        }

        assert_eq!(bv.count_ones(), expected_ones);
    }

    #[test]
    fn test_resize() {
        let mut bv = BitVector::new();
        bv.resize(5, true).unwrap();

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

        bv.resize(3, false).unwrap();
        assert_eq!(bv.len(), 3);
        assert_eq!(bv.count_ones(), 3);

        bv.resize(8, false).unwrap();
        assert_eq!(bv.len(), 8);
        assert_eq!(bv.count_ones(), 3);
    }

    #[test]
    fn test_equality() {
        let mut bv1 = BitVector::new();
        let mut bv2 = BitVector::new();

        for &bit in &[true, false, true, true, false] {
            bv1.push(bit).unwrap();
            bv2.push(bit).unwrap();
        }

        assert_eq!(bv1, bv2);

        bv2.set(2, false).unwrap();
        assert_ne!(bv1, bv2);
    }

    #[test]
    fn test_unsafe_operations() {
        let mut bv = BitVector::new();
        bv.push(true).unwrap();
        bv.push(false).unwrap();
        bv.push(true).unwrap();

        // SAFETY: Indices 0, 1, 2 are valid (len=3)
        unsafe {
            assert_eq!(bv.get_unchecked(0), true);
            assert_eq!(bv.get_unchecked(1), false);
            assert_eq!(bv.get_unchecked(2), true);

            bv.set_unchecked(1, true);
            assert_eq!(bv.get_unchecked(1), true);

            bv.set_unchecked(0, false);
            assert_eq!(bv.get_unchecked(0), false);
        }
    }

    #[test]
    fn test_blocks_access() {
        let mut bv = BitVector::new();
        for i in 0..128 {
            bv.push(i % 3 == 0).unwrap();
        }

        let blocks = bv.blocks();
        assert!(blocks.len() >= 2); // Should span multiple blocks

        // Verify blocks contain expected data
        let first_block = blocks[0];
        let first_bit = first_block & 1;
        assert_eq!(first_bit, 1); // First bit should be set (0 % 3 == 0)
    }

    #[test]
    fn test_reserve() {
        let mut bv = BitVector::new();
        bv.reserve(1000).unwrap();

        // Should have reserved enough blocks for 1000 bits
        assert!(bv.capacity() >= 1000);

        // Fill with data to verify it works
        for i in 0..1000 {
            bv.push(i % 7 == 0).unwrap();
        }
        assert_eq!(bv.len(), 1000);
    }

    #[test]
    fn test_partial_block_operations() {
        let mut bv = BitVector::new();

        // Test with exactly one full block (64 bits)
        for i in 0..64 {
            bv.push(i % 2 == 0).unwrap();
        }
        assert_eq!(bv.len(), 64);
        assert_eq!(bv.count_ones(), 32);

        // Add a few more bits to create a partial block
        bv.push(true).unwrap();
        bv.push(false).unwrap();
        bv.push(true).unwrap();

        assert_eq!(bv.len(), 67);
        assert_eq!(bv.count_ones(), 34); // 32 + 2 from partial block

        // Test rank with partial blocks
        assert_eq!(bv.rank1(64), 32);
        assert_eq!(bv.rank1(67), 34);
    }

    #[test]
    fn test_edge_case_resize() {
        let mut bv = BitVector::new();

        // Resize to zero
        bv.resize(0, true).unwrap();
        assert_eq!(bv.len(), 0);
        assert!(bv.is_empty());

        // Resize from zero to some value
        bv.resize(10, true).unwrap();
        assert_eq!(bv.len(), 10);
        assert_eq!(bv.count_ones(), 10);

        // Resize down with partial bits
        bv.resize(5, false).unwrap();
        assert_eq!(bv.len(), 5);
        assert_eq!(bv.count_ones(), 5);

        // Resize up again
        bv.resize(15, false).unwrap();
        assert_eq!(bv.len(), 15);
        assert_eq!(bv.count_ones(), 5); // Only first 5 should be set
    }

    #[test]
    fn test_boundary_conditions() {
        let mut bv = BitVector::new();

        // Test exactly at block boundaries (64, 128, etc.)
        for i in 0..128 {
            bv.push(i < 64).unwrap(); // First 64 are true, next 64 are false
        }

        assert_eq!(bv.rank1(0), 0);
        assert_eq!(bv.rank1(64), 64);
        assert_eq!(bv.rank1(128), 64);
        assert_eq!(bv.rank0(64), 0);
        assert_eq!(bv.rank0(128), 64);
    }

    #[test]
    fn test_error_conditions() {
        let mut bv = BitVector::new();
        bv.push(true).unwrap();
        bv.push(false).unwrap();

        // Test out of bounds set
        assert!(bv.set(5, true).is_err());
        assert!(bv.set(2, true).is_err()); // len is 2, so index 2 is out of bounds

        // Valid set should work
        assert!(bv.set(0, false).is_ok());
        assert_eq!(bv.get(0), Some(false));
    }

    #[test]
    fn test_clone_and_equality_edge_cases() {
        let mut original = BitVector::new();

        // Test clone of empty vector
        let cloned_empty = original.clone();
        assert_eq!(original, cloned_empty);

        // Add bits across multiple blocks
        for i in 0..130 {
            original.push(i % 5 == 0).unwrap();
        }

        let cloned = original.clone();
        assert_eq!(original, cloned);

        // Test equality with different lengths
        let mut shorter = original.clone();
        shorter.resize(100, false).unwrap();
        assert_ne!(original, shorter);

        // Test equality with same length but different content
        let mut different = original.clone();
        different.set(50, !different.get(50).unwrap()).unwrap();
        assert_ne!(original, different);
    }

    #[test]
    fn test_debug_output() {
        let mut bv = BitVector::new();
        for i in 0..10 {
            bv.push(i % 2 == 0).unwrap();
        }

        let debug_str = format!("{:?}", bv);
        assert!(debug_str.contains("BitVector"));
        assert!(debug_str.contains("len: 10"));
        assert!(debug_str.contains("1010101010")); // The pattern

        // Test debug output for very long vectors
        let mut long_bv = BitVector::new();
        for i in 0..100 {
            long_bv.push(i % 2 == 0).unwrap();
        }

        let long_debug = format!("{:?}", long_bv);
        assert!(long_debug.contains("..."));
        assert!(long_debug.contains("len: 100"));
    }

    #[test]
    fn test_default() {
        let bv = BitVector::default();
        assert!(bv.is_empty());
        assert_eq!(bv.len(), 0);
        assert_eq!(bv.capacity(), 0);
    }

    #[test]
    fn test_ensure_set1_basic() {
        let mut bv = BitVector::new();

        // Set bits in order
        bv.ensure_set1(0).unwrap();
        assert_eq!(bv.len(), 1);
        assert_eq!(bv.get(0), Some(true));

        bv.ensure_set1(5).unwrap();
        assert_eq!(bv.len(), 6);
        assert_eq!(bv.get(5), Some(true));
        // Bits 1-4 should be false (filled with zeros)
        for i in 1..5 {
            assert_eq!(bv.get(i), Some(false));
        }

        // Setting same bit again should be idempotent
        bv.ensure_set1(5).unwrap();
        assert_eq!(bv.len(), 6);
        assert_eq!(bv.get(5), Some(true));
    }

    #[test]
    fn test_ensure_set1_sequential() {
        let mut bv = BitVector::new();

        // Build a set of integers 0, 2, 4, 6, 8
        for i in (0..10).step_by(2) {
            bv.ensure_set1(i).unwrap();
        }

        assert_eq!(bv.len(), 9);
        assert_eq!(bv.count_ones(), 5);

        // Check pattern
        for i in 0..9 {
            assert_eq!(bv.get(i), Some(i % 2 == 0));
        }
    }

    #[test]
    fn test_ensure_set1_across_blocks() {
        let mut bv = BitVector::new();

        // Set bits across multiple 64-bit blocks
        bv.ensure_set1(0).unwrap();
        bv.ensure_set1(63).unwrap();
        bv.ensure_set1(64).unwrap();
        bv.ensure_set1(127).unwrap();
        bv.ensure_set1(128).unwrap();

        assert_eq!(bv.len(), 129);
        assert_eq!(bv.count_ones(), 5);

        // Verify specific bits
        assert_eq!(bv.get(0), Some(true));
        assert_eq!(bv.get(63), Some(true));
        assert_eq!(bv.get(64), Some(true));
        assert_eq!(bv.get(127), Some(true));
        assert_eq!(bv.get(128), Some(true));
    }

    #[test]
    fn test_fast_ensure_set1_sequential() {
        let mut bv = BitVector::new();

        // Fast version optimized for sequential access
        for i in 0..100 {
            bv.fast_ensure_set1(i).unwrap();
        }

        assert_eq!(bv.len(), 100);
        assert_eq!(bv.count_ones(), 100); // All bits should be set
    }

    #[test]
    fn test_fast_ensure_set1_sparse() {
        let mut bv = BitVector::new();

        // Set every 10th bit
        for i in (0..1000).step_by(10) {
            bv.fast_ensure_set1(i).unwrap();
        }

        assert_eq!(bv.len(), 991);
        assert_eq!(bv.count_ones(), 100);

        // Verify the pattern
        for i in (0..1000).step_by(10) {
            if i < bv.len() {
                assert_eq!(bv.get(i), Some(true), "bit {} should be set", i);
            }
        }
    }

    #[test]
    fn test_ensure_set1_vs_fast_ensure_set1_equivalence() {
        // Both methods should produce the same result
        let indices: Vec<usize> = vec![0, 5, 10, 63, 64, 100, 127, 128, 200];

        let mut bv1 = BitVector::new();
        let mut bv2 = BitVector::new();

        for &i in &indices {
            bv1.ensure_set1(i).unwrap();
            bv2.fast_ensure_set1(i).unwrap();
        }

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

        for i in 0..bv1.len() {
            assert_eq!(bv1.get(i), bv2.get(i), "mismatch at bit {}", i);
        }
    }

    #[test]
    fn test_ensure_set1_integer_set_use_case() {
        // Simulate building a set of integers {3, 7, 15, 31, 63}
        let integers = vec![3, 7, 15, 31, 63];
        let mut bv = BitVector::new();

        for &i in &integers {
            bv.fast_ensure_set1(i).unwrap();
        }

        // Check membership
        assert_eq!(bv.get(3), Some(true));
        assert_eq!(bv.get(7), Some(true));
        assert_eq!(bv.get(15), Some(true));
        assert_eq!(bv.get(31), Some(true));
        assert_eq!(bv.get(63), Some(true));

        // Check non-membership
        assert_eq!(bv.get(0), Some(false));
        assert_eq!(bv.get(4), Some(false));
        assert_eq!(bv.get(8), Some(false));
    }
}