From 7e57fd0d184dac47b03a474cbc74bf742e27778e Mon Sep 17 00:00:00 2001 From: Chao Sun Date: Sun, 10 Jun 2018 10:57:43 -0700 Subject: [PATCH 01/20] [WIP] ARROW-2583: [Rust] Buffer should be typeless --- rust/Cargo.toml | 5 +- rust/benches/array_from_builder.rs | 49 -- rust/benches/array_from_vec.rs | 14 +- rust/examples/dynamic_types.rs | 12 +- rust/src/array.rs | 719 ++++++++++-------- rust/src/array_data.rs | 235 ++++++ rust/src/bitmap.rs | 42 +- rust/src/buffer.rs | 333 +++----- rust/src/builder.rs | 21 +- rust/src/datatypes.rs | 23 +- rust/src/lib.rs | 6 +- rust/src/list.rs | 110 --- rust/src/list_builder.rs | 101 --- rust/src/memory.rs | 13 + rust/src/record_batch.rs | 33 +- rust/src/util/bit_util.rs | 93 +++ .../array_from_vec.rs => src/util/mod.rs} | 11 +- .../util/test_util.rs} | 30 +- 18 files changed, 961 insertions(+), 889 deletions(-) delete mode 100644 rust/benches/array_from_builder.rs create mode 100644 rust/src/array_data.rs delete mode 100644 rust/src/list.rs delete mode 100644 rust/src/list_builder.rs create mode 100644 rust/src/util/bit_util.rs rename rust/{examples/array_from_vec.rs => src/util/mod.rs} (75%) rename rust/{examples/array_from_builder.rs => src/util/test_util.rs} (53%) diff --git a/rust/Cargo.toml b/rust/Cargo.toml index 7cedb15971cb..b618ea96a338 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -37,6 +37,7 @@ path = "src/lib.rs" bytes = "0.4" libc = "0.2" serde_json = "1.0.13" +rand = "0.5" [dev-dependencies] criterion = "0.2" @@ -44,7 +45,3 @@ criterion = "0.2" [[bench]] name = "array_from_vec" harness = false - -[[bench]] -name = "array_from_builder" -harness = false \ No newline at end of file diff --git a/rust/benches/array_from_builder.rs b/rust/benches/array_from_builder.rs deleted file mode 100644 index 2398e2e41c5d..000000000000 --- a/rust/benches/array_from_builder.rs +++ /dev/null @@ -1,49 +0,0 @@ -// 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. - -#[macro_use] -extern crate criterion; - -use criterion::Criterion; - -extern crate arrow; - -use arrow::array::*; -use arrow::builder::*; - -fn array_from_builder(n: usize) { - let mut v: Builder = Builder::with_capacity(n); - for i in 0..n { - v.push(i as i32); - } - PrimitiveArray::from(v.finish()); -} - -fn criterion_benchmark(c: &mut Criterion) { - c.bench_function("array_from_builder 128", |b| { - b.iter(|| array_from_builder(128)) - }); - c.bench_function("array_from_builder 256", |b| { - b.iter(|| array_from_builder(256)) - }); - c.bench_function("array_from_builder 512", |b| { - b.iter(|| array_from_builder(512)) - }); -} - -criterion_group!(benches, criterion_benchmark); -criterion_main!(benches); diff --git a/rust/benches/array_from_vec.rs b/rust/benches/array_from_vec.rs index 50f0c52c03b9..f4f5738afde0 100644 --- a/rust/benches/array_from_vec.rs +++ b/rust/benches/array_from_vec.rs @@ -22,14 +22,22 @@ use criterion::Criterion; extern crate arrow; +use std::rc::Rc; + +use arrow::array_data::ArrayDataBuilder; use arrow::array::*; +use arrow::datatypes::*; +use arrow::buffer::Buffer; fn array_from_vec(n: usize) { - let mut v: Vec = Vec::with_capacity(n); + let mut v: Vec = Vec::with_capacity(n); for i in 0..n { - v.push(i as i32); + v.push((i % 0xffff) as u8); } - PrimitiveArray::from(v); + let arr_data = ArrayDataBuilder::new(DataType::Int32) + .add_buffer(Buffer::from(v)) + .build(); + let _: PrimitiveArray = PrimitiveArray::from(Rc::new(arr_data)); } fn criterion_benchmark(c: &mut Criterion) { diff --git a/rust/examples/dynamic_types.rs b/rust/examples/dynamic_types.rs index b8093bfadbd4..babd49e0e5b8 100644 --- a/rust/examples/dynamic_types.rs +++ b/rust/examples/dynamic_types.rs @@ -43,7 +43,7 @@ fn main() { let id = PrimitiveArray::from(vec![1, 2, 3, 4, 5]); let nested = StructArray::from(vec![ - Arc::new(ListArray::from(vec!["a", "b", "c", "d", "e"])) as Arc, + Arc::new(BinaryArray::from(vec!["a", "b", "c", "d", "e"])) as Arc, Arc::new(PrimitiveArray::from(vec![1.1, 2.2, 3.3, 4.4, 5.5])), Arc::new(PrimitiveArray::from(vec![2.2, 3.3, 4.4, 5.5, 6.6])), ]); @@ -54,7 +54,7 @@ fn main() { process(&batch); } -/// Create a new batch by performing a projection of id, (nested.b + nested.c) AS sum +/// Create a new batch by performing a projection of id, nested.c fn process(batch: &RecordBatch) { let id = batch.column(0); let nested = batch @@ -63,12 +63,12 @@ fn process(batch: &RecordBatch) { .downcast_ref::() .unwrap(); - let nested_b = nested + let _nested_b = nested .column(1) .as_any() .downcast_ref::>() .unwrap(); - let nested_c = nested + let nested_c: &PrimitiveArray = nested .column(2) .as_any() .downcast_ref::>() @@ -82,8 +82,8 @@ fn process(batch: &RecordBatch) { let _ = RecordBatch::new( Arc::new(projected_schema), vec![ - id.clone(), //NOTE: this is cloning the Arc not the array data - Arc::new(nested_b.add(nested_c)), + id.clone(), //NOTE: this is cloning the Rc not the array data + Arc::new(PrimitiveArray::::from(nested_c.data())), ], ); } diff --git a/rust/src/array.rs b/rust/src/array.rs index 1c4322cddb50..5a4fe19007f9 100644 --- a/rust/src/array.rs +++ b/rust/src/array.rs @@ -18,444 +18,511 @@ ///! Array types use std::any::Any; use std::convert::From; +<<<<<<< HEAD use std::ops::Add; use std::str; use std::string::String; +======= +use std::marker::PhantomData; +use std::mem::{transmute}; +>>>>>>> [WIP] ARROW-2583: [Rust] Buffer should be typeless use std::sync::Arc; -use super::bitmap::Bitmap; +use super::array_data::*; use super::buffer::*; -use super::builder::*; use super::datatypes::*; -use super::list::*; -use super::list_builder::*; -/// Trait for dealing with different types of Array at runtime when the type of the +/// Trait for dealing with different types of array at runtime when the type of the /// array is not known in advance pub trait Array: Send + Sync { - /// Returns the length of the array (number of items in the array) - fn len(&self) -> usize; - /// Returns the number of null values in the array - fn null_count(&self) -> usize; - /// Optional validity bitmap (can be None if there are no null values) - fn validity_bitmap(&self) -> &Option; - /// Return the array as Any so that it can be downcast to a specific implementation + /// Returns the array as Any so that it can be downcast to a specific implementation fn as_any(&self) -> &Any; -} -/// Array of List -pub struct ListArray { - len: usize, - data: List, - null_count: usize, - validity_bitmap: Option, + /// Returns a reference-counted pointer to the data of this array + fn data(&self) -> ArrayDataRef; + + /// Returns a reference-counted pointer to the data of this array + fn data_ref(&self) -> &ArrayDataRef; } -impl ListArray -where - T: ArrowPrimitiveType, -{ - pub fn len(&self) -> usize { - self.len +pub type ArrayRef = Arc; + +/// Constructs an array using the input `data`. Returns a reference-counted `Array` +/// instance. +fn make_array(data: ArrayDataRef) -> ArrayRef { + // TODO: refactor the DataType enum and remove the clone here. + match data.data_type() { + DataType::Boolean => Arc::new(PrimitiveArray::::from(data)) as ArrayRef, + DataType::Int8 => Arc::new(PrimitiveArray::::from(data)) as ArrayRef, + DataType::Int16 => Arc::new(PrimitiveArray::::from(data)) as ArrayRef, + DataType::Int32 => Arc::new(PrimitiveArray::::from(data)) as ArrayRef, + DataType::Int64 => Arc::new(PrimitiveArray::::from(data)) as ArrayRef, + DataType::UInt8 => Arc::new(PrimitiveArray::::from(data)) as ArrayRef, + DataType::UInt16 => Arc::new(PrimitiveArray::::from(data)) as ArrayRef, + DataType::UInt32 => Arc::new(PrimitiveArray::::from(data)) as ArrayRef, + DataType::UInt64 => Arc::new(PrimitiveArray::::from(data)) as ArrayRef, + DataType::Float32 => Arc::new(PrimitiveArray::::from(data)) as ArrayRef, + DataType::Float64 => Arc::new(PrimitiveArray::::from(data)) as ArrayRef, + DataType::Utf8 => Arc::new(BinaryArray::from(data)) as ArrayRef, + DataType::List(_) => Arc::new(ListArray::from(data)) as ArrayRef, + DataType::Struct(_) => Arc::new(StructArray::from(data)) as ArrayRef, + dt => panic!("Unexpected data type {:?}", dt) } +} - pub fn null_count(&self) -> usize { - self.null_count - } - pub fn validity_bitmap(&self) -> &Option { - &self.validity_bitmap - } +/// ---------------------------------------------------------------------------- +/// Implementations of different array types + +struct RawPtrBox { + inner: *const T, +} - pub fn get(&self, i: usize) -> &[T] { - self.data.get(i) +impl RawPtrBox { + fn new(inner: *const T) -> Self { + Self { inner: inner } } - pub fn list(&self) -> &List { - &self.data + fn get(&self) -> *const T { + self.inner } } -/// Create a ListArray from a List without null values -impl From> for ListArray -where - T: ArrowPrimitiveType, -{ - fn from(list: List) -> Self { - let len = list.len(); - ListArray { - len, - data: list, - validity_bitmap: None, - null_count: 0, - } - } +unsafe impl Send for RawPtrBox {} +unsafe impl Sync for RawPtrBox {} + +/// Array whose elements are of primitive types. +pub struct PrimitiveArray { + data: ArrayDataRef, + /// Pointer to the value array. The lifetime of this must be <= to the value buffer + /// stored in `data`, so it's safe to store. + raw_values: RawPtrBox, + _phantom: PhantomData, } -/// Create ListArray from Vec<&'static str> -impl From> for ListArray { - fn from(v: Vec<&'static str>) -> Self { - let mut builder: ListBuilder = ListBuilder::with_capacity(v.len()); - for s in v { - builder.push(s.as_bytes()) +/// Macro to define primitive arrays for different data types and native types. +macro_rules! def_primitive_array { + ($data_ty:path, $native_ty:ident) => { + impl PrimitiveArray<$native_ty> { + pub fn new( + length: i64, values: Buffer, null_count: i64, offset: i64 + ) -> Self { + let array_data = ArrayData::builder($data_ty) + .length(length) + .add_buffer(values) + .null_count(null_count) + .offset(offset) + .build(); + PrimitiveArray::from(array_data) + } + + /// Returns a `Buffer` holds all the values of this array. + pub fn values(&self) -> Buffer { + self.data.buffers()[0].copy() + } + + /// Returns a raw pointer to the values of this array. + pub fn raw_values(&self) -> *const $native_ty { + unsafe { + transmute(self.raw_values.get().offset(self.data.offset() as isize)) + } + } + + /// Returns the primitive value at index `i`. + pub fn value(&self, i: i64) -> $native_ty { + unsafe { + *(self.raw_values().offset(i as isize)) + } + } + } + + /// Construct a primitive array from a vector. Should only be used for testing. + impl From> for PrimitiveArray<$native_ty> { + fn from(v: Vec<$native_ty>) -> Self { + let array_data = ArrayData::builder($data_ty) + .length(v.len() as i64) + .add_buffer(Buffer::from(v.to_bytes())) + .build(); + PrimitiveArray::from(array_data) + } } - ListArray::from(builder.finish()) } } -/// Create ListArray from Vec -impl From> for ListArray { - fn from(v: Vec) -> Self { - let mut builder: ListBuilder = ListBuilder::with_capacity(v.len()); - for s in v { - builder.push(s.as_bytes()) +/// Constructs a `PrimitiveArray` from an array data reference. +impl From for PrimitiveArray { + fn from(data: ArrayDataRef) -> Self { + assert!(data.buffers().len() == 1); + let values = data.buffers()[0].copy(); + Self { + data: data, + raw_values: RawPtrBox::new(values.raw_data()), + _phantom: PhantomData, } - ListArray::from(builder.finish()) } } -impl Array for ListArray -where - T: ArrowPrimitiveType, -{ - fn len(&self) -> usize { - self.len - } - fn null_count(&self) -> usize { - self.null_count - } - fn validity_bitmap(&self) -> &Option { - &self.validity_bitmap - } +impl Array for PrimitiveArray { fn as_any(&self) -> &Any { self } + + fn data(&self) -> ArrayDataRef { + self.data.clone() + } + + fn data_ref(&self) -> &ArrayDataRef { + &self.data + } } -/// Array of T -pub struct PrimitiveArray { - len: usize, - data: Buffer, - null_count: usize, - validity_bitmap: Option, +def_primitive_array!(DataType::Boolean, bool); +def_primitive_array!(DataType::UInt8, u8); +def_primitive_array!(DataType::UInt16, u16); +def_primitive_array!(DataType::UInt32, u32); +def_primitive_array!(DataType::UInt64, u64); +def_primitive_array!(DataType::Int8, i8); +def_primitive_array!(DataType::Int16, i16); +def_primitive_array!(DataType::Int32, i32); +def_primitive_array!(DataType::Int64, i64); +def_primitive_array!(DataType::Float32, f32); +def_primitive_array!(DataType::Float64, f64); + + +/// A list array where each element is a variable-sized sequence of values with the same +/// type. +pub struct ListArray { + data: ArrayDataRef, + values: ArrayRef, + value_offsets: RawPtrBox, } -impl PrimitiveArray -where - T: ArrowPrimitiveType, -{ - pub fn new(data: Buffer, null_count: usize, validity_bitmap: Option) -> Self { - PrimitiveArray { - len: data.len(), - data: data, - null_count, - validity_bitmap, - } +impl ListArray { + /// Returns an reference to the values of this list. + pub fn values(&self) -> ArrayRef { + self.values.clone() } - pub fn len(&self) -> usize { - self.len + /// Returns the value type of this list. + pub fn value_type(&self) -> DataType { + self.values.data().data_type() } - pub fn get(&self, i: usize) -> &T { - self.data.get(i) + /// Returns the offset for value at index `i`. + #[inline] + pub fn value_offset(&self, i: i64) -> i32 { + self.value_offset_at(self.data.offset() + i) } - pub fn iter(&self) -> BufferIterator { - self.data.iter() + /// Returns the length for value at index `i`. + #[inline] + pub fn value_length(&self, mut i: i64) -> i32 { + i += self.data.offset(); + self.value_offset_at(i + 1) - self.value_offset_at(i) } - pub fn buffer(&self) -> &Buffer { - &self.data + #[inline] + fn value_offset_at(&self, i: i64) -> i32 { + unsafe { + *self.value_offsets.get().offset(i as isize) + } } +} - /// Determine the minimum value in the array - pub fn min(&self) -> Option { - let mut n: Option = None; - match &self.validity_bitmap { - &Some(ref bitmap) => for i in 0..self.len { - if bitmap.is_set(i) { - let mut m = self.data.get(i); - match n { - None => n = Some(*m), - Some(nn) => if *m < nn { - n = Some(*m) - }, - } - } - }, - &None => for i in 0..self.len { - let mut m = self.data.get(i); - match n { - None => n = Some(*m), - Some(nn) => if *m < nn { - n = Some(*m) - }, - } - }, - } - n - } - - /// Determine the maximum value in the array - pub fn max(&self) -> Option { - let mut n: Option = None; - match &self.validity_bitmap { - &Some(ref bitmap) => for i in 0..self.len { - if bitmap.is_set(i) { - let mut m = self.data.get(i); - match n { - None => n = Some(*m), - Some(nn) => if *m > nn { - n = Some(*m) - }, - } - } - }, - &None => for i in 0..self.len { - let mut m = self.data.get(i); - match n { - None => n = Some(*m), - Some(nn) => if *m > nn { - n = Some(*m) - }, - } - }, +/// Constructs a `ListArray` from an array data reference. +impl From for ListArray { + fn from(data: ArrayDataRef) -> Self { + debug_assert!(data.buffers().len() == 1); + debug_assert!(data.child_data().len() == 1); + let values = make_array(data.child_data()[0].clone()); + let value_offsets = data.buffers()[0].raw_data() as *const u8 as *const i32; + Self { + data: data.clone(), + values: values, + value_offsets: RawPtrBox::new(value_offsets), } - n } } -/// Implement the Add operation for types that support Add -impl PrimitiveArray -where - T: ArrowPrimitiveType + Add, -{ - pub fn add(&self, other: &PrimitiveArray) -> PrimitiveArray { - let mut builder: Builder = Builder::new(); - for i in 0..self.len { - let x = *self.data.get(i) + *other.data.get(i); - builder.push(x); - } - PrimitiveArray::from(builder.finish()) +impl Array for ListArray { + fn as_any(&self) -> &Any { + self + } + + fn data(&self) -> ArrayDataRef { + self.data.clone() + } + + fn data_ref(&self) -> &ArrayDataRef { + &self.data } } -impl Array for PrimitiveArray -where - T: ArrowPrimitiveType, -{ - fn len(&self) -> usize { - self.len + +/// A special type of `ListArray` whose elements are binaries. +pub struct BinaryArray { + data: ArrayDataRef, + value_offsets: RawPtrBox, + value_data: RawPtrBox, +} + +impl BinaryArray { + /// Returns the element at index `i` as a byte slice. + pub fn get_value(&self, mut i: i64) -> &[u8] { + i += self.data.offset(); + unsafe { + let pos = self.value_offset_at(i); + ::std::slice::from_raw_parts( + self.value_data.get().offset(pos as isize), + (self.value_offset_at(i + 1) - pos) as usize) + } } - fn null_count(&self) -> usize { - self.null_count + + /// Returns the element at index `i` as a string. + pub fn get_string(&self, i: i64) -> String { + let slice = self.get_value(i); + unsafe { + String::from_utf8_unchecked(Vec::from(slice)) + } } - fn validity_bitmap(&self) -> &Option { - &self.validity_bitmap + + /// Returns the offset for the element at index `i`. + #[inline] + pub fn value_offset(&self, i: i64) -> i32 { + self.value_offset_at(i) } - fn as_any(&self) -> &Any { - self + + /// Returns the length for the element at index `i`. + #[inline] + pub fn value_length(&self, mut i: i64) -> i32 { + i += self.data.offset(); + self.value_offset_at(i + 1) - self.value_offset_at(i) } -} -/// Create a BufferArray from a Buffer without null values -impl From> for PrimitiveArray -where - T: ArrowPrimitiveType, -{ - fn from(data: Buffer) -> Self { - PrimitiveArray { - len: data.len(), - data: data, - validity_bitmap: None, - null_count: 0, + #[inline] + fn value_offset_at(&self, i: i64) -> i32 { + unsafe { + *self.value_offsets.get().offset(i as isize) } } + } -/// Create a BufferArray from a Vec of primitive values -impl From> for PrimitiveArray -where - T: ArrowPrimitiveType + 'static, -{ - fn from(vec: Vec) -> Self { - PrimitiveArray::from(Buffer::from(vec)) +impl From for BinaryArray { + fn from(data: ArrayDataRef) -> Self { + assert!(data.buffers().len() == 2); + let value_offsets = data.buffers()[0].raw_data() as *const u8 as *const i32; + let value_data = data.buffers()[1].raw_data(); + Self { + data: data.clone(), + value_offsets: RawPtrBox::new(value_offsets), + value_data: RawPtrBox::new(value_data), + } } } -/// Create a BufferArray from a Vec> with null handling -impl From>> for PrimitiveArray -where - T: ArrowPrimitiveType + 'static, -{ - fn from(v: Vec>) -> Self { - let mut builder: Builder = Builder::with_capacity(v.len()); - builder.set_len(v.len()); - let mut null_count = 0; - let mut validity_bitmap = Bitmap::new(v.len()); - for i in 0..v.len() { - match v[i] { - Some(value) => builder.set(i, value), - None => { - null_count += 1; - validity_bitmap.clear(i); - } - } +impl<'a> From> for BinaryArray { + fn from(v: Vec<&'a str>) -> Self { + let mut offsets = vec![]; + let mut values = vec![]; + let mut length_so_far = 0; + offsets.push(length_so_far); + for s in &v { + length_so_far += s.len() as i32; + offsets.push(length_so_far as i32); + values.extend_from_slice(s.as_bytes()); } - PrimitiveArray::new(builder.finish(), null_count, Some(validity_bitmap)) + let array_data = ArrayData::builder(DataType::Utf8) + .length(v.len() as i64) + .add_buffer(Buffer::from(offsets.to_bytes())) + .add_buffer(Buffer::from(&values[..])) + .build(); + BinaryArray::from(array_data) } } -/// An Array of structs +impl Array for BinaryArray { + fn as_any(&self) -> &Any { + self + } + + fn data(&self) -> ArrayDataRef { + self.data.clone() + } + + fn data_ref(&self) -> &ArrayDataRef { + &self.data + } +} + + pub struct StructArray { - len: usize, - columns: Vec>, - null_count: usize, - validity_bitmap: Option, + data: ArrayDataRef, + boxed_fields: Vec, } impl StructArray { - pub fn num_columns(&self) -> usize { - self.columns.len() + /// Returns the field at `pos`. + pub fn column(&self, pos: usize) -> &ArrayRef { + &self.boxed_fields[pos] } - pub fn column(&self, i: usize) -> &Arc { - &self.columns[i] +} + +impl From for StructArray { + fn from(data: ArrayDataRef) -> Self { + let mut boxed_fields = vec![]; + for cd in data.child_data() { + boxed_fields.push(make_array(cd.clone())); + } + Self { + data: data, + boxed_fields: boxed_fields, + } } } impl Array for StructArray { - fn len(&self) -> usize { - self.len - } - fn null_count(&self) -> usize { - self.null_count - } - fn validity_bitmap(&self) -> &Option { - &self.validity_bitmap - } fn as_any(&self) -> &Any { self } + + fn data(&self) -> ArrayDataRef { + self.data.clone() + } + + fn data_ref(&self) -> &ArrayDataRef { + &self.data + } } -/// Create a StructArray from a list of arrays representing the fields of the struct. The fields -/// must be in the same order as the schema defining the struct. -impl From>> for StructArray { - fn from(data: Vec>) -> Self { - StructArray { - len: data[0].len(), - columns: data, - null_count: 0, - validity_bitmap: None, +impl From> for StructArray { + fn from(v: Vec) -> Self { + let mut field_types = vec![]; + let mut count = 0; + for arr in &v { + let idx = count.to_string(); + count += 1; + field_types.push(Field::new(&idx, arr.data().data_type(), false)); } - } + let mut builder = ArrayData::builder(DataType::Struct(field_types)); + for arr in v { + builder = builder.add_child_data(arr.data().clone()); + } + StructArray::from(builder.build()) + } } + #[cfg(test)] mod tests { - use super::*; use std::thread; - #[test] - fn array_data_from_list_u8() { - let mut b: ListBuilder = ListBuilder::new(); - b.push(&[1, 2, 3, 4, 5]); - b.push(&[5, 4, 3, 2, 1]); - let array_data = ListArray::from(b.finish()); - assert_eq!(2, array_data.len()); - } - - #[test] - fn array_from_list_u8() { - let mut b: ListBuilder = ListBuilder::new(); - b.push("Hello, ".as_bytes()); - b.push("World!".as_bytes()); - let array = ListArray::from(b.finish()); - // downcast back to the data - let array_list_u8 = array.as_any().downcast_ref::>().unwrap(); - assert_eq!(2, array_list_u8.len()); - assert_eq!("Hello, ", str::from_utf8(array_list_u8.get(0)).unwrap()); - assert_eq!("World!", str::from_utf8(array_list_u8.get(1)).unwrap()); - } - - #[test] - fn test_from_bool() { - let a = PrimitiveArray::from(vec![false, false, true, false]); - assert_eq!(4, a.len()); - assert_eq!(0, a.null_count()); - } - - #[test] - fn test_from_f32() { - let a = PrimitiveArray::from(vec![1.23, 2.34, 3.45, 4.56]); - assert_eq!(4, a.len()); - } - - #[test] - fn test_from_i32() { - let a = PrimitiveArray::from(vec![15, 14, 13, 12, 11]); - assert_eq!(5, a.len()); - } + use array_data::ArrayData; + use buffer::Buffer; + use datatypes::{DataType, Field, ToByteArray}; + use super::{PrimitiveArray, ListArray, BinaryArray, StructArray}; #[test] - fn test_from_empty_vec() { - let v: Vec = vec![]; - let a = PrimitiveArray::from(v); - assert_eq!(0, a.len()); + fn test_primitive_array() { + let values: Vec = vec![0, 1, 2, 3, 4]; + let buf = Buffer::from(&values[..].to_bytes()); + let buf2 = buf.copy(); + let pa = PrimitiveArray::::new(buf.len() as i64, buf, 0, 0); + assert_eq!(buf2, pa.values()); + assert_eq!(2, pa.value(2)); + let raw_values = pa.raw_values(); + let slice = unsafe { + ::std::slice::from_raw_parts(raw_values, 5) + }; + assert_eq!(&[0, 1, 2, 3, 4], slice); } #[test] - fn test_from_optional_i32() { - let a = PrimitiveArray::from(vec![Some(1), None, Some(2), Some(3), None]); - assert_eq!(5, a.len()); - assert_eq!(2, a.null_count()); - // 1 == not null - match a.validity_bitmap() { - &Some(ref validity_bitmap) => { - assert_eq!(true, validity_bitmap.is_set(0)); - assert_eq!(false, validity_bitmap.is_set(1)); - assert_eq!(true, validity_bitmap.is_set(2)); - assert_eq!(true, validity_bitmap.is_set(3)); - assert_eq!(false, validity_bitmap.is_set(4)); - } - _ => panic!(), - } - } - - #[test] - fn test_struct() { - let a: Arc = Arc::new(PrimitiveArray::from(Buffer::from(vec![1, 2, 3, 4, 5]))); - let b: Arc = Arc::new(PrimitiveArray::from(Buffer::from(vec![ - 1.1, 2.2, 3.3, 4.4, 5.5, - ]))); - - let s = StructArray::from(vec![a, b]); - assert_eq!(2, s.num_columns()); - assert_eq!(0, s.null_count()); + fn test_list_array() { + // First, construct a value array. + let values: Vec = vec![0, 1, 2, 3, 4, 5, 6, 7]; + let value_data = ArrayData::builder(DataType::Int32) + .length(7) + .add_buffer(Buffer::from(&values[..].to_bytes())) + .build(); + + // Then, build the list array. + let value_offset_slice: Vec = vec![0, 2, 5, 7]; + let value_offsets = Buffer::from(value_offset_slice.to_bytes()); + let list_data_type = DataType::List(Box::new(DataType::Int32)); + let list_data = ArrayData::builder(list_data_type) + .length(4) + .add_buffer(value_offsets) + .add_child_data(value_data.clone()) + .build(); + let list_array = ListArray::from(list_data); + + let values = list_array.values(); + assert_eq!(value_data, values.data()); + assert_eq!(DataType::Int32, list_array.value_type()); + assert_eq!(5, list_array.value_offset(2)); + assert_eq!(2, list_array.value_length(2)); } #[test] - fn test_buffer_array_min_max() { - let a = PrimitiveArray::from(Buffer::from(vec![5, 6, 7, 8, 9])); - assert_eq!(5, a.min().unwrap()); - assert_eq!(9, a.max().unwrap()); + fn test_binary_array() { + let values: [u8; 12] = [ + b'h', b'e', b'l', b'l', b'o', b'p', b'a', b'r', b'q', b'u', b'e', b't' + ]; + let offsets: [i32; 4] = [0, 5, 5, 12]; + + let array_data = ArrayData::builder(DataType::Utf8) + .length(4) + .add_buffer(Buffer::from(offsets.to_bytes())) + .add_buffer(Buffer::from(&values[..])) + .build(); + let binary_array = BinaryArray::from(array_data); + assert_eq!([b'h', b'e', b'l', b'l', b'o'], binary_array.get_value(0)); + assert_eq!("hello", binary_array.get_string(0)); + assert_eq!([] as [u8; 0], binary_array.get_value(1)); + assert_eq!("", binary_array.get_string(1)); + assert_eq!([b'p', b'a', b'r', b'q', b'u', b'e', b't'], binary_array.get_value(2)); + assert_eq!("parquet", binary_array.get_string(2)); + assert_eq!(5, binary_array.value_offset(2)); + assert_eq!(7, binary_array.value_length(2)); } #[test] - fn test_buffer_array_min_max_with_nulls() { - let a = PrimitiveArray::from(vec![Some(5), None, None, Some(8), Some(9)]); - assert_eq!(5, a.min().unwrap()); - assert_eq!(9, a.max().unwrap()); + fn test_struct_array() { + let boolean_data = ArrayData::builder(DataType::Boolean) + .length(4) + .add_buffer(Buffer::from([false, false, true, true].to_bytes())) + .build(); + let int_data = ArrayData::builder(DataType::Int64) + .length(4) + .add_buffer(Buffer::from([42, 28, 19, 31].to_bytes())) + .build(); + let mut field_types = vec![]; + field_types.push(Field::new("a", DataType::Boolean, false)); + field_types.push(Field::new("b", DataType::Int64, false)); + let struct_array_data = ArrayData::builder(DataType::Struct(field_types)) + .add_child_data(boolean_data.clone()) + .add_child_data(int_data.clone()) + .build(); + let struct_array = StructArray::from(struct_array_data); + + assert_eq!(boolean_data, struct_array.column(0).data()); + assert_eq!(int_data, struct_array.column(1).data()); } #[test] fn test_access_array_concurrently() { - let a = PrimitiveArray::from(Buffer::from(vec![5, 6, 7, 8, 9])); + let a = PrimitiveArray::::from(vec![5, 6, 7, 8, 9]); +<<<<<<< HEAD let ret = thread::spawn(move || a.iter().collect::>()).join(); +======= + let ret = thread::spawn(move || { + a.value(3) + }).join(); +>>>>>>> [WIP] ARROW-2583: [Rust] Buffer should be typeless assert!(ret.is_ok()); - assert_eq!(vec![5, 6, 7, 8, 9], ret.ok().unwrap()); + assert_eq!(8, ret.ok().unwrap()); } } diff --git a/rust/src/array_data.rs b/rust/src/array_data.rs new file mode 100644 index 000000000000..4a9dd16c7519 --- /dev/null +++ b/rust/src/array_data.rs @@ -0,0 +1,235 @@ +// 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 std::sync::Arc; + +use bitmap::Bitmap; +use buffer::Buffer; +use datatypes::DataType; +use util::bit_util::count_set_bits; + +#[derive(PartialEq, Debug)] +pub struct ArrayData { + /// The data type for this array data + data_type: DataType, + + /// The number of elements in this array data + length: i64, + + /// The number of null elements in this array data + null_count: i64, + + /// The offset into this array data. + offset: i64, + + /// The buffers for this array data. Note that depending on the array types, this + /// could hold different types of buffers (e.g., null bit buffer, value buffer, value + /// offset buffer) at different positions. + buffers: Vec, + + /// The child(ren) of this array. Only non-empty for `ListArray` and `StructArray`. + child_data: Vec, + + /// The null bit map. A `None` value for this indicates all values are non-null in + /// this array. + null_bitmap: Option, +} + +pub type ArrayDataRef = Arc; +pub const UNKNOWN_NULL_COUNT: i64 = -1; + +impl ArrayData { + pub fn new( + data_type: DataType, length: i64, mut null_count: i64, + null_bit_buffer: Option, offset: i64, buffers: Vec, + child_data: Vec, + ) -> Self { + if null_count < 0 { + null_count = if let Some(ref buf) = null_bit_buffer { + count_set_bits(buf.data()) + } else { + 0 + } + } + let null_bitmap = null_bit_buffer.map(Bitmap::from); + Self { + data_type, length, null_count, offset, buffers, child_data, null_bitmap + } + } + + /// Returns a builder to construct a `ArrayData` instance. + pub fn builder(data_type: DataType) -> ArrayDataBuilder { + ArrayDataBuilder::new(data_type) + } + + /// Returns a copy of the data type for this array data. + pub fn data_type(&self) -> DataType { + self.data_type.clone() + } + + /// Returns a slice of buffers for this array data. + pub fn buffers(&self) -> &[Buffer] { + &self.buffers[..] + } + + /// Returns a slice of children data arrays. + pub fn child_data(&self) -> &[ArrayDataRef] { + &self.child_data[..] + } + + /// Returns whether the element at index `i` is null. + pub fn is_null(&self, i: usize) -> bool { + if let Some(ref b) = self.null_bitmap { + return b.is_set(i) + } + false + } + + /// Returns whether the element at index `i` is not null. + pub fn is_valid(&self, i: usize) -> bool { + if let Some(ref b) = self.null_bitmap { + return !b.is_set(i) + } + true + } + + /// Returns the length (i.e., number of elements) of this array. + pub fn length(&self) -> usize { + self.length as usize + } + + /// Returns the offset of this array. + pub fn offset(&self) -> i64 { + self.offset + } + + /// Returns the total number of nulls in this array. + pub fn null_count(&self) -> i64 { + self.null_count + } +} + +pub struct ArrayDataBuilder { + data_type: DataType, + length: i64, + null_count: i64, + null_bit_buffer: Option, + offset: i64, + buffers: Vec, + child_data: Vec, +} + +impl ArrayDataBuilder { + pub fn new(data_type: DataType) -> Self { + Self { + data_type: data_type, + length: 0, + null_count: UNKNOWN_NULL_COUNT, + null_bit_buffer: None, + offset: 0, + buffers: vec![], + child_data: vec![], + } + } + + pub fn length(mut self, n: i64) -> Self { + self.length = n; + self + } + + pub fn null_count(mut self, n: i64) -> Self { + self.null_count = n; + self + } + + pub fn null_bit_buffer(mut self, buf: Buffer) -> Self { + self.null_bit_buffer = Some(buf); + self + } + + pub fn offset(mut self, n: i64) -> Self { + self.offset = n; + self + } + + pub fn buffers(mut self, v: Vec) -> Self { + self.buffers = v; + self + } + + pub fn add_buffer(mut self, b: Buffer) -> Self { + self.buffers.push(b); + self + } + + pub fn child_data(mut self, v: Vec) -> Self { + self.child_data = v; + self + } + + pub fn add_child_data(mut self, r: ArrayDataRef) -> Self { + self.child_data.push(r); + self + } + + pub fn build(self) -> ArrayDataRef { + let data = ArrayData::new( + self.data_type, self.length, self.null_count, self.null_bit_buffer, + self.offset, self.buffers, self.child_data); + Arc::new(data) + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + use buffer::Buffer; + use super::{ArrayData, DataType}; + + #[test] + fn test_new() { + let arr_data = ArrayData::new(DataType::Boolean, 10, 1, None, 2, vec![], vec![]); + assert_eq!(10, arr_data.length()); + assert_eq!(1, arr_data.null_count()); + assert_eq!(2, arr_data.offset()); + assert_eq!(0, arr_data.buffers().len()); + assert_eq!(0, arr_data.child_data().len()); + } + + #[test] + fn test_builder() { + let v = vec![0, 1, 2, 3]; + let child_arr_data = Arc::new( + ArrayData::new(DataType::Int32, 10, 0, None, 0, vec![], vec![])); + let b1 = Buffer::from(&v[..]); + let arr_data = ArrayData::builder(DataType::Int32) + .length(20) + .null_count(10) + .offset(5) + .add_buffer(b1) + .add_child_data(child_arr_data.clone()) + .build(); + + assert_eq!(20, arr_data.length()); + assert_eq!(10, arr_data.null_count()); + assert_eq!(5, arr_data.offset()); + assert_eq!(1, arr_data.buffers().len()); + assert_eq!(&[0, 1, 2, 3], arr_data.buffers()[0].data()); + assert_eq!(1, arr_data.child_data().len()); + assert_eq!(child_arr_data, arr_data.child_data()[0]); + } +} diff --git a/rust/src/bitmap.rs b/rust/src/bitmap.rs index 27bf2d69038f..661a68103009 100644 --- a/rust/src/bitmap.rs +++ b/rust/src/bitmap.rs @@ -16,9 +16,11 @@ // under the License. use super::buffer::Buffer; +use util::bit_util; +#[derive(PartialEq, Debug)] pub struct Bitmap { - bits: Buffer, + bits: Buffer, } impl Bitmap { @@ -35,7 +37,7 @@ impl Bitmap { v.push(255); // 1 is not null } Bitmap { - bits: Buffer::from(v), + bits: Buffer::from(&v[..]), } } @@ -44,20 +46,15 @@ impl Bitmap { } pub fn is_set(&self, i: usize) -> bool { - let byte_offset = i / 8; - self.bits.get(byte_offset) & (1_u8 << ((i % 8) as u8)) > 0 - } - - pub fn set(&mut self, i: usize) { - let byte_offset = i / 8; - let v: u8 = { self.bits.get(byte_offset) | (1_u8 << ((i % 8) as u8)) }; - self.bits.set(byte_offset, v); + bit_util::get_bit(self.bits.data(), i) } +} - pub fn clear(&mut self, i: usize) { - let byte_offset = i / 8; - let v: u8 = self.bits.get(byte_offset) ^ (1_u8 << ((i % 8) as u8)); - self.bits.set(byte_offset, v); +impl From for Bitmap { + fn from(buf: Buffer) -> Self { + Self { + bits: buf + } } } @@ -73,13 +70,16 @@ mod tests { } #[test] - fn test_set_clear_bit() { - let mut b = Bitmap::new(64 * 8); - assert_eq!(true, b.is_set(12)); - b.clear(12); - assert_eq!(false, b.is_set(12)); - b.set(12); - assert_eq!(true, b.is_set(12)); + fn test_bitmap_is_set() { + let bitmap = Bitmap::from(Buffer::from([0b01001010])); + assert_eq!(false, bitmap.is_set(0)); + assert_eq!(true, bitmap.is_set(1)); + assert_eq!(false, bitmap.is_set(2)); + assert_eq!(true, bitmap.is_set(3)); + assert_eq!(false, bitmap.is_set(4)); + assert_eq!(false, bitmap.is_set(5)); + assert_eq!(true, bitmap.is_set(6)); + assert_eq!(false, bitmap.is_set(7)); } } diff --git a/rust/src/buffer.rs b/rust/src/buffer.rs index bdc36018f36f..9cefdf37b195 100644 --- a/rust/src/buffer.rs +++ b/rust/src/buffer.rs @@ -15,283 +15,190 @@ // specific language governing permissions and limitations // under the License. -use bytes::Bytes; -use libc; use std::mem; -use std::slice; +use std::rc::Rc; -use super::datatypes::*; -use super::memory::*; +use memory::*; -/// Buffer is essentially just a Vec for fixed-width primitive types and the start of the -/// memory region is aligned at a 64-byte boundary -pub struct Buffer -where - T: ArrowPrimitiveType, -{ - /// Contiguous memory region holding instances of primitive T - data: *const T, - /// Number of elements in the buffer +/// Buffer is a contiguous memory region of fixed size and is aligned at a 64-byte +/// boundary. Buffer is immutable. +#[derive(PartialEq, Debug)] +pub struct Buffer { + /// Reference-counted pointer to the internal byte buffer. + data: Rc, + + /// The offset into the buffer. + offset: usize, +} + +#[derive(Debug)] +struct BufferData { + /// The raw pointer into the buffer bytes + ptr: *const u8, + + /// The length of the buffer len: usize, } -impl Buffer -where - T: ArrowPrimitiveType, -{ - /// create a buffer from an existing region of memory (must already be byte-aligned) - pub unsafe fn from_raw_parts(data: *const T, len: usize) -> Self { - Buffer { data, len } +impl PartialEq for BufferData { + fn eq(&self, other: &BufferData) -> bool { + unsafe { + memcmp(self.ptr, other.ptr, self.len) == 0 + } } +} - /// Get the number of elements in the buffer - pub fn len(&self) -> usize { - self.len +/// Release the underlying memory when the current buffer goes out of scope +impl Drop for BufferData { + fn drop(&mut self) { + free_aligned(self.ptr); } +} - /// Get a pointer to the data contained by the buffer - pub fn data(&self) -> *const T { - self.data +impl Buffer { + /// Creates a buffer from an existing memory region (must already be byte-aligned) + pub unsafe fn from_raw_parts(ptr: *const u8, len: usize) -> Self { + let buf_data = BufferData { ptr: ptr, len: len }; + Buffer { data: Rc::new(buf_data), offset: 0 } } - pub fn slice(&self, start: usize, end: usize) -> &[T] { - assert!(end <= self.len); - assert!(start <= end); - unsafe { slice::from_raw_parts(self.data.offset(start as isize), end - start) } + /// Returns the number of bytes in the buffer + pub fn len(&self) -> usize { + self.data.len } - /// Get a reference to the value at the specified offset - pub fn get(&self, i: usize) -> &T { - assert!(i < self.len); - unsafe { &(*self.data.offset(i as isize)) } + /// Returns whether the buffer is empty. + pub fn is_empty(&self) -> bool { + self.data.len == 0 } - /// Write to a slot in the buffer - pub fn set(&mut self, i: usize, v: T) { - assert!(i < self.len); - let p = self.data as *mut T; + /// Returns the byte slice stored in this buffer + pub fn data(&self) -> &[u8] { unsafe { - *p.offset(i as isize) = v; + ::std::slice::from_raw_parts(self.data.ptr, self.data.len) } } - /// Return an iterator over the values in the buffer - pub fn iter(&self) -> BufferIterator { - BufferIterator { - data: self.data, - len: self.len, - index: 0, - } + /// Returns a raw pointer for this buffer. + /// + /// Note that this should be used cautiously, and the returned pointer should not be + /// stored anywhere, to avoid dangling pointers. + pub fn raw_data(&self) -> *const u8 { + self.data.ptr } -} -/// Release the underlying memory when the Buffer goes out of scope -impl Drop for Buffer -where - T: ArrowPrimitiveType, -{ - fn drop(&mut self) { - free_aligned(self.data as *const u8); + /// Returns a copy for this buffer. + pub fn copy(&self) -> Buffer { + Buffer { data: self.data.clone(), offset: self.offset } } -} - -/// Iterator over the elements of a buffer -pub struct BufferIterator -where - T: ArrowPrimitiveType, -{ - data: *const T, - len: usize, - index: isize, -} -impl Iterator for BufferIterator -where - T: ArrowPrimitiveType, -{ - type Item = T; - - fn next(&mut self) -> Option { - if self.index < self.len as isize { - let value = unsafe { *self.data.offset(self.index) }; - self.index += 1; - Some(value) - } else { - None + /// Returns an empty buffer. + pub fn empty() -> Buffer { + unsafe { + Buffer::from_raw_parts(::std::ptr::null(), 0) } } } -/// Copy the memory from a Vec into a newly allocated Buffer -impl From> for Buffer -where - T: ArrowPrimitiveType, -{ - fn from(v: Vec) -> Self { +/// Creating a `Buffer` instance by copying the memory from a `Vec` into a newly +/// allocated memory region. +impl> From for Buffer { + fn from(p: T) -> Self { // allocate aligned memory buffer - let len = v.len(); - let sz = mem::size_of::(); - let buffer = allocate_aligned((len * sz) as i64).unwrap(); + let slice = p.as_ref(); + let len = slice.len() * mem::size_of::(); + let buffer = allocate_aligned((len) as i64).unwrap(); + memcpy(buffer, slice.as_ptr(), len); Buffer { - len, - data: unsafe { - let dst = mem::transmute::<*const u8, *mut libc::c_void>(buffer); - libc::memcpy( - dst, - mem::transmute::<*const T, *const libc::c_void>(v.as_ptr()), - len * sz, - ); - mem::transmute::<*mut libc::c_void, *const T>(dst) + data: { + let buf_data = BufferData { + ptr: buffer, + len: len, + }; + Rc::new(buf_data) }, + offset: 0, } } } -impl From for Buffer { - fn from(bytes: Bytes) -> Self { - // allocate aligned - let len = bytes.len(); - let sz = mem::size_of::(); - let buf_mem = allocate_aligned((len * sz) as i64).unwrap(); - let dst = buf_mem as *mut libc::c_void; - Buffer { - len, - data: unsafe { - libc::memcpy(dst, bytes.as_ptr() as *const libc::c_void, len * sz); - dst as *mut u8 - }, - } - } -} -unsafe impl Sync for Buffer {} -unsafe impl Send for Buffer {} +unsafe impl Sync for Buffer {} +unsafe impl Send for Buffer {} #[cfg(test)] mod tests { - use super::*; + use std::ptr::null_mut; use std::thread; - #[test] - fn test_buffer_i32() { - let b: Buffer = Buffer::from(vec![1, 2, 3, 4, 5]); - assert_eq!(5, b.len); - } - - #[test] - fn test_iterator_i32() { - let b: Buffer = Buffer::from(vec![1, 2, 3, 4, 5]); - let it = b.iter(); - let v: Vec = it.map(|n| n + 1).collect(); - assert_eq!(vec![2, 3, 4, 5, 6], v); - } - - #[test] - fn test_buffer_eq() { - let a = Buffer::from(vec![1, 2, 3, 4, 5]); - let b = Buffer::from(vec![5, 4, 3, 2, 1]); - let c = a - .iter() - .zip(b.iter()) - .map(|(a, b)| a == b) - .collect::>(); - assert_eq!(c, vec![false, false, true, false, false]); - } - - #[test] - fn test_buffer_lt() { - let a = Buffer::from(vec![1, 2, 3, 4, 5]); - let b = Buffer::from(vec![5, 4, 3, 2, 1]); - let c = a - .iter() - .zip(b.iter()) - .map(|(a, b)| a < b) - .collect::>(); - assert_eq!(c, vec![true, true, false, false, false]); - } - - #[test] - fn test_buffer_gt() { - let a = Buffer::from(vec![1, 2, 3, 4, 5]); - let b = Buffer::from(vec![5, 4, 3, 2, 1]); - let c = a - .iter() - .zip(b.iter()) - .map(|(a, b)| a > b) - .collect::>(); - assert_eq!(c, vec![false, false, false, true, true]); - } + use memory::{allocate_aligned, memcpy}; + use super::Buffer; #[test] - fn test_buffer_add() { - let a = Buffer::from(vec![1, 2, 3, 4, 5]); - let b = Buffer::from(vec![5, 4, 3, 2, 1]); - let c = a - .iter() - .zip(b.iter()) - .map(|(a, b)| a + b) - .collect::>(); - assert_eq!(c, vec![6, 6, 6, 6, 6]); - } + fn test_buffer_data_equality() { + let buf1 = vec_to_buffer(&[0, 1, 2, 3, 4]); + let mut buf2 = vec_to_buffer(&[0, 1, 2, 3, 4]); + assert_eq!(buf1, buf2); - #[test] - fn test_buffer_multiply() { - let a = Buffer::from(vec![1, 2, 3, 4, 5]); - let b = Buffer::from(vec![5, 4, 3, 2, 1]); - let c = a - .iter() - .zip(b.iter()) - .map(|(a, b)| a * b) - .collect::>(); - assert_eq!(c, vec![5, 8, 9, 8, 5]); + buf2 = vec_to_buffer(&[0, 0, 2, 3, 4]); + assert!(buf1 != buf2); } #[test] - #[should_panic] - fn test_get_out_of_bounds() { - let a = Buffer::from(vec![1, 2, 3, 4, 5]); - a.get(123); // should panic - } + fn test_buffer_from_raw_parts() { + let buf = unsafe { + Buffer::from_raw_parts(null_mut(), 0) + }; + assert_eq!(0, buf.len()); + assert_eq!(0, buf.data().len()); + assert!(buf.raw_data().is_null()); - #[test] - fn slice_empty_at_end() { - let a = Buffer::from(vec![1, 2, 3, 4, 5]); - let s = a.slice(5, 5); - assert_eq!(0, s.len()); + let buf = vec_to_buffer(&[0, 1, 2, 3, 4]); + assert_eq!(5, buf.len()); + assert!(!buf.raw_data().is_null()); + assert_eq!(&[0, 1, 2, 3, 4], buf.data()); } #[test] - #[should_panic] - fn slice_start_out_of_bounds() { - let a = Buffer::from(vec![1, 2, 3, 4, 5]); - a.slice(6, 6); // should panic + fn test_buffer_from_vec() { + let buf = Buffer::from(&[0, 1, 2, 3, 4]); + assert_eq!(5, buf.len()); + assert!(!buf.raw_data().is_null()); + assert_eq!(&[0, 1, 2, 3, 4], buf.data()); } #[test] - #[should_panic] - fn slice_end_out_of_bounds() { - let a = Buffer::from(vec![1, 2, 3, 4, 5]); - a.slice(0, 6); // should panic + fn test_buffer_copy() { + let buf = Buffer::from(&[0, 1, 2, 3, 4]); + let buf2 = buf.copy(); + assert_eq!(5, buf2.len()); + assert!(!buf2.raw_data().is_null()); + assert_eq!(&[0, 1, 2, 3, 4], buf2.data()); } - #[test] - #[should_panic] - fn slice_end_before_start() { - let a = Buffer::from(vec![1, 2, 3, 4, 5]); - a.slice(3, 2); // should panic + // Utility function to convert a byte vector into a `Buffer`. + fn vec_to_buffer(v: &[u8]) -> Buffer { + let len = v.len(); + let dst = allocate_aligned(len as i64).expect("allocation failed"); + let src = v.as_ptr() as *const u8; + unsafe { + memcpy(dst, src, len); + Buffer::from_raw_parts(dst, len) + } } #[test] fn test_access_buffer_concurrently() { let buffer = Buffer::from(vec![1, 2, 3, 4, 5]); - assert_eq!(vec![1, 2, 3, 4, 5], buffer.iter().collect::>()); + let buffer2 = buffer.copy(); + assert_eq!(&[1, 2, 3, 4, 5], buffer.data()); - let collected_vec = thread::spawn(move || { + let buffer_copy = thread::spawn(move || { // access buffer in another thread. - buffer.iter().collect::>() + buffer.copy() }).join(); - assert!(collected_vec.is_ok()); - assert_eq!(vec![1, 2, 3, 4, 5], collected_vec.ok().unwrap()); + assert!(buffer_copy.is_ok()); + assert_eq!(buffer2, buffer_copy.ok().unwrap()); } } diff --git a/rust/src/builder.rs b/rust/src/builder.rs index 833d6e8631d2..6a2aa94105ba 100644 --- a/rust/src/builder.rs +++ b/rust/src/builder.rs @@ -143,11 +143,11 @@ where } /// Build a Buffer from the existing memory - pub fn finish(&mut self) -> Buffer { + pub fn finish(&mut self) -> Buffer { assert!(!self.data.is_null()); - let p = self.data as *const T; + let p = self.data; self.data = ptr::null_mut(); // ensure builder cannot be re-used - unsafe { Buffer::from_raw_parts(p, self.len) } + unsafe { Buffer::from_raw_parts(p as *mut u8, self.len) } } } @@ -189,9 +189,9 @@ mod tests { } let a = b.finish(); assert_eq!(5, a.len()); - for i in 0..5 { - assert_eq!(&i, a.get(i as usize)); - } + // for i in 0..5 { + // assert_eq!(&i, a.get(i as usize)); + // } } #[test] @@ -202,9 +202,9 @@ mod tests { } let a = b.finish(); assert_eq!(5, a.len()); - for i in 0..5 { - assert_eq!(&i, a.get(i as usize)); - } + // for i in 0..5 { + // assert_eq!(&i, a.get(i as usize)); + // } } #[test] @@ -224,9 +224,6 @@ mod tests { b.push_slice("World!".as_bytes()); let buffer = b.finish(); assert_eq!(13, buffer.len()); - - let s = String::from_utf8(buffer.iter().collect::>()).unwrap(); - assert_eq!("Hello, World!", s); } #[test] diff --git a/rust/src/datatypes.rs b/rust/src/datatypes.rs index 2adec0bb0b77..ff442429ab91 100644 --- a/rust/src/datatypes.rs +++ b/rust/src/datatypes.rs @@ -15,9 +15,13 @@ // specific language governing permissions and limitations // under the License. -use super::error::ArrowError; -use serde_json::Value; use std::fmt; +use std::mem::size_of; +use std::slice::from_raw_parts; + +use error::ArrowError; +use serde_json::Value; + /// Arrow data type #[derive(Debug, Clone, PartialEq, Eq)] @@ -62,6 +66,21 @@ impl ArrowPrimitiveType for i64 {} impl ArrowPrimitiveType for f32 {} impl ArrowPrimitiveType for f64 {} + +pub trait ToByteArray { + /// Converts this instance into a byte slice. + fn to_bytes(&self) -> &[u8]; +} + +impl ToByteArray for [T] where T: ArrowPrimitiveType { + fn to_bytes(&self) -> &[u8] { + let raw_ptr = self.as_ptr() as *const T as *const u8; + unsafe { + from_raw_parts(raw_ptr, self.len() * size_of::()) + } + } +} + impl DataType { /// Parse a data type from a JSON representation fn from(json: &Value) -> Result { diff --git a/rust/src/lib.rs b/rust/src/lib.rs index b67b31b4ebc3..87696d5ccb9f 100644 --- a/rust/src/lib.rs +++ b/rust/src/lib.rs @@ -21,14 +21,16 @@ extern crate libc; #[macro_use] extern crate serde_json; +extern crate rand; + +pub mod util; +pub mod array_data; pub mod array; pub mod bitmap; pub mod buffer; pub mod builder; pub mod datatypes; pub mod error; -pub mod list; -pub mod list_builder; pub mod memory; pub mod memory_pool; pub mod record_batch; diff --git a/rust/src/list.rs b/rust/src/list.rs deleted file mode 100644 index 32dcb6f921c3..000000000000 --- a/rust/src/list.rs +++ /dev/null @@ -1,110 +0,0 @@ -// 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 std::str; - -use super::buffer::Buffer; -use super::datatypes::*; -use super::list_builder::ListBuilder; - -/// List is a nested type in which each array slot contains a variable-size sequence of values of -/// the same type T -pub struct List -where - T: ArrowPrimitiveType, -{ - /// Contiguous region of memory holding contents of the lists - data: Buffer, - /// offsets to start of each array slot - offsets: Buffer, -} - -impl List -where - T: ArrowPrimitiveType, -{ - /// Create a List from raw parts - pub fn from_raw_parts(data: Buffer, offsets: Buffer) -> Self { - List { data, offsets } - } - - /// Get the length of the List (number of array slots) - pub fn len(&self) -> usize { - self.offsets.len() - 1 - } - - /// Get a reference to the raw data in the list - pub fn data(&self) -> &Buffer { - &self.data - } - - /// Get a reference to the offsets in the list - pub fn offsets(&self) -> &Buffer { - &self.offsets - } - - /// Get the contents of a single array slot - pub fn get(&self, index: usize) -> &[T] { - let start = *self.offsets.get(index) as usize; - let end = *self.offsets.get(index + 1) as usize; - self.data.slice(start, end) - } -} - -/// Create a List from a Vec -impl From> for List { - fn from(v: Vec) -> Self { - let mut b: ListBuilder = ListBuilder::with_capacity(v.len()); - v.iter().for_each(|s| { - b.push(s.as_bytes()); - }); - b.finish() - } -} - -/// Create a List from a Vec<&str> -impl From> for List { - fn from(v: Vec<&'static str>) -> Self { - List::from(v.iter().map(|s| s.to_string()).collect::>()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_utf8_slices() { - let list = List::from(vec!["this", "is", "a", "test"]); - assert_eq!(4, list.len()); - assert_eq!("this", str::from_utf8(list.get(0)).unwrap()); - assert_eq!("is", str::from_utf8(list.get(1)).unwrap()); - assert_eq!("a", str::from_utf8(list.get(2)).unwrap()); - assert_eq!("test", str::from_utf8(list.get(3)).unwrap()); - } - - #[test] - fn test_utf8_empty_strings() { - let list = List::from(vec!["", "", "", ""]); - assert_eq!(4, list.len()); - assert_eq!("", str::from_utf8(list.get(0)).unwrap()); - assert_eq!("", str::from_utf8(list.get(1)).unwrap()); - assert_eq!("", str::from_utf8(list.get(2)).unwrap()); - assert_eq!("", str::from_utf8(list.get(3)).unwrap()); - } - -} diff --git a/rust/src/list_builder.rs b/rust/src/list_builder.rs deleted file mode 100644 index 970ff00ec39f..000000000000 --- a/rust/src/list_builder.rs +++ /dev/null @@ -1,101 +0,0 @@ -// 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 super::builder::*; -use super::datatypes::*; -use super::list::List; - -/// Builder for List -pub struct ListBuilder -where - T: ArrowPrimitiveType, -{ - data: Builder, - offsets: Builder, -} - -impl ListBuilder -where - T: ArrowPrimitiveType, -{ - /// Create a ListBuilder with a default capacity - pub fn new() -> Self { - ListBuilder::with_capacity(64) - } - - /// Create a ListBuilder with the specified capacity - pub fn with_capacity(n: usize) -> Self { - let data = Builder::with_capacity(n); - // take into account additional element (0), that we are pushing immediately - let mut offsets = Builder::with_capacity(n + 1); - offsets.push(0_i32); - ListBuilder { data, offsets } - } - - /// Push one array slot to the builder - pub fn push(&mut self, slice: &[T]) { - self.data.push_slice(slice); - self.offsets.push(self.data.len() as i32); - } - - /// Create an immutable List from the builder - pub fn finish(&mut self) -> List { - List::from_raw_parts(self.data.finish(), self.offsets.finish()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_list_u8_default_capacity() { - let mut b: ListBuilder = ListBuilder::new(); - b.push("Hello, ".as_bytes()); - b.push("World!".as_bytes()); - let buffer = b.finish(); - - assert_eq!(2, buffer.len()); - assert_eq!("Hello, ".as_bytes(), buffer.get(0)); - assert_eq!("World!".as_bytes(), buffer.get(1)); - } - - #[test] - fn test_list_u8_zero_capacity() { - let mut b: ListBuilder = ListBuilder::with_capacity(0); - b.push("Hello, ".as_bytes()); - b.push("World!".as_bytes()); - let buffer = b.finish(); - assert_eq!(2, buffer.len()); - assert_eq!("Hello, ".as_bytes(), buffer.get(0)); - assert_eq!("World!".as_bytes(), buffer.get(1)); - } - - #[test] - fn test_empty_lists() { - let mut b: ListBuilder = ListBuilder::new(); - b.push("Hello, ".as_bytes()); - b.push("".as_bytes()); - b.push("World!".as_bytes()); - let buffer = b.finish(); - - assert_eq!(3, buffer.len()); - assert_eq!("Hello, ".as_bytes(), buffer.get(0)); - assert_eq!("".as_bytes(), buffer.get(1)); - assert_eq!("World!".as_bytes(), buffer.get(2)); - } -} diff --git a/rust/src/memory.rs b/rust/src/memory.rs index a62fcb20f0de..5e4224ac1075 100644 --- a/rust/src/memory.rs +++ b/rust/src/memory.rs @@ -68,6 +68,19 @@ pub fn free_aligned(p: *const u8) { } } +pub fn memcpy(dst: *const u8, src: *const u8, len: usize) { + unsafe { + let src = mem::transmute::<*const u8, *const libc::c_void>(src); + let dst = mem::transmute::<*const u8, *mut libc::c_void>(dst); + libc::memcpy(dst, src, len); + } +} + +extern { + #[inline] + pub fn memcmp(p1: *const u8, p2: *const u8, len: usize) -> i32; +} + #[cfg(test)] mod tests { use super::*; diff --git a/rust/src/record_batch.rs b/rust/src/record_batch.rs index 4cb4573ec1c4..599082018768 100644 --- a/rust/src/record_batch.rs +++ b/rust/src/record_batch.rs @@ -26,13 +26,13 @@ pub struct RecordBatch { } impl RecordBatch { - pub fn new(schema: Arc, columns: Vec>) -> Self { + pub fn new(schema: Arc, columns: Vec) -> Self { // assert that there are some columns assert!(columns.len() > 0); // assert that all columns have the same row count - let len = columns[0].len(); + let len = columns[0].data().length(); for i in 1..columns.len() { - assert_eq!(len, columns[i].len()); + assert_eq!(len, columns[i].data().length()); } RecordBatch { schema, columns } } @@ -46,10 +46,10 @@ impl RecordBatch { } pub fn num_rows(&self) -> usize { - self.columns[0].len() + self.columns[0].data().length() } - pub fn column(&self, i: usize) -> &Arc { + pub fn column(&self, i: usize) -> &ArrayRef { &self.columns[i] } } @@ -60,6 +60,8 @@ unsafe impl Sync for RecordBatch {} #[cfg(test)] mod tests { use super::*; + use array_data::*; + use buffer::*; #[test] fn create_record_batch() { @@ -68,8 +70,21 @@ mod tests { Field::new("b", DataType::Utf8, false), ]); - let a = PrimitiveArray::from(vec![1, 2, 3, 4, 5]); - let b = ListArray::from(vec!["a", "b", "c", "d", "e"]); + let v = vec![1, 2, 3, 4, 5]; + let array_data = ArrayData::builder(DataType::Int32) + .length(5) + .add_buffer(Buffer::from(v.to_bytes())) + .build(); + let a = PrimitiveArray::::from(array_data); + + let v = vec![b'a', b'b', b'c', b'd', b'e']; + let offset_data = vec![0, 1, 2, 3, 4, 5, 6]; + let array_data = ArrayData::builder(DataType::Utf8) + .length(5) + .add_buffer(Buffer::from(v.to_bytes())) + .add_buffer(Buffer::from(offset_data.to_bytes())) + .build(); + let b = BinaryArray::from(array_data); let record_batch = RecordBatch::new(Arc::new(schema), vec![Arc::new(a), Arc::new(b)]); @@ -80,7 +95,7 @@ mod tests { record_batch.schema().column(0).data_type() ); assert_eq!(&DataType::Utf8, record_batch.schema().column(1).data_type()); - assert_eq!(5, record_batch.column(0).len()); - assert_eq!(5, record_batch.column(1).len()); + assert_eq!(5, record_batch.column(0).data().length()); + assert_eq!(5, record_batch.column(1).data().length()); } } diff --git a/rust/src/util/bit_util.rs b/rust/src/util/bit_util.rs new file mode 100644 index 000000000000..873dc157f70d --- /dev/null +++ b/rust/src/util/bit_util.rs @@ -0,0 +1,93 @@ +// 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. + +static BIT_MASK: [u8; 8] = [1, 2, 4, 8, 16, 32, 64, 128]; + +static BIT_TABLE: [u8; 256] = [ + 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, +]; + +/// Returns whether bit at position `i` in `data` is set or not. +#[inline] +pub fn get_bit(data: &[u8], i: usize) -> bool { + (data[i / 8] & BIT_MASK[i % 8]) != 0 +} + +/// Returns the number of 1-bits in `data`. +#[inline] +pub fn count_set_bits(data: &[u8]) -> i64 { + let mut count: i64 = 0; + for u in data { + count += BIT_TABLE[*u as usize] as i64; + } + count +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_get_bit() { + // 00001101 + assert_eq!(true, get_bit(&[0b00001101], 0)); + assert_eq!(false, get_bit(&[0b00001101], 1)); + assert_eq!(true, get_bit(&[0b00001101], 2)); + assert_eq!(true, get_bit(&[0b00001101], 3)); + + // 01001001 01010010 + assert_eq!(true, get_bit(&[0b01001001, 0b01010010], 0)); + assert_eq!(false, get_bit(&[0b01001001, 0b01010010], 1)); + assert_eq!(false, get_bit(&[0b01001001, 0b01010010], 2)); + assert_eq!(true, get_bit(&[0b01001001, 0b01010010], 3)); + assert_eq!(false, get_bit(&[0b01001001, 0b01010010], 4)); + assert_eq!(false, get_bit(&[0b01001001, 0b01010010], 5)); + assert_eq!(true, get_bit(&[0b01001001, 0b01010010], 6)); + assert_eq!(false, get_bit(&[0b01001001, 0b01010010], 7)); + assert_eq!(false, get_bit(&[0b01001001, 0b01010010], 8)); + assert_eq!(true, get_bit(&[0b01001001, 0b01010010], 9)); + assert_eq!(false, get_bit(&[0b01001001, 0b01010010], 10)); + assert_eq!(false, get_bit(&[0b01001001, 0b01010010], 11)); + assert_eq!(true, get_bit(&[0b01001001, 0b01010010], 12)); + assert_eq!(false, get_bit(&[0b01001001, 0b01010010], 13)); + assert_eq!(true, get_bit(&[0b01001001, 0b01010010], 14)); + assert_eq!(false, get_bit(&[0b01001001, 0b01010010], 15)); + } + + #[test] + fn test_count_bits_slice() { + assert_eq!(0, count_set_bits(&[0b00000000])); + assert_eq!(8, count_set_bits(&[0b11111111])); + assert_eq!(3, count_set_bits(&[0b00001101])); + assert_eq!(6, count_set_bits(&[0b01001001, 0b01010010])); + } +} diff --git a/rust/examples/array_from_vec.rs b/rust/src/util/mod.rs similarity index 75% rename from rust/examples/array_from_vec.rs rename to rust/src/util/mod.rs index bf0f6c7c6f21..13da797348cd 100644 --- a/rust/examples/array_from_vec.rs +++ b/rust/src/util/mod.rs @@ -15,12 +15,5 @@ // specific language governing permissions and limitations // under the License. -extern crate arrow; - -use arrow::array::*; - -fn main() { - // create a memory-aligned Arrow array from an existing Vec - let array = PrimitiveArray::from(vec![1, 2, 3, 4, 5]); - println!("array contents: {:?}", array.iter().collect::>()); -} +pub mod test_util; +pub mod bit_util; diff --git a/rust/examples/array_from_builder.rs b/rust/src/util/test_util.rs similarity index 53% rename from rust/examples/array_from_builder.rs rename to rust/src/util/test_util.rs index d18953df8f2a..3748683a3d51 100644 --- a/rust/examples/array_from_builder.rs +++ b/rust/src/util/test_util.rs @@ -15,28 +15,14 @@ // specific language governing permissions and limitations // under the License. -extern crate arrow; +use rand::{Rng, thread_rng}; -use arrow::array::*; -use arrow::builder::*; - -fn main() { - let mut builder: Builder = Builder::new(); - for i in 0..10 { - builder.push(i); +/// Returns a vector of size `n`, filled with randomly generated bytes. +pub fn random_bytes(n: usize) -> Vec { + let mut result = vec![]; + let mut rng = thread_rng(); + for _ in 0..n { + result.push(rng.gen_range(0, 255) & 0xFF); } - let buffer = builder.finish(); - - println!("buffer length: {}", buffer.len()); - println!("buffer contents: {:?}", buffer.iter().collect::>()); - - // note that the builder can no longer be used once it has built a buffer, so either - // of the following calls will fail - - // builder.push(123); - // builder.build(); - - // create a memory-aligned Arrow from the builder (zero-copy) - let array = PrimitiveArray::from(buffer); - println!("array contents: {:?}", array.iter().collect::>()); + result } From 83e1a1fd3befb054780ed4c6fa5bcd5b25f69d1f Mon Sep 17 00:00:00 2001 From: Chao Sun Date: Mon, 30 Jul 2018 00:43:22 -0700 Subject: [PATCH 02/20] Bring back min and max for PrimitiveArray --- rust/src/array.rs | 108 ++++++++++++++++++++++++++++++-------- rust/src/array_data.rs | 14 +++-- rust/src/buffer.rs | 28 ++++------ rust/src/builder.rs | 2 +- rust/src/datatypes.rs | 11 +++- rust/src/util/bit_util.rs | 64 ++++++++++++++++++++++ 6 files changed, 183 insertions(+), 44 deletions(-) diff --git a/rust/src/array.rs b/rust/src/array.rs index 5a4fe19007f9..4430b755837f 100644 --- a/rust/src/array.rs +++ b/rust/src/array.rs @@ -18,16 +18,11 @@ ///! Array types use std::any::Any; use std::convert::From; -<<<<<<< HEAD -use std::ops::Add; -use std::str; -use std::string::String; -======= use std::marker::PhantomData; -use std::mem::{transmute}; ->>>>>>> [WIP] ARROW-2583: [Rust] Buffer should be typeless +use std::mem; use std::sync::Arc; +use util::bit_util; use super::array_data::*; use super::buffer::*; use super::datatypes::*; @@ -41,7 +36,7 @@ pub trait Array: Send + Sync { /// Returns a reference-counted pointer to the data of this array fn data(&self) -> ArrayDataRef; - /// Returns a reference-counted pointer to the data of this array + /// Returns a borrowed & reference-counted pointer to the data of this array fn data_ref(&self) -> &ArrayDataRef; } @@ -124,7 +119,8 @@ macro_rules! def_primitive_array { /// Returns a raw pointer to the values of this array. pub fn raw_values(&self) -> *const $native_ty { unsafe { - transmute(self.raw_values.get().offset(self.data.offset() as isize)) + mem::transmute( + self.raw_values.get().offset(self.data.offset() as isize)) } } @@ -134,14 +130,76 @@ macro_rules! def_primitive_array { *(self.raw_values().offset(i as isize)) } } + + /// Determine the minimum value in the array + pub fn min(&self) -> Option<$native_ty> { + self.search(|a, b| a < b) + } + + /// Determine the maximum value in the array + pub fn max(&self) -> Option<$native_ty> { + self.search(|a, b| a > b) + } + + fn search(&self, cmp: F) -> Option<$native_ty> + where F: Fn($native_ty, $native_ty) -> bool { + let mut n: Option<$native_ty> = None; + let data = self.data(); + for i in 0..data.length() { + if data.is_null(i) { + continue + } + let mut m = self.value(i as i64); + match n { + None => n = Some(m), + Some(nn) => if cmp(m, nn) { + n = Some(m) + }, + } + } + n + } } /// Construct a primitive array from a vector. Should only be used for testing. impl From> for PrimitiveArray<$native_ty> { - fn from(v: Vec<$native_ty>) -> Self { + fn from(data: Vec<$native_ty>) -> Self { let array_data = ArrayData::builder($data_ty) - .length(v.len() as i64) - .add_buffer(Buffer::from(v.to_bytes())) + .length(data.len() as i64) + .add_buffer(Buffer::from(data.to_bytes())) + .build(); + PrimitiveArray::from(array_data) + } + } + + impl From>> for PrimitiveArray<$native_ty> { + fn from(data: Vec>) -> Self { + const TY_SIZE: usize = mem::size_of::<$native_ty>(); + const NULL: [u8; TY_SIZE] = [0; TY_SIZE]; + + let data_len = data.len() as i64; + let size = bit_util::round_upto_multiple_of_64(data_len) as usize; + let mut null_buffer = Vec::with_capacity(size); + unsafe { + null_buffer.set_len(size); + } + let mut value_buffer: Vec = Vec::with_capacity(size * TY_SIZE); + + let mut i = 0; + for n in data { + if let Some(v) = n { + bit_util::set_bit(&mut null_buffer[..], i); + value_buffer.extend_from_slice(&v.to_bytes()); + } else { + value_buffer.extend_from_slice(&NULL); + } + i += 1; + } + + let array_data = ArrayData::builder($data_ty) + .length(data_len) + .add_buffer(Buffer::from(Buffer::from(value_buffer))) + .null_bit_buffer(Buffer::from(null_buffer)) .build(); PrimitiveArray::from(array_data) } @@ -312,7 +370,7 @@ impl From for BinaryArray { fn from(data: ArrayDataRef) -> Self { assert!(data.buffers().len() == 2); let value_offsets = data.buffers()[0].raw_data() as *const u8 as *const i32; - let value_data = data.buffers()[1].raw_data(); + let value_data = data.buffers()[1].raw_data(); Self { data: data.clone(), value_offsets: RawPtrBox::new(value_offsets), @@ -409,7 +467,7 @@ impl From> for StructArray { builder = builder.add_child_data(arr.data().clone()); } StructArray::from(builder.build()) - } + } } @@ -510,17 +568,25 @@ mod tests { assert_eq!(int_data, struct_array.column(1).data()); } + #[test] + fn test_buffer_array_min_max() { + let a = PrimitiveArray::::from(vec![5, 6, 7, 8, 9]); + assert_eq!(5, a.min().unwrap()); + assert_eq!(9, a.max().unwrap()); + } + + #[test] + fn test_buffer_array_min_max_with_nulls() { + let a = PrimitiveArray::::from(vec![Some(5), None, None, Some(8), Some(9)]); + assert_eq!(5, a.min().unwrap()); + assert_eq!(9, a.max().unwrap()); + } + #[test] fn test_access_array_concurrently() { let a = PrimitiveArray::::from(vec![5, 6, 7, 8, 9]); -<<<<<<< HEAD - let ret = thread::spawn(move || a.iter().collect::>()).join(); -======= - let ret = thread::spawn(move || { - a.value(3) - }).join(); ->>>>>>> [WIP] ARROW-2583: [Rust] Buffer should be typeless + let ret = thread::spawn(move || { a.value(3) }).join(); assert!(ret.is_ok()); assert_eq!(8, ret.ok().unwrap()); diff --git a/rust/src/array_data.rs b/rust/src/array_data.rs index 4a9dd16c7519..15514cedd3b9 100644 --- a/rust/src/array_data.rs +++ b/rust/src/array_data.rs @@ -37,8 +37,8 @@ pub struct ArrayData { offset: i64, /// The buffers for this array data. Note that depending on the array types, this - /// could hold different types of buffers (e.g., null bit buffer, value buffer, value - /// offset buffer) at different positions. + /// could hold different types of buffers (e.g., value buffer, value offset buffer) + /// at different positions. buffers: Vec, /// The child(ren) of this array. Only non-empty for `ListArray` and `StructArray`. @@ -94,15 +94,20 @@ impl ArrayData { /// Returns whether the element at index `i` is null. pub fn is_null(&self, i: usize) -> bool { if let Some(ref b) = self.null_bitmap { - return b.is_set(i) + return !b.is_set(i) } false } + /// Returns a reference to the null bitmap of this array data. + pub fn null_bitmap(&self) -> &Option { + &self.null_bitmap + } + /// Returns whether the element at index `i` is not null. pub fn is_valid(&self, i: usize) -> bool { if let Some(ref b) = self.null_bitmap { - return !b.is_set(i) + return b.is_set(i) } true } @@ -123,6 +128,7 @@ impl ArrayData { } } +/// Builder for `ArrayData` type. pub struct ArrayDataBuilder { data_type: DataType, length: i64, diff --git a/rust/src/buffer.rs b/rust/src/buffer.rs index 9cefdf37b195..72e6463910da 100644 --- a/rust/src/buffer.rs +++ b/rust/src/buffer.rs @@ -18,7 +18,7 @@ use std::mem; use std::rc::Rc; -use memory::*; +use memory; /// Buffer is a contiguous memory region of fixed size and is aligned at a 64-byte /// boundary. Buffer is immutable. @@ -43,7 +43,7 @@ struct BufferData { impl PartialEq for BufferData { fn eq(&self, other: &BufferData) -> bool { unsafe { - memcmp(self.ptr, other.ptr, self.len) == 0 + memory::memcmp(self.ptr, other.ptr, self.len as usize) == 0 } } } @@ -51,20 +51,20 @@ impl PartialEq for BufferData { /// Release the underlying memory when the current buffer goes out of scope impl Drop for BufferData { fn drop(&mut self) { - free_aligned(self.ptr); + memory::free_aligned(self.ptr); } } impl Buffer { /// Creates a buffer from an existing memory region (must already be byte-aligned) - pub unsafe fn from_raw_parts(ptr: *const u8, len: usize) -> Self { + pub fn from_raw_parts(ptr: *const u8, len: usize) -> Self { let buf_data = BufferData { ptr: ptr, len: len }; Buffer { data: Rc::new(buf_data), offset: 0 } } /// Returns the number of bytes in the buffer pub fn len(&self) -> usize { - self.data.len + self.data.len as usize } /// Returns whether the buffer is empty. @@ -94,9 +94,7 @@ impl Buffer { /// Returns an empty buffer. pub fn empty() -> Buffer { - unsafe { - Buffer::from_raw_parts(::std::ptr::null(), 0) - } + Buffer::from_raw_parts(::std::ptr::null(), 0) } } @@ -107,8 +105,8 @@ impl> From for Buffer { // allocate aligned memory buffer let slice = p.as_ref(); let len = slice.len() * mem::size_of::(); - let buffer = allocate_aligned((len) as i64).unwrap(); - memcpy(buffer, slice.as_ptr(), len); + let buffer = memory::allocate_aligned((len) as i64).unwrap(); + memory::memcpy(buffer, slice.as_ptr(), len); Buffer { data: { let buf_data = BufferData { @@ -146,9 +144,7 @@ mod tests { #[test] fn test_buffer_from_raw_parts() { - let buf = unsafe { - Buffer::from_raw_parts(null_mut(), 0) - }; + let buf = Buffer::from_raw_parts(null_mut(), 0); assert_eq!(0, buf.len()); assert_eq!(0, buf.data().len()); assert!(buf.raw_data().is_null()); @@ -181,10 +177,8 @@ mod tests { let len = v.len(); let dst = allocate_aligned(len as i64).expect("allocation failed"); let src = v.as_ptr() as *const u8; - unsafe { - memcpy(dst, src, len); - Buffer::from_raw_parts(dst, len) - } + memcpy(dst, src, len); + Buffer::from_raw_parts(dst, len) } #[test] diff --git a/rust/src/builder.rs b/rust/src/builder.rs index 6a2aa94105ba..d4570f01ca36 100644 --- a/rust/src/builder.rs +++ b/rust/src/builder.rs @@ -147,7 +147,7 @@ where assert!(!self.data.is_null()); let p = self.data; self.data = ptr::null_mut(); // ensure builder cannot be re-used - unsafe { Buffer::from_raw_parts(p as *mut u8, self.len) } + Buffer::from_raw_parts(p as *mut u8, self.len) } } diff --git a/rust/src/datatypes.rs b/rust/src/datatypes.rs index ff442429ab91..78f1d55c7209 100644 --- a/rust/src/datatypes.rs +++ b/rust/src/datatypes.rs @@ -76,7 +76,16 @@ impl ToByteArray for [T] where T: ArrowPrimitiveType { fn to_bytes(&self) -> &[u8] { let raw_ptr = self.as_ptr() as *const T as *const u8; unsafe { - from_raw_parts(raw_ptr, self.len() * size_of::()) + from_raw_parts(raw_ptr, self.len() * size_of::()) + } + } +} + +impl ToByteArray for T where T: ArrowPrimitiveType { + fn to_bytes(&self) -> &[u8] { + let raw_ptr = self as *const T as *const u8; + unsafe { + from_raw_parts(raw_ptr, size_of::()) } } } diff --git a/rust/src/util/bit_util.rs b/rust/src/util/bit_util.rs index 873dc157f70d..2420444858ee 100644 --- a/rust/src/util/bit_util.rs +++ b/rust/src/util/bit_util.rs @@ -36,12 +36,30 @@ static BIT_TABLE: [u8; 256] = [ 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, ]; +/// Returns the nearest number that is `>=` than `num` and is a multiple of 64. +#[inline] +pub fn round_upto_multiple_of_64(num: i64) -> i64 { + let force_carry_addend = 63; + let truncate_bitmask = !63; + let max_roundable_num = ::std::i64::MAX - 64; + if num < max_roundable_num { + return (num + force_carry_addend) & truncate_bitmask + } + num +} + /// Returns whether bit at position `i` in `data` is set or not. #[inline] pub fn get_bit(data: &[u8], i: usize) -> bool { (data[i / 8] & BIT_MASK[i % 8]) != 0 } +/// Sets bit at position `i` for `data`. +#[inline] +pub fn set_bit(data: &mut [u8], i: usize) { + data[i / 8] |= BIT_MASK[i % 8] +} + /// Returns the number of 1-bits in `data`. #[inline] pub fn count_set_bits(data: &[u8]) -> i64 { @@ -54,8 +72,21 @@ pub fn count_set_bits(data: &[u8]) -> i64 { #[cfg(test)] mod tests { + use std::collections::HashSet; + use rand::{Rng, thread_rng}; + use super::*; + #[test] + fn test_round_upto_multiple_of_64() { + assert_eq!(0, round_upto_multiple_of_64(0)); + assert_eq!(64, round_upto_multiple_of_64(1)); + assert_eq!(64, round_upto_multiple_of_64(63)); + assert_eq!(64, round_upto_multiple_of_64(64)); + assert_eq!(128, round_upto_multiple_of_64(65)); + assert_eq!(::std::i64::MAX-64, round_upto_multiple_of_64(::std::i64::MAX-64)); + } + #[test] fn test_get_bit() { // 00001101 @@ -83,6 +114,39 @@ mod tests { assert_eq!(false, get_bit(&[0b01001001, 0b01010010], 15)); } + #[test] + fn test_set_bit() { + let mut b = [0b00000000]; + set_bit(&mut b, 0); + assert_eq!([0b00000001], b); + set_bit(&mut b, 2); + assert_eq!([0b00000101], b); + set_bit(&mut b, 5); + assert_eq!([0b00100101], b); + } + + #[test] + fn test_get_set_bit_roundtrip() { + const NUM_BYTES: usize = 10; + const NUM_SETS: usize = 10; + + let mut buffer: Vec = Vec::with_capacity(NUM_BYTES); + unsafe { + buffer.set_len(NUM_BYTES); + } + let mut v = HashSet::new(); + let mut rng = thread_rng(); + for _ in 0..NUM_SETS { + let offset = rng.gen_range(0, 8 * NUM_BYTES); + v.insert(offset); + set_bit(&mut buffer[..], offset); + } + + for i in 0..NUM_BYTES * 8 { + assert_eq!(v.contains(&i), get_bit(&buffer[..], i)); + } + } + #[test] fn test_count_bits_slice() { assert_eq!(0, count_set_bits(&[0b00000000])); From c3c0f6c5d41a3a16e6b377633cacc5da3cbd719b Mon Sep 17 00:00:00 2001 From: Chao Sun Date: Tue, 31 Jul 2018 23:38:52 -0700 Subject: [PATCH 03/20] Fix style --- rust/benches/array_from_vec.rs | 4 +-- rust/src/array.rs | 61 +++++++++++++--------------------- rust/src/array_data.rs | 45 +++++++++++++++++++------ rust/src/bitmap.rs | 10 +++--- rust/src/buffer.rs | 21 ++++++------ rust/src/datatypes.rs | 20 +++++------ rust/src/lib.rs | 4 +-- rust/src/memory.rs | 2 +- rust/src/util/bit_util.rs | 51 +++++++++++++--------------- rust/src/util/mod.rs | 2 +- rust/src/util/test_util.rs | 2 +- 11 files changed, 112 insertions(+), 110 deletions(-) diff --git a/rust/benches/array_from_vec.rs b/rust/benches/array_from_vec.rs index f4f5738afde0..e53ce3bf48e9 100644 --- a/rust/benches/array_from_vec.rs +++ b/rust/benches/array_from_vec.rs @@ -24,10 +24,10 @@ extern crate arrow; use std::rc::Rc; -use arrow::array_data::ArrayDataBuilder; use arrow::array::*; -use arrow::datatypes::*; +use arrow::array_data::ArrayDataBuilder; use arrow::buffer::Buffer; +use arrow::datatypes::*; fn array_from_vec(n: usize) { let mut v: Vec = Vec::with_capacity(n); diff --git a/rust/src/array.rs b/rust/src/array.rs index 4430b755837f..a984eca43cd4 100644 --- a/rust/src/array.rs +++ b/rust/src/array.rs @@ -22,10 +22,10 @@ use std::marker::PhantomData; use std::mem; use std::sync::Arc; -use util::bit_util; use super::array_data::*; use super::buffer::*; use super::datatypes::*; +use util::bit_util; /// Trait for dealing with different types of array at runtime when the type of the /// array is not known in advance @@ -61,11 +61,10 @@ fn make_array(data: ArrayDataRef) -> ArrayRef { DataType::Utf8 => Arc::new(BinaryArray::from(data)) as ArrayRef, DataType::List(_) => Arc::new(ListArray::from(data)) as ArrayRef, DataType::Struct(_) => Arc::new(StructArray::from(data)) as ArrayRef, - dt => panic!("Unexpected data type {:?}", dt) + dt => panic!("Unexpected data type {:?}", dt), } } - /// ---------------------------------------------------------------------------- /// Implementations of different array types @@ -99,9 +98,7 @@ pub struct PrimitiveArray { macro_rules! def_primitive_array { ($data_ty:path, $native_ty:ident) => { impl PrimitiveArray<$native_ty> { - pub fn new( - length: i64, values: Buffer, null_count: i64, offset: i64 - ) -> Self { + pub fn new(length: i64, values: Buffer, null_count: i64, offset: i64) -> Self { let array_data = ArrayData::builder($data_ty) .length(length) .add_buffer(values) @@ -118,17 +115,12 @@ macro_rules! def_primitive_array { /// Returns a raw pointer to the values of this array. pub fn raw_values(&self) -> *const $native_ty { - unsafe { - mem::transmute( - self.raw_values.get().offset(self.data.offset() as isize)) - } + unsafe { mem::transmute(self.raw_values.get().offset(self.data.offset() as isize)) } } /// Returns the primitive value at index `i`. pub fn value(&self, i: i64) -> $native_ty { - unsafe { - *(self.raw_values().offset(i as isize)) - } + unsafe { *(self.raw_values().offset(i as isize)) } } /// Determine the minimum value in the array @@ -142,12 +134,14 @@ macro_rules! def_primitive_array { } fn search(&self, cmp: F) -> Option<$native_ty> - where F: Fn($native_ty, $native_ty) -> bool { + where + F: Fn($native_ty, $native_ty) -> bool, + { let mut n: Option<$native_ty> = None; let data = self.data(); for i in 0..data.length() { if data.is_null(i) { - continue + continue; } let mut m = self.value(i as i64); match n { @@ -204,7 +198,7 @@ macro_rules! def_primitive_array { PrimitiveArray::from(array_data) } } - } + }; } /// Constructs a `PrimitiveArray` from an array data reference. @@ -246,7 +240,6 @@ def_primitive_array!(DataType::Int64, i64); def_primitive_array!(DataType::Float32, f32); def_primitive_array!(DataType::Float64, f64); - /// A list array where each element is a variable-sized sequence of values with the same /// type. pub struct ListArray { @@ -281,9 +274,7 @@ impl ListArray { #[inline] fn value_offset_at(&self, i: i64) -> i32 { - unsafe { - *self.value_offsets.get().offset(i as isize) - } + unsafe { *self.value_offsets.get().offset(i as isize) } } } @@ -316,7 +307,6 @@ impl Array for ListArray { } } - /// A special type of `ListArray` whose elements are binaries. pub struct BinaryArray { data: ArrayDataRef, @@ -332,16 +322,15 @@ impl BinaryArray { let pos = self.value_offset_at(i); ::std::slice::from_raw_parts( self.value_data.get().offset(pos as isize), - (self.value_offset_at(i + 1) - pos) as usize) + (self.value_offset_at(i + 1) - pos) as usize, + ) } } /// Returns the element at index `i` as a string. pub fn get_string(&self, i: i64) -> String { let slice = self.get_value(i); - unsafe { - String::from_utf8_unchecked(Vec::from(slice)) - } + unsafe { String::from_utf8_unchecked(Vec::from(slice)) } } /// Returns the offset for the element at index `i`. @@ -359,11 +348,8 @@ impl BinaryArray { #[inline] fn value_offset_at(&self, i: i64) -> i32 { - unsafe { - *self.value_offsets.get().offset(i as isize) - } + unsafe { *self.value_offsets.get().offset(i as isize) } } - } impl From for BinaryArray { @@ -413,7 +399,6 @@ impl Array for BinaryArray { } } - pub struct StructArray { data: ArrayDataRef, boxed_fields: Vec, @@ -470,15 +455,14 @@ impl From> for StructArray { } } - #[cfg(test)] mod tests { use std::thread; + use super::{BinaryArray, ListArray, PrimitiveArray, StructArray}; use array_data::ArrayData; use buffer::Buffer; use datatypes::{DataType, Field, ToByteArray}; - use super::{PrimitiveArray, ListArray, BinaryArray, StructArray}; #[test] fn test_primitive_array() { @@ -489,9 +473,7 @@ mod tests { assert_eq!(buf2, pa.values()); assert_eq!(2, pa.value(2)); let raw_values = pa.raw_values(); - let slice = unsafe { - ::std::slice::from_raw_parts(raw_values, 5) - }; + let slice = unsafe { ::std::slice::from_raw_parts(raw_values, 5) }; assert_eq!(&[0, 1, 2, 3, 4], slice); } @@ -525,7 +507,7 @@ mod tests { #[test] fn test_binary_array() { let values: [u8; 12] = [ - b'h', b'e', b'l', b'l', b'o', b'p', b'a', b'r', b'q', b'u', b'e', b't' + b'h', b'e', b'l', b'l', b'o', b'p', b'a', b'r', b'q', b'u', b'e', b't', ]; let offsets: [i32; 4] = [0, 5, 5, 12]; @@ -539,7 +521,10 @@ mod tests { assert_eq!("hello", binary_array.get_string(0)); assert_eq!([] as [u8; 0], binary_array.get_value(1)); assert_eq!("", binary_array.get_string(1)); - assert_eq!([b'p', b'a', b'r', b'q', b'u', b'e', b't'], binary_array.get_value(2)); + assert_eq!( + [b'p', b'a', b'r', b'q', b'u', b'e', b't'], + binary_array.get_value(2) + ); assert_eq!("parquet", binary_array.get_string(2)); assert_eq!(5, binary_array.value_offset(2)); assert_eq!(7, binary_array.value_length(2)); @@ -586,7 +571,7 @@ mod tests { fn test_access_array_concurrently() { let a = PrimitiveArray::::from(vec![5, 6, 7, 8, 9]); - let ret = thread::spawn(move || { a.value(3) }).join(); + let ret = thread::spawn(move || a.value(3)).join(); assert!(ret.is_ok()); assert_eq!(8, ret.ok().unwrap()); diff --git a/rust/src/array_data.rs b/rust/src/array_data.rs index 15514cedd3b9..44c0afd9dccc 100644 --- a/rust/src/array_data.rs +++ b/rust/src/array_data.rs @@ -54,8 +54,12 @@ pub const UNKNOWN_NULL_COUNT: i64 = -1; impl ArrayData { pub fn new( - data_type: DataType, length: i64, mut null_count: i64, - null_bit_buffer: Option, offset: i64, buffers: Vec, + data_type: DataType, + length: i64, + mut null_count: i64, + null_bit_buffer: Option, + offset: i64, + buffers: Vec, child_data: Vec, ) -> Self { if null_count < 0 { @@ -67,7 +71,13 @@ impl ArrayData { } let null_bitmap = null_bit_buffer.map(Bitmap::from); Self { - data_type, length, null_count, offset, buffers, child_data, null_bitmap + data_type, + length, + null_count, + offset, + buffers, + child_data, + null_bitmap, } } @@ -94,7 +104,7 @@ impl ArrayData { /// Returns whether the element at index `i` is null. pub fn is_null(&self, i: usize) -> bool { if let Some(ref b) = self.null_bitmap { - return !b.is_set(i) + return !b.is_set(i); } false } @@ -107,7 +117,7 @@ impl ArrayData { /// Returns whether the element at index `i` is not null. pub fn is_valid(&self, i: usize) -> bool { if let Some(ref b) = self.null_bitmap { - return b.is_set(i) + return b.is_set(i); } true } @@ -194,17 +204,23 @@ impl ArrayDataBuilder { pub fn build(self) -> ArrayDataRef { let data = ArrayData::new( - self.data_type, self.length, self.null_count, self.null_bit_buffer, - self.offset, self.buffers, self.child_data); + self.data_type, + self.length, + self.null_count, + self.null_bit_buffer, + self.offset, + self.buffers, + self.child_data, + ); Arc::new(data) } } #[cfg(test)] mod tests { - use std::sync::Arc; - use buffer::Buffer; use super::{ArrayData, DataType}; + use buffer::Buffer; + use std::sync::Arc; #[test] fn test_new() { @@ -219,8 +235,15 @@ mod tests { #[test] fn test_builder() { let v = vec![0, 1, 2, 3]; - let child_arr_data = Arc::new( - ArrayData::new(DataType::Int32, 10, 0, None, 0, vec![], vec![])); + let child_arr_data = Arc::new(ArrayData::new( + DataType::Int32, + 10, + 0, + None, + 0, + vec![], + vec![], + )); let b1 = Buffer::from(&v[..]); let arr_data = ArrayData::builder(DataType::Int32) .length(20) diff --git a/rust/src/bitmap.rs b/rust/src/bitmap.rs index 661a68103009..93c46f841a04 100644 --- a/rust/src/bitmap.rs +++ b/rust/src/bitmap.rs @@ -52,9 +52,7 @@ impl Bitmap { impl From for Bitmap { fn from(buf: Buffer) -> Self { - Self { - bits: buf - } + Self { bits: buf } } } @@ -73,12 +71,12 @@ mod tests { fn test_bitmap_is_set() { let bitmap = Bitmap::from(Buffer::from([0b01001010])); assert_eq!(false, bitmap.is_set(0)); - assert_eq!(true, bitmap.is_set(1)); + assert_eq!(true, bitmap.is_set(1)); assert_eq!(false, bitmap.is_set(2)); - assert_eq!(true, bitmap.is_set(3)); + assert_eq!(true, bitmap.is_set(3)); assert_eq!(false, bitmap.is_set(4)); assert_eq!(false, bitmap.is_set(5)); - assert_eq!(true, bitmap.is_set(6)); + assert_eq!(true, bitmap.is_set(6)); assert_eq!(false, bitmap.is_set(7)); } diff --git a/rust/src/buffer.rs b/rust/src/buffer.rs index 72e6463910da..ba3d2a3eac89 100644 --- a/rust/src/buffer.rs +++ b/rust/src/buffer.rs @@ -42,9 +42,7 @@ struct BufferData { impl PartialEq for BufferData { fn eq(&self, other: &BufferData) -> bool { - unsafe { - memory::memcmp(self.ptr, other.ptr, self.len as usize) == 0 - } + unsafe { memory::memcmp(self.ptr, other.ptr, self.len as usize) == 0 } } } @@ -59,7 +57,10 @@ impl Buffer { /// Creates a buffer from an existing memory region (must already be byte-aligned) pub fn from_raw_parts(ptr: *const u8, len: usize) -> Self { let buf_data = BufferData { ptr: ptr, len: len }; - Buffer { data: Rc::new(buf_data), offset: 0 } + Buffer { + data: Rc::new(buf_data), + offset: 0, + } } /// Returns the number of bytes in the buffer @@ -74,9 +75,7 @@ impl Buffer { /// Returns the byte slice stored in this buffer pub fn data(&self) -> &[u8] { - unsafe { - ::std::slice::from_raw_parts(self.data.ptr, self.data.len) - } + unsafe { ::std::slice::from_raw_parts(self.data.ptr, self.data.len) } } /// Returns a raw pointer for this buffer. @@ -89,7 +88,10 @@ impl Buffer { /// Returns a copy for this buffer. pub fn copy(&self) -> Buffer { - Buffer { data: self.data.clone(), offset: self.offset } + Buffer { + data: self.data.clone(), + offset: self.offset, + } } /// Returns an empty buffer. @@ -120,7 +122,6 @@ impl> From for Buffer { } } - unsafe impl Sync for Buffer {} unsafe impl Send for Buffer {} @@ -129,8 +130,8 @@ mod tests { use std::ptr::null_mut; use std::thread; - use memory::{allocate_aligned, memcpy}; use super::Buffer; + use memory::{allocate_aligned, memcpy}; #[test] fn test_buffer_data_equality() { diff --git a/rust/src/datatypes.rs b/rust/src/datatypes.rs index 78f1d55c7209..68242f1bfa6d 100644 --- a/rust/src/datatypes.rs +++ b/rust/src/datatypes.rs @@ -22,7 +22,6 @@ use std::slice::from_raw_parts; use error::ArrowError; use serde_json::Value; - /// Arrow data type #[derive(Debug, Clone, PartialEq, Eq)] pub enum DataType { @@ -66,27 +65,28 @@ impl ArrowPrimitiveType for i64 {} impl ArrowPrimitiveType for f32 {} impl ArrowPrimitiveType for f64 {} - pub trait ToByteArray { /// Converts this instance into a byte slice. fn to_bytes(&self) -> &[u8]; } -impl ToByteArray for [T] where T: ArrowPrimitiveType { +impl ToByteArray for [T] +where + T: ArrowPrimitiveType, +{ fn to_bytes(&self) -> &[u8] { let raw_ptr = self.as_ptr() as *const T as *const u8; - unsafe { - from_raw_parts(raw_ptr, self.len() * size_of::()) - } + unsafe { from_raw_parts(raw_ptr, self.len() * size_of::()) } } } -impl ToByteArray for T where T: ArrowPrimitiveType { +impl ToByteArray for T +where + T: ArrowPrimitiveType, +{ fn to_bytes(&self) -> &[u8] { let raw_ptr = self as *const T as *const u8; - unsafe { - from_raw_parts(raw_ptr, size_of::()) - } + unsafe { from_raw_parts(raw_ptr, size_of::()) } } } diff --git a/rust/src/lib.rs b/rust/src/lib.rs index 87696d5ccb9f..d4983416f370 100644 --- a/rust/src/lib.rs +++ b/rust/src/lib.rs @@ -23,9 +23,8 @@ extern crate serde_json; extern crate rand; -pub mod util; -pub mod array_data; pub mod array; +pub mod array_data; pub mod bitmap; pub mod buffer; pub mod builder; @@ -34,3 +33,4 @@ pub mod error; pub mod memory; pub mod memory_pool; pub mod record_batch; +pub mod util; diff --git a/rust/src/memory.rs b/rust/src/memory.rs index 5e4224ac1075..1222016d900e 100644 --- a/rust/src/memory.rs +++ b/rust/src/memory.rs @@ -76,7 +76,7 @@ pub fn memcpy(dst: *const u8, src: *const u8, len: usize) { } } -extern { +extern "C" { #[inline] pub fn memcmp(p1: *const u8, p2: *const u8, len: usize) -> i32; } diff --git a/rust/src/util/bit_util.rs b/rust/src/util/bit_util.rs index 2420444858ee..209fa6f4631b 100644 --- a/rust/src/util/bit_util.rs +++ b/rust/src/util/bit_util.rs @@ -18,22 +18,14 @@ static BIT_MASK: [u8; 8] = [1, 2, 4, 8, 16, 32, 64, 128]; static BIT_TABLE: [u8; 256] = [ - 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, + 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, ]; /// Returns the nearest number that is `>=` than `num` and is a multiple of 64. @@ -43,7 +35,7 @@ pub fn round_upto_multiple_of_64(num: i64) -> i64 { let truncate_bitmask = !63; let max_roundable_num = ::std::i64::MAX - 64; if num < max_roundable_num { - return (num + force_carry_addend) & truncate_bitmask + return (num + force_carry_addend) & truncate_bitmask; } num } @@ -72,8 +64,8 @@ pub fn count_set_bits(data: &[u8]) -> i64 { #[cfg(test)] mod tests { + use rand::{thread_rng, Rng}; use std::collections::HashSet; - use rand::{Rng, thread_rng}; use super::*; @@ -84,33 +76,36 @@ mod tests { assert_eq!(64, round_upto_multiple_of_64(63)); assert_eq!(64, round_upto_multiple_of_64(64)); assert_eq!(128, round_upto_multiple_of_64(65)); - assert_eq!(::std::i64::MAX-64, round_upto_multiple_of_64(::std::i64::MAX-64)); + assert_eq!( + ::std::i64::MAX - 64, + round_upto_multiple_of_64(::std::i64::MAX - 64) + ); } #[test] fn test_get_bit() { // 00001101 - assert_eq!(true, get_bit(&[0b00001101], 0)); + assert_eq!(true, get_bit(&[0b00001101], 0)); assert_eq!(false, get_bit(&[0b00001101], 1)); - assert_eq!(true, get_bit(&[0b00001101], 2)); - assert_eq!(true, get_bit(&[0b00001101], 3)); + assert_eq!(true, get_bit(&[0b00001101], 2)); + assert_eq!(true, get_bit(&[0b00001101], 3)); // 01001001 01010010 - assert_eq!(true, get_bit(&[0b01001001, 0b01010010], 0)); + assert_eq!(true, get_bit(&[0b01001001, 0b01010010], 0)); assert_eq!(false, get_bit(&[0b01001001, 0b01010010], 1)); assert_eq!(false, get_bit(&[0b01001001, 0b01010010], 2)); - assert_eq!(true, get_bit(&[0b01001001, 0b01010010], 3)); + assert_eq!(true, get_bit(&[0b01001001, 0b01010010], 3)); assert_eq!(false, get_bit(&[0b01001001, 0b01010010], 4)); assert_eq!(false, get_bit(&[0b01001001, 0b01010010], 5)); - assert_eq!(true, get_bit(&[0b01001001, 0b01010010], 6)); + assert_eq!(true, get_bit(&[0b01001001, 0b01010010], 6)); assert_eq!(false, get_bit(&[0b01001001, 0b01010010], 7)); assert_eq!(false, get_bit(&[0b01001001, 0b01010010], 8)); - assert_eq!(true, get_bit(&[0b01001001, 0b01010010], 9)); + assert_eq!(true, get_bit(&[0b01001001, 0b01010010], 9)); assert_eq!(false, get_bit(&[0b01001001, 0b01010010], 10)); assert_eq!(false, get_bit(&[0b01001001, 0b01010010], 11)); - assert_eq!(true, get_bit(&[0b01001001, 0b01010010], 12)); + assert_eq!(true, get_bit(&[0b01001001, 0b01010010], 12)); assert_eq!(false, get_bit(&[0b01001001, 0b01010010], 13)); - assert_eq!(true, get_bit(&[0b01001001, 0b01010010], 14)); + assert_eq!(true, get_bit(&[0b01001001, 0b01010010], 14)); assert_eq!(false, get_bit(&[0b01001001, 0b01010010], 15)); } diff --git a/rust/src/util/mod.rs b/rust/src/util/mod.rs index 13da797348cd..c20abba180ea 100644 --- a/rust/src/util/mod.rs +++ b/rust/src/util/mod.rs @@ -15,5 +15,5 @@ // specific language governing permissions and limitations // under the License. -pub mod test_util; pub mod bit_util; +pub mod test_util; diff --git a/rust/src/util/test_util.rs b/rust/src/util/test_util.rs index 3748683a3d51..4ef48e600329 100644 --- a/rust/src/util/test_util.rs +++ b/rust/src/util/test_util.rs @@ -15,7 +15,7 @@ // specific language governing permissions and limitations // under the License. -use rand::{Rng, thread_rng}; +use rand::{thread_rng, Rng}; /// Returns a vector of size `n`, filled with randomly generated bytes. pub fn random_bytes(n: usize) -> Vec { From 08fb8479143636530bd824e449603f4109c42ee9 Mon Sep 17 00:00:00 2001 From: Chao Sun Date: Tue, 31 Jul 2018 23:53:57 -0700 Subject: [PATCH 04/20] Fix to_bytes() collision and test failure --- rust/src/array.rs | 20 ++++++++++---------- rust/src/datatypes.rs | 12 ++++++------ rust/src/record_batch.rs | 6 +++--- rust/src/util/bit_util.rs | 6 +----- 4 files changed, 20 insertions(+), 24 deletions(-) diff --git a/rust/src/array.rs b/rust/src/array.rs index a984eca43cd4..0881215d1597 100644 --- a/rust/src/array.rs +++ b/rust/src/array.rs @@ -160,7 +160,7 @@ macro_rules! def_primitive_array { fn from(data: Vec<$native_ty>) -> Self { let array_data = ArrayData::builder($data_ty) .length(data.len() as i64) - .add_buffer(Buffer::from(data.to_bytes())) + .add_buffer(Buffer::from(data.to_byte_slice())) .build(); PrimitiveArray::from(array_data) } @@ -183,7 +183,7 @@ macro_rules! def_primitive_array { for n in data { if let Some(v) = n { bit_util::set_bit(&mut null_buffer[..], i); - value_buffer.extend_from_slice(&v.to_bytes()); + value_buffer.extend_from_slice(&v.to_byte_slice()); } else { value_buffer.extend_from_slice(&NULL); } @@ -378,7 +378,7 @@ impl<'a> From> for BinaryArray { } let array_data = ArrayData::builder(DataType::Utf8) .length(v.len() as i64) - .add_buffer(Buffer::from(offsets.to_bytes())) + .add_buffer(Buffer::from(offsets.to_byte_slice())) .add_buffer(Buffer::from(&values[..])) .build(); BinaryArray::from(array_data) @@ -462,12 +462,12 @@ mod tests { use super::{BinaryArray, ListArray, PrimitiveArray, StructArray}; use array_data::ArrayData; use buffer::Buffer; - use datatypes::{DataType, Field, ToByteArray}; + use datatypes::{DataType, Field, ToByteSlice}; #[test] fn test_primitive_array() { let values: Vec = vec![0, 1, 2, 3, 4]; - let buf = Buffer::from(&values[..].to_bytes()); + let buf = Buffer::from(&values[..].to_byte_slice()); let buf2 = buf.copy(); let pa = PrimitiveArray::::new(buf.len() as i64, buf, 0, 0); assert_eq!(buf2, pa.values()); @@ -483,12 +483,12 @@ mod tests { let values: Vec = vec![0, 1, 2, 3, 4, 5, 6, 7]; let value_data = ArrayData::builder(DataType::Int32) .length(7) - .add_buffer(Buffer::from(&values[..].to_bytes())) + .add_buffer(Buffer::from(&values[..].to_byte_slice())) .build(); // Then, build the list array. let value_offset_slice: Vec = vec![0, 2, 5, 7]; - let value_offsets = Buffer::from(value_offset_slice.to_bytes()); + let value_offsets = Buffer::from(value_offset_slice.to_byte_slice()); let list_data_type = DataType::List(Box::new(DataType::Int32)); let list_data = ArrayData::builder(list_data_type) .length(4) @@ -513,7 +513,7 @@ mod tests { let array_data = ArrayData::builder(DataType::Utf8) .length(4) - .add_buffer(Buffer::from(offsets.to_bytes())) + .add_buffer(Buffer::from(offsets.to_byte_slice())) .add_buffer(Buffer::from(&values[..])) .build(); let binary_array = BinaryArray::from(array_data); @@ -534,11 +534,11 @@ mod tests { fn test_struct_array() { let boolean_data = ArrayData::builder(DataType::Boolean) .length(4) - .add_buffer(Buffer::from([false, false, true, true].to_bytes())) + .add_buffer(Buffer::from([false, false, true, true].to_byte_slice())) .build(); let int_data = ArrayData::builder(DataType::Int64) .length(4) - .add_buffer(Buffer::from([42, 28, 19, 31].to_bytes())) + .add_buffer(Buffer::from([42, 28, 19, 31].to_byte_slice())) .build(); let mut field_types = vec![]; field_types.push(Field::new("a", DataType::Boolean, false)); diff --git a/rust/src/datatypes.rs b/rust/src/datatypes.rs index 68242f1bfa6d..2ce0cc016acf 100644 --- a/rust/src/datatypes.rs +++ b/rust/src/datatypes.rs @@ -65,26 +65,26 @@ impl ArrowPrimitiveType for i64 {} impl ArrowPrimitiveType for f32 {} impl ArrowPrimitiveType for f64 {} -pub trait ToByteArray { +pub trait ToByteSlice { /// Converts this instance into a byte slice. - fn to_bytes(&self) -> &[u8]; + fn to_byte_slice(&self) -> &[u8]; } -impl ToByteArray for [T] +impl ToByteSlice for [T] where T: ArrowPrimitiveType, { - fn to_bytes(&self) -> &[u8] { + fn to_byte_slice(&self) -> &[u8] { let raw_ptr = self.as_ptr() as *const T as *const u8; unsafe { from_raw_parts(raw_ptr, self.len() * size_of::()) } } } -impl ToByteArray for T +impl ToByteSlice for T where T: ArrowPrimitiveType, { - fn to_bytes(&self) -> &[u8] { + fn to_byte_slice(&self) -> &[u8] { let raw_ptr = self as *const T as *const u8; unsafe { from_raw_parts(raw_ptr, size_of::()) } } diff --git a/rust/src/record_batch.rs b/rust/src/record_batch.rs index 599082018768..25c65aa80a01 100644 --- a/rust/src/record_batch.rs +++ b/rust/src/record_batch.rs @@ -73,7 +73,7 @@ mod tests { let v = vec![1, 2, 3, 4, 5]; let array_data = ArrayData::builder(DataType::Int32) .length(5) - .add_buffer(Buffer::from(v.to_bytes())) + .add_buffer(Buffer::from(v.to_byte_slice())) .build(); let a = PrimitiveArray::::from(array_data); @@ -81,8 +81,8 @@ mod tests { let offset_data = vec![0, 1, 2, 3, 4, 5, 6]; let array_data = ArrayData::builder(DataType::Utf8) .length(5) - .add_buffer(Buffer::from(v.to_bytes())) - .add_buffer(Buffer::from(offset_data.to_bytes())) + .add_buffer(Buffer::from(v.to_byte_slice())) + .add_buffer(Buffer::from(offset_data.to_byte_slice())) .build(); let b = BinaryArray::from(array_data); diff --git a/rust/src/util/bit_util.rs b/rust/src/util/bit_util.rs index 209fa6f4631b..bfe5734060ad 100644 --- a/rust/src/util/bit_util.rs +++ b/rust/src/util/bit_util.rs @@ -125,10 +125,7 @@ mod tests { const NUM_BYTES: usize = 10; const NUM_SETS: usize = 10; - let mut buffer: Vec = Vec::with_capacity(NUM_BYTES); - unsafe { - buffer.set_len(NUM_BYTES); - } + let mut buffer: [u8; NUM_BYTES * 8] = [0; NUM_BYTES * 8]; let mut v = HashSet::new(); let mut rng = thread_rng(); for _ in 0..NUM_SETS { @@ -136,7 +133,6 @@ mod tests { v.insert(offset); set_bit(&mut buffer[..], offset); } - for i in 0..NUM_BYTES * 8 { assert_eq!(v.contains(&i), get_bit(&buffer[..], i)); } From ac782f1441e14ba3309fd64d8292519e4f81478e Mon Sep 17 00:00:00 2001 From: Chao Sun Date: Wed, 1 Aug 2018 09:54:35 -0700 Subject: [PATCH 05/20] Remove commented out code --- rust/src/builder.rs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/rust/src/builder.rs b/rust/src/builder.rs index d4570f01ca36..ba9422dec299 100644 --- a/rust/src/builder.rs +++ b/rust/src/builder.rs @@ -189,9 +189,6 @@ mod tests { } let a = b.finish(); assert_eq!(5, a.len()); - // for i in 0..5 { - // assert_eq!(&i, a.get(i as usize)); - // } } #[test] @@ -202,9 +199,6 @@ mod tests { } let a = b.finish(); assert_eq!(5, a.len()); - // for i in 0..5 { - // assert_eq!(&i, a.get(i as usize)); - // } } #[test] From 51327fed95efc6a9276211ab7bd7ee22aa11edd7 Mon Sep 17 00:00:00 2001 From: Chao Sun Date: Wed, 1 Aug 2018 23:49:40 -0700 Subject: [PATCH 06/20] Address comments --- rust/examples/dynamic_types.rs | 11 ++++++--- rust/src/array.rs | 36 ++++++++++++++--------------- rust/src/array_data.rs | 12 +++++++--- rust/src/buffer.rs | 41 +++++++++++----------------------- rust/src/memory.rs | 12 +++++----- rust/src/memory_pool.rs | 4 ++-- rust/src/util/bit_util.rs | 24 +++++++++----------- 7 files changed, 67 insertions(+), 73 deletions(-) diff --git a/rust/examples/dynamic_types.rs b/rust/examples/dynamic_types.rs index babd49e0e5b8..d6bb840d9bdf 100644 --- a/rust/examples/dynamic_types.rs +++ b/rust/examples/dynamic_types.rs @@ -43,9 +43,14 @@ fn main() { let id = PrimitiveArray::from(vec![1, 2, 3, 4, 5]); let nested = StructArray::from(vec![ - Arc::new(BinaryArray::from(vec!["a", "b", "c", "d", "e"])) as Arc, - Arc::new(PrimitiveArray::from(vec![1.1, 2.2, 3.3, 4.4, 5.5])), - Arc::new(PrimitiveArray::from(vec![2.2, 3.3, 4.4, 5.5, 6.6])), + (Field::new("a", DataType::Utf8, false), + Arc::new(BinaryArray::from(vec!["a", "b", "c", "d", "e"])) as Arc), + (Field::new("b", DataType::Float64, false), + Arc::new(PrimitiveArray::from(vec![1.1, 2.2, 3.3, 4.4, 5.5])), + ), + (Field::new("c", DataType::Float64, false), + Arc::new(PrimitiveArray::from(vec![2.2, 3.3, 4.4, 5.5, 6.6])), + ), ]); // build a record batch diff --git a/rust/src/array.rs b/rust/src/array.rs index 0881215d1597..2b462aa7385f 100644 --- a/rust/src/array.rs +++ b/rust/src/array.rs @@ -45,7 +45,8 @@ pub type ArrayRef = Arc; /// Constructs an array using the input `data`. Returns a reference-counted `Array` /// instance. fn make_array(data: ArrayDataRef) -> ArrayRef { - // TODO: refactor the DataType enum and remove the clone here. + // TODO: here data_type() needs to clone the type - maybe add a type tag enum to + // avoid the cloning. match data.data_type() { DataType::Boolean => Arc::new(PrimitiveArray::::from(data)) as ArrayRef, DataType::Int8 => Arc::new(PrimitiveArray::::from(data)) as ArrayRef, @@ -91,6 +92,7 @@ pub struct PrimitiveArray { /// Pointer to the value array. The lifetime of this must be <= to the value buffer /// stored in `data`, so it's safe to store. raw_values: RawPtrBox, + /// Marker to let the compiler know that `T` is used. _phantom: PhantomData, } @@ -143,7 +145,7 @@ macro_rules! def_primitive_array { if data.is_null(i) { continue; } - let mut m = self.value(i as i64); + let m = self.value(i as i64); match n { None => n = Some(m), Some(nn) => if cmp(m, nn) { @@ -284,7 +286,12 @@ impl From for ListArray { debug_assert!(data.buffers().len() == 1); debug_assert!(data.child_data().len() == 1); let values = make_array(data.child_data()[0].clone()); - let value_offsets = data.buffers()[0].raw_data() as *const u8 as *const i32; + let value_offsets = data.buffers()[0].raw_data() as *const i32; + unsafe { + debug_assert!(*value_offsets.offset(0) == 0); + debug_assert!(*value_offsets.offset(data.length() as isize) + == values.data().length() as i32); + } Self { data: data.clone(), values: values, @@ -438,20 +445,13 @@ impl Array for StructArray { } } -impl From> for StructArray { - fn from(v: Vec) -> Self { - let mut field_types = vec![]; - let mut count = 0; - for arr in &v { - let idx = count.to_string(); - count += 1; - field_types.push(Field::new(&idx, arr.data().data_type(), false)); - } - let mut builder = ArrayData::builder(DataType::Struct(field_types)); - for arr in v { - builder = builder.add_child_data(arr.data().clone()); - } - StructArray::from(builder.build()) +impl From> for StructArray { + fn from(v: Vec<(Field, ArrayRef)>) -> Self { + let (field_types, field_values): (Vec<_>, Vec<_>) = v.into_iter().unzip(); + let data = ArrayData::builder(DataType::Struct(field_types)) + .child_data(field_values.into_iter().map(|a| a.data()).collect()) + .build(); + StructArray::from(data) } } @@ -491,7 +491,7 @@ mod tests { let value_offsets = Buffer::from(value_offset_slice.to_byte_slice()); let list_data_type = DataType::List(Box::new(DataType::Int32)); let list_data = ArrayData::builder(list_data_type) - .length(4) + .length(3) .add_buffer(value_offsets) .add_child_data(value_data.clone()) .build(); diff --git a/rust/src/array_data.rs b/rust/src/array_data.rs index 44c0afd9dccc..cfe545ec2351 100644 --- a/rust/src/array_data.rs +++ b/rust/src/array_data.rs @@ -37,14 +37,15 @@ pub struct ArrayData { offset: i64, /// The buffers for this array data. Note that depending on the array types, this - /// could hold different types of buffers (e.g., value buffer, value offset buffer) + /// could hold different kinds of buffers (e.g., value buffer, value offset buffer) /// at different positions. buffers: Vec, - /// The child(ren) of this array. Only non-empty for `ListArray` and `StructArray`. + /// The child(ren) of this array. Only non-empty for nested types, currently + /// `ListArray` and `StructArray`. child_data: Vec, - /// The null bit map. A `None` value for this indicates all values are non-null in + /// The null bitmap. A `None` value for this indicates all values are non-null in /// this array. null_bitmap: Option, } @@ -91,6 +92,11 @@ impl ArrayData { self.data_type.clone() } + /// Returns a reference to the data type of this array data. + pub fn data_type_ref(&self) -> &DataType { + &self.data_type + } + /// Returns a slice of buffers for this array data. pub fn buffers(&self) -> &[Buffer] { &self.buffers[..] diff --git a/rust/src/buffer.rs b/rust/src/buffer.rs index ba3d2a3eac89..09e7f66ca983 100644 --- a/rust/src/buffer.rs +++ b/rust/src/buffer.rs @@ -16,7 +16,7 @@ // under the License. use std::mem; -use std::rc::Rc; +use std::sync::Arc; use memory; @@ -25,7 +25,7 @@ use memory; #[derive(PartialEq, Debug)] pub struct Buffer { /// Reference-counted pointer to the internal byte buffer. - data: Rc, + data: Arc, /// The offset into the buffer. offset: usize, @@ -58,7 +58,7 @@ impl Buffer { pub fn from_raw_parts(ptr: *const u8, len: usize) -> Self { let buf_data = BufferData { ptr: ptr, len: len }; Buffer { - data: Rc::new(buf_data), + data: Arc::new(buf_data), offset: 0, } } @@ -86,7 +86,8 @@ impl Buffer { self.data.ptr } - /// Returns a copy for this buffer. + /// Returns a shallow copy for this buffer, i.e., a new buffer that points to the + /// same memory location of this buffer. pub fn copy(&self) -> Buffer { Buffer { data: self.data.clone(), @@ -109,16 +110,7 @@ impl> From for Buffer { let len = slice.len() * mem::size_of::(); let buffer = memory::allocate_aligned((len) as i64).unwrap(); memory::memcpy(buffer, slice.as_ptr(), len); - Buffer { - data: { - let buf_data = BufferData { - ptr: buffer, - len: len, - }; - Rc::new(buf_data) - }, - offset: 0, - } + Buffer::from_raw_parts(buffer, len) } } @@ -131,15 +123,17 @@ mod tests { use std::thread; use super::Buffer; - use memory::{allocate_aligned, memcpy}; #[test] fn test_buffer_data_equality() { - let buf1 = vec_to_buffer(&[0, 1, 2, 3, 4]); - let mut buf2 = vec_to_buffer(&[0, 1, 2, 3, 4]); + let buf1 = Buffer::from(&[0, 1, 2, 3, 4]); + let mut buf2 = Buffer::from(&[0, 1, 2, 3, 4]); assert_eq!(buf1, buf2); - buf2 = vec_to_buffer(&[0, 0, 2, 3, 4]); + buf2 = Buffer::from(&[0, 0, 2, 3, 4]); + assert!(buf1 != buf2); + + buf2 = Buffer::from(&[0, 1, 2, 3]); assert!(buf1 != buf2); } @@ -150,7 +144,7 @@ mod tests { assert_eq!(0, buf.data().len()); assert!(buf.raw_data().is_null()); - let buf = vec_to_buffer(&[0, 1, 2, 3, 4]); + let buf = Buffer::from(&[0, 1, 2, 3, 4]); assert_eq!(5, buf.len()); assert!(!buf.raw_data().is_null()); assert_eq!(&[0, 1, 2, 3, 4], buf.data()); @@ -173,15 +167,6 @@ mod tests { assert_eq!(&[0, 1, 2, 3, 4], buf2.data()); } - // Utility function to convert a byte vector into a `Buffer`. - fn vec_to_buffer(v: &[u8]) -> Buffer { - let len = v.len(); - let dst = allocate_aligned(len as i64).expect("allocation failed"); - let src = v.as_ptr() as *const u8; - memcpy(dst, src, len); - Buffer::from_raw_parts(dst, len) - } - #[test] fn test_access_buffer_concurrently() { let buffer = Buffer::from(vec![1, 2, 3, 4, 5]); diff --git a/rust/src/memory.rs b/rust/src/memory.rs index 1222016d900e..c0be273dd4d7 100644 --- a/rust/src/memory.rs +++ b/rust/src/memory.rs @@ -30,23 +30,23 @@ extern "C" { } #[cfg(windows)] -pub fn allocate_aligned(size: i64) -> Result<*const u8, ArrowError> { +pub fn allocate_aligned(size: i64) -> Result<*mut u8, ArrowError> { let page = unsafe { _aligned_malloc(size as libc::size_t, ALIGNMENT as libc::size_t) }; match page { 0 => Err(ArrowError::MemoryError( "Failed to allocate memory".to_string(), )), - _ => Ok(unsafe { mem::transmute::(page) }), + _ => Ok(unsafe { mem::transmute::(page) }), } } #[cfg(not(windows))] -pub fn allocate_aligned(size: i64) -> Result<*const u8, ArrowError> { +pub fn allocate_aligned(size: i64) -> Result<*mut u8, ArrowError> { unsafe { let mut page: *mut libc::c_void = mem::uninitialized(); let result = libc::posix_memalign(&mut page, ALIGNMENT, size as usize); match result { - 0 => Ok(mem::transmute::<*mut libc::c_void, *const u8>(page)), + 0 => Ok(mem::transmute::<*mut libc::c_void, *mut u8>(page)), _ => Err(ArrowError::MemoryError( "Failed to allocate memory".to_string(), )), @@ -68,10 +68,10 @@ pub fn free_aligned(p: *const u8) { } } -pub fn memcpy(dst: *const u8, src: *const u8, len: usize) { +pub fn memcpy(dst: *mut u8, src: *const u8, len: usize) { unsafe { let src = mem::transmute::<*const u8, *const libc::c_void>(src); - let dst = mem::transmute::<*const u8, *mut libc::c_void>(dst); + let dst = mem::transmute::<*mut u8, *mut libc::c_void>(dst); libc::memcpy(dst, src, len); } } diff --git a/rust/src/memory_pool.rs b/rust/src/memory_pool.rs index c8deeaca85c4..207debc7b6d8 100644 --- a/rust/src/memory_pool.rs +++ b/rust/src/memory_pool.rs @@ -26,7 +26,7 @@ use super::memory::{allocate_aligned, free_aligned}; pub trait MemoryPool { /// Allocate memory. /// The implementation should ensures that allocated memory is aligned. - fn allocate(&self, size: usize) -> Result<*const u8, ArrowError>; + fn allocate(&self, size: usize) -> Result<*mut u8, ArrowError>; /// Reallocate memory. /// If the implementation doesn't support reallocating aligned memory, it allocates new memory @@ -47,7 +47,7 @@ pub trait MemoryPool { struct LibcMemoryPool; impl MemoryPool for LibcMemoryPool { - fn allocate(&self, size: usize) -> Result<*const u8, ArrowError> { + fn allocate(&self, size: usize) -> Result<*mut u8, ArrowError> { allocate_aligned(size as i64) } diff --git a/rust/src/util/bit_util.rs b/rust/src/util/bit_util.rs index bfe5734060ad..2b532c37ed47 100644 --- a/rust/src/util/bit_util.rs +++ b/rust/src/util/bit_util.rs @@ -17,7 +17,7 @@ static BIT_MASK: [u8; 8] = [1, 2, 4, 8, 16, 32, 64, 128]; -static BIT_TABLE: [u8; 256] = [ +static POPCOUNT_TABLE: [u8; 256] = [ 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, @@ -28,16 +28,17 @@ static BIT_TABLE: [u8; 256] = [ 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, ]; +/// Returns the nearest multiple of `factor` that is `>=` than `num`. Here `factor` must +/// be a power of 2. +pub fn round_upto_power_of_2(num: i64, factor: i64) -> i64 { + debug_assert!(factor > 0 && (factor & (factor - 1)) == 0); + (num + (factor - 1)) & !(factor - 1) +} + /// Returns the nearest number that is `>=` than `num` and is a multiple of 64. #[inline] pub fn round_upto_multiple_of_64(num: i64) -> i64 { - let force_carry_addend = 63; - let truncate_bitmask = !63; - let max_roundable_num = ::std::i64::MAX - 64; - if num < max_roundable_num { - return (num + force_carry_addend) & truncate_bitmask; - } - num + round_upto_power_of_2(num, 64) } /// Returns whether bit at position `i` in `data` is set or not. @@ -57,7 +58,7 @@ pub fn set_bit(data: &mut [u8], i: usize) { pub fn count_set_bits(data: &[u8]) -> i64 { let mut count: i64 = 0; for u in data { - count += BIT_TABLE[*u as usize] as i64; + count += POPCOUNT_TABLE[*u as usize] as i64; } count } @@ -76,10 +77,7 @@ mod tests { assert_eq!(64, round_upto_multiple_of_64(63)); assert_eq!(64, round_upto_multiple_of_64(64)); assert_eq!(128, round_upto_multiple_of_64(65)); - assert_eq!( - ::std::i64::MAX - 64, - round_upto_multiple_of_64(::std::i64::MAX - 64) - ); + assert_eq!(192, round_upto_multiple_of_64(129)); } #[test] From 18e5dead335ab85aede8e8462e727848d6dd8066 Mon Sep 17 00:00:00 2001 From: Chao Sun Date: Wed, 8 Aug 2018 00:50:20 -0700 Subject: [PATCH 07/20] Address comments --- rust/examples/dynamic_types.rs | 16 ++++++++----- rust/src/array.rs | 44 ++++++++++++++++++---------------- rust/src/array_data.rs | 39 +++++++++++++----------------- rust/src/bitmap.rs | 2 +- rust/src/buffer.rs | 7 +++++- rust/src/memory.rs | 10 ++++---- rust/src/record_batch.rs | 16 ++++++------- rust/src/util/bit_util.rs | 14 +++++------ 8 files changed, 76 insertions(+), 72 deletions(-) diff --git a/rust/examples/dynamic_types.rs b/rust/examples/dynamic_types.rs index d6bb840d9bdf..22a2a4493034 100644 --- a/rust/examples/dynamic_types.rs +++ b/rust/examples/dynamic_types.rs @@ -43,13 +43,17 @@ fn main() { let id = PrimitiveArray::from(vec![1, 2, 3, 4, 5]); let nested = StructArray::from(vec![ - (Field::new("a", DataType::Utf8, false), - Arc::new(BinaryArray::from(vec!["a", "b", "c", "d", "e"])) as Arc), - (Field::new("b", DataType::Float64, false), - Arc::new(PrimitiveArray::from(vec![1.1, 2.2, 3.3, 4.4, 5.5])), + ( + Field::new("a", DataType::Utf8, false), + Arc::new(BinaryArray::from(vec!["a", "b", "c", "d", "e"])) as Arc, ), - (Field::new("c", DataType::Float64, false), - Arc::new(PrimitiveArray::from(vec![2.2, 3.3, 4.4, 5.5, 6.6])), + ( + Field::new("b", DataType::Float64, false), + Arc::new(PrimitiveArray::from(vec![1.1, 2.2, 3.3, 4.4, 5.5])), + ), + ( + Field::new("c", DataType::Float64, false), + Arc::new(PrimitiveArray::from(vec![2.2, 3.3, 4.4, 5.5, 6.6])), ), ]); diff --git a/rust/src/array.rs b/rust/src/array.rs index 2b462aa7385f..5d109d106f56 100644 --- a/rust/src/array.rs +++ b/rust/src/array.rs @@ -20,6 +20,7 @@ use std::any::Any; use std::convert::From; use std::marker::PhantomData; use std::mem; +use std::ptr; use std::sync::Arc; use super::array_data::*; @@ -47,7 +48,7 @@ pub type ArrayRef = Arc; fn make_array(data: ArrayDataRef) -> ArrayRef { // TODO: here data_type() needs to clone the type - maybe add a type tag enum to // avoid the cloning. - match data.data_type() { + match data.data_type().clone() { DataType::Boolean => Arc::new(PrimitiveArray::::from(data)) as ArrayRef, DataType::Int8 => Arc::new(PrimitiveArray::::from(data)) as ArrayRef, DataType::Int16 => Arc::new(PrimitiveArray::::from(data)) as ArrayRef, @@ -102,7 +103,7 @@ macro_rules! def_primitive_array { impl PrimitiveArray<$native_ty> { pub fn new(length: i64, values: Buffer, null_count: i64, offset: i64) -> Self { let array_data = ArrayData::builder($data_ty) - .length(length) + .len(length) .add_buffer(values) .null_count(null_count) .offset(offset) @@ -127,21 +128,21 @@ macro_rules! def_primitive_array { /// Determine the minimum value in the array pub fn min(&self) -> Option<$native_ty> { - self.search(|a, b| a < b) + self.min_max_helper(|a, b| a < b) } /// Determine the maximum value in the array pub fn max(&self) -> Option<$native_ty> { - self.search(|a, b| a > b) + self.min_max_helper(|a, b| a > b) } - fn search(&self, cmp: F) -> Option<$native_ty> + fn min_max_helper(&self, cmp: F) -> Option<$native_ty> where F: Fn($native_ty, $native_ty) -> bool, { let mut n: Option<$native_ty> = None; let data = self.data(); - for i in 0..data.length() { + for i in 0..data.len() { if data.is_null(i) { continue; } @@ -161,7 +162,7 @@ macro_rules! def_primitive_array { impl From> for PrimitiveArray<$native_ty> { fn from(data: Vec<$native_ty>) -> Self { let array_data = ArrayData::builder($data_ty) - .length(data.len() as i64) + .len(data.len() as i64) .add_buffer(Buffer::from(data.to_byte_slice())) .build(); PrimitiveArray::from(array_data) @@ -177,6 +178,7 @@ macro_rules! def_primitive_array { let size = bit_util::round_upto_multiple_of_64(data_len) as usize; let mut null_buffer = Vec::with_capacity(size); unsafe { + ptr::write_bytes(null_buffer.as_mut_ptr(), 0, size); null_buffer.set_len(size); } let mut value_buffer: Vec = Vec::with_capacity(size * TY_SIZE); @@ -193,7 +195,7 @@ macro_rules! def_primitive_array { } let array_data = ArrayData::builder($data_ty) - .length(data_len) + .len(data_len) .add_buffer(Buffer::from(Buffer::from(value_buffer))) .null_bit_buffer(Buffer::from(null_buffer)) .build(); @@ -258,7 +260,7 @@ impl ListArray { /// Returns the value type of this list. pub fn value_type(&self) -> DataType { - self.values.data().data_type() + self.values.data().data_type().clone() } /// Returns the offset for value at index `i`. @@ -289,8 +291,7 @@ impl From for ListArray { let value_offsets = data.buffers()[0].raw_data() as *const i32; unsafe { debug_assert!(*value_offsets.offset(0) == 0); - debug_assert!(*value_offsets.offset(data.length() as isize) - == values.data().length() as i32); + debug_assert!(*value_offsets.offset(data.len() as isize) == values.data().len() as i32); } Self { data: data.clone(), @@ -323,13 +324,14 @@ pub struct BinaryArray { impl BinaryArray { /// Returns the element at index `i` as a byte slice. - pub fn get_value(&self, mut i: i64) -> &[u8] { - i += self.data.offset(); + pub fn get_value(&self, i: i64) -> &[u8] { + assert!(i >= 0 && i <= self.data.len()); + let offset = i.checked_add(self.data.offset()).unwrap(); unsafe { - let pos = self.value_offset_at(i); + let pos = self.value_offset_at(offset); ::std::slice::from_raw_parts( self.value_data.get().offset(pos as isize), - (self.value_offset_at(i + 1) - pos) as usize, + (self.value_offset_at(offset + 1) - pos) as usize, ) } } @@ -384,7 +386,7 @@ impl<'a> From> for BinaryArray { values.extend_from_slice(s.as_bytes()); } let array_data = ArrayData::builder(DataType::Utf8) - .length(v.len() as i64) + .len(v.len() as i64) .add_buffer(Buffer::from(offsets.to_byte_slice())) .add_buffer(Buffer::from(&values[..])) .build(); @@ -482,7 +484,7 @@ mod tests { // First, construct a value array. let values: Vec = vec![0, 1, 2, 3, 4, 5, 6, 7]; let value_data = ArrayData::builder(DataType::Int32) - .length(7) + .len(7) .add_buffer(Buffer::from(&values[..].to_byte_slice())) .build(); @@ -491,7 +493,7 @@ mod tests { let value_offsets = Buffer::from(value_offset_slice.to_byte_slice()); let list_data_type = DataType::List(Box::new(DataType::Int32)); let list_data = ArrayData::builder(list_data_type) - .length(3) + .len(3) .add_buffer(value_offsets) .add_child_data(value_data.clone()) .build(); @@ -512,7 +514,7 @@ mod tests { let offsets: [i32; 4] = [0, 5, 5, 12]; let array_data = ArrayData::builder(DataType::Utf8) - .length(4) + .len(4) .add_buffer(Buffer::from(offsets.to_byte_slice())) .add_buffer(Buffer::from(&values[..])) .build(); @@ -533,11 +535,11 @@ mod tests { #[test] fn test_struct_array() { let boolean_data = ArrayData::builder(DataType::Boolean) - .length(4) + .len(4) .add_buffer(Buffer::from([false, false, true, true].to_byte_slice())) .build(); let int_data = ArrayData::builder(DataType::Int64) - .length(4) + .len(4) .add_buffer(Buffer::from([42, 28, 19, 31].to_byte_slice())) .build(); let mut field_types = vec![]; diff --git a/rust/src/array_data.rs b/rust/src/array_data.rs index cfe545ec2351..80910409defc 100644 --- a/rust/src/array_data.rs +++ b/rust/src/array_data.rs @@ -28,7 +28,7 @@ pub struct ArrayData { data_type: DataType, /// The number of elements in this array data - length: i64, + len: i64, /// The number of null elements in this array data null_count: i64, @@ -56,7 +56,7 @@ pub const UNKNOWN_NULL_COUNT: i64 = -1; impl ArrayData { pub fn new( data_type: DataType, - length: i64, + len: i64, mut null_count: i64, null_bit_buffer: Option, offset: i64, @@ -68,12 +68,12 @@ impl ArrayData { count_set_bits(buf.data()) } else { 0 - } + }; } let null_bitmap = null_bit_buffer.map(Bitmap::from); Self { data_type, - length, + len, null_count, offset, buffers, @@ -87,13 +87,8 @@ impl ArrayData { ArrayDataBuilder::new(data_type) } - /// Returns a copy of the data type for this array data. - pub fn data_type(&self) -> DataType { - self.data_type.clone() - } - /// Returns a reference to the data type of this array data. - pub fn data_type_ref(&self) -> &DataType { + pub fn data_type(&self) -> &DataType { &self.data_type } @@ -108,7 +103,7 @@ impl ArrayData { } /// Returns whether the element at index `i` is null. - pub fn is_null(&self, i: usize) -> bool { + pub fn is_null(&self, i: i64) -> bool { if let Some(ref b) = self.null_bitmap { return !b.is_set(i); } @@ -121,7 +116,7 @@ impl ArrayData { } /// Returns whether the element at index `i` is not null. - pub fn is_valid(&self, i: usize) -> bool { + pub fn is_valid(&self, i: i64) -> bool { if let Some(ref b) = self.null_bitmap { return b.is_set(i); } @@ -129,8 +124,8 @@ impl ArrayData { } /// Returns the length (i.e., number of elements) of this array. - pub fn length(&self) -> usize { - self.length as usize + pub fn len(&self) -> i64 { + self.len } /// Returns the offset of this array. @@ -147,7 +142,7 @@ impl ArrayData { /// Builder for `ArrayData` type. pub struct ArrayDataBuilder { data_type: DataType, - length: i64, + len: i64, null_count: i64, null_bit_buffer: Option, offset: i64, @@ -159,7 +154,7 @@ impl ArrayDataBuilder { pub fn new(data_type: DataType) -> Self { Self { data_type: data_type, - length: 0, + len: 0, null_count: UNKNOWN_NULL_COUNT, null_bit_buffer: None, offset: 0, @@ -168,8 +163,8 @@ impl ArrayDataBuilder { } } - pub fn length(mut self, n: i64) -> Self { - self.length = n; + pub fn len(mut self, n: i64) -> Self { + self.len = n; self } @@ -211,7 +206,7 @@ impl ArrayDataBuilder { pub fn build(self) -> ArrayDataRef { let data = ArrayData::new( self.data_type, - self.length, + self.len, self.null_count, self.null_bit_buffer, self.offset, @@ -231,7 +226,7 @@ mod tests { #[test] fn test_new() { let arr_data = ArrayData::new(DataType::Boolean, 10, 1, None, 2, vec![], vec![]); - assert_eq!(10, arr_data.length()); + assert_eq!(10, arr_data.len()); assert_eq!(1, arr_data.null_count()); assert_eq!(2, arr_data.offset()); assert_eq!(0, arr_data.buffers().len()); @@ -252,14 +247,14 @@ mod tests { )); let b1 = Buffer::from(&v[..]); let arr_data = ArrayData::builder(DataType::Int32) - .length(20) + .len(20) .null_count(10) .offset(5) .add_buffer(b1) .add_child_data(child_arr_data.clone()) .build(); - assert_eq!(20, arr_data.length()); + assert_eq!(20, arr_data.len()); assert_eq!(10, arr_data.null_count()); assert_eq!(5, arr_data.offset()); assert_eq!(1, arr_data.buffers().len()); diff --git a/rust/src/bitmap.rs b/rust/src/bitmap.rs index 93c46f841a04..2fdcf872326f 100644 --- a/rust/src/bitmap.rs +++ b/rust/src/bitmap.rs @@ -45,7 +45,7 @@ impl Bitmap { self.bits.len() } - pub fn is_set(&self, i: usize) -> bool { + pub fn is_set(&self, i: i64) -> bool { bit_util::get_bit(self.bits.data(), i) } } diff --git a/rust/src/buffer.rs b/rust/src/buffer.rs index 09e7f66ca983..22de88dfeaa9 100644 --- a/rust/src/buffer.rs +++ b/rust/src/buffer.rs @@ -42,6 +42,9 @@ struct BufferData { impl PartialEq for BufferData { fn eq(&self, other: &BufferData) -> bool { + if self.len != other.len { + return false; + } unsafe { memory::memcmp(self.ptr, other.ptr, self.len as usize) == 0 } } } @@ -109,7 +112,9 @@ impl> From for Buffer { let slice = p.as_ref(); let len = slice.len() * mem::size_of::(); let buffer = memory::allocate_aligned((len) as i64).unwrap(); - memory::memcpy(buffer, slice.as_ptr(), len); + unsafe { + memory::memcpy(buffer, slice.as_ptr(), len); + } Buffer::from_raw_parts(buffer, len) } } diff --git a/rust/src/memory.rs b/rust/src/memory.rs index c0be273dd4d7..33e7f4d380db 100644 --- a/rust/src/memory.rs +++ b/rust/src/memory.rs @@ -68,12 +68,10 @@ pub fn free_aligned(p: *const u8) { } } -pub fn memcpy(dst: *mut u8, src: *const u8, len: usize) { - unsafe { - let src = mem::transmute::<*const u8, *const libc::c_void>(src); - let dst = mem::transmute::<*mut u8, *mut libc::c_void>(dst); - libc::memcpy(dst, src, len); - } +pub unsafe fn memcpy(dst: *mut u8, src: *const u8, len: usize) { + let src = mem::transmute::<*const u8, *const libc::c_void>(src); + let dst = mem::transmute::<*mut u8, *mut libc::c_void>(dst); + libc::memcpy(dst, src, len); } extern "C" { diff --git a/rust/src/record_batch.rs b/rust/src/record_batch.rs index 25c65aa80a01..4f8e82b12fa0 100644 --- a/rust/src/record_batch.rs +++ b/rust/src/record_batch.rs @@ -30,9 +30,9 @@ impl RecordBatch { // assert that there are some columns assert!(columns.len() > 0); // assert that all columns have the same row count - let len = columns[0].data().length(); + let len = columns[0].data().len(); for i in 1..columns.len() { - assert_eq!(len, columns[i].data().length()); + assert_eq!(len, columns[i].data().len()); } RecordBatch { schema, columns } } @@ -45,8 +45,8 @@ impl RecordBatch { self.columns.len() } - pub fn num_rows(&self) -> usize { - self.columns[0].data().length() + pub fn num_rows(&self) -> i64 { + self.columns[0].data().len() } pub fn column(&self, i: usize) -> &ArrayRef { @@ -72,7 +72,7 @@ mod tests { let v = vec![1, 2, 3, 4, 5]; let array_data = ArrayData::builder(DataType::Int32) - .length(5) + .len(5) .add_buffer(Buffer::from(v.to_byte_slice())) .build(); let a = PrimitiveArray::::from(array_data); @@ -80,7 +80,7 @@ mod tests { let v = vec![b'a', b'b', b'c', b'd', b'e']; let offset_data = vec![0, 1, 2, 3, 4, 5, 6]; let array_data = ArrayData::builder(DataType::Utf8) - .length(5) + .len(5) .add_buffer(Buffer::from(v.to_byte_slice())) .add_buffer(Buffer::from(offset_data.to_byte_slice())) .build(); @@ -95,7 +95,7 @@ mod tests { record_batch.schema().column(0).data_type() ); assert_eq!(&DataType::Utf8, record_batch.schema().column(1).data_type()); - assert_eq!(5, record_batch.column(0).data().length()); - assert_eq!(5, record_batch.column(1).data().length()); + assert_eq!(5, record_batch.column(0).data().len()); + assert_eq!(5, record_batch.column(1).data().len()); } } diff --git a/rust/src/util/bit_util.rs b/rust/src/util/bit_util.rs index 2b532c37ed47..a756be310476 100644 --- a/rust/src/util/bit_util.rs +++ b/rust/src/util/bit_util.rs @@ -30,7 +30,7 @@ static POPCOUNT_TABLE: [u8; 256] = [ /// Returns the nearest multiple of `factor` that is `>=` than `num`. Here `factor` must /// be a power of 2. -pub fn round_upto_power_of_2(num: i64, factor: i64) -> i64 { +fn round_upto_power_of_2(num: i64, factor: i64) -> i64 { debug_assert!(factor > 0 && (factor & (factor - 1)) == 0); (num + (factor - 1)) & !(factor - 1) } @@ -43,14 +43,14 @@ pub fn round_upto_multiple_of_64(num: i64) -> i64 { /// Returns whether bit at position `i` in `data` is set or not. #[inline] -pub fn get_bit(data: &[u8], i: usize) -> bool { - (data[i / 8] & BIT_MASK[i % 8]) != 0 +pub fn get_bit(data: &[u8], i: i64) -> bool { + (data[(i / 8) as usize] & BIT_MASK[(i % 8) as usize]) != 0 } /// Sets bit at position `i` for `data`. #[inline] -pub fn set_bit(data: &mut [u8], i: usize) { - data[i / 8] |= BIT_MASK[i % 8] +pub fn set_bit(data: &mut [u8], i: i64) { + data[(i / 8) as usize] |= BIT_MASK[(i % 8) as usize] } /// Returns the number of 1-bits in `data`. @@ -129,10 +129,10 @@ mod tests { for _ in 0..NUM_SETS { let offset = rng.gen_range(0, 8 * NUM_BYTES); v.insert(offset); - set_bit(&mut buffer[..], offset); + set_bit(&mut buffer[..], offset as i64); } for i in 0..NUM_BYTES * 8 { - assert_eq!(v.contains(&i), get_bit(&buffer[..], i)); + assert_eq!(v.contains(&i), get_bit(&buffer[..], i as i64)); } } From 042796b4e381fcd4d0478f24b71ea285200b4ea8 Mon Sep 17 00:00:00 2001 From: Chao Sun Date: Thu, 9 Aug 2018 23:01:21 -0700 Subject: [PATCH 08/20] Add check for pointer alignment --- rust/src/array.rs | 101 +++++++++++++++++++++++++++++++++++++-------- rust/src/memory.rs | 7 ++++ 2 files changed, 90 insertions(+), 18 deletions(-) diff --git a/rust/src/array.rs b/rust/src/array.rs index 5d109d106f56..9e7a0969055c 100644 --- a/rust/src/array.rs +++ b/rust/src/array.rs @@ -16,6 +16,7 @@ // under the License. ///! Array types + use std::any::Any; use std::convert::From; use std::marker::PhantomData; @@ -23,15 +24,16 @@ use std::mem; use std::ptr; use std::sync::Arc; -use super::array_data::*; -use super::buffer::*; -use super::datatypes::*; +use array_data::*; +use buffer::*; +use datatypes::*; +use memory; use util::bit_util; /// Trait for dealing with different types of array at runtime when the type of the /// array is not known in advance pub trait Array: Send + Sync { - /// Returns the array as Any so that it can be downcast to a specific implementation + /// Returns the array as `Any` so that it can be downcast to a specific implementation fn as_any(&self) -> &Any; /// Returns a reference-counted pointer to the data of this array @@ -92,7 +94,7 @@ pub struct PrimitiveArray { data: ArrayDataRef, /// Pointer to the value array. The lifetime of this must be <= to the value buffer /// stored in `data`, so it's safe to store. - raw_values: RawPtrBox, + raw_values: RawPtrBox, /// Marker to let the compiler know that `T` is used. _phantom: PhantomData, } @@ -112,6 +114,8 @@ macro_rules! def_primitive_array { } /// Returns a `Buffer` holds all the values of this array. + /// + /// Note this doesn't take account into the offset of this array. pub fn values(&self) -> Buffer { self.data.buffers()[0].copy() } @@ -122,16 +126,18 @@ macro_rules! def_primitive_array { } /// Returns the primitive value at index `i`. + /// + /// Note this doesn't do any bound checking, for performance reason. pub fn value(&self, i: i64) -> $native_ty { unsafe { *(self.raw_values().offset(i as isize)) } } - /// Determine the minimum value in the array + /// Returns the minimum value in the array, according to the natural order. pub fn min(&self) -> Option<$native_ty> { self.min_max_helper(|a, b| a < b) } - /// Determine the maximum value in the array + /// Returns the maximum value in the array, according to the natural order. pub fn max(&self) -> Option<$native_ty> { self.min_max_helper(|a, b| a > b) } @@ -158,7 +164,7 @@ macro_rules! def_primitive_array { } } - /// Construct a primitive array from a vector. Should only be used for testing. + /// Constructs a primitive array from a vector. Should only be used for testing. impl From> for PrimitiveArray<$native_ty> { fn from(data: Vec<$native_ty>) -> Self { let array_data = ArrayData::builder($data_ty) @@ -209,10 +215,11 @@ macro_rules! def_primitive_array { impl From for PrimitiveArray { fn from(data: ArrayDataRef) -> Self { assert!(data.buffers().len() == 1); - let values = data.buffers()[0].copy(); + let raw_values = data.buffers()[0].raw_data(); + debug_assert!(memory::is_aligned::(raw_values, mem::size_of::())); Self { data: data, - raw_values: RawPtrBox::new(values.raw_data()), + raw_values: RawPtrBox::new(raw_values as *const T), _phantom: PhantomData, } } @@ -258,18 +265,22 @@ impl ListArray { self.values.clone() } - /// Returns the value type of this list. + /// Returns a clone of the value type of this list. pub fn value_type(&self) -> DataType { self.values.data().data_type().clone() } /// Returns the offset for value at index `i`. + /// + /// Note this doesn't do any bound checking, for performance reason. #[inline] pub fn value_offset(&self, i: i64) -> i32 { self.value_offset_at(self.data.offset() + i) } /// Returns the length for value at index `i`. + /// + /// Note this doesn't do any bound checking, for performance reason. #[inline] pub fn value_length(&self, mut i: i64) -> i32 { i += self.data.offset(); @@ -288,7 +299,9 @@ impl From for ListArray { debug_assert!(data.buffers().len() == 1); debug_assert!(data.child_data().len() == 1); let values = make_array(data.child_data()[0].clone()); - let value_offsets = data.buffers()[0].raw_data() as *const i32; + let raw_value_offsets = data.buffers()[0].raw_data(); + debug_assert!(memory::is_aligned(raw_value_offsets, mem::size_of::())); + let value_offsets = raw_value_offsets as *const i32; unsafe { debug_assert!(*value_offsets.offset(0) == 0); debug_assert!(*value_offsets.offset(data.len() as isize) == values.data().len() as i32); @@ -324,6 +337,8 @@ pub struct BinaryArray { impl BinaryArray { /// Returns the element at index `i` as a byte slice. + /// + /// Note this doesn't do any bound checking, for performance reason. pub fn get_value(&self, i: i64) -> &[u8] { assert!(i >= 0 && i <= self.data.len()); let offset = i.checked_add(self.data.offset()).unwrap(); @@ -337,18 +352,24 @@ impl BinaryArray { } /// Returns the element at index `i` as a string. + /// + /// Note this doesn't do any bound checking, for performance reason. pub fn get_string(&self, i: i64) -> String { let slice = self.get_value(i); unsafe { String::from_utf8_unchecked(Vec::from(slice)) } } /// Returns the offset for the element at index `i`. + /// + /// Note this doesn't do any bound checking, for performance reason. #[inline] pub fn value_offset(&self, i: i64) -> i32 { self.value_offset_at(i) } /// Returns the length for the element at index `i`. + /// + /// Note this doesn't do any bound checking, for performance reason. #[inline] pub fn value_length(&self, mut i: i64) -> i32 { i += self.data.offset(); @@ -364,11 +385,12 @@ impl BinaryArray { impl From for BinaryArray { fn from(data: ArrayDataRef) -> Self { assert!(data.buffers().len() == 2); - let value_offsets = data.buffers()[0].raw_data() as *const u8 as *const i32; + let raw_value_offsets = data.buffers()[0].raw_data(); + debug_assert!(memory::is_aligned(raw_value_offsets, mem::size_of::())); let value_data = data.buffers()[1].raw_data(); Self { data: data.clone(), - value_offsets: RawPtrBox::new(value_offsets), + value_offsets: RawPtrBox::new(raw_value_offsets as *const i32), value_data: RawPtrBox::new(value_data), } } @@ -408,6 +430,7 @@ impl Array for BinaryArray { } } +/// A nested array type where each child (called *field*) is represented by a separate array. pub struct StructArray { data: ArrayDataRef, boxed_fields: Vec, @@ -477,24 +500,39 @@ mod tests { let raw_values = pa.raw_values(); let slice = unsafe { ::std::slice::from_raw_parts(raw_values, 5) }; assert_eq!(&[0, 1, 2, 3, 4], slice); + + // Test building an primitive array with ArrayData builder and offset + let buf = Buffer::from(&[2, 4, 6, 8, 10].to_byte_slice()); + let buf2 = buf.copy(); + let data = ArrayData::builder(DataType::Int32) + .len(5) + .offset(2) + .add_buffer(buf) + .build(); + let pa = PrimitiveArray::::from(data); + assert_eq!(buf2, pa.values()); + assert_eq!(6, pa.value(0)); } #[test] fn test_list_array() { - // First, construct a value array. + // Construct a value array let values: Vec = vec![0, 1, 2, 3, 4, 5, 6, 7]; let value_data = ArrayData::builder(DataType::Int32) .len(7) .add_buffer(Buffer::from(&values[..].to_byte_slice())) .build(); - // Then, build the list array. + // Construct a buffer for value offsets, for the nested array: + // [[0, 1, 2], [3, 4, 5], [6, 7]] let value_offset_slice: Vec = vec![0, 2, 5, 7]; let value_offsets = Buffer::from(value_offset_slice.to_byte_slice()); + + // Construct a list array from the above two let list_data_type = DataType::List(Box::new(DataType::Int32)); - let list_data = ArrayData::builder(list_data_type) + let list_data = ArrayData::builder(list_data_type.clone()) .len(3) - .add_buffer(value_offsets) + .add_buffer(value_offsets.copy()) .add_child_data(value_data.clone()) .build(); let list_array = ListArray::from(list_data); @@ -504,6 +542,21 @@ mod tests { assert_eq!(DataType::Int32, list_array.value_type()); assert_eq!(5, list_array.value_offset(2)); assert_eq!(2, list_array.value_length(2)); + + // Now test with a non-zero offset + let list_data = ArrayData::builder(list_data_type) + .len(3) + .offset(1) + .add_buffer(value_offsets) + .add_child_data(value_data.clone()) + .build(); + let list_array = ListArray::from(list_data); + + let values = list_array.values(); + assert_eq!(value_data, values.data()); + assert_eq!(DataType::Int32, list_array.value_type()); + assert_eq!(5, list_array.value_offset(1)); + assert_eq!(2, list_array.value_length(1)); } #[test] @@ -513,6 +566,7 @@ mod tests { ]; let offsets: [i32; 4] = [0, 5, 5, 12]; + // Array data: ["hello", "", "parquet"] let array_data = ArrayData::builder(DataType::Utf8) .len(4) .add_buffer(Buffer::from(offsets.to_byte_slice())) @@ -530,6 +584,17 @@ mod tests { assert_eq!("parquet", binary_array.get_string(2)); assert_eq!(5, binary_array.value_offset(2)); assert_eq!(7, binary_array.value_length(2)); + + // Test binary array with offset + let array_data = ArrayData::builder(DataType::Utf8) + .len(4) + .offset(1) + .add_buffer(Buffer::from(offsets.to_byte_slice())) + .add_buffer(Buffer::from(&values[..])) + .build(); + let binary_array = BinaryArray::from(array_data); + assert_eq!([b'p', b'a', b'r', b'q', b'u', b'e', b't'], binary_array.get_value(1)); + assert_eq!("parquet", binary_array.get_string(1)); } #[test] diff --git a/rust/src/memory.rs b/rust/src/memory.rs index 33e7f4d380db..65b6813e447d 100644 --- a/rust/src/memory.rs +++ b/rust/src/memory.rs @@ -79,6 +79,13 @@ extern "C" { pub fn memcmp(p1: *const u8, p2: *const u8, len: usize) -> i32; } +/// Check if the pointer `p` is aligned to offset `a`. +pub fn is_aligned(p: *const T, a: usize) -> bool { + let a_minus_one = a.wrapping_sub(1); + let pmoda = p as usize & a_minus_one; + pmoda == 0 +} + #[cfg(test)] mod tests { use super::*; From 363e7cfced6029e49ea4751f1601d2dd26572b91 Mon Sep 17 00:00:00 2001 From: Chao Sun Date: Thu, 9 Aug 2018 23:41:55 -0700 Subject: [PATCH 09/20] Fix bench. Change Buffer#copy() to Buffer#clone() --- rust/benches/array_from_vec.rs | 4 +--- rust/examples/dynamic_types.rs | 2 +- rust/src/array.rs | 8 ++++---- rust/src/array_data.rs | 3 +++ rust/src/buffer.rs | 23 ++++++++++++----------- 5 files changed, 21 insertions(+), 19 deletions(-) diff --git a/rust/benches/array_from_vec.rs b/rust/benches/array_from_vec.rs index e53ce3bf48e9..f922be2f3853 100644 --- a/rust/benches/array_from_vec.rs +++ b/rust/benches/array_from_vec.rs @@ -22,8 +22,6 @@ use criterion::Criterion; extern crate arrow; -use std::rc::Rc; - use arrow::array::*; use arrow::array_data::ArrayDataBuilder; use arrow::buffer::Buffer; @@ -37,7 +35,7 @@ fn array_from_vec(n: usize) { let arr_data = ArrayDataBuilder::new(DataType::Int32) .add_buffer(Buffer::from(v)) .build(); - let _: PrimitiveArray = PrimitiveArray::from(Rc::new(arr_data)); + criterion::black_box(PrimitiveArray::::from(arr_data)); } fn criterion_benchmark(c: &mut Criterion) { diff --git a/rust/examples/dynamic_types.rs b/rust/examples/dynamic_types.rs index 22a2a4493034..678564e3eccd 100644 --- a/rust/examples/dynamic_types.rs +++ b/rust/examples/dynamic_types.rs @@ -91,7 +91,7 @@ fn process(batch: &RecordBatch) { let _ = RecordBatch::new( Arc::new(projected_schema), vec![ - id.clone(), //NOTE: this is cloning the Rc not the array data + id.clone(), //NOTE: this is cloning the Arc not the array data Arc::new(PrimitiveArray::::from(nested_c.data())), ], ); diff --git a/rust/src/array.rs b/rust/src/array.rs index 9e7a0969055c..22a676d4dac8 100644 --- a/rust/src/array.rs +++ b/rust/src/array.rs @@ -117,7 +117,7 @@ macro_rules! def_primitive_array { /// /// Note this doesn't take account into the offset of this array. pub fn values(&self) -> Buffer { - self.data.buffers()[0].copy() + self.data.buffers()[0].clone() } /// Returns a raw pointer to the values of this array. @@ -493,7 +493,7 @@ mod tests { fn test_primitive_array() { let values: Vec = vec![0, 1, 2, 3, 4]; let buf = Buffer::from(&values[..].to_byte_slice()); - let buf2 = buf.copy(); + let buf2 = buf.clone(); let pa = PrimitiveArray::::new(buf.len() as i64, buf, 0, 0); assert_eq!(buf2, pa.values()); assert_eq!(2, pa.value(2)); @@ -503,7 +503,7 @@ mod tests { // Test building an primitive array with ArrayData builder and offset let buf = Buffer::from(&[2, 4, 6, 8, 10].to_byte_slice()); - let buf2 = buf.copy(); + let buf2 = buf.clone(); let data = ArrayData::builder(DataType::Int32) .len(5) .offset(2) @@ -532,7 +532,7 @@ mod tests { let list_data_type = DataType::List(Box::new(DataType::Int32)); let list_data = ArrayData::builder(list_data_type.clone()) .len(3) - .add_buffer(value_offsets.copy()) + .add_buffer(value_offsets.clone()) .add_child_data(value_data.clone()) .build(); let list_array = ListArray::from(list_data); diff --git a/rust/src/array_data.rs b/rust/src/array_data.rs index 80910409defc..3650d501c3a5 100644 --- a/rust/src/array_data.rs +++ b/rust/src/array_data.rs @@ -22,6 +22,9 @@ use buffer::Buffer; use datatypes::DataType; use util::bit_util::count_set_bits; +/// An generic representation of Arrow array data which encapsulates common attributes and +/// operations for Arrow array. Specific operations for different arrays types (e.g., +/// primitive, list, struct) are implemented in `Array`. #[derive(PartialEq, Debug)] pub struct ArrayData { /// The data type for this array data diff --git a/rust/src/buffer.rs b/rust/src/buffer.rs index 22de88dfeaa9..012496267019 100644 --- a/rust/src/buffer.rs +++ b/rust/src/buffer.rs @@ -89,21 +89,22 @@ impl Buffer { self.data.ptr } - /// Returns a shallow copy for this buffer, i.e., a new buffer that points to the - /// same memory location of this buffer. - pub fn copy(&self) -> Buffer { + /// Returns an empty buffer. + pub fn empty() -> Buffer { + Buffer::from_raw_parts(::std::ptr::null(), 0) + } +} + +impl Clone for Buffer { + fn clone(&self) -> Buffer { Buffer { data: self.data.clone(), offset: self.offset, } } - - /// Returns an empty buffer. - pub fn empty() -> Buffer { - Buffer::from_raw_parts(::std::ptr::null(), 0) - } } + /// Creating a `Buffer` instance by copying the memory from a `Vec` into a newly /// allocated memory region. impl> From for Buffer { @@ -166,7 +167,7 @@ mod tests { #[test] fn test_buffer_copy() { let buf = Buffer::from(&[0, 1, 2, 3, 4]); - let buf2 = buf.copy(); + let buf2 = buf.clone(); assert_eq!(5, buf2.len()); assert!(!buf2.raw_data().is_null()); assert_eq!(&[0, 1, 2, 3, 4], buf2.data()); @@ -175,12 +176,12 @@ mod tests { #[test] fn test_access_buffer_concurrently() { let buffer = Buffer::from(vec![1, 2, 3, 4, 5]); - let buffer2 = buffer.copy(); + let buffer2 = buffer.clone(); assert_eq!(&[1, 2, 3, 4, 5], buffer.data()); let buffer_copy = thread::spawn(move || { // access buffer in another thread. - buffer.copy() + buffer.clone() }).join(); assert!(buffer_copy.is_ok()); From 1e8dab51f638e07e29f7fc9c5aed869b03a207fe Mon Sep 17 00:00:00 2001 From: Chao Sun Date: Fri, 10 Aug 2018 09:15:38 -0700 Subject: [PATCH 10/20] In is_aligned(), should use align_of instead of size_of --- rust/src/array.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/rust/src/array.rs b/rust/src/array.rs index 22a676d4dac8..e28256454a15 100644 --- a/rust/src/array.rs +++ b/rust/src/array.rs @@ -216,7 +216,7 @@ impl From for PrimitiveArray { fn from(data: ArrayDataRef) -> Self { assert!(data.buffers().len() == 1); let raw_values = data.buffers()[0].raw_data(); - debug_assert!(memory::is_aligned::(raw_values, mem::size_of::())); + debug_assert!(memory::is_aligned::(raw_values, mem::align_of::())); Self { data: data, raw_values: RawPtrBox::new(raw_values as *const T), @@ -300,7 +300,7 @@ impl From for ListArray { debug_assert!(data.child_data().len() == 1); let values = make_array(data.child_data()[0].clone()); let raw_value_offsets = data.buffers()[0].raw_data(); - debug_assert!(memory::is_aligned(raw_value_offsets, mem::size_of::())); + debug_assert!(memory::is_aligned(raw_value_offsets, mem::align_of::())); let value_offsets = raw_value_offsets as *const i32; unsafe { debug_assert!(*value_offsets.offset(0) == 0); @@ -386,7 +386,7 @@ impl From for BinaryArray { fn from(data: ArrayDataRef) -> Self { assert!(data.buffers().len() == 2); let raw_value_offsets = data.buffers()[0].raw_data(); - debug_assert!(memory::is_aligned(raw_value_offsets, mem::size_of::())); + debug_assert!(memory::is_aligned(raw_value_offsets, mem::align_of::())); let value_data = data.buffers()[1].raw_data(); Self { data: data.clone(), From 1863448156a5922a345f66b0bd4cb5d7996784fd Mon Sep 17 00:00:00 2001 From: Chao Sun Date: Fri, 10 Aug 2018 09:16:51 -0700 Subject: [PATCH 11/20] Fix lint --- rust/src/array.rs | 16 ++++++++++++---- rust/src/buffer.rs | 1 - 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/rust/src/array.rs b/rust/src/array.rs index e28256454a15..58a591b67041 100644 --- a/rust/src/array.rs +++ b/rust/src/array.rs @@ -16,7 +16,6 @@ // under the License. ///! Array types - use std::any::Any; use std::convert::From; use std::marker::PhantomData; @@ -300,7 +299,10 @@ impl From for ListArray { debug_assert!(data.child_data().len() == 1); let values = make_array(data.child_data()[0].clone()); let raw_value_offsets = data.buffers()[0].raw_data(); - debug_assert!(memory::is_aligned(raw_value_offsets, mem::align_of::())); + debug_assert!(memory::is_aligned( + raw_value_offsets, + mem::align_of::() + )); let value_offsets = raw_value_offsets as *const i32; unsafe { debug_assert!(*value_offsets.offset(0) == 0); @@ -386,7 +388,10 @@ impl From for BinaryArray { fn from(data: ArrayDataRef) -> Self { assert!(data.buffers().len() == 2); let raw_value_offsets = data.buffers()[0].raw_data(); - debug_assert!(memory::is_aligned(raw_value_offsets, mem::align_of::())); + debug_assert!(memory::is_aligned( + raw_value_offsets, + mem::align_of::() + )); let value_data = data.buffers()[1].raw_data(); Self { data: data.clone(), @@ -593,7 +598,10 @@ mod tests { .add_buffer(Buffer::from(&values[..])) .build(); let binary_array = BinaryArray::from(array_data); - assert_eq!([b'p', b'a', b'r', b'q', b'u', b'e', b't'], binary_array.get_value(1)); + assert_eq!( + [b'p', b'a', b'r', b'q', b'u', b'e', b't'], + binary_array.get_value(1) + ); assert_eq!("parquet", binary_array.get_string(1)); } diff --git a/rust/src/buffer.rs b/rust/src/buffer.rs index 012496267019..fe7d2cd83e1a 100644 --- a/rust/src/buffer.rs +++ b/rust/src/buffer.rs @@ -104,7 +104,6 @@ impl Clone for Buffer { } } - /// Creating a `Buffer` instance by copying the memory from a `Vec` into a newly /// allocated memory region. impl> From for Buffer { From a3206cc55ec18605672fefc69fffe04a8581da4c Mon Sep 17 00:00:00 2001 From: Chao Sun Date: Fri, 10 Aug 2018 10:27:06 -0700 Subject: [PATCH 12/20] Address review comments --- rust/src/array.rs | 10 +++------- rust/src/memory.rs | 7 +++++++ 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/rust/src/array.rs b/rust/src/array.rs index 58a591b67041..8b6f48c88799 100644 --- a/rust/src/array.rs +++ b/rust/src/array.rs @@ -18,7 +18,6 @@ ///! Array types use std::any::Any; use std::convert::From; -use std::marker::PhantomData; use std::mem; use std::ptr; use std::sync::Arc; @@ -94,8 +93,6 @@ pub struct PrimitiveArray { /// Pointer to the value array. The lifetime of this must be <= to the value buffer /// stored in `data`, so it's safe to store. raw_values: RawPtrBox, - /// Marker to let the compiler know that `T` is used. - _phantom: PhantomData, } /// Macro to define primitive arrays for different data types and native types. @@ -215,11 +212,10 @@ impl From for PrimitiveArray { fn from(data: ArrayDataRef) -> Self { assert!(data.buffers().len() == 1); let raw_values = data.buffers()[0].raw_data(); - debug_assert!(memory::is_aligned::(raw_values, mem::align_of::())); + assert!(memory::is_aligned::(raw_values, mem::align_of::())); Self { data: data, raw_values: RawPtrBox::new(raw_values as *const T), - _phantom: PhantomData, } } } @@ -299,7 +295,7 @@ impl From for ListArray { debug_assert!(data.child_data().len() == 1); let values = make_array(data.child_data()[0].clone()); let raw_value_offsets = data.buffers()[0].raw_data(); - debug_assert!(memory::is_aligned( + assert!(memory::is_aligned( raw_value_offsets, mem::align_of::() )); @@ -388,7 +384,7 @@ impl From for BinaryArray { fn from(data: ArrayDataRef) -> Self { assert!(data.buffers().len() == 2); let raw_value_offsets = data.buffers()[0].raw_data(); - debug_assert!(memory::is_aligned( + assert!(memory::is_aligned( raw_value_offsets, mem::align_of::() )); diff --git a/rust/src/memory.rs b/rust/src/memory.rs index 65b6813e447d..e9f79c4d91af 100644 --- a/rust/src/memory.rs +++ b/rust/src/memory.rs @@ -99,4 +99,11 @@ mod tests { } } + #[test] + fn test_is_aligned() { + let ptr: [u8; 5] = [1, 0, 1, 0, 1]; + assert_eq!(true, is_aligned::(ptr.as_ptr(), 1)); + assert_eq!(false, is_aligned::(ptr.as_ptr(), 2)); + assert_eq!(false, is_aligned::(ptr.as_ptr(), 3)); + } } From c1941651d352a0c3e10c62d5dd82d8d855627154 Mon Sep 17 00:00:00 2001 From: Chao Sun Date: Sun, 12 Aug 2018 00:43:51 -0700 Subject: [PATCH 13/20] Fix Buffer offset and test for Array alignment --- rust/src/array.rs | 49 ++++++++++++++++++++++++++++++++++++++++++ rust/src/buffer.rs | 53 ++++++++++++++++++++++++++++++++++++++++++---- rust/src/memory.rs | 7 +++++- 3 files changed, 104 insertions(+), 5 deletions(-) diff --git a/rust/src/array.rs b/rust/src/array.rs index 8b6f48c88799..769ed1aabda6 100644 --- a/rust/src/array.rs +++ b/rust/src/array.rs @@ -489,6 +489,7 @@ mod tests { use array_data::ArrayData; use buffer::Buffer; use datatypes::{DataType, Field, ToByteSlice}; + use memory; #[test] fn test_primitive_array() { @@ -624,6 +625,54 @@ mod tests { assert_eq!(int_data, struct_array.column(1).data()); } + #[test] + #[should_panic(expected = "")] + fn test_primitive_array_alignment() { + let ptr = memory::allocate_aligned(8).unwrap(); + let buf = Buffer::from_raw_parts(ptr, 8); + let buf2 = buf.slice(1); + let array_data = ArrayData::builder(DataType::Int32) + .add_buffer(buf2) + .build(); + PrimitiveArray::::from(array_data); + } + + #[test] + #[should_panic(expected = "")] + fn test_list_array_alignment() { + let ptr = memory::allocate_aligned(8).unwrap(); + let buf = Buffer::from_raw_parts(ptr, 8); + let buf2 = buf.slice(1); + + let values: [i32; 8] = [0; 8]; + let value_data = ArrayData::builder(DataType::Int32) + .add_buffer(Buffer::from(values.to_byte_slice())) + .build(); + + let list_data_type = DataType::List(Box::new(DataType::Int32)); + let list_data = ArrayData::builder(list_data_type.clone()) + .add_buffer(buf2) + .add_child_data(value_data.clone()) + .build(); + ListArray::from(list_data); + } + + #[test] + #[should_panic(expected = "")] + fn test_binary_array_alignment() { + let ptr = memory::allocate_aligned(8).unwrap(); + let buf = Buffer::from_raw_parts(ptr, 8); + let buf2 = buf.slice(1); + + let values: [u8; 12] = [0; 12]; + + let array_data = ArrayData::builder(DataType::Utf8) + .add_buffer(buf2) + .add_buffer(Buffer::from(&values[..])) + .build(); + BinaryArray::from(array_data); + } + #[test] fn test_buffer_array_min_max() { let a = PrimitiveArray::::from(vec![5, 6, 7, 8, 9]); diff --git a/rust/src/buffer.rs b/rust/src/buffer.rs index fe7d2cd83e1a..df1e93c47ea6 100644 --- a/rust/src/buffer.rs +++ b/rust/src/buffer.rs @@ -68,17 +68,26 @@ impl Buffer { /// Returns the number of bytes in the buffer pub fn len(&self) -> usize { - self.data.len as usize + self.data.len - self.offset as usize } /// Returns whether the buffer is empty. pub fn is_empty(&self) -> bool { - self.data.len == 0 + self.data.len - self.offset == 0 } /// Returns the byte slice stored in this buffer pub fn data(&self) -> &[u8] { - unsafe { ::std::slice::from_raw_parts(self.data.ptr, self.data.len) } + unsafe { ::std::slice::from_raw_parts(self.raw_data(), self.data.len - self.offset) } + } + + /// Returns a slice of this buffer, starting from `offset`. + pub fn slice(&self, offset: usize) -> Buffer { + assert!(self.offset + offset <= self.len()); + Buffer { + data: self.data.clone(), + offset: self.offset + offset, + } } /// Returns a raw pointer for this buffer. @@ -86,7 +95,9 @@ impl Buffer { /// Note that this should be used cautiously, and the returned pointer should not be /// stored anywhere, to avoid dangling pointers. pub fn raw_data(&self) -> *const u8 { - self.data.ptr + unsafe { + self.data.ptr.offset(self.offset as isize) + } } /// Returns an empty buffer. @@ -135,11 +146,17 @@ mod tests { let mut buf2 = Buffer::from(&[0, 1, 2, 3, 4]); assert_eq!(buf1, buf2); + let buf3 = buf1.slice(2); + assert!(buf1 != buf3); + let buf4 = buf2.slice(2); + assert_eq!(buf3, buf4); + buf2 = Buffer::from(&[0, 0, 2, 3, 4]); assert!(buf1 != buf2); buf2 = Buffer::from(&[0, 1, 2, 3]); assert!(buf1 != buf2); + } #[test] @@ -172,6 +189,34 @@ mod tests { assert_eq!(&[0, 1, 2, 3, 4], buf2.data()); } + #[test] + fn test_buffer_slice() { + let buf = Buffer::from(&[2, 4, 6, 8, 10]); + let buf2 = buf.slice(2); + + assert_eq!(&[6, 8, 10], buf2.data()); + assert_eq!(3, buf2.len()); + assert_eq!(unsafe {buf.raw_data().offset(2)}, buf2.raw_data()); + + let buf3 = buf2.slice(1); + assert_eq!(&[8, 10], buf3.data()); + assert_eq!(2, buf3.len()); + assert_eq!(unsafe {buf.raw_data().offset(3)}, buf3.raw_data()); + + let buf4 = buf.slice(5); + let empty_slice: [u8; 0] = []; + assert_eq!(empty_slice, buf4.data()); + assert_eq!(0, buf4.len()); + assert!(buf4.is_empty()); + } + + #[test] + #[should_panic(expected = "")] + fn test_buffer_slice_bad_offset() { + let buf = Buffer::from(&[2, 4, 6, 8, 10]); + buf.slice(6); + } + #[test] fn test_access_buffer_concurrently() { let buffer = Buffer::from(vec![1, 2, 3, 4, 5]); diff --git a/rust/src/memory.rs b/rust/src/memory.rs index e9f79c4d91af..cc5d7ab9526c 100644 --- a/rust/src/memory.rs +++ b/rust/src/memory.rs @@ -101,9 +101,14 @@ mod tests { #[test] fn test_is_aligned() { - let ptr: [u8; 5] = [1, 0, 1, 0, 1]; + let ptr: [u8; 5] = [0; 5]; assert_eq!(true, is_aligned::(ptr.as_ptr(), 1)); assert_eq!(false, is_aligned::(ptr.as_ptr(), 2)); assert_eq!(false, is_aligned::(ptr.as_ptr(), 3)); + + let ptr: [u8; 8] = [0; 8]; + assert_eq!(true, is_aligned::(ptr.as_ptr(), 1)); + assert_eq!(true, is_aligned::(ptr.as_ptr(), 2)); + assert_eq!(true, is_aligned::(ptr.as_ptr(), 4)); } } From a29ae4a212ff213ca67aa6debe5463b91103be05 Mon Sep 17 00:00:00 2001 From: Chao Sun Date: Sun, 12 Aug 2018 17:20:25 -0700 Subject: [PATCH 14/20] Fix test for is_aligned --- rust/src/memory.rs | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/rust/src/memory.rs b/rust/src/memory.rs index cc5d7ab9526c..dc0fb015177c 100644 --- a/rust/src/memory.rs +++ b/rust/src/memory.rs @@ -101,14 +101,19 @@ mod tests { #[test] fn test_is_aligned() { - let ptr: [u8; 5] = [0; 5]; - assert_eq!(true, is_aligned::(ptr.as_ptr(), 1)); - assert_eq!(false, is_aligned::(ptr.as_ptr(), 2)); - assert_eq!(false, is_aligned::(ptr.as_ptr(), 3)); - - let ptr: [u8; 8] = [0; 8]; - assert_eq!(true, is_aligned::(ptr.as_ptr(), 1)); - assert_eq!(true, is_aligned::(ptr.as_ptr(), 2)); - assert_eq!(true, is_aligned::(ptr.as_ptr(), 4)); + // allocate memory aligned to 64-byte + let mut ptr = allocate_aligned(10).unwrap(); + assert_eq!(true, is_aligned::(ptr, 1)); + assert_eq!(true, is_aligned::(ptr, 2)); + assert_eq!(true, is_aligned::(ptr, 4)); + + // now make the memory aligned to 63-byte + ptr = unsafe { + ptr.offset(1) + }; + assert_eq!(true, is_aligned::(ptr, 1)); + assert_eq!(false, is_aligned::(ptr, 2)); + assert_eq!(false, is_aligned::(ptr, 4)); + } } From 2ee3cf95e7f47d092a0d95229c2d665da68ebf50 Mon Sep 17 00:00:00 2001 From: Chao Sun Date: Sun, 12 Aug 2018 17:20:43 -0700 Subject: [PATCH 15/20] Fix lint --- rust/src/array.rs | 4 +--- rust/src/buffer.rs | 9 +++------ rust/src/memory.rs | 5 +---- 3 files changed, 5 insertions(+), 13 deletions(-) diff --git a/rust/src/array.rs b/rust/src/array.rs index 769ed1aabda6..b3d5c402f053 100644 --- a/rust/src/array.rs +++ b/rust/src/array.rs @@ -631,9 +631,7 @@ mod tests { let ptr = memory::allocate_aligned(8).unwrap(); let buf = Buffer::from_raw_parts(ptr, 8); let buf2 = buf.slice(1); - let array_data = ArrayData::builder(DataType::Int32) - .add_buffer(buf2) - .build(); + let array_data = ArrayData::builder(DataType::Int32).add_buffer(buf2).build(); PrimitiveArray::::from(array_data); } diff --git a/rust/src/buffer.rs b/rust/src/buffer.rs index df1e93c47ea6..de288a313c44 100644 --- a/rust/src/buffer.rs +++ b/rust/src/buffer.rs @@ -95,9 +95,7 @@ impl Buffer { /// Note that this should be used cautiously, and the returned pointer should not be /// stored anywhere, to avoid dangling pointers. pub fn raw_data(&self) -> *const u8 { - unsafe { - self.data.ptr.offset(self.offset as isize) - } + unsafe { self.data.ptr.offset(self.offset as isize) } } /// Returns an empty buffer. @@ -156,7 +154,6 @@ mod tests { buf2 = Buffer::from(&[0, 1, 2, 3]); assert!(buf1 != buf2); - } #[test] @@ -196,12 +193,12 @@ mod tests { assert_eq!(&[6, 8, 10], buf2.data()); assert_eq!(3, buf2.len()); - assert_eq!(unsafe {buf.raw_data().offset(2)}, buf2.raw_data()); + assert_eq!(unsafe { buf.raw_data().offset(2) }, buf2.raw_data()); let buf3 = buf2.slice(1); assert_eq!(&[8, 10], buf3.data()); assert_eq!(2, buf3.len()); - assert_eq!(unsafe {buf.raw_data().offset(3)}, buf3.raw_data()); + assert_eq!(unsafe { buf.raw_data().offset(3) }, buf3.raw_data()); let buf4 = buf.slice(5); let empty_slice: [u8; 0] = []; diff --git a/rust/src/memory.rs b/rust/src/memory.rs index dc0fb015177c..adcfe2f69209 100644 --- a/rust/src/memory.rs +++ b/rust/src/memory.rs @@ -108,12 +108,9 @@ mod tests { assert_eq!(true, is_aligned::(ptr, 4)); // now make the memory aligned to 63-byte - ptr = unsafe { - ptr.offset(1) - }; + ptr = unsafe { ptr.offset(1) }; assert_eq!(true, is_aligned::(ptr, 1)); assert_eq!(false, is_aligned::(ptr, 2)); assert_eq!(false, is_aligned::(ptr, 4)); - } } From 383cc3efcd70e1f8ac86a3c80c8e9dab81ffa2bf Mon Sep 17 00:00:00 2001 From: Chao Sun Date: Sun, 12 Aug 2018 17:40:22 -0700 Subject: [PATCH 16/20] More refactoring --- rust/src/buffer.rs | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/rust/src/buffer.rs b/rust/src/buffer.rs index de288a313c44..624354a67fd0 100644 --- a/rust/src/buffer.rs +++ b/rust/src/buffer.rs @@ -59,6 +59,7 @@ impl Drop for BufferData { impl Buffer { /// Creates a buffer from an existing memory region (must already be byte-aligned) pub fn from_raw_parts(ptr: *const u8, len: usize) -> Self { + assert!(memory::is_aligned(ptr, 64)); let buf_data = BufferData { ptr: ptr, len: len }; Buffer { data: Arc::new(buf_data), @@ -78,7 +79,7 @@ impl Buffer { /// Returns the byte slice stored in this buffer pub fn data(&self) -> &[u8] { - unsafe { ::std::slice::from_raw_parts(self.raw_data(), self.data.len - self.offset) } + unsafe { ::std::slice::from_raw_parts(self.raw_data(), self.len()) } } /// Returns a slice of this buffer, starting from `offset`. @@ -113,7 +114,7 @@ impl Clone for Buffer { } } -/// Creating a `Buffer` instance by copying the memory from a `Vec` into a newly +/// Creating a `Buffer` instance by copying the memory from a `AsRef<[u8]>` into a newly /// allocated memory region. impl> From for Buffer { fn from(p: T) -> Self { @@ -144,20 +145,23 @@ mod tests { let mut buf2 = Buffer::from(&[0, 1, 2, 3, 4]); assert_eq!(buf1, buf2); + // slice with same offset should still preserve equality let buf3 = buf1.slice(2); assert!(buf1 != buf3); let buf4 = buf2.slice(2); assert_eq!(buf3, buf4); + // unequal because of different elements buf2 = Buffer::from(&[0, 0, 2, 3, 4]); assert!(buf1 != buf2); + // unequal because of different length buf2 = Buffer::from(&[0, 1, 2, 3]); assert!(buf1 != buf2); } #[test] - fn test_buffer_from_raw_parts() { + fn test_from_raw_parts() { let buf = Buffer::from_raw_parts(null_mut(), 0); assert_eq!(0, buf.len()); assert_eq!(0, buf.data().len()); @@ -170,7 +174,7 @@ mod tests { } #[test] - fn test_buffer_from_vec() { + fn test_from_vec() { let buf = Buffer::from(&[0, 1, 2, 3, 4]); assert_eq!(5, buf.len()); assert!(!buf.raw_data().is_null()); @@ -178,7 +182,7 @@ mod tests { } #[test] - fn test_buffer_copy() { + fn test_copy() { let buf = Buffer::from(&[0, 1, 2, 3, 4]); let buf2 = buf.clone(); assert_eq!(5, buf2.len()); @@ -187,7 +191,7 @@ mod tests { } #[test] - fn test_buffer_slice() { + fn test_slice() { let buf = Buffer::from(&[2, 4, 6, 8, 10]); let buf2 = buf.slice(2); @@ -209,13 +213,13 @@ mod tests { #[test] #[should_panic(expected = "")] - fn test_buffer_slice_bad_offset() { + fn test_slice_offset_out_of_bound() { let buf = Buffer::from(&[2, 4, 6, 8, 10]); buf.slice(6); } #[test] - fn test_access_buffer_concurrently() { + fn test_access_concurrently() { let buffer = Buffer::from(vec![1, 2, 3, 4, 5]); let buffer2 = buffer.clone(); assert_eq!(&[1, 2, 3, 4, 5], buffer.data()); From 2493d122091f63568d73c690c50f389d3c0b2136 Mon Sep 17 00:00:00 2001 From: Chao Sun Date: Mon, 13 Aug 2018 00:41:48 -0700 Subject: [PATCH 17/20] Fix a few more issues and add more tests --- rust/src/array.rs | 197 +++++++++++++++++++++++++++++++++----- rust/src/array_data.rs | 56 ++++++++--- rust/src/util/bit_util.rs | 53 ++++++++-- 3 files changed, 261 insertions(+), 45 deletions(-) diff --git a/rust/src/array.rs b/rust/src/array.rs index b3d5c402f053..c2b49c079775 100644 --- a/rust/src/array.rs +++ b/rust/src/array.rs @@ -39,6 +39,37 @@ pub trait Array: Send + Sync { /// Returns a borrowed & reference-counted pointer to the data of this array fn data_ref(&self) -> &ArrayDataRef; + + + /// Returns a reference to the data type of this array + fn data_type(&self) -> &DataType { + self.data_ref().data_type() + } + + /// Returns the length (i.e., number of elements) of this array + fn len(&self) -> i64 { + self.data().len() + } + + /// Returns the offset of this array + fn offset(&self) -> i64 { + self.data().offset() + } + + /// Returns whether the element at index `i` is null + fn is_null(&self, i: i64) -> bool { + self.data().is_null(i) + } + + /// Returns whether the element at index `i` is not null + fn is_valid(&self, i: i64) -> bool { + self.data().is_valid(i) + } + + /// Returns the total number of nulls in this array + fn null_count(&self) -> i64 { + self.data().null_count() + } } pub type ArrayRef = Arc; @@ -291,8 +322,8 @@ impl ListArray { /// Constructs a `ListArray` from an array data reference. impl From for ListArray { fn from(data: ArrayDataRef) -> Self { - debug_assert!(data.buffers().len() == 1); - debug_assert!(data.child_data().len() == 1); + assert!(data.buffers().len() == 1); + assert!(data.child_data().len() == 1); let values = make_array(data.child_data()[0].clone()); let raw_value_offsets = data.buffers()[0].raw_data(); assert!(memory::is_aligned( @@ -301,8 +332,8 @@ impl From for ListArray { )); let value_offsets = raw_value_offsets as *const i32; unsafe { - debug_assert!(*value_offsets.offset(0) == 0); - debug_assert!(*value_offsets.offset(data.len() as isize) == values.data().len() as i32); + assert!(*value_offsets.offset(0) == 0); + assert!(*value_offsets.offset(data.len() as isize) == values.data().len() as i32); } Self { data: data.clone(), @@ -335,10 +366,8 @@ pub struct BinaryArray { impl BinaryArray { /// Returns the element at index `i` as a byte slice. - /// - /// Note this doesn't do any bound checking, for performance reason. pub fn get_value(&self, i: i64) -> &[u8] { - assert!(i >= 0 && i <= self.data.len()); + assert!(i >= 0 && i < self.data.len()); let offset = i.checked_add(self.data.offset()).unwrap(); unsafe { let pos = self.value_offset_at(offset); @@ -485,26 +514,53 @@ impl From> for StructArray { mod tests { use std::thread; - use super::{BinaryArray, ListArray, PrimitiveArray, StructArray}; + use super::{Array, BinaryArray, ListArray, PrimitiveArray, StructArray}; use array_data::ArrayData; use buffer::Buffer; use datatypes::{DataType, Field, ToByteSlice}; use memory; #[test] - fn test_primitive_array() { - let values: Vec = vec![0, 1, 2, 3, 4]; - let buf = Buffer::from(&values[..].to_byte_slice()); + fn test_primitive_array_from_vec() { + let buf = Buffer::from(&[0, 1, 2, 3, 4].to_byte_slice()); let buf2 = buf.clone(); - let pa = PrimitiveArray::::new(buf.len() as i64, buf, 0, 0); + let pa = PrimitiveArray::::new(5, buf, 0, 0); + let slice = unsafe { ::std::slice::from_raw_parts(pa.raw_values(), 5) }; assert_eq!(buf2, pa.values()); - assert_eq!(2, pa.value(2)); - let raw_values = pa.raw_values(); - let slice = unsafe { ::std::slice::from_raw_parts(raw_values, 5) }; assert_eq!(&[0, 1, 2, 3, 4], slice); + assert_eq!(5, pa.len()); + assert_eq!(0, pa.offset()); + assert_eq!(0, pa.null_count()); + for i in 0..5 { + assert!(!pa.is_null(i)); + assert!(pa.is_valid(i)); + assert_eq!(i as i32, pa.value(i)); + } + } + + #[test] + fn test_primitive_array_from_vec_option() { + // Test building a primitive array with null values + let pa = PrimitiveArray::::from(vec![Some(0), None, Some(2), None, Some(4)]); + assert_eq!(5, pa.len()); + assert_eq!(0, pa.offset()); + assert_eq!(2, pa.null_count()); + for i in 0..5 { + if i % 2 == 0 { + assert!(!pa.is_null(i)); + assert!(pa.is_valid(i)); + assert_eq!(i as i32, pa.value(i)); + } else { + assert!(pa.is_null(i)); + assert!(!pa.is_valid(i)); + } + } + } + #[test] + fn test_primitive_array_builder() { // Test building an primitive array with ArrayData builder and offset - let buf = Buffer::from(&[2, 4, 6, 8, 10].to_byte_slice()); + let buf = Buffer::from(&[0, 1, 2, 3, 4].to_byte_slice()); let buf2 = buf.clone(); let data = ArrayData::builder(DataType::Int32) .len(5) @@ -513,22 +569,24 @@ mod tests { .build(); let pa = PrimitiveArray::::from(data); assert_eq!(buf2, pa.values()); - assert_eq!(6, pa.value(0)); + assert_eq!(5, pa.len()); + assert_eq!(0, pa.null_count()); + for i in 0..3 { + assert_eq!((i + 2) as i32, pa.value(i)); + } } #[test] fn test_list_array() { // Construct a value array - let values: Vec = vec![0, 1, 2, 3, 4, 5, 6, 7]; let value_data = ArrayData::builder(DataType::Int32) .len(7) - .add_buffer(Buffer::from(&values[..].to_byte_slice())) + .add_buffer(Buffer::from(&[0, 1, 2, 3, 4, 5, 6, 7].to_byte_slice())) .build(); // Construct a buffer for value offsets, for the nested array: // [[0, 1, 2], [3, 4, 5], [6, 7]] - let value_offset_slice: Vec = vec![0, 2, 5, 7]; - let value_offsets = Buffer::from(value_offset_slice.to_byte_slice()); + let value_offsets = Buffer::from(&[0, 2, 5, 7].to_byte_slice()); // Construct a list array from the above two let list_data_type = DataType::List(Box::new(DataType::Int32)); @@ -542,8 +600,14 @@ mod tests { let values = list_array.values(); assert_eq!(value_data, values.data()); assert_eq!(DataType::Int32, list_array.value_type()); + assert_eq!(3, list_array.len()); + assert_eq!(0, list_array.null_count()); assert_eq!(5, list_array.value_offset(2)); assert_eq!(2, list_array.value_length(2)); + for i in 0..3 { + assert!(list_array.is_valid(i as i64)); + assert!(!list_array.is_null(i as i64)); + } // Now test with a non-zero offset let list_data = ArrayData::builder(list_data_type) @@ -557,10 +621,77 @@ mod tests { let values = list_array.values(); assert_eq!(value_data, values.data()); assert_eq!(DataType::Int32, list_array.value_type()); + assert_eq!(3, list_array.len()); + assert_eq!(0, list_array.null_count()); assert_eq!(5, list_array.value_offset(1)); assert_eq!(2, list_array.value_length(1)); } + #[test] + #[should_panic(expected = "")] + fn test_list_array_invalid_buffer_len() { + let value_data = ArrayData::builder(DataType::Int32) + .len(7) + .add_buffer(Buffer::from(&[0, 1, 2, 3, 4, 5, 6, 7].to_byte_slice())) + .build(); + let list_data_type = DataType::List(Box::new(DataType::Int32)); + let list_data = ArrayData::builder(list_data_type) + .len(3) + .add_child_data(value_data) + .build(); + ListArray::from(list_data); + } + + #[test] + #[should_panic(expected = "")] + fn test_list_array_invalid_child_array_len() { + let value_offsets = Buffer::from(&[0, 2, 5, 7].to_byte_slice()); + let list_data_type = DataType::List(Box::new(DataType::Int32)); + let list_data = ArrayData::builder(list_data_type) + .len(3) + .add_buffer(value_offsets) + .build(); + ListArray::from(list_data); + } + + #[test] + #[should_panic(expected = "")] + fn test_list_array_invalid_value_offset_start() { + let value_data = ArrayData::builder(DataType::Int32) + .len(7) + .add_buffer(Buffer::from(&[0, 1, 2, 3, 4, 5, 6, 7].to_byte_slice())) + .build(); + + let value_offsets = Buffer::from(&[2, 2, 5, 7].to_byte_slice()); + + let list_data_type = DataType::List(Box::new(DataType::Int32)); + let list_data = ArrayData::builder(list_data_type.clone()) + .len(3) + .add_buffer(value_offsets.clone()) + .add_child_data(value_data.clone()) + .build(); + ListArray::from(list_data); + } + + #[test] + #[should_panic(expected = "")] + fn test_list_array_invalid_value_offset_end() { + let value_data = ArrayData::builder(DataType::Int32) + .len(7) + .add_buffer(Buffer::from(&[0, 1, 2, 3, 4, 5, 6, 7].to_byte_slice())) + .build(); + + let value_offsets = Buffer::from(&[0, 2, 5, 8].to_byte_slice()); + + let list_data_type = DataType::List(Box::new(DataType::Int32)); + let list_data = ArrayData::builder(list_data_type.clone()) + .len(3) + .add_buffer(value_offsets.clone()) + .add_child_data(value_data.clone()) + .build(); + ListArray::from(list_data); + } + #[test] fn test_binary_array() { let values: [u8; 12] = [ @@ -570,11 +701,13 @@ mod tests { // Array data: ["hello", "", "parquet"] let array_data = ArrayData::builder(DataType::Utf8) - .len(4) + .len(3) .add_buffer(Buffer::from(offsets.to_byte_slice())) .add_buffer(Buffer::from(&values[..])) .build(); let binary_array = BinaryArray::from(array_data); + assert_eq!(3, binary_array.len()); + assert_eq!(0, binary_array.null_count()); assert_eq!([b'h', b'e', b'l', b'l', b'o'], binary_array.get_value(0)); assert_eq!("hello", binary_array.get_string(0)); assert_eq!([] as [u8; 0], binary_array.get_value(1)); @@ -586,6 +719,10 @@ mod tests { assert_eq!("parquet", binary_array.get_string(2)); assert_eq!(5, binary_array.value_offset(2)); assert_eq!(7, binary_array.value_length(2)); + for i in 0..3 { + assert!(binary_array.is_valid(i as i64)); + assert!(!binary_array.is_null(i as i64)); + } // Test binary array with offset let array_data = ArrayData::builder(DataType::Utf8) @@ -602,6 +739,22 @@ mod tests { assert_eq!("parquet", binary_array.get_string(1)); } + #[test] + #[should_panic(expected = "")] + fn test_binary_array_get_value_index_out_of_bound() { + let values: [u8; 12] = [ + b'h', b'e', b'l', b'l', b'o', b'p', b'a', b'r', b'q', b'u', b'e', b't', + ]; + let offsets: [i32; 4] = [0, 5, 5, 12]; + let array_data = ArrayData::builder(DataType::Utf8) + .len(3) + .add_buffer(Buffer::from(offsets.to_byte_slice())) + .add_buffer(Buffer::from(&values[..])) + .build(); + let binary_array = BinaryArray::from(array_data); + binary_array.get_value(4); + } + #[test] fn test_struct_array() { let boolean_data = ArrayData::builder(DataType::Boolean) diff --git a/rust/src/array_data.rs b/rust/src/array_data.rs index 3650d501c3a5..09134971aa90 100644 --- a/rust/src/array_data.rs +++ b/rust/src/array_data.rs @@ -20,7 +20,7 @@ use std::sync::Arc; use bitmap::Bitmap; use buffer::Buffer; use datatypes::DataType; -use util::bit_util::count_set_bits; +use util::bit_util; /// An generic representation of Arrow array data which encapsulates common attributes and /// operations for Arrow array. Specific operations for different arrays types (e.g., @@ -36,7 +36,7 @@ pub struct ArrayData { /// The number of null elements in this array data null_count: i64, - /// The offset into this array data. + /// The offset into this array data offset: i64, /// The buffers for this array data. Note that depending on the array types, this @@ -68,7 +68,7 @@ impl ArrayData { ) -> Self { if null_count < 0 { null_count = if let Some(ref buf) = null_bit_buffer { - count_set_bits(buf.data()) + len - bit_util::count_set_bits_offset(buf.data(), offset) } else { 0 }; @@ -90,22 +90,22 @@ impl ArrayData { ArrayDataBuilder::new(data_type) } - /// Returns a reference to the data type of this array data. + /// Returns a reference to the data type of this array data pub fn data_type(&self) -> &DataType { &self.data_type } - /// Returns a slice of buffers for this array data. + /// Returns a slice of buffers for this array data pub fn buffers(&self) -> &[Buffer] { &self.buffers[..] } - /// Returns a slice of children data arrays. + /// Returns a slice of children data arrays pub fn child_data(&self) -> &[ArrayDataRef] { &self.child_data[..] } - /// Returns whether the element at index `i` is null. + /// Returns whether the element at index `i` is null pub fn is_null(&self, i: i64) -> bool { if let Some(ref b) = self.null_bitmap { return !b.is_set(i); @@ -113,12 +113,12 @@ impl ArrayData { false } - /// Returns a reference to the null bitmap of this array data. + /// Returns a reference to the null bitmap of this array data pub fn null_bitmap(&self) -> &Option { &self.null_bitmap } - /// Returns whether the element at index `i` is not null. + /// Returns whether the element at index `i` is not null pub fn is_valid(&self, i: i64) -> bool { if let Some(ref b) = self.null_bitmap { return b.is_set(i); @@ -126,23 +126,23 @@ impl ArrayData { true } - /// Returns the length (i.e., number of elements) of this array. + /// Returns the length (i.e., number of elements) of this array pub fn len(&self) -> i64 { self.len } - /// Returns the offset of this array. + /// Returns the offset of this array pub fn offset(&self) -> i64 { self.offset } - /// Returns the total number of nulls in this array. + /// Returns the total number of nulls in this array pub fn null_count(&self) -> i64 { self.null_count } } -/// Builder for `ArrayData` type. +/// Builder for `ArrayData` type pub struct ArrayDataBuilder { data_type: DataType, len: i64, @@ -222,9 +222,11 @@ impl ArrayDataBuilder { #[cfg(test)] mod tests { + use std::sync::Arc; + use super::{ArrayData, DataType}; use buffer::Buffer; - use std::sync::Arc; + use util::bit_util; #[test] fn test_new() { @@ -265,4 +267,30 @@ mod tests { assert_eq!(1, arr_data.child_data().len()); assert_eq!(child_arr_data, arr_data.child_data()[0]); } + + #[test] + fn test_null_count() { + let mut bit_v: [u8; 2] = [0; 2]; + bit_util::set_bit(&mut bit_v, 0); + bit_util::set_bit(&mut bit_v, 3); + bit_util::set_bit(&mut bit_v, 10); + let arr_data = ArrayData::builder(DataType::Int32) + .len(16) + .null_bit_buffer(Buffer::from(bit_v)) + .build(); + assert_eq!(13, arr_data.null_count()); + + // Test with offset + let mut bit_v: [u8; 2] = [0; 2]; + bit_util::set_bit(&mut bit_v, 0); + bit_util::set_bit(&mut bit_v, 3); + bit_util::set_bit(&mut bit_v, 10); + let arr_data = ArrayData::builder(DataType::Int32) + .len(16) + .offset(2) + .null_bit_buffer(Buffer::from(bit_v)) + .build(); + assert_eq!(14, arr_data.null_count()); + + } } diff --git a/rust/src/util/bit_util.rs b/rust/src/util/bit_util.rs index a756be310476..8d9a805ac1c2 100644 --- a/rust/src/util/bit_util.rs +++ b/rust/src/util/bit_util.rs @@ -28,6 +28,12 @@ static POPCOUNT_TABLE: [u8; 256] = [ 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, ]; +/// Returns the nearest number that is `>=` than `num` and is a multiple of 64 +#[inline] +pub fn round_upto_multiple_of_64(num: i64) -> i64 { + round_upto_power_of_2(num, 64) +} + /// Returns the nearest multiple of `factor` that is `>=` than `num`. Here `factor` must /// be a power of 2. fn round_upto_power_of_2(num: i64, factor: i64) -> i64 { @@ -35,25 +41,19 @@ fn round_upto_power_of_2(num: i64, factor: i64) -> i64 { (num + (factor - 1)) & !(factor - 1) } -/// Returns the nearest number that is `>=` than `num` and is a multiple of 64. -#[inline] -pub fn round_upto_multiple_of_64(num: i64) -> i64 { - round_upto_power_of_2(num, 64) -} - -/// Returns whether bit at position `i` in `data` is set or not. +/// Returns whether bit at position `i` in `data` is set or not #[inline] pub fn get_bit(data: &[u8], i: i64) -> bool { (data[(i / 8) as usize] & BIT_MASK[(i % 8) as usize]) != 0 } -/// Sets bit at position `i` for `data`. +/// Sets bit at position `i` for `data` #[inline] pub fn set_bit(data: &mut [u8], i: i64) { data[(i / 8) as usize] |= BIT_MASK[(i % 8) as usize] } -/// Returns the number of 1-bits in `data`. +/// Returns the number of 1-bits in `data` #[inline] pub fn count_set_bits(data: &[u8]) -> i64 { let mut count: i64 = 0; @@ -63,6 +63,28 @@ pub fn count_set_bits(data: &[u8]) -> i64 { count } +/// Returns the number of 1-bits in `data`, starting from `offset`. +#[inline] +pub fn count_set_bits_offset(data: &[u8], offset: i64) -> i64 { + debug_assert!(offset <= (data.len() * 8) as i64); + + let start_byte_pos = (offset / 8) as usize; + let start_bit_pos = offset % 8; + + if start_bit_pos == 0 { + count_set_bits(&data[start_byte_pos..]) + } else { + let mut result = 0; + result += count_set_bits(&data[start_byte_pos + 1..]); + for i in start_bit_pos..8 { + if get_bit(&data[start_byte_pos..start_byte_pos + 1], i as i64) { + result += 1; + } + } + result + } +} + #[cfg(test)] mod tests { use rand::{thread_rng, Rng}; @@ -143,4 +165,17 @@ mod tests { assert_eq!(3, count_set_bits(&[0b00001101])); assert_eq!(6, count_set_bits(&[0b01001001, 0b01010010])); } + + #[test] + fn test_count_bits_offset_slice() { + assert_eq!(8, count_set_bits_offset(&[0b11111111], 0)); + assert_eq!(5, count_set_bits_offset(&[0b11111111], 3)); + assert_eq!(0, count_set_bits_offset(&[0b11111111], 8)); + assert_eq!(16, count_set_bits_offset(&[0b11111111, 0b11111111], 0)); + assert_eq!(13, count_set_bits_offset(&[0b11111111, 0b11111111], 3)); + assert_eq!(8, count_set_bits_offset(&[0b11111111, 0b11111111], 8)); + assert_eq!(5, count_set_bits_offset(&[0b11111111, 0b11111111], 11)); + assert_eq!(0, count_set_bits_offset(&[0b11111111, 0b11111111], 16)); + } + } From 21b8d1dfd87d08e74669a11894b85350d233fe6b Mon Sep 17 00:00:00 2001 From: Chao Sun Date: Mon, 13 Aug 2018 00:52:40 -0700 Subject: [PATCH 18/20] Fix lint --- rust/src/array.rs | 1 - rust/src/array_data.rs | 1 - 2 files changed, 2 deletions(-) diff --git a/rust/src/array.rs b/rust/src/array.rs index c2b49c079775..4db3c98c01af 100644 --- a/rust/src/array.rs +++ b/rust/src/array.rs @@ -40,7 +40,6 @@ pub trait Array: Send + Sync { /// Returns a borrowed & reference-counted pointer to the data of this array fn data_ref(&self) -> &ArrayDataRef; - /// Returns a reference to the data type of this array fn data_type(&self) -> &DataType { self.data_ref().data_type() diff --git a/rust/src/array_data.rs b/rust/src/array_data.rs index 09134971aa90..6ad9e2edbe27 100644 --- a/rust/src/array_data.rs +++ b/rust/src/array_data.rs @@ -291,6 +291,5 @@ mod tests { .null_bit_buffer(Buffer::from(bit_v)) .build(); assert_eq!(14, arr_data.null_count()); - } } From 0e8a8dc96b7e09f3eb22ccf60aab85c4a6694852 Mon Sep 17 00:00:00 2001 From: Chao Sun Date: Wed, 15 Aug 2018 09:31:23 -0700 Subject: [PATCH 19/20] Address review comments --- rust/benches/array_from_vec.rs | 2 +- rust/src/array.rs | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/rust/benches/array_from_vec.rs b/rust/benches/array_from_vec.rs index f922be2f3853..509628d172c6 100644 --- a/rust/benches/array_from_vec.rs +++ b/rust/benches/array_from_vec.rs @@ -30,7 +30,7 @@ use arrow::datatypes::*; fn array_from_vec(n: usize) { let mut v: Vec = Vec::with_capacity(n); for i in 0..n { - v.push((i % 0xffff) as u8); + v.push((i & 0xffff) as u8); } let arr_data = ArrayDataBuilder::new(DataType::Int32) .add_buffer(Buffer::from(v)) diff --git a/rust/src/array.rs b/rust/src/array.rs index 4db3c98c01af..77ca01028e61 100644 --- a/rust/src/array.rs +++ b/rust/src/array.rs @@ -575,6 +575,15 @@ mod tests { } } + #[test] + #[should_panic(expected = "")] + fn test_primitive_array_invalid_buffer_len() { + let data = ArrayData::builder(DataType::Int32) + .len(5) + .build(); + PrimitiveArray::::from(data); + } + #[test] fn test_list_array() { // Construct a value array From 91c580b85681d416d2d5e1ec24acc1e76d2c6d84 Mon Sep 17 00:00:00 2001 From: Chao Sun Date: Wed, 15 Aug 2018 09:46:56 -0700 Subject: [PATCH 20/20] Fix lint --- rust/src/array.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/rust/src/array.rs b/rust/src/array.rs index 77ca01028e61..c5d7ee189e52 100644 --- a/rust/src/array.rs +++ b/rust/src/array.rs @@ -578,9 +578,7 @@ mod tests { #[test] #[should_panic(expected = "")] fn test_primitive_array_invalid_buffer_len() { - let data = ArrayData::builder(DataType::Int32) - .len(5) - .build(); + let data = ArrayData::builder(DataType::Int32).len(5).build(); PrimitiveArray::::from(data); }