Skip to main content

parquet/arrow/buffer/
bit_util.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use arrow_buffer::bit_chunk_iterator::UnalignedBitChunk;
19use std::ops::Range;
20
21/// Counts the number of set bits in the provided range
22pub fn count_set_bits(bytes: &[u8], range: Range<usize>) -> usize {
23    let unaligned = UnalignedBitChunk::new(bytes, range.start, range.end - range.start);
24    unaligned.count_ones()
25}
26
27/// Iterates through the set bit positions in `bytes` in reverse order
28pub fn iter_set_bits_rev(bytes: &[u8]) -> impl Iterator<Item = usize> + '_ {
29    let bit_length = bytes.len() * 8;
30    let unaligned = UnalignedBitChunk::new(bytes, 0, bit_length);
31    let mut chunk_end_idx = bit_length + unaligned.lead_padding() + unaligned.trailing_padding();
32
33    let iter = unaligned
34        .prefix()
35        .into_iter()
36        .chain(unaligned.chunks().iter().cloned())
37        .chain(unaligned.suffix());
38
39    iter.rev().flat_map(move |chunk| {
40        let chunk_idx = chunk_end_idx - 64;
41        chunk_end_idx = chunk_idx;
42        let mut rev_chunk = chunk.reverse_bits();
43        std::iter::from_fn(move || {
44            if rev_chunk != 0 {
45                let bit_pos = rev_chunk.trailing_zeros();
46                rev_chunk &= rev_chunk - 1;
47                return Some(chunk_idx + (63 - bit_pos as usize));
48            }
49            None
50        })
51    })
52}
53
54/// Performs big endian sign extension
55pub fn sign_extend_be<const N: usize>(b: &[u8]) -> [u8; N] {
56    assert!(b.len() <= N, "Array too large, expected less than {N}");
57    let is_negative = (b[0] & 128u8) == 128u8;
58    let mut result = if is_negative { [255u8; N] } else { [0u8; N] };
59    for (d, s) in result.iter_mut().skip(N - b.len()).zip(b) {
60        *d = *s;
61    }
62    result
63}
64
65#[cfg(test)]
66mod tests {
67    use super::*;
68    use arrow_array::builder::BooleanBufferBuilder;
69    use rand::{prelude::*, rng};
70
71    #[test]
72    fn test_bit_fns() {
73        let mut rng = rng();
74        let mask_length = rng.random_range(1..1024);
75        let bools: Vec<_> = std::iter::from_fn(|| Some(rng.next_u32() & 1 == 0))
76            .take(mask_length)
77            .collect();
78
79        let mut nulls = BooleanBufferBuilder::new(mask_length);
80        bools.iter().for_each(|b| nulls.append(*b));
81
82        let actual: Vec<_> = iter_set_bits_rev(nulls.as_slice()).collect();
83        let expected: Vec<_> = bools
84            .iter()
85            .enumerate()
86            .rev()
87            .filter_map(|(x, y)| y.then_some(x))
88            .collect();
89        assert_eq!(actual, expected);
90
91        assert_eq!(iter_set_bits_rev(&[]).count(), 0);
92        assert_eq!(count_set_bits(&[], 0..0), 0);
93        assert_eq!(count_set_bits(&[0xFF], 1..1), 0);
94
95        for _ in 0..20 {
96            let start = rng.random_range(0..bools.len());
97            let end = rng.random_range(start..bools.len());
98
99            let actual = count_set_bits(nulls.as_slice(), start..end);
100            let expected = bools[start..end].iter().filter(|x| **x).count();
101
102            assert_eq!(actual, expected);
103        }
104    }
105}