Skip to main content

zu_vector/
sel.rs

1//! Selection vectors (perf/02 section 1.3).
2//!
3//! Filters never move data: they produce or refine a selection, a sorted
4//! list of u16 row indices into the vectors of a chunk. `None` at the
5//! chunk level means identity. Compaction to flat happens only at
6//! pipeline breaks when selectivity drops below 1/8.
7
8use crate::VECTOR_SIZE;
9use crate::arena::{MorselArena, RawBuf};
10use crate::bitmap::Bitmap;
11
12pub struct SelVector {
13    idx: RawBuf,
14    len: u32,
15}
16
17impl SelVector {
18    /// Allocate an empty selection with room for `cap` indices.
19    pub fn with_capacity(arena: &mut MorselArena, cap: usize) -> Self {
20        debug_assert!(cap <= VECTOR_SIZE);
21        Self {
22            idx: arena.alloc_of::<u16>(cap),
23            len: 0,
24        }
25    }
26
27    /// Build a selection from the set bits of a predicate bitmap. This is
28    /// the bitmap_to_sel kernel: one trailing_zeros loop per word, no
29    /// per-bit branch on the clear bits. Output offsets are popcounted up
30    /// front so the extraction chains of different words carry no
31    /// dependence on each other and overlap in the out-of-order window;
32    /// that roughly halves the latency at dense selectivities.
33    pub fn from_bitmap(arena: &mut MorselArena, bits: &Bitmap) -> Self {
34        let mut sel = Self::with_capacity(arena, bits.len());
35        let out = sel.idx.as_mut_slice::<u16>();
36        let words = bits.words();
37        debug_assert!(words.len() <= VECTOR_SIZE / 64);
38        let mut offsets = [0u32; VECTOR_SIZE / 64];
39        let mut n = 0u32;
40        for (o, &w) in offsets.iter_mut().zip(words) {
41            *o = n;
42            n += w.count_ones();
43        }
44        for (wi, &word) in words.iter().enumerate() {
45            let base = (wi * 64) as u16;
46            let mut w = word;
47            let mut at = offsets[wi] as usize;
48            while w != 0 {
49                out[at] = base + w.trailing_zeros() as u16;
50                at += 1;
51                w &= w - 1;
52            }
53        }
54        sel.len = n;
55        sel
56    }
57
58    /// Refine an existing selection by a bitmap evaluated over the same
59    /// chunk positions: keep index i when `bits` holds at sel[i]'s row.
60    pub fn refine(arena: &mut MorselArena, sel: &SelVector, bits: &Bitmap) -> Self {
61        let mut out = Self::with_capacity(arena, sel.len());
62        let dst = out.idx.as_mut_slice::<u16>();
63        let mut n = 0usize;
64        for &row in sel.as_slice() {
65            // Branch-free append: write always, advance on keep.
66            dst[n] = row;
67            n += usize::from(bits.get(row as usize));
68        }
69        out.len = n as u32;
70        out
71    }
72
73    pub fn push(&mut self, row: u16) {
74        let n = self.len as usize;
75        self.idx.as_mut_slice::<u16>()[n] = row;
76        self.len += 1;
77    }
78
79    pub fn len(&self) -> usize {
80        self.len as usize
81    }
82
83    pub fn is_empty(&self) -> bool {
84        self.len == 0
85    }
86
87    pub fn as_slice(&self) -> &[u16] {
88        &self.idx.as_slice::<u16>()[..self.len as usize]
89    }
90}
91
92#[cfg(test)]
93mod tests {
94    use super::*;
95
96    #[test]
97    fn from_bitmap_matches_naive() {
98        let mut arena = MorselArena::new();
99        let mut bits = Bitmap::new_in(&mut arena, 200, false);
100        let rows = [0usize, 1, 63, 64, 65, 127, 128, 199];
101        for &r in &rows {
102            bits.set(r);
103        }
104        let sel = SelVector::from_bitmap(&mut arena, &bits);
105        let got: Vec<usize> = sel.as_slice().iter().map(|&i| i as usize).collect();
106        assert_eq!(got, rows);
107    }
108
109    #[test]
110    fn refine_keeps_hits_in_order() {
111        let mut arena = MorselArena::new();
112        let mut bits = Bitmap::new_in(&mut arena, 100, false);
113        bits.set(10);
114        bits.set(30);
115        let mut sel = SelVector::with_capacity(&mut arena, 3);
116        sel.push(5);
117        sel.push(10);
118        sel.push(30);
119        let refined = SelVector::refine(&mut arena, &sel, &bits);
120        assert_eq!(refined.as_slice(), &[10, 30]);
121    }
122}