Apache DataFusion SQL Query Engine
ARROW-3541: [Rust] Update BufferBuilder to allow for new bit-packed BooleanArray
Paddy Horanf502887b14f8
diff --git a/rust/src/buffer.rs b/rust/src/buffer.rsindex 005a0511bb..dd6069a988 100644--- a/rust/src/buffer.rs+++ b/rust/src/buffer.rs@@ -176,22 +176,43 @@ impl MutableBuffer {self}+ /// Manually sets the `len` of this buffer+ pub fn set_len(&mut self, new_len: usize) {+ assert!(+ new_len <= self.capacity,+ "Unable to set len outside capacity"+ );+ self.len = new_len;+ }++ /// Ensure that `count` bytes from `start` contain zero bits+ ///+ /// This is used to initialize the bits in a buffer, however, it has no impact on the `len`+ /// of the buffer and so can be used to initialize the memory region from `len` to `capacity`.+ pub fn set_null_bits(&mut self, start: usize, count: usize) {+ assert!(start + count <= self.capacity);+ unsafe {+ ::std::ptr::write_bytes(self.data.offset(start as isize), 0, count);+ }+ }+/// Adjust the capacity of this buffer to be at least `new_capacity`.////// If the `new_capacity` is less than the current capacity, nothing is done and `Ok`/// will be returned. Otherwise, the new capacity value will be chosen between the/// larger one of the incoming `new_capacity` (after rounding up to the nearest 64)- /// and the doubled value of the existing capacity.- pub fn resize(&mut self, new_capacity: usize) -> Result<()> {+ /// and the doubled value of the existing capacity, the capacity added is returned.+ pub fn resize(&mut self, new_capacity: usize) -> Result<usize> {if new_capacity <= self.capacity {- return Ok(());+ return Ok(0);}let new_capacity = bit_util::round_upto_multiple_of_64(new_capacity as i64);- let new_capacity = cmp::max(new_capacity, self.capacity as i64 * 2);- let new_data = memory::reallocate(self.capacity, new_capacity as usize, self.data)?;+ let new_capacity = cmp::max(new_capacity, self.capacity as i64 * 2) as usize;+ let new_data = memory::reallocate(self.capacity, new_capacity, self.data)?;self.data = new_data as *mut u8;- self.capacity = new_capacity as usize;- Ok(())+ let capacity_added = new_capacity - self.capacity;+ self.capacity = new_capacity;+ Ok(capacity_added)}/// Returns whether this buffer is empty or not.@@ -380,6 +401,19 @@ mod tests {assert_eq!(512, bit_util::count_set_bits(buf.data()));}+ #[test]+ fn test_set_null_bits() {+ let mut mut_buf = MutableBuffer::new(64).with_bitset(64, true);+ mut_buf.set_null_bits(0, 64);+ let buf = mut_buf.freeze();+ assert_eq!(0, bit_util::count_set_bits(buf.data()));++ let mut mut_buf = MutableBuffer::new(64).with_bitset(64, true);+ mut_buf.set_null_bits(32, 32);+ let buf = mut_buf.freeze();+ assert_eq!(256, bit_util::count_set_bits(buf.data()));+ }+#[test]fn test_mutable_new() {let buf = MutableBuffer::new(63);diff --git a/rust/src/builder.rs b/rust/src/builder.rsindex 2584ae93fc..2f694b033e 100644--- a/rust/src/builder.rs+++ b/rust/src/builder.rs@@ -22,9 +22,10 @@ use std::io::Write;use std::marker::PhantomData;use std::mem;-use super::buffer::*;-use super::datatypes::*;+use buffer::{Buffer, MutableBuffer};+use datatypes::{ArrowPrimitiveType, ToByteSlice};use error::{ArrowError, Result};+use util::bit_util;/// Buffer builder with zero-copy build methodpub struct BufferBuilder<T>@@ -36,13 +37,102 @@ where_marker: PhantomData<T>,}-impl<T> BufferBuilder<T>-where- T: ArrowPrimitiveType,-{+macro_rules! impl_buffer_builder {+ ($native_ty:ident) => {+ impl BufferBuilder<$native_ty> {+ /// Creates a builder with a fixed initial capacity+ pub fn new(capacity: i64) -> Self {+ let buffer = MutableBuffer::new(capacity as usize * mem::size_of::<$native_ty>());+ Self {+ buffer,+ len: 0,+ _marker: PhantomData,+ }+ }++ /// Returns the number of array elements (slots) in the builder+ pub fn len(&self) -> i64 {+ self.len+ }++ /// Returns the current capacity of the builder (number of elements)+ pub fn capacity(&self) -> i64 {+ let byte_capacity = self.buffer.capacity();+ (byte_capacity / mem::size_of::<$native_ty>()) as i64+ }++ /// Push a value into the builder, growing the internal buffer as needed+ pub fn push(&mut self, v: $native_ty) -> Result<()> {+ self.reserve(1)?;+ self.write_bytes(v.to_byte_slice(), 1)+ }++ /// Push a slice of type T, growing the internal buffer as needed+ pub fn push_slice(&mut self, slice: &[$native_ty]) -> Result<()> {+ let array_slots = slice.len() as i64;+ self.reserve(array_slots)?;+ self.write_bytes(slice.to_byte_slice(), array_slots)+ }++ /// Reserve memory for n elements of type T+ pub fn reserve(&mut self, n: i64) -> Result<()> {+ let new_capacity = self.len + n;+ if new_capacity > self.capacity() {+ return self.grow(new_capacity);+ }+ Ok(())+ }++ /// Grow the internal buffer to `new_capacity`, where `new_capacity` is the capacity in+ /// elements of type T+ fn grow(&mut self, new_capacity: i64) -> Result<()> {+ let byte_capacity = mem::size_of::<$native_ty>() * new_capacity as usize;+ self.buffer.resize(byte_capacity)?;+ Ok(())+ }++ /// Build an immutable `Buffer` from the existing internal `MutableBuffer`'s memory+ pub fn finish(self) -> Buffer {+ self.buffer.freeze()+ }++ /// Writes a byte slice to the underlying buffer and updates the `len`, i.e. the number array+ /// elements in the builder. Also, converts the `io::Result` required by the `Write` trait+ /// to the Arrow `Result` type.+ fn write_bytes(&mut self, bytes: &[u8], len_added: i64) -> Result<()> {+ let write_result = self.buffer.write(bytes);+ // `io::Result` has many options one of which we use, so pattern matching is overkill here+ if write_result.is_err() {+ Err(ArrowError::MemoryError(+ "Could not write to Buffer, not big enough".to_string(),+ ))+ } else {+ self.len += len_added;+ Ok(())+ }+ }+ }+ };+}++impl_buffer_builder!(u8);+impl_buffer_builder!(u16);+impl_buffer_builder!(u32);+impl_buffer_builder!(u64);+impl_buffer_builder!(i8);+impl_buffer_builder!(i16);+impl_buffer_builder!(i32);+impl_buffer_builder!(i64);+impl_buffer_builder!(f32);+impl_buffer_builder!(f64);++impl BufferBuilder<bool> {/// Creates a builder with a fixed initial capacitypub fn new(capacity: i64) -> Self {- let buffer = MutableBuffer::new(capacity as usize * mem::size_of::<T>());+ let byte_capacity = bit_util::ceil(capacity, 8);+ let actual_capacity = bit_util::round_upto_multiple_of_64(byte_capacity) as usize;+ let mut buffer = MutableBuffer::new(actual_capacity);+ buffer.set_null_bits(0, actual_capacity);Self {buffer,len: 0,@@ -57,21 +147,31 @@ where/// Returns the current capacity of the builder (number of elements)pub fn capacity(&self) -> i64 {- let byte_capacity = self.buffer.capacity();- (byte_capacity / mem::size_of::<T>()) as i64+ let byte_capacity = self.buffer.capacity() as i64;+ byte_capacity * 8}/// Push a value into the builder, growing the internal buffer as needed- pub fn push(&mut self, v: T) -> Result<()> {+ pub fn push(&mut self, v: bool) -> Result<()> {self.reserve(1)?;- self.write_bytes(v.to_byte_slice(), 1)+ if v {+ // For performance the `len` of the buffer is not updated on each push but+ // is updated in the `freeze` method instead+ unsafe {+ bit_util::set_bit_raw(self.buffer.raw_data() as *mut u8, (self.len) as usize);+ }+ }+ self.len += 1;+ Ok(())}/// Push a slice of type T, growing the internal buffer as needed- pub fn push_slice(&mut self, slice: &[T]) -> Result<()> {- let array_slots = slice.len() as i64;- self.reserve(array_slots)?;- self.write_bytes(slice.to_byte_slice(), array_slots)+ pub fn push_slice(&mut self, slice: &[bool]) -> Result<()> {+ let array_slots = slice.len();+ for i in 0..array_slots {+ self.push(slice[i])?;+ }+ Ok(())}/// Reserve memory for n elements of type T@@ -86,30 +186,20 @@ where/// Grow the internal buffer to `new_capacity`, where `new_capacity` is the capacity in/// elements of type Tfn grow(&mut self, new_capacity: i64) -> Result<()> {- let byte_capacity = mem::size_of::<T>() * new_capacity as usize;- self.buffer.resize(byte_capacity)+ let new_byte_capacity = bit_util::ceil(new_capacity, 8) as usize;+ let existing_capacity = self.buffer.capacity();+ let capacity_added = self.buffer.resize(new_byte_capacity)?;+ self.buffer.set_null_bits(existing_capacity, capacity_added);+ Ok(())}/// Build an immutable `Buffer` from the existing internal `MutableBuffer`'s memory- pub fn finish(self) -> Buffer {+ pub fn finish(mut self) -> Buffer {+ // `push` does not update the buffer's `len` to it is done before `freeze` is called+ let new_buffer_len = bit_util::ceil(self.len, 8);+ self.buffer.set_len(new_buffer_len as usize);self.buffer.freeze()}-- /// Writes a byte slice to the underlying buffer and updates the `len`, i.e. the number array- /// elements in the builder. Also, converts the `io::Result` required by the `Write` trait- /// to the Arrow `Result` type.- fn write_bytes(&mut self, bytes: &[u8], len_added: i64) -> Result<()> {- let write_result = self.buffer.write(bytes);- // `io::Result` has many options one of which we use, so pattern matching is overkill here- if write_result.is_err() {- Err(ArrowError::MemoryError(- "Could not write to Buffer, not big enough".to_string(),- ))- } else {- self.len += len_added;- Ok(())- }- }}#[cfg(test)]@@ -190,19 +280,58 @@ mod tests {#[test]fn test_write_bytes() {let mut b = BufferBuilder::<bool>::new(4);- let bytes = [false, true, false, true].to_byte_slice();+ b.push(false).unwrap();+ b.push(true).unwrap();+ b.push(false).unwrap();+ b.push(true).unwrap();+ assert_eq!(4, b.len());+ assert_eq!(512, b.capacity());+ let buffer = b.finish();+ assert_eq!(1, buffer.len());++ let mut b = BufferBuilder::<bool>::new(4);+ b.push_slice(&[false, true, false, true]).unwrap();+ assert_eq!(4, b.len());+ assert_eq!(512, b.capacity());+ let buffer = b.finish();+ assert_eq!(1, buffer.len());+ }++ #[test]+ fn test_write_bytes_i32() {+ let mut b = BufferBuilder::<i32>::new(4);+ let bytes = [8, 16, 32, 64].to_byte_slice();b.write_bytes(bytes, 4).unwrap();assert_eq!(4, b.len());- assert_eq!(64, b.capacity());+ assert_eq!(16, b.capacity());let buffer = b.finish();- assert_eq!(4, buffer.len());+ assert_eq!(16, buffer.len());}#[test]#[should_panic(expected = "Could not write to Buffer, not big enough")]fn test_write_too_many_bytes() {- let mut b = BufferBuilder::<bool>::new(0);- let bytes = [false, true, false, true].to_byte_slice();+ let mut b = BufferBuilder::<i32>::new(0);+ let bytes = [8, 16, 32, 64].to_byte_slice();b.write_bytes(bytes, 4).unwrap();}++ #[test]+ fn test_boolean_builder_increases_buffer_len() {+ // 00000010 01001000+ let buf = Buffer::from([72_u8, 2_u8]);+ let mut builder = BufferBuilder::<bool>::new(8);++ for i in 0..10 {+ if i == 3 || i == 6 || i == 9 {+ builder.push(true).unwrap();+ } else {+ builder.push(false).unwrap();+ }+ }+ let buf2 = builder.finish();++ assert_eq!(buf.len(), buf2.len());+ assert_eq!(buf.data(), buf2.data());+ }}diff --git a/rust/src/util/bit_util.rs b/rust/src/util/bit_util.rsindex e652281775..da6d10d269 100644--- a/rust/src/util/bit_util.rs+++ b/rust/src/util/bit_util.rs@@ -62,6 +62,15 @@ pub fn set_bit(data: &mut [u8], i: usize) {data[i >> 3] |= BIT_MASK[i & 7]}+/// Sets bit at position `i` for `data`+///+/// Note this doesn't do any bound checking, for performance reason. The caller is+/// responsible to guarantee that `i` is within bounds.+#[inline]+pub unsafe fn set_bit_raw(data: *mut u8, i: usize) {+ *data.offset((i >> 3) as isize) |= BIT_MASK[i & 7]+}+/// Returns the number of 1-bits in `data`#[inline]pub fn count_set_bits(data: &[u8]) -> i64 {@@ -181,6 +190,30 @@ mod tests {assert_eq!([0b00100101], b);}+ #[test]+ fn test_set_bit_raw() {+ const NUM_BYTE: usize = 10;+ let mut buf = vec![0; NUM_BYTE];+ let mut expected = vec![];+ let mut rng = thread_rng();+ for i in 0..8 * NUM_BYTE {+ let b = rng.gen_bool(0.5);+ expected.push(b);+ if b {+ unsafe {+ set_bit_raw(buf.as_mut_ptr(), i);+ }+ }+ }++ let raw_ptr = buf.as_ptr();+ for (i, b) in expected.iter().enumerate() {+ unsafe {+ assert_eq!(*b, get_bit_raw(raw_ptr, i));+ }+ }+ }+#[test]fn test_get_set_bit_roundtrip() {const NUM_BYTES: usize = 10;