zipora 3.1.3

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
//! Rank9: Fast rank/select with 512-bit blocks and 25% space overhead.
//!
//! Based on Vigna's "Broadword Implementation of Rank/Select Queries" (2008).
//!
//! Layout per 512-bit block (16 bytes):
//! - `base`: u64 — cumulative popcount up to this block
//! - `sub`: u64 — 7 packed 9-bit sub-block counts within the block
//!   sub_k = popcount of words 0..k within the block (k = 1..7)
//!
//! Rank is O(1): one lookup in the block index + one popcount of a partial word.
//! Select uses binary search on blocks + select_in_word within a block.

use crate::error::{Result, ZiporaError};
use super::RankSelectOps;
use crate::succinct::BitVector;
use crate::algorithms::bit_ops::select_in_word;

/// Words per block. 8 words × 64 bits = 512 bits per block.
const WORDS_PER_BLOCK: usize = 8;
/// Bits per block.
const BITS_PER_BLOCK: usize = WORDS_PER_BLOCK * 64;

/// Rank9 index entry: base rank + packed sub-block counts.
#[derive(Debug, Clone, Copy)]
#[repr(C)]
struct Rank9Entry {
    /// Cumulative popcount of all bits before this block.
    base: u64,
    /// 7 packed 9-bit sub-block counts.
    /// Bits [0..9) = popcount of word 0
    /// Bits [9..18) = popcount of words 0..1
    /// ...
    /// Bits [54..63) = popcount of words 0..6
    /// (word 7 is not stored — it equals block total = next_base - base)
    sub: u64,
}

/// Fast rank/select structure with 512-bit blocks and O(1) rank.
///
/// Space overhead: 25% of the original bitvector (16 bytes per 64 bytes of data).
/// Rank: O(1) — one index lookup + one `popcnt` instruction.
/// Select: O(log n) binary search on blocks + O(1) within block.
///
/// # Examples
///
/// ```rust
/// use zipora::succinct::BitVector;
/// use zipora::succinct::rank_select::{Rank9, RankSelectOps};
///
/// let mut bv = BitVector::new();
/// for i in 0..1000 {
///     bv.push(i % 3 == 0).unwrap();
/// }
/// let r9 = Rank9::new(bv).unwrap();
///
/// // O(1) rank
/// let rank = r9.rank1(500);
/// assert_eq!(rank, 167); // floor(500/3) + 1 = 167
///
/// // Select via binary search
/// let pos = r9.select1(100).unwrap();
/// assert_eq!(pos, 300);
/// ```
pub struct Rank9 {
    /// Raw bitvector words.
    data: Vec<u64>,
    /// Rank9 index: one entry per 512-bit block, plus sentinel.
    index: Vec<Rank9Entry>,
    /// Total number of valid bits.
    len_bits: usize,
    /// Total number of set bits.
    total_ones: usize,
}

impl Rank9 {
    /// Build from a BitVector.
    pub fn new(bv: BitVector) -> Result<Self> {
        let len_bits = bv.len();
        let data = bv.blocks().to_vec();
        let num_blocks = (data.len() + WORDS_PER_BLOCK - 1) / WORDS_PER_BLOCK;

        let mut index = Vec::with_capacity(num_blocks + 1);
        let mut cumul: u64 = 0;

        for block_idx in 0..num_blocks {
            let start_word = block_idx * WORDS_PER_BLOCK;
            let mut sub: u64 = 0;
            let mut block_cumul: u64 = 0;

            for k in 0..WORDS_PER_BLOCK {
                let word_idx = start_word + k;
                let word = if word_idx < data.len() { data[word_idx] } else { 0 };
                block_cumul += word.count_ones() as u64;
                // Store cumulative count after word k in sub-block position k
                // (positions 0..6 are stored; position 7 is implied)
                if k < 7 {
                    sub |= block_cumul << (k * 9);
                }
            }

            index.push(Rank9Entry { base: cumul, sub });
            cumul += block_cumul;
        }

        // Sentinel entry
        index.push(Rank9Entry { base: cumul, sub: 0 });

        Ok(Self {
            data,
            index,
            len_bits,
            total_ones: cumul as usize,
        })
    }

    /// O(1) rank1: count set bits in [0, pos).
    #[inline]
    pub fn rank1_fast(&self, pos: usize) -> usize {
        if pos == 0 { return 0; }
        let pos = pos.min(self.len_bits);

        let block = pos / BITS_PER_BLOCK;
        let entry = &self.index[block];

        let word_in_block = (pos % BITS_PER_BLOCK) / 64;
        let bit_in_word = pos % 64;

        // Base rank from block
        let mut rank = entry.base as usize;

        // Add sub-block count (cumulative within block up to word_in_block)
        if word_in_block > 0 {
            rank += ((entry.sub >> ((word_in_block - 1) * 9)) & 0x1FF) as usize;
        }

        // Add popcount of partial word
        let global_word = block * WORDS_PER_BLOCK + word_in_block;
        if global_word < self.data.len() && bit_in_word > 0 {
            let mask = (1u64 << bit_in_word) - 1;
            rank += (self.data[global_word] & mask).count_ones() as usize;
        }

        rank
    }

    /// Select1 via binary search on blocks.
    pub fn select1_fast(&self, k: usize) -> Result<usize> {
        if k >= self.total_ones {
            return Err(ZiporaError::invalid_data(format!(
                "select1({}) out of range (total_ones={})", k, self.total_ones)));
        }

        let target = k as u64;

        // Binary search for the block containing the k-th set bit
        let num_blocks = self.index.len() - 1;
        let mut lo = 0usize;
        let mut hi = num_blocks;
        while lo < hi {
            let mid = (lo + hi) / 2;
            if self.index[mid + 1].base <= target {
                lo = mid + 1;
            } else {
                hi = mid;
            }
        }

        let block = lo;
        let entry = &self.index[block];
        let mut remaining = target - entry.base;
        let start_word = block * WORDS_PER_BLOCK;

        // Scan sub-blocks to find the word within the block
        let mut word_offset = 0usize;
        for j in 0..7 {
            let sub_cumul = (entry.sub >> (j * 9)) & 0x1FF;
            if sub_cumul > remaining {
                break;
            }
            word_offset = j + 1;
        }

        // Adjust remaining by sub-block count before this word
        if word_offset > 0 {
            let sub_before = (entry.sub >> ((word_offset - 1) * 9)) & 0x1FF;
            remaining -= sub_before;
        }

        let global_word = start_word + word_offset;
        if global_word < self.data.len() {
            let word = self.data[global_word];
            let bit_pos = select_in_word(word, remaining as usize);
            Ok(global_word * 64 + bit_pos)
        } else {
            Err(ZiporaError::invalid_data("select1 internal error: word out of range"))
        }
    }

    /// Memory usage in bytes.
    pub fn mem_size(&self) -> usize {
        self.data.len() * 8 + self.index.len() * std::mem::size_of::<Rank9Entry>()
    }
}

impl RankSelectOps for Rank9 {
    #[inline]
    fn rank1(&self, pos: usize) -> usize { self.rank1_fast(pos) }

    fn rank0(&self, pos: usize) -> usize {
        let pos = pos.min(self.len_bits);
        pos - self.rank1(pos)
    }

    fn select1(&self, k: usize) -> Result<usize> { self.select1_fast(k) }

    fn select0(&self, k: usize) -> Result<usize> {
        let total_zeros = self.len_bits - self.total_ones;
        if k >= total_zeros {
            return Err(ZiporaError::invalid_data("select0 out of range"));
        }
        // Binary search using rank0
        let mut lo = 0usize;
        let mut hi = self.len_bits;
        while lo < hi {
            let mid = (lo + hi) / 2;
            if self.rank0(mid) <= k {
                lo = mid + 1;
            } else {
                hi = mid;
            }
        }
        if lo > 0 { Ok(lo - 1) } else { Ok(0) }
    }

    fn len(&self) -> usize { self.len_bits }
    fn count_ones(&self) -> usize { self.total_ones }

    fn get(&self, index: usize) -> Option<bool> {
        if index >= self.len_bits { return None; }
        let word_idx = index / 64;
        let bit_idx = index % 64;
        if word_idx < self.data.len() {
            Some((self.data[word_idx] >> bit_idx) & 1 == 1)
        } else {
            Some(false)
        }
    }

    fn space_overhead_percent(&self) -> f64 {
        if self.len_bits == 0 { return 0.0; }
        let data_bytes = self.data.len() * 8;
        let index_bytes = self.index.len() * std::mem::size_of::<Rank9Entry>();
        (index_bytes as f64 / data_bytes as f64) * 100.0
    }
}

impl std::fmt::Debug for Rank9 {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Rank9")
            .field("len_bits", &self.len_bits)
            .field("total_ones", &self.total_ones)
            .field("blocks", &(self.index.len().saturating_sub(1)))
            .field("overhead", &format!("{:.1}%", self.space_overhead_percent()))
            .finish()
    }
}

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

    fn make_bv(pattern: &[bool]) -> BitVector {
        let mut bv = BitVector::new();
        for &b in pattern { bv.push(b).unwrap(); }
        bv
    }

    #[test]
    fn test_empty() {
        let r9 = Rank9::new(BitVector::new()).unwrap();
        assert_eq!(r9.len(), 0);
        assert_eq!(r9.count_ones(), 0);
        assert_eq!(r9.rank1(0), 0);
    }

    #[test]
    fn test_single_bit() {
        let r9 = Rank9::new(make_bv(&[true])).unwrap();
        assert_eq!(r9.len(), 1);
        assert_eq!(r9.count_ones(), 1);
        assert_eq!(r9.rank1(0), 0);
        assert_eq!(r9.rank1(1), 1);
        assert_eq!(r9.select1(0).unwrap(), 0);
    }

    #[test]
    fn test_alternating() {
        let pattern: Vec<bool> = (0..1000).map(|i| i % 2 == 0).collect();
        let r9 = Rank9::new(make_bv(&pattern)).unwrap();

        assert_eq!(r9.len(), 1000);
        assert_eq!(r9.count_ones(), 500);

        // Rank invariant
        for pos in (0..=1000).step_by(50) {
            assert_eq!(r9.rank0(pos) + r9.rank1(pos), pos,
                "rank invariant at pos {}", pos);
        }

        // Select roundtrip
        for k in 0..500 {
            let pos = r9.select1(k).unwrap();
            assert_eq!(r9.rank1(pos + 1), k + 1,
                "select1({}) roundtrip failed", k);
        }
    }

    #[test]
    fn test_sparse() {
        let pattern: Vec<bool> = (0..10000).map(|i| i % 100 == 0).collect();
        let r9 = Rank9::new(make_bv(&pattern)).unwrap();

        assert_eq!(r9.count_ones(), 100);
        assert_eq!(r9.select1(0).unwrap(), 0);
        assert_eq!(r9.select1(1).unwrap(), 100);
        assert_eq!(r9.select1(99).unwrap(), 9900);
        assert_eq!(r9.rank1(100), 1);
        assert_eq!(r9.rank1(200), 2);
    }

    #[test]
    fn test_dense() {
        let pattern: Vec<bool> = (0..1000).map(|i| i % 4 != 3).collect();
        let r9 = Rank9::new(make_bv(&pattern)).unwrap();

        assert_eq!(r9.count_ones(), 750);

        for pos in (0..=1000).step_by(37) {
            assert_eq!(r9.rank0(pos) + r9.rank1(pos), pos);
        }
    }

    #[test]
    fn test_crossing_blocks() {
        // Test data crossing 512-bit block boundaries
        let pattern: Vec<bool> = (0..2000).map(|i| i % 13 == 0).collect();
        let r9 = Rank9::new(make_bv(&pattern)).unwrap();

        // Verify rank at block boundaries
        for pos in (0..=2000).step_by(64) {
            let expected: usize = (0..pos).filter(|&i| i % 13 == 0).count();
            assert_eq!(r9.rank1(pos), expected, "rank1({}) failed", pos);
        }

        // Verify select roundtrip
        let total = r9.count_ones();
        for k in (0..total).step_by(10) {
            let pos = r9.select1(k).unwrap();
            assert_eq!(pos % 13, 0, "select1({}) = {} not multiple of 13", k, pos);
        }
    }

    #[test]
    fn test_all_ones() {
        let bv = BitVector::with_size(1000, true).unwrap();
        let r9 = Rank9::new(bv).unwrap();
        assert_eq!(r9.count_ones(), 1000);
        assert_eq!(r9.rank1(500), 500);
        assert_eq!(r9.select1(499).unwrap(), 499);
    }

    #[test]
    fn test_all_zeros() {
        let bv = BitVector::with_size(1000, false).unwrap();
        let r9 = Rank9::new(bv).unwrap();
        assert_eq!(r9.count_ones(), 0);
        assert_eq!(r9.rank1(500), 0);
        assert!(r9.select1(0).is_err());
    }

    #[test]
    fn test_space_overhead() {
        let pattern: Vec<bool> = (0..10000).map(|i| i % 3 == 0).collect();
        let r9 = Rank9::new(make_bv(&pattern)).unwrap();

        let overhead = r9.space_overhead_percent();
        // Rank9 should have ~25% overhead
        assert!(overhead > 20.0 && overhead < 30.0,
            "Expected ~25% overhead, got {:.1}%", overhead);
    }

    #[test]
    fn test_get() {
        let pattern: Vec<bool> = (0..100).map(|i| i % 5 == 0).collect();
        let r9 = Rank9::new(make_bv(&pattern)).unwrap();

        for i in 0..100 {
            assert_eq!(r9.get(i), Some(i % 5 == 0), "get({}) failed", i);
        }
        assert_eq!(r9.get(100), None);
    }

    #[test]
    fn test_large_scale() {
        let pattern: Vec<bool> = (0..100000).map(|i| (i * 13 + 7) % 71 == 0).collect();
        let r9 = Rank9::new(make_bv(&pattern)).unwrap();

        // Verify rank at various positions
        for pos in [0, 1000, 10000, 50000, 99999, 100000] {
            let expected: usize = (0..pos).filter(|&i| (i * 13 + 7) % 71 == 0).count();
            assert_eq!(r9.rank1(pos), expected, "rank1({}) failed", pos);
        }

        // Verify select roundtrip for a sample
        let total = r9.count_ones();
        for k in (0..total).step_by(total / 20 + 1) {
            let pos = r9.select1(k).unwrap();
            assert_eq!(r9.rank1(pos), k, "select1({}) roundtrip: rank1({}) != {}", k, pos, k);
            assert_eq!(r9.get(pos), Some(true));
        }
    }

    #[test]
    fn test_select0() {
        let pattern: Vec<bool> = (0..100).map(|i| i % 3 == 0).collect();
        let r9 = Rank9::new(make_bv(&pattern)).unwrap();

        // First zero is at position 1
        let pos = r9.select0(0).unwrap();
        assert_eq!(r9.get(pos), Some(false));

        // Verify a few select0 values
        let total_zeros = r9.len() - r9.count_ones();
        for k in (0..total_zeros).step_by(total_zeros / 5 + 1) {
            let pos = r9.select0(k).unwrap();
            assert_eq!(r9.get(pos), Some(false), "select0({}) = {} is not a zero bit", k, pos);
        }
    }

    /// Performance comparison with RankSelectInterleaved256 — release only.
    #[test]
    fn test_rank9_performance() {
        let pattern: Vec<bool> = (0..100000).map(|i| (i * 13 + 7) % 71 == 0).collect();
        let r9 = Rank9::new(make_bv(&pattern)).unwrap();

        #[cfg(not(debug_assertions))]
        {
            let positions: Vec<usize> = (0..10000).map(|i| i * 10).collect();
            let iterations = 100;

            let start = std::time::Instant::now();
            let mut sink = 0usize;
            for _ in 0..iterations {
                for &pos in &positions {
                    sink += r9.rank1(pos);
                }
            }
            let elapsed = start.elapsed();
            let per_call = elapsed.as_nanos() as f64 / (iterations as f64 * positions.len() as f64);

            eprintln!("Rank9 rank1: {per_call:.1}ns/call, overhead={:.1}%, [sink={sink}]",
                r9.space_overhead_percent());
        }
    }
}