vortex-buffer 0.94.0

A byte buffer implementation for Vortex
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
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors

//! Filtering of fixed-width values by a [`Selection`].
//!
//! [`filter_buffer`] filters values that are already in memory, and [`filter_chunked`] filters
//! values that a [`ChunkDecoder`] decodes one chunk at a time. Both work for any `T: Copy` and
//! share one strategy ladder. [`filter_records`] filters records whose byte width is known only
//! at run time, and uses [`filter_buffer`] for power-of-two widths. The first matching row wins:
//!
//! | Priority | Selection or condition                              | Out-of-place   | In-place      |
//! | -------- | --------------------------------------------------- | -------------- | ------------- |
//! | 1        | slices                                              | copy runs      | move runs     |
//! | 2        | indices                                             | gather indices | move indices  |
//! | 3        | bitmap, an eligible architecture kernel             | SIMD compress  | SIMD compress |
//! | 4        | bitmap, density reaches the byte compress threshold | byte compress  | bitmap walk   |
//! | 5        | bitmap, runs average at least 8 values and 96 bytes | copy runs      | bitmap walk   |
//! | 6        | bitmap, otherwise                                   | bitmap walk    | bitmap walk   |
//!
//! [`append_filtered`] appends to an existing buffer with the out-of-place column. Before row 3,
//! it copies bitmap selections of values of at least 16 bytes at density >= 0.50 without branches.
//!
//! Row 5 counts the runs of the first 256 words that have a set bit, unless the runs of the
//! whole bitmap are already too many before then.
//!
//! [`filter_buffer`] compacts in place only a uniquely owned buffer with density >= 0.50.
//! [`filter_chunked`] applies the ladder to each chunk that it decodes, at the density of that
//! chunk. SIMD eligibility is summarized in the `simd` module.

use std::mem::MaybeUninit;

use crate::BitBuffer;
use crate::Buffer;
use crate::BufferAllocatorRef;
use crate::BufferMut;

mod bits;
mod byte_compress;
mod chunked;
mod records;
mod scalar;
mod simd;
#[cfg(test)]
mod tests;

use bits::MaskBits;
pub use chunked::ChunkDecoder;
pub use chunked::FILTER_CHUNK_LEN;
pub use chunked::filter_chunked;
pub use records::filter_records;

const IN_PLACE_MIN_DENSITY: f64 = 0.5;

/// Bitmaps without a SIMD kernel whose runs of selected values average at least this many bytes,
/// and at least [`MIN_RUN_LEN`] values, copy each run.
const MIN_RUN_BYTES: usize = 96;

/// The smallest average run length, in values, for which a bitmap copies each run. Random masks
/// of wide values reach [`MIN_RUN_BYTES`] with runs of only a few values, and the bitmap walk is
/// faster for those.
const MIN_RUN_LEN: usize = 8;

/// The number of words with a set bit from which [`has_long_runs`] decides, when the runs of the
/// whole bitmap do not rule out long runs first. Both walks give the same result, so a sample
/// that is not typical of the bitmap costs speed only.
const RUN_SAMPLE_WORDS: usize = 256;

/// When [`append_filtered`] filters values of at least [`BRANCHLESS_MIN_WIDTH`] bytes by a bitmap
/// at this density or above, copying every value without branches is faster than the byte
/// compress and bitmap walks.
const BRANCHLESS_MIN_DENSITY: f64 = 0.5;

/// The smallest value width, in bytes, for which [`append_filtered`] can copy without branches.
/// No SIMD kernel exists for values of this width.
const BRANCHLESS_MIN_WIDTH: usize = 16;

/// The positions that a filter keeps, out of `len` positions.
///
/// A selection holds one representation of the positions. The caller chooses the
/// representation, because the cost to make one from another is higher than the cost to filter.
#[derive(Clone, Copy)]
pub struct Selection<'a> {
    len: usize,
    true_count: usize,
    repr: Repr<'a>,
}

#[derive(Clone, Copy)]
enum Repr<'a> {
    Bitmap(&'a BitBuffer),
    Indices(&'a [usize]),
    Slices(&'a [(usize, usize)]),
}

impl<'a> Selection<'a> {
    /// Selects the set bits of `bits`.
    ///
    /// # Safety
    ///
    /// `true_count` must equal the number of set bits in `bits`.
    pub unsafe fn from_bitmap_unchecked(bits: &'a BitBuffer, true_count: usize) -> Self {
        debug_assert_eq!(bits.true_count(), true_count);

        Self {
            len: bits.len(),
            true_count,
            repr: Repr::Bitmap(bits),
        }
    }

    /// Selects the positions in `indices`, out of `len` positions.
    ///
    /// # Safety
    ///
    /// `indices` must be strictly increasing, and each index must be less than `len`.
    pub unsafe fn from_indices_unchecked(len: usize, indices: &'a [usize]) -> Self {
        debug_assert!(indices.is_sorted_by(|a, b| a < b));
        debug_assert!(indices.last().is_none_or(|&last| last < len));

        Self {
            len,
            true_count: indices.len(),
            repr: Repr::Indices(indices),
        }
    }

    /// Selects the positions in the `(start, end)` ranges of `slices`, out of `len` positions.
    ///
    /// # Safety
    ///
    /// The ranges must be sorted and disjoint, each `start` must not be more than its `end`, the
    /// last `end` must not be more than `len`, and `true_count` must equal the total length of
    /// the ranges.
    pub unsafe fn from_slices_unchecked(
        len: usize,
        slices: &'a [(usize, usize)],
        true_count: usize,
    ) -> Self {
        debug_assert!(slices.iter().all(|&(start, end)| start <= end));
        debug_assert!(slices.is_sorted_by(|a, b| a.1 <= b.0));
        debug_assert!(slices.last().is_none_or(|&(_, end)| end <= len));
        debug_assert_eq!(
            slices.iter().map(|(start, end)| end - start).sum::<usize>(),
            true_count
        );

        Self {
            len,
            true_count,
            repr: Repr::Slices(slices),
        }
    }

    /// Returns the number of positions that the selection keeps or drops.
    pub fn len(&self) -> usize {
        self.len
    }

    /// Returns whether the selection has no positions.
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Returns the number of positions that the selection keeps.
    pub fn true_count(&self) -> usize {
        self.true_count
    }

    fn density(&self) -> f64 {
        if self.len == 0 {
            return 0.0;
        }

        self.true_count as f64 / self.len as f64
    }
}

/// Filters `buffer` by `selection` and returns the selected values.
///
/// A uniquely owned buffer with density of at least 0.50 is compacted in place. Other buffers
/// are copied to a new allocation from `allocator`.
///
/// # Panics
///
/// Panics if `buffer` and `selection` have different lengths.
pub fn filter_buffer<T: Copy>(
    buffer: Buffer<T>,
    selection: Selection<'_>,
    allocator: &BufferAllocatorRef,
) -> Buffer<T> {
    assert_eq!(
        buffer.len(),
        selection.len(),
        "Selection length must equal the buffer length"
    );

    let buffer = if selection.density() >= IN_PLACE_MIN_DENSITY {
        match buffer.try_into_mut() {
            Ok(mut buffer_mut) => {
                let new_len = filter_slice_in_place(buffer_mut.as_mut_slice(), selection);
                buffer_mut.truncate(new_len);
                return buffer_mut.freeze();
            }
            Err(buffer) => buffer,
        }
    } else {
        buffer
    };

    filter_slice(buffer.as_slice(), selection, allocator)
}

/// Appends the values of `values` that `selection` keeps to the end of `out`.
///
/// This uses the out-of-place strategies of [`filter_buffer`], with one addition: a bitmap
/// selection of values of at least 16 bytes at density >= 0.50 copies every value without
/// branches and advances the output only past the selected values.
///
/// # Panics
///
/// Panics if `values` and `selection` have different lengths.
pub fn append_filtered<T: Copy>(values: &[T], selection: Selection<'_>, out: &mut BufferMut<T>) {
    assert_eq!(
        values.len(),
        selection.len(),
        "Selection length must equal the values length"
    );

    let start = out.len();
    let true_count = selection.true_count();
    // The SIMD kernels can store one vector past the last value that they write, and the
    // branchless copy stores one value past it.
    out.reserve(true_count + (simd::SLACK_BYTES / size_of::<T>()).max(1));
    let dst = out.spare_capacity_mut();

    let written = match selection.repr {
        Repr::Slices(slices) => scalar::copy_slices(values, slices, dst),
        Repr::Indices(indices) => {
            // SAFETY: the selection guarantees that each index is less than `values.len()`.
            unsafe { scalar::gather_indices(values, indices, dst) };
            indices.len()
        }
        Repr::Bitmap(bits) => {
            let bits = MaskBits::Bitmap(bits);

            // SAFETY: the bitmap has one bit for each value, and the output has room for every
            // selected value plus the slack, which is at least one value.
            unsafe {
                if size_of::<T>() >= BRANCHLESS_MIN_WIDTH
                    && selection.density() >= BRANCHLESS_MIN_DENSITY
                {
                    scalar::compact_branchless(values, bits, dst)
                } else {
                    compact_bits(values, bits, true_count, dst)
                }
            }
        }
    };

    assert_eq!(written, true_count);
    // SAFETY: the strategy above initialized the `true_count` values after `start`.
    unsafe { out.set_len(start + true_count) };
}

/// Copies the values of `values` that `selection` keeps to a new buffer.
fn filter_slice<T: Copy>(
    values: &[T],
    selection: Selection<'_>,
    allocator: &BufferAllocatorRef,
) -> Buffer<T> {
    debug_assert_eq!(values.len(), selection.len());

    let true_count = selection.true_count();
    // The SIMD kernels can store one vector past the last value that they write.
    let mut out = BufferMut::<T>::with_capacity_in(
        true_count + simd::SLACK_BYTES / size_of::<T>(),
        allocator.clone(),
    );
    let dst = out.spare_capacity_mut();

    let written = match selection.repr {
        Repr::Slices(slices) => scalar::copy_slices(values, slices, dst),
        Repr::Indices(indices) => {
            // SAFETY: the selection guarantees that each index is less than `values.len()`.
            unsafe { scalar::gather_indices(values, indices, dst) };
            indices.len()
        }
        // SAFETY: the bitmap has one bit for each value, and the output has room for every
        // selected value plus the slack.
        Repr::Bitmap(bits) => unsafe {
            compact_bits(values, MaskBits::Bitmap(bits), true_count, dst)
        },
    };

    debug_assert_eq!(written, true_count);
    // SAFETY: the strategy above initialized the first `true_count` values.
    unsafe { out.set_len(true_count) };
    out.freeze()
}

/// Compacts the values of `values` that `selection` keeps to its front, and returns the new
/// length.
fn filter_slice_in_place<T: Copy>(values: &mut [T], selection: Selection<'_>) -> usize {
    debug_assert_eq!(values.len(), selection.len());

    let written = match selection.repr {
        Repr::Slices(slices) => scalar::compact_in_place_by_slices(values, slices),
        // SAFETY: the selection guarantees that each index is less than `values.len()`.
        Repr::Indices(indices) => unsafe { scalar::compact_in_place_by_indices(values, indices) },
        Repr::Bitmap(bits) => {
            let bits = MaskBits::Bitmap(bits);
            // SAFETY: the bitmap has one bit for each value.
            unsafe { simd::compress_in_place(values, bits, selection.density()) }
                .unwrap_or_else(|| scalar::compact_in_place_by_bitmap(values, bits))
        }
    };

    debug_assert_eq!(written, selection.true_count());
    written
}

/// Copies the `selected` values of `src` that `bits` selects to `dst` and returns the number
/// copied.
///
/// This is rows 3 to 6 of the [module](self) ladder: the SIMD kernel for the density, if any.
/// Otherwise, a density at or above the byte compress threshold uses byte compress, long runs
/// of set bits are copied run by run, and shorter runs use the bitmap walk.
///
/// # Safety
///
/// `bits` must select only values of `src`, and `dst` must hold every selected value plus
/// [`SLACK_BYTES`](simd::SLACK_BYTES).
unsafe fn compact_bits<T: Copy>(
    src: &[T],
    bits: MaskBits<'_>,
    selected: usize,
    dst: &mut [MaybeUninit<T>],
) -> usize {
    let density = if src.is_empty() {
        0.0
    } else {
        selected as f64 / src.len() as f64
    };

    // SAFETY: forwarded from the caller contract.
    unsafe {
        if let Some(written) = simd::compress(src, bits, density, dst) {
            written
        } else if density >= byte_compress_density_threshold::<T>() {
            byte_compress::compress(src, bits, dst)
        } else if has_long_runs::<T>(bits, selected) {
            scalar::compact_runs_by_bitmap(src, bits, dst)
        } else {
            scalar::compact_by_bitmap(src, bits, dst)
        }
    }
}

/// Returns whether the runs of the `selected` set bits of `bits` average at least
/// [`MIN_RUN_LEN`] values and [`MIN_RUN_BYTES`] of `T`.
///
/// The answer comes from the first [`RUN_SAMPLE_WORDS`] words that have a set bit, unless the
/// runs of the whole bitmap are already too many before then.
// Inlining this check into `compact_bits` makes the bit walk up to 1.3x slower on x86-64.
#[inline(never)]
fn has_long_runs<T>(bits: MaskBits<'_>, selected: usize) -> bool {
    // The run walk copies at most one word of values at a time, so narrow values never qualify.
    if 64 * size_of::<T>() < MIN_RUN_BYTES {
        return false;
    }

    // A run that crosses a word boundary counts once in each word, as the run walk copies it. The
    // count stops at the first word that takes it past the limit for the whole bitmap, because a
    // popcount is not a native instruction on baseline x86-64.
    //
    // A bitmap with long runs has few runs, so that limit is never reached. The count then stops
    // after a sample of words and compares the runs of the sample with the selected values of the
    // sample. Empty words are skipped and full words skip the popcounts.
    let max_runs = max_long_runs::<T>(selected);
    let mut runs = 0;
    let mut sample_selected = 0;
    let mut sample_words = 0;

    let visited_all = bits::all_set_mask_words(bits, |word| {
        let (word_runs, word_selected) = match word {
            u64::MAX => (1, 64),
            _ => (
                (word & !(word << 1)).count_ones() as usize,
                word.count_ones() as usize,
            ),
        };
        runs += word_runs;
        sample_selected += word_selected;
        sample_words += 1;

        runs <= max_runs && sample_words < RUN_SAMPLE_WORDS
    });

    visited_all || (runs <= max_runs && runs <= max_long_runs::<T>(sample_selected))
}

/// Returns the most runs that `selected` values of `T` can form while the runs still average at
/// least [`MIN_RUN_LEN`] values and [`MIN_RUN_BYTES`].
fn max_long_runs<T>(selected: usize) -> usize {
    (selected * size_of::<T>() / MIN_RUN_BYTES).min(selected / MIN_RUN_LEN)
}

/// Returns the density at or above which byte compress is used after the higher-priority
/// strategies have declined the bitmap.
fn byte_compress_density_threshold<T>() -> f64 {
    let width = size_of::<T>();

    // These crossovers are benchmarked in `vortex-array/benches/filter_fixed_width.rs`.
    //
    // | Target  | 1 byte | 2 bytes | 4 bytes | 8 bytes | other |
    // | ------- | -----: | ------: | ------: | ------: | ----: |
    // | aarch64 |   0.90 |    0.90 |    0.90 |    0.75 |  0.90 |
    // | other   |   0.00 |    0.50 |    0.50 |    0.75 | 0.875 |
    if cfg!(target_arch = "aarch64") {
        return match width {
            8 => 0.75,
            _ => 0.9,
        };
    }

    match width {
        1 => 0.0,
        2 | 4 => 0.5,
        8 => 0.75,
        _ => 0.875,
    }
}