crates/kleene-index/src/cand.rs
//! Candidates: a key to the ids filed under it (trait to implementors, type to impls,
//! canonical signature to functions). Keys are 128 bits (the sets' two-word hashes).
use arrow_buffer::ScalarBuffer;
use crate::error::{Result, bad};
/// Sorted distinct keys, and under each the ids filed with it (rising, no repeats).
#[derive(Clone, Debug)]
pub struct Groups {
hi: ScalarBuffer<u64>,
lo: ScalarBuffer<u64>,
off: ScalarBuffer<u64>,
ids: ScalarBuffer<u32>,
}
impl Groups {
/// Group `ids[k]` under the key `(hi[k], lo[k])`.
pub fn build(hi: &[u64], lo: &[u64], ids: &[u32]) -> Result<Self> {
if hi.len() != lo.len() || hi.len() != ids.len() {
return Err(bad("key and id columns of unequal length"));
}
let mut rows: Vec<(u64, u64, u32)> =
(0..ids.len()).map(|k| (hi[k], lo[k], ids[k])).collect();
rows.sort_unstable();
rows.dedup();
let (mut h, mut l, mut off, mut out) = (Vec::new(), Vec::new(), vec![0u64], Vec::new());
for (k, &(a, b, id)) in rows.iter().enumerate() {
if k == 0 || (a, b) != (rows[k - 1].0, rows[k - 1].1) {
if k > 0 {
off.push(out.len() as u64);
}
h.push(a);
l.push(b);
}
out.push(id);
}
if !rows.is_empty() {
off.push(out.len() as u64);
}
Ok(Groups {
hi: h.into(),
lo: l.into(),
off: off.into(),
ids: out.into(),
})
}
/// Groups from their stored parts (as [`Groups::parts`] gave them).
pub fn from_parts(keys: [ScalarBuffer<u64>; 3], ids: ScalarBuffer<u32>) -> Result<Self> {
let [hi, lo, off] = keys;
let n = hi.len();
if lo.len() != n
|| off.len() != n + 1
|| off[0] != 0
|| off.windows(2).any(|w| w[0] >= w[1])
|| off[n] != ids.len() as u64
|| (1..n).any(|k| (hi[k - 1], lo[k - 1]) >= (hi[k], lo[k]))
{
return Err(bad("stored groups do not fit together"));
}
Ok(Groups { hi, lo, off, ids })
}
/// `[hi, lo, offsets]` and the ids.
pub fn parts(&self) -> ([&ScalarBuffer<u64>; 3], &ScalarBuffer<u32>) {
([&self.hi, &self.lo, &self.off], &self.ids)
}
/// The number of distinct keys.
pub fn keys(&self) -> usize {
self.hi.len()
}
/// The ids filed under `(hi, lo)`, rising; empty for an unknown key.
#[inline]
pub fn get(&self, hi: u64, lo: u64) -> &[u32] {
let at = {
let (mut a, mut b) = (0usize, self.hi.len());
while a < b {
let m = a + (b - a) / 2;
if (self.hi[m], self.lo[m]) < (hi, lo) {
a = m + 1;
} else {
b = m;
}
}
a
};
if at < self.hi.len() && (self.hi[at], self.lo[at]) == (hi, lo) {
&self.ids[self.off[at] as usize..self.off[at + 1] as usize]
} else {
&[]
}
}
}