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 |mut chunk| {
40        let chunk_idx = chunk_end_idx - 64;
41        chunk_end_idx = chunk_idx;
42        std::iter::from_fn(move || {
43            if chunk != 0 {
44                let bit_pos = 63 - chunk.leading_zeros();
45                chunk ^= 1 << bit_pos;
46                return Some(chunk_idx + (bit_pos as usize));
47            }
48            None
49        })
50    })
51}
52
53/// Performs big endian sign extension
54pub fn sign_extend_be<const N: usize>(b: &[u8]) -> [u8; N] {
55    assert!(b.len() <= N, "Array too large, expected less than {N}");
56    let is_negative = (b[0] & 128u8) == 128u8;
57    let mut result = if is_negative { [255u8; N] } else { [0u8; N] };
58    for (d, s) in result.iter_mut().skip(N - b.len()).zip(b) {
59        *d = *s;
60    }
61    result
62}
63
64#[cfg(test)]
65mod tests {
66    use super::*;
67    use arrow_array::builder::BooleanBufferBuilder;
68    use rand::prelude::*;
69
70    #[test]
71    fn test_bit_fns() {
72        let mut rng = thread_rng();
73        let mask_length = rng.gen_range(1..1024);
74        let bools: Vec<_> = std::iter::from_fn(|| Some(rng.next_u32() & 1 == 0))
75            .take(mask_length)
76            .collect();
77
78        let mut nulls = BooleanBufferBuilder::new(mask_length);
79        bools.iter().for_each(|b| nulls.append(*b));
80
81        let actual: Vec<_> = iter_set_bits_rev(nulls.as_slice()).collect();
82        let expected: Vec<_> = bools
83            .iter()
84            .enumerate()
85            .rev()
86            .filter_map(|(x, y)| y.then_some(x))
87            .collect();
88        assert_eq!(actual, expected);
89
90        assert_eq!(iter_set_bits_rev(&[]).count(), 0);
91        assert_eq!(count_set_bits(&[], 0..0), 0);
92        assert_eq!(count_set_bits(&[0xFF], 1..1), 0);
93
94        for _ in 0..20 {
95            let start = rng.gen_range(0..bools.len());
96            let end = rng.gen_range(start..bools.len());
97
98            let actual = count_set_bits(nulls.as_slice(), start..end);
99            let expected = bools[start..end].iter().filter(|x| **x).count();
100
101            assert_eq!(actual, expected);
102        }
103    }
104}