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.
1718use arrow_buffer::bit_chunk_iterator::UnalignedBitChunk;
19use std::ops::Range;
2021/// Counts the number of set bits in the provided range
22pub fn count_set_bits(bytes: &[u8], range: Range<usize>) -> usize {
23let unaligned = UnalignedBitChunk::new(bytes, range.start, range.end - range.start);
24 unaligned.count_ones()
25}
2627/// Iterates through the set bit positions in `bytes` in reverse order
28pub fn iter_set_bits_rev(bytes: &[u8]) -> impl Iterator<Item = usize> + '_ {
29let bit_length = bytes.len() * 8;
30let unaligned = UnalignedBitChunk::new(bytes, 0, bit_length);
31let mut chunk_end_idx = bit_length + unaligned.lead_padding() + unaligned.trailing_padding();
3233let iter = unaligned
34 .prefix()
35 .into_iter()
36 .chain(unaligned.chunks().iter().cloned())
37 .chain(unaligned.suffix());
3839 iter.rev().flat_map(move |mut chunk| {
40let chunk_idx = chunk_end_idx - 64;
41 chunk_end_idx = chunk_idx;
42 std::iter::from_fn(move || {
43if chunk != 0 {
44let bit_pos = 63 - chunk.leading_zeros();
45 chunk ^= 1 << bit_pos;
46return Some(chunk_idx + (bit_pos as usize));
47 }
48None
49})
50 })
51}
5253/// Performs big endian sign extension
54pub fn sign_extend_be<const N: usize>(b: &[u8]) -> [u8; N] {
55assert!(b.len() <= N, "Array too large, expected less than {N}");
56let is_negative = (b[0] & 128u8) == 128u8;
57let mut result = if is_negative { [255u8; N] } else { [0u8; N] };
58for (d, s) in result.iter_mut().skip(N - b.len()).zip(b) {
59*d = *s;
60 }
61 result
62}
6364#[cfg(test)]
65mod tests {
66use super::*;
67use arrow_array::builder::BooleanBufferBuilder;
68use rand::prelude::*;
6970#[test]
71fn test_bit_fns() {
72let mut rng = thread_rng();
73let mask_length = rng.gen_range(1..1024);
74let bools: Vec<_> = std::iter::from_fn(|| Some(rng.next_u32() & 1 == 0))
75 .take(mask_length)
76 .collect();
7778let mut nulls = BooleanBufferBuilder::new(mask_length);
79 bools.iter().for_each(|b| nulls.append(*b));
8081let actual: Vec<_> = iter_set_bits_rev(nulls.as_slice()).collect();
82let expected: Vec<_> = bools
83 .iter()
84 .enumerate()
85 .rev()
86 .filter_map(|(x, y)| y.then_some(x))
87 .collect();
88assert_eq!(actual, expected);
8990assert_eq!(iter_set_bits_rev(&[]).count(), 0);
91assert_eq!(count_set_bits(&[], 0..0), 0);
92assert_eq!(count_set_bits(&[0xFF], 1..1), 0);
9394for _ in 0..20 {
95let start = rng.gen_range(0..bools.len());
96let end = rng.gen_range(start..bools.len());
9798let actual = count_set_bits(nulls.as_slice(), start..end);
99let expected = bools[start..end].iter().filter(|x| **x).count();
100101assert_eq!(actual, expected);
102 }
103 }
104}