Refactors the building process to utilize memory mapping (`memmap2`) for file creation and introduces the necessary infrastructure for publishing built files atomically. This includes expanding the public API surface and cleaning up deprecated architectural components.
291 lines
10 KiB
Rust
291 lines
10 KiB
Rust
//! Rank/select-capable bitvector — extends the crate's existing bit-count
|
|
//! (`count_ones`, a global reduction) with `rank1`/`rank0` (count of 1s/0s
|
|
//! in a prefix) and `select1`/`select0` (position of the k-th 1/0 bit).
|
|
//! Needed by two consumers in the sparse presence-matrix design (see
|
|
//! `DevDocMD/architecture/siblings.md` and the sparse-matrix plan): the
|
|
//! `is_multi` row-kind flag (needs rank, to locate a row's position within
|
|
//! whichever of the two split arrays it belongs to) and the Elias-Fano high
|
|
//! bits (needs select1 to decode a value by index, select0 to jump to a
|
|
//! bucket boundary for `next_geq`/`contains`).
|
|
//!
|
|
//! Two-level structure, the standard succinct-bitvector approach: a
|
|
//! cumulative rank sampled every [`BLOCK_WORDS`] words, plus a linear scan
|
|
//! within the block (at most [`BLOCK_WORDS`] popcounts) for the remainder.
|
|
//! `select1` binary-searches the block samples, then
|
|
//! `common_traits::SelectInWord` locates the exact bit within the winning
|
|
//! word.
|
|
|
|
use std::io;
|
|
use std::path::{Path, PathBuf};
|
|
|
|
use common_traits::SelectInWord;
|
|
use memmap2::{Mmap, MmapMut};
|
|
|
|
use crate::mmap_file::{create_mmap_file, open_mmap_file, publish_built};
|
|
|
|
const MAGIC: [u8; 4] = *b"PRSB";
|
|
|
|
/// Words per rank-sample block — 8 words = 512 bits, one cache line's
|
|
/// worth of linear-scan work for the within-block remainder.
|
|
const BLOCK_WORDS: usize = 8;
|
|
|
|
// Header: magic(4) + _pad(4) + n(8) + total_ones(8) = 24 bytes (8-aligned).
|
|
const HEADER_SIZE: usize = 24;
|
|
|
|
#[inline]
|
|
fn n_words(n: usize) -> usize {
|
|
n.div_ceil(64)
|
|
}
|
|
|
|
#[inline]
|
|
fn n_blocks(n: usize) -> usize {
|
|
n_words(n).div_ceil(BLOCK_WORDS)
|
|
}
|
|
|
|
#[inline]
|
|
fn bits_bytes(n: usize) -> usize {
|
|
n_words(n) * 8
|
|
}
|
|
|
|
#[inline]
|
|
fn blocks_bytes(n: usize) -> usize {
|
|
n_blocks(n) * 8
|
|
}
|
|
|
|
// ── PersistentRankSelectBitVec ──────────────────────────────────────────────
|
|
|
|
pub struct PersistentRankSelectBitVec {
|
|
mmap: Mmap,
|
|
n: usize,
|
|
total_ones: u64,
|
|
path: PathBuf,
|
|
}
|
|
|
|
impl PersistentRankSelectBitVec {
|
|
pub fn open(path: &Path) -> io::Result<Self> {
|
|
let (mmap, n) = open_mmap_file(path, MAGIC, HEADER_SIZE)?;
|
|
let total_ones = u64::from_le_bytes(mmap[16..24].try_into().unwrap());
|
|
Ok(Self { mmap, n, total_ones, path: path.to_path_buf() })
|
|
}
|
|
|
|
#[inline]
|
|
pub fn path(&self) -> &Path { &self.path }
|
|
#[inline]
|
|
pub fn len(&self) -> usize { self.n }
|
|
#[inline]
|
|
pub fn is_empty(&self) -> bool { self.n == 0 }
|
|
#[inline]
|
|
pub fn count_ones(&self) -> u64 { self.total_ones }
|
|
#[inline]
|
|
pub fn count_zeros(&self) -> u64 { self.n as u64 - self.total_ones }
|
|
|
|
// SAFETY: mmap is page-aligned, HEADER_SIZE=24 divisible by 8 → u64-aligned.
|
|
#[inline]
|
|
fn bit_words(&self) -> &[u64] {
|
|
let nw = n_words(self.n);
|
|
let ptr = self.mmap[HEADER_SIZE..].as_ptr() as *const u64;
|
|
unsafe { std::slice::from_raw_parts(ptr, nw) }
|
|
}
|
|
|
|
#[inline]
|
|
fn block_ranks(&self) -> &[u64] {
|
|
let nb = n_blocks(self.n);
|
|
let off = HEADER_SIZE + bits_bytes(self.n);
|
|
let ptr = self.mmap[off..].as_ptr() as *const u64;
|
|
unsafe { std::slice::from_raw_parts(ptr, nb) }
|
|
}
|
|
|
|
#[inline]
|
|
pub fn get(&self, pos: usize) -> bool {
|
|
debug_assert!(pos < self.n);
|
|
(self.bit_words()[pos >> 6] >> (pos & 63)) & 1 != 0
|
|
}
|
|
|
|
/// Number of 1 bits in `[0, pos)`.
|
|
pub fn rank1(&self, pos: usize) -> u64 {
|
|
debug_assert!(pos <= self.n);
|
|
if pos == 0 {
|
|
return 0;
|
|
}
|
|
let words = self.bit_words();
|
|
let block_ranks = self.block_ranks();
|
|
let word_idx = (pos - 1) / 64;
|
|
let block_idx = word_idx / BLOCK_WORDS;
|
|
let mut rank = block_ranks[block_idx];
|
|
let block_start_word = block_idx * BLOCK_WORDS;
|
|
for w in &words[block_start_word..word_idx] {
|
|
rank += w.count_ones() as u64;
|
|
}
|
|
let bit_in_word = pos - word_idx * 64;
|
|
let last = words[word_idx];
|
|
let masked = if bit_in_word >= 64 { last } else { last & ((1u64 << bit_in_word) - 1) };
|
|
rank += masked.count_ones() as u64;
|
|
rank
|
|
}
|
|
|
|
/// Number of 0 bits in `[0, pos)`.
|
|
#[inline]
|
|
pub fn rank0(&self, pos: usize) -> u64 {
|
|
pos as u64 - self.rank1(pos)
|
|
}
|
|
|
|
/// Position of the `k`-th (0-indexed) 1 bit. Panics if fewer than
|
|
/// `k + 1` ones exist.
|
|
pub fn select1(&self, k: u64) -> usize {
|
|
assert!(k < self.total_ones, "select1({k}) out of range: only {} ones", self.total_ones);
|
|
let block_ranks = self.block_ranks();
|
|
let words = self.bit_words();
|
|
|
|
// Binary search: last block whose cumulative rank is <= k.
|
|
let mut lo = 0usize;
|
|
let mut hi = block_ranks.len();
|
|
while lo + 1 < hi {
|
|
let mid = lo + (hi - lo) / 2;
|
|
if block_ranks[mid] <= k { lo = mid; } else { hi = mid; }
|
|
}
|
|
let block_idx = lo;
|
|
let mut remaining = k - block_ranks[block_idx];
|
|
let start_word = block_idx * BLOCK_WORDS;
|
|
let end_word = (start_word + BLOCK_WORDS).min(words.len());
|
|
for (i, &w) in words[start_word..end_word].iter().enumerate() {
|
|
let c = w.count_ones() as u64;
|
|
if remaining < c {
|
|
return (start_word + i) * 64 + w.select_in_word(remaining as usize);
|
|
}
|
|
remaining -= c;
|
|
}
|
|
unreachable!("select1({k}): ran off the end of its own block — rank/select index inconsistent");
|
|
}
|
|
|
|
/// Position of the `k`-th (0-indexed) 0 bit. Panics if fewer than
|
|
/// `k + 1` zeros exist.
|
|
///
|
|
/// Mirrors [`select1`](Self::select1): binary-searches a per-block
|
|
/// zero count derived from `block_ranks` (`block_start_bit -
|
|
/// block_ranks[block]`, no separate index needed), then locates the
|
|
/// exact bit within the winning word via `SelectInWord` on `!w`.
|
|
pub fn select0(&self, k: u64) -> usize {
|
|
let total_zeros = self.count_zeros();
|
|
assert!(k < total_zeros, "select0({k}) out of range: only {total_zeros} zeros");
|
|
let block_ranks = self.block_ranks();
|
|
let words = self.bit_words();
|
|
|
|
// Binary search: last block whose cumulative zero-count is <= k.
|
|
let mut lo = 0usize;
|
|
let mut hi = block_ranks.len();
|
|
while lo + 1 < hi {
|
|
let mid = lo + (hi - lo) / 2;
|
|
let zeros_at_mid = (mid * BLOCK_WORDS * 64) as u64 - block_ranks[mid];
|
|
if zeros_at_mid <= k { lo = mid; } else { hi = mid; }
|
|
}
|
|
let block_idx = lo;
|
|
let zeros_before_block = (block_idx * BLOCK_WORDS * 64) as u64 - block_ranks[block_idx];
|
|
let mut remaining = k - zeros_before_block;
|
|
let start_word = block_idx * BLOCK_WORDS;
|
|
let end_word = (start_word + BLOCK_WORDS).min(words.len());
|
|
for (i, &w) in words[start_word..end_word].iter().enumerate() {
|
|
let zw = !w;
|
|
let c = zw.count_ones() as u64;
|
|
if remaining < c {
|
|
return (start_word + i) * 64 + zw.select_in_word(remaining as usize);
|
|
}
|
|
remaining -= c;
|
|
}
|
|
unreachable!("select0({k}): ran off the end of its own block — rank/select index inconsistent");
|
|
}
|
|
}
|
|
|
|
// ── PersistentRankSelectBitVecBuilder ───────────────────────────────────────
|
|
|
|
pub struct PersistentRankSelectBitVecBuilder {
|
|
mmap: MmapMut,
|
|
n: usize,
|
|
path: PathBuf,
|
|
}
|
|
|
|
impl PersistentRankSelectBitVecBuilder {
|
|
pub fn new(n: usize, path: &Path) -> io::Result<Self> {
|
|
let file_size = HEADER_SIZE + bits_bytes(n) + blocks_bytes(n);
|
|
// 8 extra header zero bytes: `total_ones`, patched in close().
|
|
let mmap = create_mmap_file(path, MAGIC, [0u8; 4], n, 8, file_size)?;
|
|
Ok(Self { mmap, n, path: path.to_path_buf() })
|
|
}
|
|
|
|
#[inline]
|
|
pub fn len(&self) -> usize { self.n }
|
|
#[inline]
|
|
pub fn is_empty(&self) -> bool { self.n == 0 }
|
|
|
|
#[inline]
|
|
fn bit_words_mut(&mut self) -> &mut [u64] {
|
|
let nw = n_words(self.n);
|
|
let ptr = self.mmap[HEADER_SIZE..].as_mut_ptr() as *mut u64;
|
|
unsafe { std::slice::from_raw_parts_mut(ptr, nw) }
|
|
}
|
|
|
|
#[inline]
|
|
pub fn get(&self, pos: usize) -> bool {
|
|
debug_assert!(pos < self.n);
|
|
let nw = n_words(self.n);
|
|
let ptr = self.mmap[HEADER_SIZE..].as_ptr() as *const u64;
|
|
let words = unsafe { std::slice::from_raw_parts(ptr, nw) };
|
|
(words[pos >> 6] >> (pos & 63)) & 1 != 0
|
|
}
|
|
|
|
#[inline]
|
|
pub fn set(&mut self, pos: usize, value: bool) {
|
|
debug_assert!(pos < self.n);
|
|
let bit = 1u64 << (pos & 63);
|
|
let words = self.bit_words_mut();
|
|
if value {
|
|
words[pos >> 6] |= bit;
|
|
} else {
|
|
words[pos >> 6] &= !bit;
|
|
}
|
|
}
|
|
|
|
/// Computes the block-rank index and total-ones count from the bits
|
|
/// written so far, then flushes. Must run after every `set()` call —
|
|
/// the index is a function of the final bit pattern, not maintainable
|
|
/// incrementally through arbitrary overwrites.
|
|
pub fn close(mut self) -> io::Result<()> {
|
|
let nb = n_blocks(self.n);
|
|
let nw = n_words(self.n);
|
|
let mut block_ranks = vec![0u64; nb];
|
|
let mut running = 0u64;
|
|
{
|
|
let words = self.bit_words_mut();
|
|
for (block_idx, block_rank) in block_ranks.iter_mut().enumerate() {
|
|
*block_rank = running;
|
|
let start = block_idx * BLOCK_WORDS;
|
|
let end = (start + BLOCK_WORDS).min(nw);
|
|
for &w in &words[start..end] {
|
|
running += w.count_ones() as u64;
|
|
}
|
|
}
|
|
}
|
|
self.mmap[16..24].copy_from_slice(&running.to_le_bytes());
|
|
let block_off = HEADER_SIZE + bits_bytes(self.n);
|
|
let block_bytes = u64_slice_to_le_bytes(&block_ranks);
|
|
self.mmap[block_off..block_off + block_bytes.len()].copy_from_slice(&block_bytes);
|
|
self.mmap.flush()?;
|
|
publish_built(&self.path)
|
|
}
|
|
|
|
pub fn finish(self) -> io::Result<PersistentRankSelectBitVec> {
|
|
let path = self.path.clone();
|
|
self.close()?;
|
|
PersistentRankSelectBitVec::open(&path)
|
|
}
|
|
}
|
|
|
|
/// Minimal, local `u64` slice -> byte vec conversion (little-endian,
|
|
/// matching every other on-disk format in this crate).
|
|
fn u64_slice_to_le_bytes(values: &[u64]) -> Vec<u8> {
|
|
let mut out = Vec::with_capacity(values.len() * 8);
|
|
for &v in values {
|
|
out.extend_from_slice(&v.to_le_bytes());
|
|
}
|
|
out
|
|
}
|