packmem 0.3.2

Packed, operation-aware columns for record collections: filter and aggregate in memory without decompressing.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
//! String columns: dictionary (predicates run once per distinct value) and/or FSST
//! (per-string random access, equality on compressed bytes).
use crate::buf::Buf;
use crate::ints::{Hint, Store};
use crate::ztext::ZBlocks;
use fsst::{Compressor, CompressorParts, Decompressor};
use std::collections::HashMap;
use std::mem::MaybeUninit;

/// Concatenated strings + offsets, optionally FSST-compressed (each string independently decodable).
/// Only the 255-entry symbol table is kept (about 2.3 KB); the encoder is rebuilt on demand.
pub struct StrPool {
    bytes: Buf<u8>,
    offs: Buf<u32>,
    fsst: Option<Box<CompressorParts>>,
    raw_bytes: usize,
    /// Encoder for needles, built lazily on the first equality query (not needed for decoding).
    enc: std::sync::OnceLock<Compressor>,
    /// When set, the strings live here (Zstandard blocks) and `bytes` and `offs` are empty.
    z: Option<Box<ZBlocks>>,
}

fn rebuild(p: &CompressorParts) -> Compressor {
    let n = p.n_symbols as usize;
    Compressor::rebuild_from(&p.symbols[..n], &p.lengths[..n])
}

impl StrPool {
    fn build<'a>(items: &[&'a str], hint: Hint) -> Self {
        let raw: usize = items.iter().map(|s| s.len()).sum();
        let mut fsst = None;
        let mut fsst_ratio = 1.0;
        if hint != Hint::Speed && raw >= 128 * 1024 {
            let step = (items.len() / 4096).max(1);
            let sample: Vec<&[u8]> = items.iter().step_by(step).map(|s| s.as_bytes()).collect();
            let c = Compressor::train(&sample);
            let (a, b) = sample.iter().fold((0usize, 0usize), |(a, b), s| {
                (a + s.len(), b + c.compress(s).len())
            });
            let ratio = a as f64 / b.max(1) as f64;
            if ratio
                >= if matches!(hint, Hint::Memory | Hint::Compact) {
                    1.05
                } else {
                    1.3
                }
            {
                fsst = Some(Box::new(c.into_parts()));
                fsst_ratio = ratio
            }
        }
        if hint == Hint::Compact && raw >= 256 * 1024 {
            // long text: Zstandard blocks, if they come out clearly smaller than what FSST is expected to give
            if let Some(z) = ZBlocks::build(items) {
                let other = raw as f64 / fsst_ratio + 4.0 * items.len() as f64;
                if (z.bytes() as f64) < other * 0.9 {
                    return StrPool {
                        bytes: Vec::new().into(),
                        offs: vec![0u32].into(),
                        fsst: None,
                        raw_bytes: raw,
                        enc: std::sync::OnceLock::new(),
                        z: Some(Box::new(z)),
                    };
                }
            }
        }
        let mut bytes = Vec::with_capacity(raw / 2);
        let mut offs = Vec::with_capacity(items.len() + 1);
        offs.push(0u32);
        // encode with the rebuilt encoder so that later needle encodings are byte-identical
        let enc = fsst.as_deref().map(rebuild);
        for s in items {
            match &enc {
                Some(c) => bytes.extend_from_slice(&c.compress(s.as_bytes())),
                None => bytes.extend_from_slice(s.as_bytes()),
            }
            offs.push(bytes.len() as u32);
        }
        bytes.shrink_to_fit();
        StrPool {
            bytes: bytes.into(),
            offs: offs.into(),
            fsst,
            raw_bytes: raw,
            enc: std::sync::OnceLock::new(),
            z: None,
        }
    }
    pub fn len(&self) -> usize {
        match &self.z {
            Some(z) => z.len(),
            None => self.offs.len() - 1,
        }
    }
    pub fn bytes(&self) -> usize {
        self.z.as_ref().map_or(0, |z| z.bytes())
            + self.bytes.len()
            + self.offs.len() * 4
            + if self.fsst.is_some() {
                std::mem::size_of::<CompressorParts>()
            } else {
                0
            }
    }
    #[inline]
    fn enc(&self, i: usize) -> &[u8] {
        &self.bytes[self.offs[i] as usize..self.offs[i + 1] as usize]
    }
    /// Decode string i into `buf` (reused across calls) and return it. Touches only that string.
    #[inline]
    pub fn get<'a>(&'a self, i: usize, buf: &'a mut Vec<u8>) -> &'a [u8] {
        if let Some(z) = &self.z {
            return z.get(i, buf);
        }
        let e = self.enc(i);
        match &self.fsst {
            None => e,
            Some(c) => {
                let d = Decompressor::new(&c.symbols, &c.lengths);
                buf.clear();
                buf.reserve(d.max_decompression_capacity(e));
                let spare: &mut [MaybeUninit<u8>] = buf.spare_capacity_mut();
                let n = d.decompress_into(e, spare);
                unsafe { buf.set_len(n) }
                &buf[..]
            }
        }
    }
    /// Equality without decoding: compress the needle once, then compare encoded bytes.
    fn count_eq(&self, needle: &[u8]) -> usize {
        if let Some(z) = &self.z {
            let mut buf = Vec::new();
            return (0..z.len())
                .filter(|&i| z.get(i, &mut buf) == needle)
                .count();
        }
        let nd = match &self.fsst {
            Some(c) => self.enc.get_or_init(|| rebuild(c)).compress(needle),
            None => needle.to_vec(),
        };
        let (nd, b) = (&nd[..], &self.bytes[..]);
        self.offs
            .windows(2)
            .filter(|w| {
                (w[1] - w[0]) as usize == nd.len() && &b[w[0] as usize..w[1] as usize] == nd
            })
            .count()
    }
}

pub enum PackedStrs {
    Dict {
        pool: StrPool,
        codes: Store,
        len: usize,
    },
    Direct {
        pool: StrPool,
    },
}

impl PackedStrs {
    pub fn encode<S: AsRef<str>>(vals: &[S], hint: Hint) -> Self {
        let n = vals.len();
        let mut map: HashMap<&str, u32> = HashMap::new();
        let mut distinct: Vec<&str> = vec![];
        let mut codes: Vec<u32> = Vec::with_capacity(n);
        let mut dict_ok = true;
        for s in vals {
            let s = s.as_ref();
            if dict_ok {
                let next = distinct.len() as u32;
                let c = *map.entry(s).or_insert_with(|| {
                    distinct.push(s);
                    next
                });
                codes.push(c);
                if distinct.len() > n / 2 + 64 {
                    dict_ok = false
                }
            }
        }
        if dict_ok {
            let total: usize = vals.iter().map(|s| s.as_ref().len()).sum();
            let dbytes: usize = distinct.iter().map(|s| s.len()).sum();
            let w = (32 - (distinct.len() as u32).leading_zeros()).max(1) as usize;
            let dict_cost = dbytes + 4 * distinct.len() + n * w / 8;
            let direct_cost = total + 4 * n;
            if dict_cost * 10 < direct_cost * 9 {
                let pool = StrPool::build(&distinct, hint);
                let max = distinct.len().saturating_sub(1) as u64;
                return PackedStrs::Dict {
                    pool,
                    codes: Store::pack(codes.iter().map(|&c| c as u64), n, max, hint),
                    len: n,
                };
            }
        }
        let refs: Vec<&str> = vals.iter().map(|s| s.as_ref()).collect();
        PackedStrs::Direct {
            pool: StrPool::build(&refs, hint),
        }
    }
    pub fn len(&self) -> usize {
        match self {
            PackedStrs::Dict { len, .. } => *len,
            PackedStrs::Direct { pool } => pool.len(),
        }
    }
    pub fn bytes(&self) -> usize {
        match self {
            PackedStrs::Dict { pool, codes, .. } => pool.bytes() + codes.bytes(),
            PackedStrs::Direct { pool } => pool.bytes(),
        }
    }
    pub fn raw_bytes(&self) -> usize {
        match self {
            PackedStrs::Dict { pool, .. } | PackedStrs::Direct { pool } => pool.raw_bytes,
        }
    }
    pub fn describe(&self) -> String {
        let f = |p: &StrPool| {
            if p.z.is_some() {
                "+zstd"
            } else if p.fsst.is_some() {
                "+fsst"
            } else {
                ""
            }
        };
        match self {
            PackedStrs::Dict { pool, codes, .. } => {
                format!("dict({}){}/{}", pool.len(), f(pool), codes.kind())
            }
            PackedStrs::Direct { pool } => format!("direct{}", f(pool)),
        }
    }
    #[inline]
    pub fn get<'a>(&'a self, i: usize, buf: &'a mut Vec<u8>) -> &'a [u8] {
        match self {
            PackedStrs::Dict { pool, codes, .. } => pool.get(codes.get(i) as usize, buf),
            PackedStrs::Direct { pool } => pool.get(i, buf),
        }
    }
    /// Dictionary code of row i and the dictionary size, when this column is dictionary-encoded.
    #[inline]
    pub fn dict_code(&self, i: usize) -> Option<(u32, usize)> {
        match self {
            PackedStrs::Dict { pool, codes, .. } => Some((codes.get(i) as u32, pool.len())),
            _ => None,
        }
    }
    /// The string behind a dictionary code.
    pub fn dict_value(&self, code: u32) -> String {
        match self {
            PackedStrs::Dict { pool, .. } => {
                let mut b = vec![];
                String::from_utf8_lossy(pool.get(code as usize, &mut b)).into_owned()
            }
            _ => String::new(),
        }
    }
    pub fn get_string(&self, i: usize) -> String {
        let mut b = vec![];
        String::from_utf8_lossy(self.get(i, &mut b)).into_owned()
    }
    /// Evaluate an arbitrary predicate. Dict: once per distinct value, then a scan of the codes.
    pub fn count_where(&self, pred: impl Fn(&[u8]) -> bool) -> usize {
        let mut buf = vec![];
        match self {
            PackedStrs::Dict { pool, codes, len } => {
                let hit: Vec<u64> = (0..pool.len())
                    .map(|i| pred(pool.get(i, &mut buf)) as u64)
                    .collect();
                let mut c = 0u64;
                codes.for_each(*len, |k| c += hit[k as usize]);
                c as usize
            }
            PackedStrs::Direct { pool } => (0..pool.len())
                .filter(|&i| pred(pool.get(i, &mut buf)))
                .count(),
        }
    }
    pub fn select_where(&self, pred: impl Fn(&[u8]) -> bool, out: &mut Vec<u32>) {
        let mut buf = vec![];
        match self {
            PackedStrs::Dict { pool, codes, len } => {
                let hit: Vec<bool> = (0..pool.len())
                    .map(|i| pred(pool.get(i, &mut buf)))
                    .collect();
                let mut i = 0u32;
                codes.for_each(*len, |k| {
                    if hit[k as usize] {
                        out.push(i)
                    }
                    i += 1
                })
            }
            PackedStrs::Direct { pool } => {
                for i in 0..pool.len() {
                    if pred(pool.get(i, &mut buf)) {
                        out.push(i as u32)
                    }
                }
            }
        }
    }
    pub fn count_eq(&self, needle: &str) -> usize {
        match self {
            PackedStrs::Dict { .. } => self.count_where(|s| s == needle.as_bytes()),
            PackedStrs::Direct { pool } => pool.count_eq(needle.as_bytes()),
        }
    }
    /// GROUP BY value -> count. Dict: a histogram over codes; strings are never materialised per row.
    /// Calls `f(value, count)` for the groups of this column without allocating per value. A dictionary column reports each
    /// distinct value once; a direct column reports every row with a count of 1, leaving the merging to the caller.
    pub fn for_each_group(&self, mut f: impl FnMut(&[u8], usize)) {
        let mut b = vec![];
        match self {
            PackedStrs::Dict { pool, codes, len } => {
                let mut h = vec![0usize; pool.len()];
                codes.for_each(*len, |k| h[k as usize] += 1);
                for (i, c) in h.into_iter().enumerate().filter(|(_, c)| *c > 0) {
                    f(pool.get(i, &mut b), c)
                }
            }
            PackedStrs::Direct { pool } => {
                for i in 0..pool.len() {
                    f(pool.get(i, &mut b), 1)
                }
            }
        }
    }
    pub fn group_count(&self) -> Vec<(String, usize)> {
        match self {
            PackedStrs::Dict { pool, codes, len } => {
                let mut h = vec![0usize; pool.len()];
                codes.for_each(*len, |k| h[k as usize] += 1);
                let mut b = vec![];
                h.into_iter()
                    .enumerate()
                    .map(|(i, c)| (String::from_utf8_lossy(pool.get(i, &mut b)).into_owned(), c))
                    .collect()
            }
            PackedStrs::Direct { pool } => {
                let mut m: HashMap<Vec<u8>, usize> = HashMap::new();
                let mut b = vec![];
                for i in 0..pool.len() {
                    *m.entry(pool.get(i, &mut b).to_vec()).or_default() += 1
                }
                m.into_iter()
                    .map(|(k, c)| (String::from_utf8_lossy(&k).into_owned(), c))
                    .collect()
            }
        }
    }
}

use crate::wire::{R, Res, W, bad};

impl StrPool {
    fn write(&self, w: &mut W) {
        w.v_u8(&self.bytes);
        w.v_u32(&self.offs);
        w.u64(self.raw_bytes as u64);
        if let Some(z) = &self.z {
            w.u8(2);
            return z.write(w);
        }
        match &self.fsst {
            None => w.u8(0),
            Some(p) => {
                w.u8(1);
                w.u8(p.n_symbols);
                for s in &p.symbols {
                    w.u64_raw(s.to_u64())
                }
                w.raw(&p.lengths)
            }
        }
    }
    fn read(r: &mut R) -> Res<StrPool> {
        let (bytes, offs, raw_bytes) = (r.get_v_u8()?, r.get_v_u32()?, r.get_u64()? as usize);
        if offs.is_empty()
            || offs.windows(2).any(|p| p[0] > p[1])
            || *offs.last().unwrap() as usize > bytes.len()
        {
            return bad("string offsets");
        }
        let mut z = None;
        let fsst = match r.get_u8()? {
            0 => None,
            2 => {
                z = Some(Box::new(ZBlocks::read(r)?));
                None
            }
            1 => {
                let n_symbols = r.get_u8()?;
                let mut symbols = [fsst::Symbol::ZERO; 255];
                for s in &mut symbols {
                    *s = fsst::Symbol::from_slice(&r.get_u64_raw()?.to_le_bytes())
                }
                let lengths: [u8; 255] = r.take(255)?.try_into().unwrap();
                if lengths.iter().any(|&l| l > 8) {
                    return bad("symbol length");
                }
                Some(Box::new(CompressorParts {
                    symbols,
                    lengths,
                    n_symbols,
                }))
            }
            _ => return bad("string pool"),
        };
        Ok(StrPool {
            bytes,
            offs,
            fsst,
            raw_bytes,
            enc: std::sync::OnceLock::new(),
            z,
        })
    }
}

impl PackedStrs {
    pub(crate) fn write(&self, w: &mut W) {
        match self {
            PackedStrs::Dict { pool, codes, len } => {
                w.u8(0);
                pool.write(w);
                codes.write(w);
                w.u64(*len as u64)
            }
            PackedStrs::Direct { pool } => {
                w.u8(1);
                pool.write(w)
            }
        }
    }
    pub(crate) fn read(r: &mut R) -> Res<PackedStrs> {
        Ok(match r.get_u8()? {
            0 => PackedStrs::Dict {
                pool: StrPool::read(r)?,
                codes: Store::read(r)?,
                len: r.get_u64()? as usize,
            },
            1 => PackedStrs::Direct {
                pool: StrPool::read(r)?,
            },
            _ => return bad("string encoding"),
        })
    }
}