This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-12347-f9c8085476d0cdd77605d69d5114b2f98808106f in repository https://gitbox.apache.org/repos/asf/arrow-rs.git
commit bef1132ae8dd220acfe8487b5d2e8f9e9500a08c Author: Matt Butrovich <[email protected]> AuthorDate: Mon Nov 23 19:33:11 2026 +0000 feat: add `SetBitCounter` for counting set bits over many ranges of a bitmap (#12347) # Which issue does this PR close? - Closes #12346 # Rationale for this change The issue explains the problem. @neilconway wrote the DataFusion version in apache/datafusion#26507, which this follows. apache/datafusion#27598 and apache/datafusion-spark#379 track switching DataFusion and datafusion-spark to this counter. # What changes are included in this PR? New public items: - `arrow_buffer::bit_iterator::SetBitCounter`, with `new`, `count_before`, and `count_range` - `BooleanBuffer::set_bit_counter` Compared with the DataFusion version, the counter takes the bitmap instead of an iterator of words, steps back when a position decreases instead of looping forever, and panics on a position past the end. A call reads the words between the previous position and the new one, in either direction. Positions that jump across the bitmap, such as the rows of a list view in random order, cost the distance jumped, and the rustdoc points those callers to `count_set_bits_offset`. `BitChunkIterator` now overrides `Iterator::nth` to skip in constant time. The counter uses it to reposition after a step back. # Are these changes tested? - Unit tests in `arrow-buffer/src/util/bit_iterator.rs` compare every position in order and in reverse, and ranges in order and in random order, against a naive count, for lengths from 0 to 300 at byte-aligned and unaligned offsets. - Unit tests in the same file cover decreasing positions, including a step back followed by a read of the final partial word, and each panic. - `test_bit_chunk_iterator_nth` in `arrow-buffer/src/util/bit_chunk_iterator.rs` compares `nth` with the collected chunks from every start position, for skips up to past the end and for `usize::MAX`. - `SetBitCounter::new`, `SetBitCounter::count_before`, `SetBitCounter::count_range`, and `BooleanBuffer::set_bit_counter` have doctests. - The `set_bit_counter` benchmark in `arrow-buffer/benches` compares per-row `count_set_bits_offset` with the counter over 8192 rows, with rows visited in order, in reverse, and in random order. # Benchmark results The bot times both methods in the same run, and these are its times at this PR's head (654b9d2). The charts show the default-layout runs for rows in forward and reverse order. <img width="1600" height="2468" alt="set-bit-counter-bot-654b9d2-forward" src="https://github.com/user-attachments/assets/be5ff510-0873-4b99-b34c-78dcbfe23189" /> The one slower case in forward order is width 256 with constant lengths at offset 0 on baseline x86-64, which has no `POPCNT` instruction. There `u64::count_ones` compiles to shifts, masks, and a multiply. Each row is four 64-bit words starting on a word boundary, and `count_set_bits_offset` counts them in one iteration of an SSE2 loop. The counter counts each word separately, plus the masked word at the row's start and end, which holds no bits here. That is six scalar popcounts per row. Rows that don't all start on a word boundary, at offset 3 or with random lengths, are faster with the counter. Comet builds its amd64 release with [`-Ctarget-cpu=x86-64-v3`](https://github.com/apache/datafusion-comet/blob/d187e6823f9052e7331e8a810b08a1202debb91c/Makefile#L80-L81). <img width="1600" height="2468" alt="set-bit-counter-bot-654b9d2-reverse" src="https://github.com/user-attachments/assets/e397e144-c3a4-4ff8-8ab2-7fa2dd32059c" /> In reverse order the counter is slower at width 256, except with random lengths on x86-64-v3. For each row it steps back over two rows of words and forward over one, so it reads each word three times. With rows in shuffled order the counter is 11x to more than 1000x slower (0.00x to 0.09x), because each jump costs the distance jumped. The rustdoc sends these callers to `count_set_bits_offset`. The speedups in the aligned runs differ from the default runs by at most 16%, except `width_32/random/offset_0/forward` on Neoverse-V2 (3.34x default, 2.68x aligned) and `width_4/constant/offset_0/reverse` on x86-64-v3 (3.52x default, 4.08x aligned). <details><summary>Neoverse-V2</summary> Times in us from the [default](https://github.com/apache/arrow-rs/pull/12347#issuecomment-7051892186) and [aligned](https://github.com/apache/arrow-rs/pull/12347#issuecomment-7051892664) runs. | Case | `count_set_bits_offset` | `SetBitCounter` | Speedup | `count_set_bits_offset`, aligned | `SetBitCounter`, aligned | Speedup, aligned | |---|--:|--:|--:|--:|--:|--:| | `width_4/constant/offset_0/forward` | 85.5 | 17.3 | 4.94x | 89.7 | 17.1 | 5.25x | | `width_4/constant/offset_3/forward` | 85.5 | 17.6 | 4.86x | 89.6 | 17.4 | 5.15x | | `width_4/random/offset_0/forward` | 80.5 | 18.2 | 4.42x | 84.8 | 18.9 | 4.49x | | `width_4/random/offset_3/forward` | 80.6 | 18.3 | 4.40x | 84.8 | 19 | 4.46x | | `width_32/constant/offset_0/forward` | 85.4 | 21.2 | 4.03x | 89.7 | 21.1 | 4.25x | | `width_32/constant/offset_3/forward` | 85.5 | 24.1 | 3.55x | 89.7 | 24.1 | 3.72x | | `width_32/random/offset_0/forward` | 80.6 | 24.1 | 3.34x | 86 | 32.1 | 2.68x | | `width_32/random/offset_3/forward` | 80.4 | 27.3 | 2.95x | 86.5 | 31.6 | 2.74x | | `width_256/constant/offset_0/forward` | 50.5 | 43.6 | 1.16x | 50.7 | 41.3 | 1.23x | | `width_256/constant/offset_3/forward` | 109.6 | 52.7 | 2.08x | 109.7 | 52.3 | 2.10x | | `width_256/random/offset_0/forward` | 138.5 | 67.6 | 2.05x | 141 | 66.3 | 2.13x | | `width_256/random/offset_3/forward` | 138.2 | 78.6 | 1.76x | 140.7 | 78.8 | 1.79x | | `width_4/constant/offset_0/reverse` | 85.5 | 20.7 | 4.13x | 89.8 | 20.4 | 4.40x | | `width_4/constant/offset_3/reverse` | 85.5 | 21.9 | 3.90x | 89.9 | 21.8 | 4.12x | | `width_4/random/offset_0/reverse` | 80.6 | 21.8 | 3.70x | 84.8 | 20.8 | 4.08x | | `width_4/random/offset_3/reverse` | 80.5 | 22.5 | 3.58x | 84.8 | 23.1 | 3.67x | | `width_32/constant/offset_0/reverse` | 85.4 | 45.5 | 1.88x | 89.7 | 45.8 | 1.96x | | `width_32/constant/offset_3/reverse` | 85.5 | 54 | 1.58x | 89.6 | 54.2 | 1.65x | | `width_32/random/offset_0/reverse` | 80.5 | 50.7 | 1.59x | 85.9 | 48.9 | 1.76x | | `width_32/random/offset_3/reverse` | 80.5 | 55.6 | 1.45x | 86.3 | 57.8 | 1.49x | | `width_256/constant/offset_0/reverse` | 50.6 | 128.7 | 0.39x | 50.8 | 127.6 | 0.40x | | `width_256/constant/offset_3/reverse` | 109.4 | 167.5 | 0.65x | 109.4 | 167 | 0.66x | | `width_256/random/offset_0/reverse` | 138.3 | 157.7 | 0.88x | 141.1 | 155.7 | 0.91x | | `width_256/random/offset_3/reverse` | 138.2 | 191.2 | 0.72x | 140.6 | 197.1 | 0.71x | | `width_4/constant/offset_0/shuffled` | 85.5 | 1018 | 0.08x | 89.6 | 1018 | 0.09x | | `width_4/constant/offset_3/shuffled` | 85.5 | 1387 | 0.06x | 90 | 1390 | 0.06x | | `width_4/random/offset_0/shuffled` | 80.5 | 1026 | 0.08x | 84.6 | 1025 | 0.08x | | `width_4/random/offset_3/shuffled` | 80.5 | 1402 | 0.06x | 84.7 | 1397 | 0.06x | | `width_32/constant/offset_0/shuffled` | 85.5 | 7600 | 0.01x | 89.7 | 7600 | 0.01x | | `width_32/constant/offset_3/shuffled` | 85.5 | 10800 | 0.01x | 89.7 | 10500 | 0.01x | | `width_32/random/offset_0/shuffled` | 80.6 | 7800 | 0.01x | 86.3 | 7700 | 0.01x | | `width_32/random/offset_3/shuffled` | 80.6 | 10800 | 0.01x | 86.2 | 10800 | 0.01x | | `width_256/constant/offset_0/shuffled` | 54.3 | 60800 | 0.00x | 54.5 | 60200 | 0.00x | | `width_256/constant/offset_3/shuffled` | 109.4 | 83300 | 0.00x | 109.3 | 83700 | 0.00x | | `width_256/random/offset_0/shuffled` | 141.8 | 61600 | 0.00x | 144.3 | 60600 | 0.00x | | `width_256/random/offset_3/shuffled` | 142.3 | 84900 | 0.00x | 144.3 | 83700 | 0.00x | </details> <details><summary>Xeon Platinum 8581C</summary> Times in us from the [default](https://github.com/apache/arrow-rs/pull/12347#issuecomment-7051912316) and [aligned](https://github.com/apache/arrow-rs/pull/12347#issuecomment-7051912753) runs. | Case | `count_set_bits_offset` | `SetBitCounter` | Speedup | `count_set_bits_offset`, aligned | `SetBitCounter`, aligned | Speedup, aligned | |---|--:|--:|--:|--:|--:|--:| | `width_4/constant/offset_0/forward` | 85.9 | 32.4 | 2.65x | 83.6 | 34.8 | 2.40x | | `width_4/constant/offset_3/forward` | 89.3 | 32.7 | 2.73x | 85.7 | 35.5 | 2.41x | | `width_4/random/offset_0/forward` | 84.1 | 34.4 | 2.44x | 80.9 | 34.9 | 2.32x | | `width_4/random/offset_3/forward` | 84.2 | 35 | 2.41x | 81.6 | 35.3 | 2.31x | | `width_32/constant/offset_0/forward` | 86.5 | 36.7 | 2.36x | 84.2 | 35 | 2.41x | | `width_32/constant/offset_3/forward` | 92.9 | 38.8 | 2.39x | 88.1 | 37.3 | 2.36x | | `width_32/random/offset_0/forward` | 88.9 | 47.5 | 1.87x | 82.7 | 42.1 | 1.96x | | `width_32/random/offset_3/forward` | 88.6 | 49.7 | 1.78x | 82.9 | 46.2 | 1.79x | | `width_256/constant/offset_0/forward` | 52.5 | 72.5 | 0.72x | 47.3 | 64.8 | 0.73x | | `width_256/constant/offset_3/forward` | 116.7 | 86.8 | 1.34x | 109 | 84.5 | 1.29x | | `width_256/random/offset_0/forward` | 192 | 107.1 | 1.79x | 173.6 | 101 | 1.72x | | `width_256/random/offset_3/forward` | 190.8 | 127.5 | 1.50x | 173.6 | 124.4 | 1.40x | | `width_4/constant/offset_0/reverse` | 86.2 | 38.3 | 2.25x | 83.7 | 39.8 | 2.10x | | `width_4/constant/offset_3/reverse` | 89.9 | 38.9 | 2.31x | 85.7 | 41.3 | 2.08x | | `width_4/random/offset_0/reverse` | 84.3 | 41.1 | 2.05x | 80.6 | 39.5 | 2.04x | | `width_4/random/offset_3/reverse` | 85.1 | 41.4 | 2.06x | 81.4 | 41.1 | 1.98x | | `width_32/constant/offset_0/reverse` | 87 | 70.8 | 1.23x | 84.5 | 61.6 | 1.37x | | `width_32/constant/offset_3/reverse` | 93.4 | 76.1 | 1.23x | 88 | 69.6 | 1.26x | | `width_32/random/offset_0/reverse` | 88.9 | 76.5 | 1.16x | 82.6 | 67.7 | 1.22x | | `width_32/random/offset_3/reverse` | 88.9 | 88.2 | 1.01x | 83.2 | 75.1 | 1.11x | | `width_256/constant/offset_0/reverse` | 52.3 | 205.9 | 0.25x | 47.1 | 183.8 | 0.26x | | `width_256/constant/offset_3/reverse` | 117 | 254.8 | 0.46x | 108.2 | 239.5 | 0.45x | | `width_256/random/offset_0/reverse` | 198.9 | 256.9 | 0.77x | 181.4 | 222.1 | 0.82x | | `width_256/random/offset_3/reverse` | 200 | 303.6 | 0.66x | 181.9 | 279.6 | 0.65x | | `width_4/constant/offset_0/shuffled` | 86.9 | 2000 | 0.04x | 83.8 | 1690 | 0.05x | | `width_4/constant/offset_3/shuffled` | 94.3 | 2400 | 0.04x | 89.2 | 2200 | 0.04x | | `width_4/random/offset_0/shuffled` | 85.1 | 2000 | 0.04x | 80.9 | 1700 | 0.05x | | `width_4/random/offset_3/shuffled` | 84.8 | 2400 | 0.04x | 82.2 | 2200 | 0.04x | | `width_32/constant/offset_0/shuffled` | 87.4 | 15300 | 0.01x | 84.3 | 12800 | 0.01x | | `width_32/constant/offset_3/shuffled` | 92.8 | 17800 | 0.01x | 88.5 | 16800 | 0.01x | | `width_32/random/offset_0/shuffled` | 89.5 | 15600 | 0.01x | 83.6 | 13000 | 0.01x | | `width_32/random/offset_3/shuffled` | 88.6 | 18300 | 0.00x | 83.3 | 17100 | 0.00x | | `width_256/constant/offset_0/shuffled` | 53.8 | 122200 | 0.00x | 49.6 | 101600 | 0.00x | | `width_256/constant/offset_3/shuffled` | 117.9 | 140200 | 0.00x | 108.9 | 132100 | 0.00x | | `width_256/random/offset_0/shuffled` | 200.7 | 123000 | 0.00x | 183.3 | 101300 | 0.00x | | `width_256/random/offset_3/shuffled` | 201.9 | 141800 | 0.00x | 183.3 | 133600 | 0.00x | </details> <details><summary>Xeon Platinum 8581C, x86-64-v3</summary> Times in us from the [default](https://github.com/apache/arrow-rs/pull/12347#issuecomment-7051890012) and [aligned](https://github.com/apache/arrow-rs/pull/12347#issuecomment-7052371201) runs. | Case | `count_set_bits_offset` | `SetBitCounter` | Speedup | `count_set_bits_offset`, aligned | `SetBitCounter`, aligned | Speedup, aligned | |---|--:|--:|--:|--:|--:|--:| | `width_4/constant/offset_0/forward` | 84.5 | 20.6 | 4.10x | 83 | 18.9 | 4.39x | | `width_4/constant/offset_3/forward` | 86.7 | 18.6 | 4.66x | 86.7 | 19 | 4.56x | | `width_4/random/offset_0/forward` | 90 | 23.7 | 3.80x | 86.7 | 22.2 | 3.91x | | `width_4/random/offset_3/forward` | 88.9 | 23 | 3.87x | 86.8 | 21.8 | 3.98x | | `width_32/constant/offset_0/forward` | 83 | 25.4 | 3.27x | 83.6 | 25.3 | 3.30x | | `width_32/constant/offset_3/forward` | 86.8 | 23.9 | 3.63x | 85.3 | 23.8 | 3.58x | | `width_32/random/offset_0/forward` | 90.5 | 39.7 | 2.28x | 83 | 35.8 | 2.32x | | `width_32/random/offset_3/forward` | 91 | 38.9 | 2.34x | 86 | 36.2 | 2.38x | | `width_256/constant/offset_0/forward` | 56.3 | 44.8 | 1.26x | 59.3 | 48.1 | 1.23x | | `width_256/constant/offset_3/forward` | 97.2 | 46.4 | 2.09x | 95.3 | 47.3 | 2.01x | | `width_256/random/offset_0/forward` | 194.1 | 85.8 | 2.26x | 198.9 | 90.3 | 2.20x | | `width_256/random/offset_3/forward` | 202.9 | 90.9 | 2.23x | 196.5 | 92.9 | 2.12x | | `width_4/constant/offset_0/reverse` | 84.4 | 24 | 3.52x | 83.7 | 20.5 | 4.08x | | `width_4/constant/offset_3/reverse` | 86.3 | 24 | 3.60x | 86.3 | 21.6 | 4.00x | | `width_4/random/offset_0/reverse` | 89.9 | 29.5 | 3.05x | 87.2 | 27.8 | 3.14x | | `width_4/random/offset_3/reverse` | 88.5 | 29.8 | 2.97x | 86.2 | 29.7 | 2.90x | | `width_32/constant/offset_0/reverse` | 83 | 42.8 | 1.94x | 83.5 | 41.8 | 2.00x | | `width_32/constant/offset_3/reverse` | 87.1 | 49.8 | 1.75x | 83.9 | 47.8 | 1.76x | | `width_32/random/offset_0/reverse` | 91.2 | 62.1 | 1.47x | 84 | 56.3 | 1.49x | | `width_32/random/offset_3/reverse` | 91.7 | 70.7 | 1.30x | 87.2 | 69.4 | 1.26x | | `width_256/constant/offset_0/reverse` | 56.7 | 119.4 | 0.47x | 59.2 | 111.7 | 0.53x | | `width_256/constant/offset_3/reverse` | 97.1 | 148.3 | 0.65x | 95 | 148.8 | 0.64x | | `width_256/random/offset_0/reverse` | 211.8 | 172 | 1.23x | 210 | 174.4 | 1.20x | | `width_256/random/offset_3/reverse` | 216.5 | 210.3 | 1.03x | 207 | 204.9 | 1.01x | | `width_4/constant/offset_0/shuffled` | 84.7 | 1027 | 0.08x | 83.9 | 1016 | 0.08x | | `width_4/constant/offset_3/shuffled` | 98.3 | 1431 | 0.07x | 96.5 | 1412 | 0.07x | | `width_4/random/offset_0/shuffled` | 90 | 1019 | 0.09x | 87.4 | 1016 | 0.09x | | `width_4/random/offset_3/shuffled` | 90.3 | 1420 | 0.06x | 86.3 | 1403 | 0.06x | | `width_32/constant/offset_0/shuffled` | 83 | 7200 | 0.01x | 83.1 | 7300 | 0.01x | | `width_32/constant/offset_3/shuffled` | 87.4 | 10400 | 0.01x | 86.9 | 10300 | 0.01x | | `width_32/random/offset_0/shuffled` | 88.5 | 7300 | 0.01x | 85.7 | 7200 | 0.01x | | `width_32/random/offset_3/shuffled` | 90.1 | 10300 | 0.01x | 87.1 | 10500 | 0.01x | | `width_256/constant/offset_0/shuffled` | 57.1 | 56800 | 0.00x | 59.3 | 56200 | 0.00x | | `width_256/constant/offset_3/shuffled` | 96.9 | 79700 | 0.00x | 98 | 80200 | 0.00x | | `width_256/random/offset_0/shuffled` | 207.7 | 55100 | 0.00x | 210.1 | 56900 | 0.00x | | `width_256/random/offset_3/shuffled` | 208.7 | 80800 | 0.00x | 202.7 | 77400 | 0.00x | </details> # Are there any significant user-facing changes? No. The change only adds API. # AI usage disclosure I wrote this PR with help from Claude but understand and support the core approach, implementation, and test coverage. --- arrow-buffer/Cargo.toml | 4 + arrow-buffer/benches/set_bit_counter.rs | 83 +++++++ arrow-buffer/src/buffer/boolean.rs | 19 +- arrow-buffer/src/util/bit_chunk_iterator.rs | 30 +++ arrow-buffer/src/util/bit_iterator.rs | 338 +++++++++++++++++++++++++++- 5 files changed, 472 insertions(+), 2 deletions(-) diff --git a/arrow-buffer/Cargo.toml b/arrow-buffer/Cargo.toml index baa65a7bdb..cb2b5b8a82 100644 --- a/arrow-buffer/Cargo.toml +++ b/arrow-buffer/Cargo.toml @@ -55,6 +55,10 @@ harness = false name = "offset" harness = false +[[bench]] +name = "set_bit_counter" +harness = false + [[bench]] name = "mutable_buffer_repeat_slice" harness = false diff --git a/arrow-buffer/benches/set_bit_counter.rs b/arrow-buffer/benches/set_bit_counter.rs new file mode 100644 index 0000000000..19ff05b103 --- /dev/null +++ b/arrow-buffer/benches/set_bit_counter.rs @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership +// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements + +//! Counts the set bits in each row of a list's element bitmap, as a kernel +//! does to count the valid elements of each row. + +use arrow_buffer::{BooleanBuffer, OffsetBuffer}; +use criterion::*; +use rand::rngs::StdRng; +use rand::seq::SliceRandom; +use rand::{RngExt, SeedableRng}; +use std::hint; + +/// DataFusion's default batch size +const ROWS: usize = 8192; + +fn criterion_benchmark(c: &mut Criterion) { + let mut group = c.benchmark_group("set_bit_counter"); + for width in [4, 32, 256] { + // Constant row lengths, and random lengths with the same mean. + for (lengths_name, random_lengths) in [("constant", false), ("random", true)] { + // A byte-aligned bitmap, and one sliced to an unaligned offset. + for offset in [0, 3] { + // Rows in order, as in a list, and in reverse and random + // order, as in a list view. + for order in ["forward", "reverse", "shuffled"] { + let mut rng = StdRng::seed_from_u64(42); + let offsets = OffsetBuffer::<i32>::from_lengths((0..ROWS).map(|_| { + if random_lengths { + rng.random_range(0..=2 * width) + } else { + width + } + })); + let len = offsets.last() as usize; + let bits = (0..offset + len) + .map(|_| rng.random_bool(0.5)) + .collect::<BooleanBuffer>() + .slice(offset, len); + let mut ranges: Vec<_> = offsets + .windows(2) + .map(|w| w[0] as usize..w[1] as usize) + .collect(); + match order { + "reverse" => ranges.reverse(), + "shuffled" => ranges.shuffle(&mut rng), + _ => {} + } + let name = format!("width_{width}/{lengths_name}/offset_{offset}/{order}"); + + group.bench_function(format!("count_set_bits_offset/{name}"), |b| { + b.iter(|| { + let buffer = hint::black_box(&bits); + ranges + .iter() + .map(|r| { + buffer + .inner() + .count_set_bits_offset(buffer.offset() + r.start, r.len()) + }) + .sum::<usize>() + }) + }); + + group.bench_function(format!("set_bit_counter/{name}"), |b| { + b.iter(|| { + let mut counter = hint::black_box(&bits).set_bit_counter(); + ranges + .iter() + .map(|r| counter.count_range(r.clone())) + .sum::<usize>() + }) + }); + } + } + } + } + group.finish(); +} + +criterion_group!(benches, criterion_benchmark); +criterion_main!(benches); diff --git a/arrow-buffer/src/buffer/boolean.rs b/arrow-buffer/src/buffer/boolean.rs index a50feb1f0b..b955430fb0 100644 --- a/arrow-buffer/src/buffer/boolean.rs +++ b/arrow-buffer/src/buffer/boolean.rs @@ -3,7 +3,9 @@ // SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements use crate::bit_chunk_iterator::{BitChunks, UnalignedBitChunk}; -use crate::bit_iterator::{BitIndexIterator, BitIndexU32Iterator, BitIterator, BitSliceIterator}; +use crate::bit_iterator::{ + BitIndexIterator, BitIndexU32Iterator, BitIterator, BitSliceIterator, SetBitCounter, +}; use crate::bit_util::read_u64; use crate::{ BooleanBufferBuilder, Buffer, MutableBuffer, bit_util, buffer_bin_and, buffer_bin_or, @@ -77,6 +79,7 @@ use std::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, N /// /// # See Also /// * [`BooleanBufferBuilder`] for building [`BooleanBuffer`] instances +/// * [`Self::set_bit_counter`] for counting the set bits in many ranges of one buffer /// * [`NullBuffer`] for representing null values in Arrow arrays /// /// [`NullBuffer`]: crate::NullBuffer @@ -620,6 +623,20 @@ impl BooleanBuffer { BitSliceIterator::new(self.values(), self.bit_offset, self.bit_len) } + /// Returns a [`SetBitCounter`] that counts the set bits in ranges of this + /// [`BooleanBuffer`] + /// + /// ``` + /// # use arrow_buffer::BooleanBuffer; + /// let bits = BooleanBuffer::from(vec![true, false, true, true, false, true]); + /// let mut counter = bits.set_bit_counter(); + /// assert_eq!(counter.count_range(0..2), 1); + /// assert_eq!(counter.count_range(2..4), 2); + /// ``` + pub fn set_bit_counter(&self) -> SetBitCounter<'_> { + SetBitCounter::new(self.values(), self.bit_offset, self.bit_len) + } + /// Block size for chunked fold operations in [`Self::has_true`] and [`Self::has_false`]. /// Using `chunks_exact` with this size lets the compiler fully unroll the inner /// fold (no inner branch/loop), enabling short-circuit exits every N chunks. diff --git a/arrow-buffer/src/util/bit_chunk_iterator.rs b/arrow-buffer/src/util/bit_chunk_iterator.rs index ba55ce5cee..b0f9a43034 100644 --- a/arrow-buffer/src/util/bit_chunk_iterator.rs +++ b/arrow-buffer/src/util/bit_chunk_iterator.rs @@ -465,6 +465,12 @@ impl Iterator for BitChunkIterator<'_> { Some(combined) } + #[inline] + fn nth(&mut self, n: usize) -> Option<u64> { + self.index = self.index.saturating_add(n).min(self.chunk_len); + self.next() + } + #[inline] fn size_hint(&self) -> (usize, Option<usize>) { ( @@ -612,6 +618,30 @@ mod tests { } } + #[test] + fn test_bit_chunk_iterator_nth() { + let input: Vec<u8> = (0..26_u8).map(|i| i.wrapping_mul(13)).collect(); + let buffer = Buffer::from(input); + for offset in [0, 3] { + let chunks = buffer.bit_chunks(offset, 192); + let all: Vec<u64> = chunks.iter().collect(); + // From every position, skip to every chunk and one past the end + for start in 0..=all.len() { + for n in 0..=all.len() + 1 { + let mut iter = chunks.iter(); + iter.by_ref().take(start).for_each(drop); + assert_eq!(iter.nth(n), all.get(start + n).copied()); + assert_eq!(iter.len(), all.len().saturating_sub(start + n + 1)); + assert_eq!(iter.next(), all.get(start + n + 1).copied()); + } + } + let mut iter = chunks.iter(); + iter.next(); + assert_eq!(iter.nth(usize::MAX), None); + assert_eq!(iter.len(), 0); + } + } + #[test] #[should_panic(expected = "chunk index out of bounds")] fn test_chunk_out_of_bounds() { diff --git a/arrow-buffer/src/util/bit_iterator.rs b/arrow-buffer/src/util/bit_iterator.rs index 048dc90885..5876e7a132 100644 --- a/arrow-buffer/src/util/bit_iterator.rs +++ b/arrow-buffer/src/util/bit_iterator.rs @@ -4,8 +4,11 @@ //! Types for iterating over packed bitmasks -use crate::bit_chunk_iterator::{UnalignedBitChunk, UnalignedBitChunkIterator}; +use crate::bit_chunk_iterator::{ + BitChunkIterator, BitChunks, UnalignedBitChunk, UnalignedBitChunkIterator, +}; use crate::bit_util::{ceil, get_bit_raw}; +use std::ops::Range; /// Iterator over the bits within a packed bitmask /// @@ -363,6 +366,184 @@ impl Iterator for BitIndexU32Iterator<'_> { } } +/// Counts the set bits in ranges of a packed bitmask +/// +/// [`Self::count_range`] returns the number of set bits in a range, and +/// [`Self::count_before`] the number before a position. A result depends only +/// on the arguments, so calls can come in any order and repeat. +/// +/// # Example +/// ``` +/// # use arrow_buffer::BooleanBuffer; +/// let bits = BooleanBuffer::from(vec![true, false, true, true, false, true]); +/// let mut counter = bits.set_bit_counter(); +/// assert_eq!(counter.count_range(0..2), 1); +/// assert_eq!(counter.count_range(2..4), 2); +/// assert_eq!(counter.count_before(6), 4); +/// // Calls can go back, and a repeated call returns the same count +/// assert_eq!(counter.count_range(0..2), 1); +/// ``` +/// +/// # Performance +/// +/// The counter keeps the 64-bit word that holds the last position, and a call +/// reads the words between that position and the new one. When positions do +/// not decrease, as in a pass over the rows of a list, each word is read once, +/// and a call within the current word costs a mask and a popcount. Calling +/// [`Buffer::count_set_bits_offset`] for each range instead pays a setup cost on +/// every call, which dominates for short ranges. +/// +/// When positions jump across the bitmask, such as the rows of a list view in +/// random order, a call reads every word it jumps over. Calling +/// [`Buffer::count_set_bits_offset`] for each range is faster there. +/// +/// # Example: Count the valid elements of each row of a list +/// ``` +/// # use arrow_buffer::{BooleanBuffer, OffsetBuffer}; +/// // A list with rows of 3, 0, and 3 elements, and the validity of its elements +/// let offsets = OffsetBuffer::<i32>::from_lengths([3, 0, 3]); +/// let valid = BooleanBuffer::from(vec![true, false, true, true, false, true]); +/// +/// // One counter for all rows. The rows are visited in order, so each word of +/// // `valid` is read once. +/// let mut counter = valid.set_bit_counter(); +/// // Each pair of adjacent offsets is the start and end of a row +/// let valid_per_row: Vec<usize> = offsets +/// .windows(2) +/// .map(|w| counter.count_range(w[0] as usize..w[1] as usize)) +/// .collect(); +/// assert_eq!(valid_per_row, [2, 0, 2]); +/// ``` +/// +/// [`Buffer::count_set_bits_offset`]: crate::Buffer::count_set_bits_offset +#[derive(Debug)] +pub struct SetBitCounter<'a> { + chunks: BitChunks<'a>, + /// Yields the words after `word` + iter: BitChunkIterator<'a>, + /// The bitmask's final partial word, zero padded + remainder: u64, + /// The word containing the most recent position + word: u64, + /// Position of the first bit of `word` + word_start: usize, + /// Set bits before `word_start` + count_before_word: usize, + len: usize, +} + +impl<'a> SetBitCounter<'a> { + /// Create a new [`SetBitCounter`] from the provided `buffer`, + /// and `offset` and `len` in bits + /// + /// ``` + /// # use arrow_buffer::bit_iterator::SetBitCounter; + /// // Bits 3..9 of the buffer are 1, 0, 1, 1, 0, 1 + /// let mut counter = SetBitCounter::new(&[0b0110_1000, 0b0000_0001], 3, 6); + /// assert_eq!(counter.count_range(2..4), 2); + /// assert_eq!(counter.count_before(6), 4); + /// ``` + /// + /// # Panics + /// + /// Panics if `buffer` is too short for the provided offset and length + pub fn new(buffer: &'a [u8], offset: usize, len: usize) -> Self { + let chunks = BitChunks::new(buffer, offset, len); + let mut counter = Self { + iter: chunks.iter(), + remainder: chunks.remainder_bits(), + chunks, + word: 0, + word_start: 0, + count_before_word: 0, + len, + }; + counter.word = counter.next_word(); + counter + } + + #[inline] + fn next_word(&mut self) -> u64 { + self.iter.next().unwrap_or(self.remainder) + } + + // Cold and out of line because callers that pass positions in order never + // call it, and inlining would copy it into every caller of the inlined + // `count_before`. + #[cold] + fn step_back(&mut self, end: usize) { + while end < self.word_start { + self.word_start -= 64; + // A word before the current one is never the remainder + self.word = self.chunks.chunk(self.word_start / 64); + self.count_before_word -= self.word.count_ones() as usize; + } + // Leave `iter` after `word` + self.iter = self.chunks.iter(); + self.iter.nth(self.word_start / 64); + } + + /// Returns the number of set bits before position `end` + /// + /// ``` + /// # use arrow_buffer::BooleanBuffer; + /// let bits = BooleanBuffer::from(vec![true, false, true, true, false, true]); + /// let mut counter = bits.set_bit_counter(); + /// assert_eq!(counter.count_before(0), 0); + /// assert_eq!(counter.count_before(3), 2); + /// assert_eq!(counter.count_before(6), 4); + /// ``` + /// + /// # Panics + /// + /// Panics if `end` is greater than the length of the bitmask + #[inline] + pub fn count_before(&mut self, end: usize) -> usize { + assert!( + end <= self.len, + "position {end} out of bounds for length {}", + self.len + ); + if end < self.word_start { + self.step_back(end); + } + while end - self.word_start >= 64 { + self.count_before_word += self.word.count_ones() as usize; + self.word = self.next_word(); + self.word_start += 64; + } + let mask = (1u64 << (end - self.word_start)) - 1; + self.count_before_word + (self.word & mask).count_ones() as usize + } + + /// Returns the number of set bits in `range` + /// + /// ``` + /// # use arrow_buffer::BooleanBuffer; + /// let bits = BooleanBuffer::from(vec![true, false, true, true, false, true]); + /// let mut counter = bits.set_bit_counter(); + /// assert_eq!(counter.count_range(0..2), 1); + /// assert_eq!(counter.count_range(2..2), 0); + /// assert_eq!(counter.count_range(2..4), 2); + /// ``` + /// + /// # Panics + /// + /// Panics if `range.start` is greater than `range.end`, or if `range.end` + /// is greater than the length of the bitmask + #[inline] + pub fn count_range(&mut self, range: Range<usize>) -> usize { + assert!( + range.start <= range.end, + "range start {} is greater than end {}", + range.start, + range.end + ); + let before = self.count_before(range.start); + self.count_before(range.end) - before + } +} + /// Calls the provided closure for each index in the provided null mask that is set, /// using an adaptive strategy based on the null count /// @@ -989,4 +1170,159 @@ mod tests { }, ); } + + /// Sliced buffers covering empty, sub-word, exact-word, and multi-word + /// lengths at byte-aligned and unaligned offsets, with their bits. + fn set_bit_counter_cases() -> Vec<(BooleanBuffer, Vec<bool>)> { + let mut rng = StdRng::seed_from_u64(42); + let mut cases = vec![]; + for len in [0, 1, 63, 64, 65, 127, 128, 129, 300] { + for offset in [0, 1, 7, 8, 63, 64, 67] { + for density in [0.0, 0.5, 1.0] { + let bits = (0..offset + len) + .map(|_| rng.random_bool(density)) + .collect::<Vec<_>>(); + let buffer = BooleanBuffer::from(bits.as_slice()).slice(offset, len); + cases.push((buffer, bits[offset..].to_vec())); + } + } + } + cases + } + + fn count_set(bits: &[bool]) -> usize { + bits.iter().filter(|&&b| b).count() + } + + #[test] + fn test_set_bit_counter_every_position() { + for (buffer, bits) in set_bit_counter_cases() { + let mut counter = buffer.set_bit_counter(); + for end in 0..=bits.len() { + assert_eq!( + counter.count_before(end), + count_set(&bits[..end]), + "offset {} len {} end {end}", + buffer.offset(), + buffer.len() + ); + } + } + } + + #[test] + fn test_set_bit_counter_every_position_reversed() { + for (buffer, bits) in set_bit_counter_cases() { + let mut counter = buffer.set_bit_counter(); + for end in (0..=bits.len()).rev() { + assert_eq!( + counter.count_before(end), + count_set(&bits[..end]), + "offset {} len {} end {end}", + buffer.offset(), + buffer.len() + ); + } + } + } + + #[test] + fn test_set_bit_counter_shuffled_ranges() { + let mut rng = StdRng::seed_from_u64(42); + for (buffer, bits) in set_bit_counter_cases() { + let len = bits.len(); + let mut counter = buffer.set_bit_counter(); + for _ in 0..100 { + let start = rng.random_range(0..=len); + let end = rng.random_range(start..=len); + assert_eq!( + counter.count_range(start..end), + count_set(&bits[start..end]), + "offset {} len {len} range {start}..{end}", + buffer.offset() + ); + } + } + } + + #[test] + fn test_set_bit_counter_ranges() { + for (buffer, bits) in set_bit_counter_cases() { + let len = bits.len(); + // Empty, contiguous, and gapped ranges, some spanning several words. + let ranges = [ + (0, 0), + (0, len / 3), + (len / 3, len / 3), + (len / 3, len / 2), + (len / 2 + 1, len - len / 4), + (len, len), + ]; + let mut counter = buffer.set_bit_counter(); + for (start, end) in ranges { + let (start, end) = (start.min(len), end.min(len)); + assert_eq!( + counter.count_range(start..end), + count_set(&bits[start..end]), + "offset {} len {len} range {start}..{end}", + buffer.offset() + ); + } + } + } + + #[test] + fn test_set_bit_counter_decreasing_positions() { + let bits = (0..300).map(|i| i % 3 != 0).collect::<Vec<_>>(); + let buffer = BooleanBuffer::from(bits.as_slice()).slice(5, 290); + let bits = &bits[5..]; + let mut counter = buffer.set_bit_counter(); + // Back to an earlier word, back within the current word, then forward. + for end in [290, 130, 10, 129, 128, 70, 64, 0, 200, 290] { + assert_eq!( + counter.count_before(end), + count_set(&bits[..end]), + "end {end}" + ); + } + assert_eq!(counter.count_range(10..20), count_set(&bits[10..20])); + } + + #[test] + fn test_set_bit_counter_new() { + // Bits 3..9 of 0b1011_0101, 0b0000_0001 are 0, 1, 1, 0, 1, 1. + let mut counter = SetBitCounter::new(&[0b1011_0101, 0b0000_0001], 3, 6); + assert_eq!(counter.count_before(0), 0); + assert_eq!(counter.count_before(3), 2); + assert_eq!(counter.count_before(6), 4); + } + + #[test] + #[should_panic(expected = "position 4 out of bounds for length 3")] + fn test_set_bit_counter_out_of_bounds() { + let buffer = BooleanBuffer::from(&[true, false, true][..]); + buffer.set_bit_counter().count_before(4); + } + + #[test] + #[should_panic(expected = "position 1 out of bounds for length 0")] + fn test_set_bit_counter_empty_out_of_bounds() { + BooleanBuffer::new_unset(0) + .set_bit_counter() + .count_before(1); + } + + #[test] + #[should_panic(expected = "range start 3 is greater than end 2")] + #[expect(clippy::reversed_empty_ranges)] + fn test_set_bit_counter_reversed_range() { + let buffer = BooleanBuffer::new_set(10); + buffer.set_bit_counter().count_range(3..2); + } + + #[test] + #[should_panic(expected = "offset + len out of bounds")] + fn test_set_bit_counter_new_buffer_too_short() { + SetBitCounter::new(&[0xFF], 3, 6); + } }
