Skip to main content

rypipe_core/
dict.rs

1use std::sync::Arc;
2
3use rustc_hash::FxHashMap;
4
5use crate::columnar::ColumnBuilder;
6
7/// Immutable seed dictionary built from a sample.
8///
9/// Shared `Arc` across threads, read-only after construction.
10#[derive(Debug, Clone)]
11pub struct SeedDict {
12    pub values: Vec<u8>,
13    pub offsets: Vec<i32>,
14    pub index: FxHashMap<Box<str>, i32>,
15}
16
17impl SeedDict {
18    pub fn new(values: Vec<String>) -> Self {
19        let mut data = Vec::new();
20        let mut offsets = Vec::with_capacity(values.len() + 1);
21        offsets.push(0);
22        let mut index = FxHashMap::default();
23        for (i, s) in values.into_iter().enumerate() {
24            index.insert(s.clone().into_boxed_str(), i as i32);
25            data.extend_from_slice(s.as_bytes());
26            offsets.push(data.len() as i32);
27        }
28        Self {
29            values: data,
30            offsets,
31            index,
32        }
33    }
34
35    pub fn len(&self) -> usize {
36        self.offsets.len().saturating_sub(1)
37    }
38
39    pub fn is_empty(&self) -> bool {
40        self.len() == 0
41    }
42}
43
44/// Column plan from sampling.
45#[derive(Debug, Clone)]
46pub struct ColumnPlan {
47    pub encode_as_dict: bool,
48    pub seed: Option<Arc<SeedDict>>,
49    pub est_cardinality: usize,
50}
51
52/// Remap table for one chunk's codes.
53#[derive(Debug, Clone)]
54pub struct RemapTable {
55    pub map: Vec<i32>,
56    pub is_identity: bool,
57}
58
59impl RemapTable {
60    pub fn identity(len: usize) -> Self {
61        Self {
62            map: (0..len as i32).collect(),
63            is_identity: true,
64        }
65    }
66}
67
68/// Unified dictionary values.
69#[derive(Debug, Clone)]
70pub struct DictValues {
71    pub data: Vec<u8>,
72    pub offsets: Vec<i32>,
73}
74
75/// Unify per-chunk dictionaries with the seed.
76///
77/// Works with `ColumnBuilder::Dictionary { codes, dict, index }`.
78/// Seed codes are `0..seed.len()`, overflow are `seed.len()..`.
79pub(crate) fn unify_dictionaries(
80    seed: &SeedDict,
81    locals: &[&ColumnBuilder],
82) -> (DictValues, Vec<RemapTable>) {
83    let mut global_index: FxHashMap<Box<str>, i32> = FxHashMap::default();
84    let mut global_data = seed.values.clone();
85    let mut global_offsets = seed.offsets.clone();
86    let mut next_code = seed.len() as i32;
87
88    for (k, &v) in &seed.index {
89        global_index.insert(k.clone(), v);
90    }
91
92    // Collect overflow values not in seed
93    for col in locals {
94        if let ColumnBuilder::Dictionary { dict, .. } = col {
95            for s in dict.iter().skip(seed.len()) {
96                let k: Box<str> = s.clone().into_boxed_str();
97                if !global_index.contains_key(&k) {
98                    global_index.insert(k.clone(), next_code);
99                    global_data.extend_from_slice(s.as_bytes());
100                    global_offsets.push(global_data.len() as i32);
101                    next_code += 1;
102                }
103            }
104        }
105    }
106
107    let dict_values = DictValues {
108        data: global_data,
109        offsets: global_offsets,
110    };
111
112    // Build remap tables: local code -> global code
113    let mut remaps = Vec::with_capacity(locals.len());
114    for col in locals {
115        if let ColumnBuilder::Dictionary { dict, index, .. } = col {
116            let local_len = dict.len();
117            let mut map = Vec::with_capacity(local_len);
118            let mut is_identity = true;
119            for s in dict {
120                let k: Box<str> = s.clone().into_boxed_str();
121                let g = *global_index.get(&k).unwrap();
122                let local = *index.get(k.as_ref()).unwrap();
123                if g != local {
124                    is_identity = false;
125                }
126                map.push(g);
127            }
128            // If no overflow, it's essentially identity if dict == seed
129            if dict.len() == seed.len() && is_identity {
130                // All seed, identity
131            } else if dict.len() > seed.len() {
132                is_identity = false;
133            }
134            remaps.push(RemapTable { map, is_identity });
135        } else {
136            remaps.push(RemapTable::identity(0));
137        }
138    }
139
140    (dict_values, remaps)
141}
142
143/// Apply remap to codes in place (parallel, L1-resident).
144#[inline]
145pub fn apply_remap(codes: &mut [Option<i32>], remap: &RemapTable) {
146    if remap.is_identity {
147        return;
148    }
149    for v in codes.iter_mut().flatten() {
150        debug_assert!((*v as usize) < remap.map.len(), "code out of bounds");
151        unsafe {
152            *v = *remap.map.get_unchecked(*v as usize);
153        }
154    }
155}
156
157#[cfg(test)]
158mod tests {
159    use super::*;
160    use crate::columnar::ColumnBuilder;
161    use crate::plan::FieldType;
162
163    fn make_dict(values: Vec<&str>) -> ColumnBuilder {
164        let mut b = ColumnBuilder::with_capacity(10, &FieldType::Dictionary);
165        for v in values {
166            b.push_str(Some(v));
167        }
168        b
169    }
170
171    #[test]
172    fn test_unify_no_overflow() {
173        let seed = SeedDict::new(vec!["a".into(), "b".into()]);
174        let col1 = make_dict(vec!["a", "b", "a"]);
175        let col2 = make_dict(vec!["b", "a"]);
176        let (dict, remaps) = unify_dictionaries(&seed, &[&col1, &col2]);
177        assert_eq!(dict.offsets.len(), 3);
178        // Both remaps should be identity or at least map correctly
179        assert_eq!(remaps.len(), 2);
180    }
181
182    #[test]
183    fn test_apply_remap_identity() {
184        let mut codes = vec![Some(0), Some(1), Some(0), None];
185        let remap = RemapTable::identity(2);
186        apply_remap(&mut codes, &remap);
187        assert_eq!(codes, vec![Some(0), Some(1), Some(0), None]);
188    }
189}