Skip to main content

zu_vector/kernels/
gather.rs

1//! Gather and compaction kernels.
2//!
3//! Gather is the late-materialization primitive: fetch rows named by an
4//! index vector out of a decoded column. Compaction turns a selected
5//! vector flat at pipeline breaks when selectivity has dropped far
6//! enough that downstream full-vector loops would mostly touch dead
7//! rows (perf/02 puts the crossover at 1/8).
8
9use crate::arena::MorselArena;
10use crate::bitmap::Bitmap;
11use crate::sel::SelVector;
12use crate::str::StrView;
13use crate::vector::{ValueVector, VecEncoding};
14
15/// out[i] = src[idx[i]]. The loop is unrolled by four so the loads
16/// overlap; indices are u32 because gather sources (decoded groups) are
17/// bounded by group size, not vector size.
18pub fn gather_u64(src: &[u64], idx: &[u32], out: &mut [u64]) {
19    debug_assert_eq!(idx.len(), out.len());
20    // Fours as arrays rather than as slices, which is the same unroll
21    // with the length in the type, so the four stores need no bounds
22    // check to prove.
23    let (fours, tail) = idx.as_chunks::<4>();
24    let (outs, out_tail) = out.as_chunks_mut::<4>();
25    for (i4, o4) in fours.iter().zip(outs) {
26        o4[0] = src[i4[0] as usize];
27        o4[1] = src[i4[1] as usize];
28        o4[2] = src[i4[2] as usize];
29        o4[3] = src[i4[3] as usize];
30    }
31    for (o, &i) in out_tail.iter_mut().zip(tail) {
32        *o = src[i as usize];
33    }
34}
35
36/// Compact a selected vector to a flat unselected one. Word-addressed
37/// types move 8 or 16 bytes per surviving row; validity compacts with
38/// the rows. Constant vectors just shrink their logical length.
39pub fn compact(arena: &mut MorselArena, v: &ValueVector, sel: &SelVector) -> ValueVector {
40    let n = sel.len();
41    match v.encoding {
42        VecEncoding::Constant => {
43            let mut out = ValueVector::flat_uninit(arena, v.phys, 0);
44            out.encoding = VecEncoding::Constant;
45            out.data = {
46                let mut d = arena.alloc(v.phys.width().expect("word type"), 8);
47                d.as_mut_slice::<u8>()
48                    .copy_from_slice(v.data.as_slice::<u8>());
49                d
50            };
51            out.len = n as u32;
52            out
53        }
54        VecEncoding::Flat => {
55            let mut out = ValueVector::flat_uninit(arena, v.phys, n);
56            match v.phys.width() {
57                Some(8) => {
58                    let src = v.data.as_slice::<u64>();
59                    let dst = out.values_mut::<u64>();
60                    for (o, &row) in dst.iter_mut().zip(sel.as_slice()) {
61                        *o = src[row as usize];
62                    }
63                }
64                Some(16) => {
65                    let src = v.data.as_slice::<StrView>();
66                    let dst = out.values_mut::<StrView>();
67                    for (o, &row) in dst.iter_mut().zip(sel.as_slice()) {
68                        *o = src[row as usize];
69                    }
70                }
71                _ => unreachable!("compact on {:?}", v.phys),
72            }
73            if let Some(valid) = &v.validity {
74                let mut vout = Bitmap::new_in(arena, n, true);
75                for (i, &row) in sel.as_slice().iter().enumerate() {
76                    if !valid.get(row as usize) {
77                        vout.clear(i);
78                    }
79                }
80                out.validity = Some(vout);
81            }
82            out.aux = clone_aux(&v.aux);
83            out
84        }
85        VecEncoding::Dict { codes_width: 2 } => {
86            let src = v.codes_u16();
87            let mut data = arena.alloc_of::<u16>(n);
88            {
89                let dst = data.as_mut_slice::<u16>();
90                for (o, &row) in dst.iter_mut().zip(sel.as_slice()) {
91                    *o = src[row as usize];
92                }
93            }
94            let mut out = ValueVector {
95                phys: v.phys,
96                encoding: v.encoding,
97                data,
98                validity: None,
99                aux: clone_aux(&v.aux),
100                len: n as u32,
101            };
102            if let Some(valid) = &v.validity {
103                let mut vout = Bitmap::new_in(arena, n, true);
104                for (i, &row) in sel.as_slice().iter().enumerate() {
105                    if !valid.get(row as usize) {
106                        vout.clear(i);
107                    }
108                }
109                out.validity = Some(vout);
110            }
111            out
112        }
113        VecEncoding::Dict { .. } => unreachable!("only u16 codes exist today"),
114    }
115}
116
117/// Aux data is shared, not copied: buffers and dictionaries are Arcs.
118fn clone_aux(aux: &crate::vector::Aux) -> crate::vector::Aux {
119    use crate::vector::Aux;
120    match aux {
121        Aux::None => Aux::None,
122        Aux::Str(b) => Aux::Str(std::sync::Arc::clone(b)),
123        Aux::Dict(d) => Aux::Dict(std::sync::Arc::clone(d)),
124        Aux::List(_) => unimplemented!("list compaction lands with the list operators"),
125    }
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131    use crate::vector::PhysType;
132
133    #[test]
134    fn gather_matches_indexing() {
135        let src: Vec<u64> = (0..100).map(|i| i * 7).collect();
136        let idx = [0u32, 99, 50, 1, 2, 98, 3];
137        let mut out = [0u64; 7];
138        gather_u64(&src, &idx, &mut out);
139        for (o, &i) in out.iter().zip(&idx) {
140            assert_eq!(*o, src[i as usize]);
141        }
142    }
143
144    #[test]
145    fn compact_flat_i64() {
146        let mut arena = MorselArena::new();
147        let mut v = ValueVector::flat_from(&mut arena, PhysType::Int64, &[10i64, 20, 30, 40]);
148        let mut valid = Bitmap::new_in(&mut arena, 4, true);
149        valid.clear(3);
150        v.validity = Some(valid);
151        let mut sel = SelVector::with_capacity(&mut arena, 2);
152        sel.push(1);
153        sel.push(3);
154        let out = compact(&mut arena, &v, &sel);
155        assert_eq!(out.values::<i64>(), &[20, 40]);
156        assert!(out.is_valid(0));
157        assert!(!out.is_valid(1));
158    }
159}