jorgecarleitao commented on a change in pull request #8664:
URL: https://github.com/apache/arrow/pull/8664#discussion_r530331929



##########
File path: rust/arrow/src/util/bit_ops.rs
##########
@@ -0,0 +1,588 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use crate::buffer::Buffer;
+
+use bitvec::prelude::*;
+use bitvec::slice::ChunksExact;
+
+use rayon::iter::plumbing::*;
+use rayon::prelude::*;
+use std::fmt::Debug;
+use std::marker::PhantomData as marker;
+
+///
+/// Immutable bit slice view of `Buffer` data.
+///
+/// `BufferBitSlice` does not own any underlying data, but rather wraps 
references
+/// to the underlying data in a `Buffer` and has methods for addressing and 
interacting with
+/// individual bits
+#[derive(Debug)]
+pub struct BufferBitSlice<'a> {
+    bit_slice: &'a BitSlice<LocalBits, u8>,
+}
+
+impl<'a> BufferBitSlice<'a> {
+    ///
+    /// Creates a immutable bit slice over the given data
+    #[inline]
+    pub fn new(buffer_data: &'a [u8]) -> Self {
+        let bit_slice = BitSlice::<LocalBits, 
_>::from_slice(buffer_data).unwrap();
+
+        BufferBitSlice {
+            bit_slice: &bit_slice,
+        }
+    }
+
+    ///
+    /// Returns immutable view with the given offset in bits and length in 
bits.
+    /// This view have zero-copy representation over the actual data.
+    #[inline]
+    pub fn slicing(&self, offset_in_bits: usize, len_in_bits: usize) -> Self {
+        Self {
+            bit_slice: &self.bit_slice[offset_in_bits..offset_in_bits + 
len_in_bits],
+        }
+    }
+
+    ///
+    /// Returns bit chunks in given byte width.
+    /// This can be u64(native Arrow byte representation size) or any other 
unsigned primitive like:
+    /// u8, u16, u32, u128 and usize.
+    ///
+    /// This method is generic over the given primitives to enable user to 
filter out
+    /// any upper/lower nibble/s which is not used like:
+    ///
+    /// # Example
+    ///
+    /// ```
+    /// # use arrow::buffer::Buffer;
+    /// let input: &[u8] = &[
+    ///     0b11111111, 0b00000000, 0b11111111, 0b00000000,
+    ///     0b11111111, 0b00000000, 0b11111111, 0b00000000,
+    /// ];
+    ///
+    /// let buffer: Buffer = Buffer::from(input);
+    /// let bit_slice = buffer.bit_slice();
+    /// // Interpret bit slice as u8
+    /// let chunks = bit_slice.chunks::<u8>();
+    ///
+    /// // Filter out null bytes for compression
+    /// let bytes = chunks.into_native_iter().filter(|e| *e != 
0x00_u8).collect::<Vec<u8>>();
+    /// assert_eq!(bytes.len(), 4);
+    /// ```
+    /// Native representations in Arrow follows 64-bit convention.
+    /// Chunks can still be reinterpreted in any primitive type lower than u64.
+    #[inline]
+    pub fn chunks<T>(&self) -> BufferBitChunksExact<T>
+    where
+        T: BitMemory,
+    {
+        let offset_size_in_bits = 8 * std::mem::size_of::<T>();
+        let chunks_exact = self.bit_slice.chunks_exact(offset_size_in_bits);
+        let remainder_bits = chunks_exact.remainder();
+        let remainder: T = if remainder_bits.is_empty() {
+            T::default()
+        } else {
+            remainder_bits.load::<T>()
+        };
+        BufferBitChunksExact {
+            chunks_exact,
+            remainder,
+            remainder_len_in_bits: remainder_bits.len(),
+        }
+    }
+
+    #[inline]
+    pub fn par_chunks<T>(&self) -> ParallelChunksExact<T>
+    where
+        T: BitMemory,
+    {
+        let offset_size_in_bits = 8 * std::mem::size_of::<T>();
+        let chunks_exact = self.bit_slice.chunks_exact(offset_size_in_bits);
+        let remainder_bits = chunks_exact.remainder();
+        let remainder: T = if remainder_bits.is_empty() {
+            T::default()
+        } else {
+            remainder_bits.load::<T>()
+        };
+        ParallelChunksExact {
+            bit_slice: self.bit_slice,
+            chunk_size: offset_size_in_bits,
+            remainder,
+            remainder_len_in_bits: remainder_bits.len(),
+        }
+    }
+
+    ///
+    /// Converts the bit view into a Buffer.
+    /// Buffer is always byte-aligned and it's pointer is aligned to size of 
u64.
+    #[inline]
+    pub fn as_buffer(&self) -> Buffer {
+        Buffer::from(self.bit_slice.as_slice())
+    }
+
+    ///
+    /// Count ones in the given bit view
+    #[inline]
+    pub fn count_ones(&self) -> usize {
+        self.bit_slice.count_ones()
+    }
+
+    ///
+    /// Count zeros in the given bit view
+    #[inline]
+    pub fn count_zeros(&self) -> usize {
+        self.bit_slice.count_zeros()
+    }
+
+    ///
+    /// Get bit value at the given index in this bit view
+    #[inline]
+    pub fn get_bit(&self, index: usize) -> bool {
+        *unsafe { self.bit_slice.get_unchecked(index) }
+    }
+
+    ///
+    /// Get bits in this view as vector of booleans
+    #[inline]
+    pub fn typed_bits(&self) -> Vec<bool> {
+        self.bit_slice.iter().copied().collect()
+    }
+
+    ///
+    /// Get manipulated data as byte slice
+    #[inline]
+    pub fn to_slice(&self) -> &[u8] {
+        self.bit_slice.as_slice()
+    }
+}
+
+impl<'a> PartialEq for BufferBitSlice<'a> {
+    fn eq(&self, other: &Self) -> bool {
+        self.bit_slice == other.bit_slice
+    }
+}
+
+///
+/// Conversion from mutable slice to immutable bit slice
+impl<'a> From<&'a [u8]> for BufferBitSlice<'a> {
+    fn from(data: &'a [u8]) -> Self {
+        BufferBitSlice::new(data)
+    }
+}
+
+///
+/// Mutable bit slice view of buffer data
+///
+/// `BufferBitSliceMut` does not own any underlying data, but rather
+/// has methods for addressing and interacting with individual bits.
+#[derive(Debug)]
+pub struct BufferBitSliceMut<'a> {
+    bit_slice: &'a mut BitSlice<LocalBits, u8>,
+}
+
+impl<'a> BufferBitSliceMut<'a> {
+    ///
+    /// Creates a mutable bit slice over the given data
+    #[inline]
+    pub fn new(buffer_data: &'a mut [u8]) -> Self {
+        let bit_slice = BitSlice::<LocalBits, 
_>::from_slice_mut(buffer_data).unwrap();
+
+        BufferBitSliceMut { bit_slice }
+    }
+
+    ///
+    /// Returns mutable view with the given offset in bits and length in bits.
+    /// This view have zero-copy representation over the actual data.
+    #[inline]
+    pub fn slicing(&'a mut self, offset_in_bits: usize, len_in_bits: usize) -> 
Self {
+        Self {
+            bit_slice: &mut self.bit_slice[offset_in_bits..offset_in_bits + 
len_in_bits],
+        }
+    }
+
+    ///
+    /// Sets all bits in this slice to the given value
+    #[inline]
+    pub fn set_bit_all(&mut self, value: bool) {
+        self.bit_slice.set_all(value)
+    }
+
+    ///
+    /// Set given bit at the position to a given value
+    #[inline]
+    pub fn set_bit(&mut self, index: usize, value: bool) {
+        unsafe { self.bit_slice.set_unchecked(index, value) }
+    }
+
+    ///
+    /// Converts the bit view into a Buffer.
+    /// Buffer is always byte-aligned and it's pointer is aligned to size of 
u64.
+    #[inline]
+    pub fn as_buffer(&self) -> Buffer {
+        Buffer::from(self.bit_slice.as_slice())
+    }
+
+    ///
+    /// Count ones in the given bit view
+    #[inline]
+    pub fn count_ones(&self) -> usize {
+        self.bit_slice.count_ones()
+    }
+
+    ///
+    /// Count zeros in the given bit view
+    #[inline]
+    pub fn count_zeros(&self) -> usize {
+        self.bit_slice.count_zeros()
+    }
+
+    ///
+    /// Get bit value at the given index in this bit view
+    #[inline]
+    pub fn get_bit(&self, index: usize) -> bool {

Review comment:
       can't this go out of bounds? What do you think about making this unsafe 
and expose a safe version with a check?




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
[email protected]


Reply via email to