Skip to content

Apache DataFusion SQL Query Engine

ARROW-4151: [Rust] Restructure project directories

Chao Sun39d173cde4ff
diff --git a/.travis.yml b/.travis.yml
index 916ccf460e..ffbb691f65 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -307,7 +307,7 @@ matrix:
- pushd ${TRAVIS_BUILD_DIR}/rust
# Run coverage for codecov.io
- mkdir -p target/kcov
- - RUST_BACKTRACE=1 RUSTUP_TOOLCHAIN=stable cargo coverage --verbose
+ - RUST_BACKTRACE=1 RUSTUP_TOOLCHAIN=nightly cargo coverage --verbose
- bash <(curl -s https://codecov.io/bash) || echo "Codecov did not collect coverage reports"
- name: Go
language: go
diff --git a/ci/travis_script_rust.sh b/ci/travis_script_rust.sh
index af61dd3944..8e3c8c3906 100755
--- a/ci/travis_script_rust.sh
+++ b/ci/travis_script_rust.sh
@@ -31,11 +31,11 @@ rustup show
# raises on any formatting errors
cargo +stable fmt --all -- --check
-# raises on any warnings
-cargo rustc -- -D warnings
-
-cargo build
+RUSTFLAGS="-D warnings" cargo build
cargo test
+
+# run examples
+cd arrow
cargo run --example builders
cargo run --example dynamic_types
cargo run --example read_csv
diff --git a/dev/release/00-prepare.sh b/dev/release/00-prepare.sh
index 20d9ab8fce..1c233a35c2 100755
--- a/dev/release/00-prepare.sh
+++ b/dev/release/00-prepare.sh
@@ -100,9 +100,9 @@ update_versions() {
cd "${SOURCE_DIR}/../../rust"
sed -i.bak -r -e \
"s/^version = \".+\"/version = \"${version}\"/g" \
- Cargo.toml parquet/Cargo.toml
- rm -f Cargo.toml.bak parquet/Cargo.toml.bak
- git add Cargo.toml parquet/Cargo.toml
+ arrow/Cargo.toml parquet/Cargo.toml
+ rm -f arrow/Cargo.toml.bak parquet/Cargo.toml.bak
+ git add arrow/Cargo.toml parquet/Cargo.toml
cd -
}
diff --git a/dev/release/rat_exclude_files.txt b/dev/release/rat_exclude_files.txt
index 1086793630..720b19d894 100644
--- a/dev/release/rat_exclude_files.txt
+++ b/dev/release/rat_exclude_files.txt
@@ -187,5 +187,5 @@ r/README.Rmd
r/man/*.Rd
.gitattributes
ruby/red-arrow/.yardopts
-rust/test/data/*.csv
+rust/arrow/test/data/*.csv
rust/rust-toolchain
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index 1bf64d73ad..abfb71ada7 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -15,46 +15,8 @@
# specific language governing permissions and limitations
# under the License.
-[package]
-name = "arrow"
-version = "0.12.0-SNAPSHOT"
-description = "Rust implementation of Apache Arrow"
-homepage = "https://github.com/apache/arrow"
-repository = "https://github.com/apache/arrow"
-authors = ["Apache Arrow <[email protected]>"]
-license = "Apache-2.0"
-keywords = [ "arrow" ]
-include = [
- "src/**/*.rs",
- "Cargo.toml",
-]
-edition = "2018"
-
-[lib]
-name = "arrow"
-path = "src/lib.rs"
-
-[dependencies]
-bytes = "0.4"
-libc = "0.2"
-serde = { version = "1.0.80", features = ["alloc", "rc"] }
-serde_derive = "1.0.80"
-serde_json = "1.0.13"
-rand = "0.5"
-csv = "1.0.0"
-num = "0.2"
-
-[dev-dependencies]
-criterion = "0.2"
-lazy_static = "1"
-
-[[bench]]
-name = "array_from_vec"
-harness = false
-
-[[bench]]
-name = "builder"
-harness = false
-
[workspace]
-members = ["parquet"]
\ No newline at end of file
+members = [
+ "arrow",
+ "parquet",
+]
\ No newline at end of file
diff --git a/rust/README.md b/rust/README.md
deleted file mode 100644
index cbfd4dd684..0000000000
--- a/rust/README.md
+++ /dev/null
@@ -1,111 +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.
--->
-
-# Native Rust implementation of Apache Arrow
-
-[![Build Status](https://travis-ci.org/apache/arrow.svg?branch=master)](https://travis-ci.org/apache/arrow)
-[![Coverage Status](https://coveralls.io/repos/github/apache/arrow/badge.svg)](https://coveralls.io/github/apache/arrow)
-
-## Status
-
-This is a native Rust implementation of Apache Arrow. Currently the project
-is developed and tested against nightly Rust. The current status is:
-
-- [x] Primitive Arrays
-- [x] List Arrays
-- [x] Struct Arrays
-- [x] CSV Reader
-- [ ] CSV Writer
-- [ ] Parquet Reader
-- [ ] Parquet Writer
-- [ ] Arrow IPC
-- [ ] Interop tests with other implementations
-
-## Dependencies
-
-Parquet support for Apache Arrow requires LLVM. Our windows CI image
-includes LLVM but to build the libraries locally windows users will have
-to install LLVM. Follow [this](https://github.com/appveyor/ci/issues/2651)
-link for info.
-
-## Examples
-
-The examples folder shows how to construct some different types of Arrow
-arrays, including dynamic arrays created at runtime.
-
-Examples can be run using the `cargo run --example` command. For example:
-
-```bash
-cargo run --example builders
-cargo run --example dynamic_types
-cargo run --example read_csv
-```
-
-## Run Tests
-
-Parquet support in Arrow requires data to test against, this data is in a
-git submodule. To pull down this data run the following:
-
-```bash
-git submodule update --init
-```
-
-The data can then be found in `cpp/submodules/parquet_testing/data`.
-Create a new environment variable called `PARQUET_TEST_DATA` to point
-to this location and then `cargo test` as usual.
-
-Our CI uses `rustfmt` to check code formatting. Although the project is
-built and tested against nightly rust we use the stable version of
-`rustfmt`. So before submitting a PR be sure to run the following
-and check for lint issues:
-
-```bash
-cargo +stable fmt --all -- --check
-```
-
-# Publishing to crates.io
-
-An Arrow committer can publish this crate after an official project release has
-been made to crates.io using the following instructions.
-
-Follow [these
-instructions](https://doc.rust-lang.org/cargo/reference/publishing.html) to
-create an account and login to crates.io before asking to be added as an owner
-of the [arrow crate](https://crates.io/crates/arrow).
-
-Checkout the tag for the version to be released. For example:
-
-```bash
-git checkout apache-arrow-0.11.0
-```
-
-If the Cargo.toml in this tag already contains `version = "0.11.0"` (as it
-should) then the crate can be published with the following command:
-
-```bash
-cargo publish
-```
-
-If the Cargo.toml does not have the correct version then it will be necessary
-to modify it manually. Since there is now a modified file locally that is not
-committed to github it will be necessary to use the following command.
-
-```bash
-cargo publish --allow-dirty
-```
diff --git a/rust/benches/array_from_vec.rs b/rust/benches/array_from_vec.rs
deleted file mode 100644
index f935714092..0000000000
--- a/rust/benches/array_from_vec.rs
+++ /dev/null
@@ -1,47 +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::array_data::ArrayDataBuilder;
-use arrow::buffer::Buffer;
-use arrow::datatypes::*;
-
-fn array_from_vec(n: usize) {
- let mut v: Vec<u8> = Vec::with_capacity(n);
- for i in 0..n {
- v.push((i & 0xffff) as u8);
- }
- let arr_data = ArrayDataBuilder::new(DataType::Int32)
- .add_buffer(Buffer::from(v))
- .build();
- criterion::black_box(Int32Array::from(arr_data));
-}
-
-fn criterion_benchmark(c: &mut Criterion) {
- c.bench_function("array_from_vec 128", |b| b.iter(|| array_from_vec(128)));
- c.bench_function("array_from_vec 256", |b| b.iter(|| array_from_vec(256)));
- c.bench_function("array_from_vec 512", |b| b.iter(|| array_from_vec(512)));
-}
-
-criterion_group!(benches, criterion_benchmark);
-criterion_main!(benches);
diff --git a/rust/benches/builder.rs b/rust/benches/builder.rs
deleted file mode 100644
index 90fd75a0da..0000000000
--- a/rust/benches/builder.rs
+++ /dev/null
@@ -1,77 +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.
-
-extern crate arrow;
-extern crate criterion;
-extern crate rand;
-
-use std::mem::size_of;
-
-use criterion::*;
-use rand::distributions::Standard;
-use rand::{thread_rng, Rng};
-
-use arrow::builder::*;
-
-// Build arrays with 512k elements.
-const BATCH_SIZE: usize = 8 << 10;
-const NUM_BATCHES: usize = 64;
-
-fn bench_primitive(c: &mut Criterion) {
- let data: [i64; BATCH_SIZE] = [100; BATCH_SIZE];
- c.bench(
- "bench_primitive",
- Benchmark::new("bench_primitive", move |b| {
- b.iter(|| {
- let mut builder = Int64Builder::new(64);
- for _ in 0..NUM_BATCHES {
- let _ = black_box(builder.push_slice(&data[..]));
- }
- black_box(builder.finish());
- })
- })
- .throughput(Throughput::Bytes(
- (data.len() * NUM_BATCHES * size_of::<i64>()) as u32,
- )),
- );
-}
-
-fn bench_bool(c: &mut Criterion) {
- let data: Vec<bool> = thread_rng()
- .sample_iter(&Standard)
- .take(BATCH_SIZE)
- .collect();
- let data_len = data.len();
- c.bench(
- "bench_bool",
- Benchmark::new("bench_bool", move |b| {
- b.iter(|| {
- let mut builder = BooleanBuilder::new(64);
- for _ in 0..NUM_BATCHES {
- let _ = black_box(builder.push_slice(&data[..]));
- }
- black_box(builder.finish());
- })
- })
- .throughput(Throughput::Bytes(
- (data_len * NUM_BATCHES * size_of::<bool>()) as u32,
- )),
- );
-}
-
-criterion_group!(benches, bench_primitive, bench_bool);
-criterion_main!(benches);
diff --git a/rust/examples/builders.rs b/rust/examples/builders.rs
deleted file mode 100644
index 5273558d96..0000000000
--- a/rust/examples/builders.rs
+++ /dev/null
@@ -1,43 +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.
-
-///! Many builders are available to easily create different types of arrow arrays
-extern crate arrow;
-
-use arrow::builder::{ArrayBuilder, Int32Builder};
-
-fn main() {
- // Primitive Arrays
- //
- // Primitive arrays are arrays of fixed-width primitive types (bool, u8, u16, u32, u64, i8, i16,
- // i32, i64, f32, f64)
-
- // Create a new builder with a capacity of 100
- let mut primitive_array_builder = Int32Builder::new(100);
-
- // Push an individual primitive value
- primitive_array_builder.push(55).unwrap();
-
- // Push a null value
- primitive_array_builder.push_null().unwrap();
-
- // Push a slice of primitive values
- primitive_array_builder.push_slice(&[39, 89, 12]).unwrap();
-
- // Build the `PrimitiveArray`
- let _primitive_array = primitive_array_builder.finish();
-}
diff --git a/rust/examples/dynamic_types.rs b/rust/examples/dynamic_types.rs
deleted file mode 100644
index 8e6bb5d41c..0000000000
--- a/rust/examples/dynamic_types.rs
+++ /dev/null
@@ -1,98 +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.
-
-///! This example demonstrates dealing with mixed types dynamically at runtime
-use std::sync::Arc;
-
-extern crate arrow;
-
-use arrow::array::*;
-use arrow::datatypes::*;
-use arrow::record_batch::*;
-
-fn main() {
- // define schema
- let schema = Schema::new(vec![
- Field::new("id", DataType::Int32, false),
- Field::new(
- "nested",
- DataType::Struct(vec![
- Field::new("a", DataType::Utf8, false),
- Field::new("b", DataType::Float64, false),
- Field::new("c", DataType::Float64, false),
- ]),
- false,
- ),
- ]);
-
- // create some data
- let id = Int32Array::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<Array>,
- ),
- (
- Field::new("b", DataType::Float64, false),
- Arc::new(Float64Array::from(vec![1.1, 2.2, 3.3, 4.4, 5.5])),
- ),
- (
- Field::new("c", DataType::Float64, false),
- Arc::new(Float64Array::from(vec![2.2, 3.3, 4.4, 5.5, 6.6])),
- ),
- ]);
-
- // build a record batch
- let batch = RecordBatch::new(Arc::new(schema), vec![Arc::new(id), Arc::new(nested)]);
-
- process(&batch);
-}
-
-/// Create a new batch by performing a projection of id, nested.c
-fn process(batch: &RecordBatch) {
- let id = batch.column(0);
- let nested = batch
- .column(1)
- .as_any()
- .downcast_ref::<StructArray>()
- .unwrap();
-
- let _nested_b = nested
- .column(1)
- .as_any()
- .downcast_ref::<Float64Array>()
- .unwrap();
- let nested_c: &Float64Array = nested
- .column(2)
- .as_any()
- .downcast_ref::<Float64Array>()
- .unwrap();
-
- let projected_schema = Schema::new(vec![
- Field::new("id", DataType::Int32, false),
- Field::new("sum", DataType::Float64, false),
- ]);
-
- let _ = RecordBatch::new(
- Arc::new(projected_schema),
- vec![
- id.clone(), // NOTE: this is cloning the Arc not the array data
- Arc::new(Float64Array::from(nested_c.data())),
- ],
- );
-}
diff --git a/rust/examples/read_csv.rs b/rust/examples/read_csv.rs
deleted file mode 100644
index 147d2f9c23..0000000000
--- a/rust/examples/read_csv.rs
+++ /dev/null
@@ -1,71 +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.
-
-extern crate arrow;
-
-use std::fs::File;
-use std::sync::Arc;
-
-use arrow::array::{BinaryArray, Float64Array};
-use arrow::csv;
-use arrow::datatypes::{DataType, Field, Schema};
-
-fn main() {
- let schema = Schema::new(vec![
- Field::new("city", DataType::Utf8, false),
- Field::new("lat", DataType::Float64, false),
- Field::new("lng", DataType::Float64, false),
- ]);
-
- let file = File::open("test/data/uk_cities.csv").unwrap();
-
- let mut csv = csv::Reader::new(file, Arc::new(schema), false, 1024, None);
- let batch = csv.next().unwrap().unwrap();
-
- println!(
- "Loaded {} rows containing {} columns",
- batch.num_rows(),
- batch.num_columns()
- );
-
- let city = batch
- .column(0)
- .as_any()
- .downcast_ref::<BinaryArray>()
- .unwrap();
- let lat = batch
- .column(1)
- .as_any()
- .downcast_ref::<Float64Array>()
- .unwrap();
- let lng = batch
- .column(2)
- .as_any()
- .downcast_ref::<Float64Array>()
- .unwrap();
-
- for i in 0..batch.num_rows() {
- let city_name: String = String::from_utf8(city.get_value(i).to_vec()).unwrap();
-
- println!(
- "City: {}, Latitude: {}, Longitude: {}",
- city_name,
- lat.value(i),
- lng.value(i)
- );
- }
-}
diff --git a/rust/src/array.rs b/rust/src/array.rs
deleted file mode 100644
index 251dd35eea..0000000000
--- a/rust/src/array.rs
+++ /dev/null
@@ -1,1198 +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.
-
-///! Array types
-use std::any::Any;
-use std::convert::From;
-use std::io::Write;
-use std::mem;
-use std::sync::Arc;
-
-use crate::array_data::{ArrayData, ArrayDataRef};
-use crate::buffer::{Buffer, MutableBuffer};
-use crate::builder::*;
-use crate::datatypes::*;
-use crate::memory;
-use crate::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
- fn as_any(&self) -> &Any;
-
- /// Returns a reference-counted pointer to the data of this array
- fn data(&self) -> ArrayDataRef;
-
- /// 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) -> usize {
- self.data().len()
- }
-
- /// Returns the offset of this array
- fn offset(&self) -> usize {
- self.data().offset()
- }
-
- /// Returns whether the element at index `i` is null
- fn is_null(&self, i: usize) -> bool {
- self.data().is_null(i)
- }
-
- /// Returns whether the element at index `i` is not null
- fn is_valid(&self, i: usize) -> bool {
- self.data().is_valid(i)
- }
-
- /// Returns the total number of nulls in this array
- fn null_count(&self) -> usize {
- self.data().null_count()
- }
-}
-
-pub type ArrayRef = Arc<Array>;
-
-/// Constructs an array using the input `data`. Returns a reference-counted `Array`
-/// instance.
-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().clone() {
- DataType::Boolean => Arc::new(BooleanArray::from(data)) as ArrayRef,
- DataType::Int8 => Arc::new(Int8Array::from(data)) as ArrayRef,
- DataType::Int16 => Arc::new(Int16Array::from(data)) as ArrayRef,
- DataType::Int32 => Arc::new(Int32Array::from(data)) as ArrayRef,
- DataType::Int64 => Arc::new(Int64Array::from(data)) as ArrayRef,
- DataType::UInt8 => Arc::new(UInt8Array::from(data)) as ArrayRef,
- DataType::UInt16 => Arc::new(UInt16Array::from(data)) as ArrayRef,
- DataType::UInt32 => Arc::new(UInt32Array::from(data)) as ArrayRef,
- DataType::UInt64 => Arc::new(UInt64Array::from(data)) as ArrayRef,
- DataType::Float32 => Arc::new(Float32Array::from(data)) as ArrayRef,
- DataType::Float64 => Arc::new(Float64Array::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),
- }
-}
-
-/// ----------------------------------------------------------------------------
-/// Implementations of different array types
-
-struct RawPtrBox<T> {
- inner: *const T,
-}
-
-impl<T> RawPtrBox<T> {
- fn new(inner: *const T) -> Self {
- Self { inner }
- }
-
- fn get(&self) -> *const T {
- self.inner
- }
-}
-
-unsafe impl<T> Send for RawPtrBox<T> {}
-unsafe impl<T> Sync for RawPtrBox<T> {}
-
-/// Array whose elements are of primitive types.
-pub struct PrimitiveArray<T: ArrowPrimitiveType> {
- 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.
- /// Also note that boolean arrays are bit-packed, so although the underlying pointer is of type
- /// bool it should be cast back to u8 before being used.
- /// i.e. `self.raw_values.get() as *const u8`
- raw_values: RawPtrBox<T::Native>,
-}
-
-pub type BooleanArray = PrimitiveArray<BooleanType>;
-pub type Int8Array = PrimitiveArray<Int8Type>;
-pub type Int16Array = PrimitiveArray<Int16Type>;
-pub type Int32Array = PrimitiveArray<Int32Type>;
-pub type Int64Array = PrimitiveArray<Int64Type>;
-pub type UInt8Array = PrimitiveArray<UInt8Type>;
-pub type UInt16Array = PrimitiveArray<UInt16Type>;
-pub type UInt32Array = PrimitiveArray<UInt32Type>;
-pub type UInt64Array = PrimitiveArray<UInt64Type>;
-pub type Float32Array = PrimitiveArray<Float32Type>;
-pub type Float64Array = PrimitiveArray<Float64Type>;
-
-impl<T: ArrowPrimitiveType> Array for PrimitiveArray<T> {
- fn as_any(&self) -> &Any {
- self
- }
-
- fn data(&self) -> ArrayDataRef {
- self.data.clone()
- }
-
- fn data_ref(&self) -> &ArrayDataRef {
- &self.data
- }
-}
-
-/// Implementation for primitive arrays with numeric types.
-/// Boolean arrays are bit-packed and so implemented separately.
-impl<T: ArrowNumericType> PrimitiveArray<T> {
- pub fn new(length: usize, values: Buffer, null_count: usize, offset: usize) -> Self {
- let array_data = ArrayData::builder(T::get_data_type())
- .len(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.
- ///
- /// Note this doesn't take account into the offset of this array.
- pub fn values(&self) -> Buffer {
- self.data.buffers()[0].clone()
- }
-
- /// Returns the length of this array
- pub fn len(&self) -> usize {
- self.data.len()
- }
-
- /// Returns a raw pointer to the values of this array.
- pub fn raw_values(&self) -> *const T::Native {
- unsafe { mem::transmute(self.raw_values.get().offset(self.data.offset() as isize)) }
- }
-
- /// Returns the primitive value at index `i`.
- ///
- /// Note this doesn't do any bound checking, for performance reason.
- pub fn value(&self, i: usize) -> T::Native {
- unsafe { *(self.raw_values().offset(i as isize)) }
- }
-
- /// Returns a slice for the given offset and length
- ///
- /// Note this doesn't do any bound checking, for performance reason.
- pub fn value_slice(&self, offset: usize, len: usize) -> &[T::Native] {
- let raw = unsafe { std::slice::from_raw_parts(self.raw_values(), self.len()) };
- &raw[offset..offset + len]
- }
-
- // Returns a new primitive array builder
- pub fn builder(capacity: usize) -> PrimitiveArrayBuilder<T> {
- PrimitiveArrayBuilder::<T>::new(capacity)
- }
-}
-
-/// Specific implementation for Boolean arrays due to bit-packing
-impl PrimitiveArray<BooleanType> {
- pub fn new(length: usize, values: Buffer, null_count: usize, offset: usize) -> Self {
- let array_data = ArrayData::builder(DataType::Boolean)
- .len(length)
- .add_buffer(values)
- .null_count(null_count)
- .offset(offset)
- .build();
- BooleanArray::from(array_data)
- }
-
- /// 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].clone()
- }
-
- /// Returns the boolean value at index `i`.
- pub fn value(&self, i: usize) -> bool {
- let offset = i + self.offset();
- assert!(offset < self.data.len());
- unsafe { bit_util::get_bit_raw(self.raw_values.get() as *const u8, offset) }
- }
-
- // Returns a new primitive array builder
- pub fn builder(capacity: usize) -> BooleanBuilder {
- BooleanBuilder::new(capacity)
- }
-}
-
-// TODO: the macro is needed here because we'd get "conflicting implementations" error
-// otherwise with both `From<Vec<T::Native>>` and `From<Vec<Option<T::Native>>>`.
-// We should revisit this in future.
-macro_rules! def_numeric_from_vec {
- ( $ty:ident, $native_ty:ident, $ty_id:path ) => {
- impl From<Vec<$native_ty>> for PrimitiveArray<$ty> {
- fn from(data: Vec<$native_ty>) -> Self {
- let array_data = ArrayData::builder($ty_id)
- .len(data.len())
- .add_buffer(Buffer::from(data.to_byte_slice()))
- .build();
- PrimitiveArray::from(array_data)
- }
- }
-
- // Constructs a primitive array from a vector. Should only be used for testing.
- impl From<Vec<Option<$native_ty>>> for PrimitiveArray<$ty> {
- fn from(data: Vec<Option<$native_ty>>) -> Self {
- let data_len = data.len();
- let num_bytes = bit_util::ceil(data_len, 8);
- let mut null_buf = MutableBuffer::new(num_bytes).with_bitset(num_bytes, false);
- let mut val_buf = MutableBuffer::new(data_len * mem::size_of::<$native_ty>());
-
- {
- let null = vec![0; mem::size_of::<$native_ty>()];
- let null_slice = null_buf.data_mut();
- for (i, v) in data.iter().enumerate() {
- if let Some(n) = v {
- bit_util::set_bit(null_slice, i);
- // unwrap() in the following should be safe here since we've
- // made sure enough space is allocated for the values.
- val_buf.write(&n.to_byte_slice()).unwrap();
- } else {
- val_buf.write(&null).unwrap();
- }
- }
- }
-
- let array_data = ArrayData::builder($ty_id)
- .len(data_len)
- .add_buffer(val_buf.freeze())
- .null_bit_buffer(null_buf.freeze())
- .build();
- PrimitiveArray::from(array_data)
- }
- }
- };
-}
-
-def_numeric_from_vec!(Int8Type, i8, DataType::Int8);
-def_numeric_from_vec!(Int16Type, i16, DataType::Int16);
-def_numeric_from_vec!(Int32Type, i32, DataType::Int32);
-def_numeric_from_vec!(Int64Type, i64, DataType::Int64);
-def_numeric_from_vec!(UInt8Type, u8, DataType::UInt8);
-def_numeric_from_vec!(UInt16Type, u16, DataType::UInt16);
-def_numeric_from_vec!(UInt32Type, u32, DataType::UInt32);
-def_numeric_from_vec!(UInt64Type, u64, DataType::UInt64);
-def_numeric_from_vec!(Float32Type, f32, DataType::Float32);
-def_numeric_from_vec!(Float64Type, f64, DataType::Float64);
-
-/// Constructs a boolean array from a vector. Should only be used for testing.
-impl From<Vec<bool>> for BooleanArray {
- fn from(data: Vec<bool>) -> Self {
- let num_byte = bit_util::ceil(data.len(), 8);
- let mut mut_buf = MutableBuffer::new(num_byte).with_bitset(num_byte, false);
- {
- let mut_slice = mut_buf.data_mut();
- for (i, b) in data.iter().enumerate() {
- if *b {
- bit_util::set_bit(mut_slice, i);
- }
- }
- }
- let array_data = ArrayData::builder(DataType::Boolean)
- .len(data.len())
- .add_buffer(mut_buf.freeze())
- .build();
- BooleanArray::from(array_data)
- }
-}
-
-impl From<Vec<Option<bool>>> for BooleanArray {
- fn from(data: Vec<Option<bool>>) -> Self {
- let data_len = data.len();
- let num_byte = bit_util::ceil(data_len, 8);
- let mut null_buf = MutableBuffer::new(num_byte).with_bitset(num_byte, false);
- let mut val_buf = MutableBuffer::new(num_byte).with_bitset(num_byte, false);
-
- {
- let null_slice = null_buf.data_mut();
- let val_slice = val_buf.data_mut();
-
- for (i, v) in data.iter().enumerate() {
- if let Some(b) = v {
- bit_util::set_bit(null_slice, i);
- if *b {
- bit_util::set_bit(val_slice, i);
- }
- }
- }
- }
-
- let array_data = ArrayData::builder(DataType::Boolean)
- .len(data_len)
- .add_buffer(val_buf.freeze())
- .null_bit_buffer(null_buf.freeze())
- .build();
- BooleanArray::from(array_data)
- }
-}
-
-/// Constructs a `PrimitiveArray` from an array data reference.
-impl<T: ArrowPrimitiveType> From<ArrayDataRef> for PrimitiveArray<T> {
- default fn from(data: ArrayDataRef) -> Self {
- assert_eq!(
- data.buffers().len(),
- 1,
- "PrimitiveArray data should contain a single buffer only (values buffer)"
- );
- let raw_values = data.buffers()[0].raw_data();
- assert!(
- memory::is_aligned::<u8>(raw_values, mem::align_of::<T::Native>()),
- "memory is not aligned"
- );
- Self {
- data,
- raw_values: RawPtrBox::new(raw_values as *const T::Native),
- }
- }
-}
-
-/// 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<i32>,
-}
-
-impl ListArray {
- /// Returns an reference to the values of this list.
- pub fn values(&self) -> ArrayRef {
- self.values.clone()
- }
-
- /// 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: usize) -> 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: usize) -> i32 {
- i += self.data.offset();
- self.value_offset_at(i + 1) - self.value_offset_at(i)
- }
-
- #[inline]
- fn value_offset_at(&self, i: usize) -> i32 {
- unsafe { *self.value_offsets.get().offset(i as isize) }
- }
-}
-
-/// Constructs a `ListArray` from an array data reference.
-impl From<ArrayDataRef> for ListArray {
- fn from(data: ArrayDataRef) -> Self {
- assert_eq!(
- data.buffers().len(),
- 1,
- "ListArray data should contain a single buffer only (value offsets)"
- );
- assert_eq!(
- data.child_data().len(),
- 1,
- "ListArray should contain a single child array (values array)"
- );
- let values = make_array(data.child_data()[0].clone());
- let raw_value_offsets = data.buffers()[0].raw_data();
- assert!(
- memory::is_aligned(raw_value_offsets, mem::align_of::<i32>()),
- "memory is not aligned"
- );
- let value_offsets = raw_value_offsets as *const i32;
- unsafe {
- assert_eq!(*value_offsets.offset(0), 0, "offsets do not start at zero");
- assert_eq!(
- *value_offsets.offset(data.len() as isize),
- values.data().len() as i32,
- "inconsistent offsets buffer and values array"
- );
- }
- Self {
- data: data.clone(),
- values,
- value_offsets: RawPtrBox::new(value_offsets),
- }
- }
-}
-
-impl Array for ListArray {
- fn as_any(&self) -> &Any {
- self
- }
-
- fn data(&self) -> ArrayDataRef {
- self.data.clone()
- }
-
- fn data_ref(&self) -> &ArrayDataRef {
- &self.data
- }
-}
-
-/// A special type of `ListArray` whose elements are binaries.
-pub struct BinaryArray {
- data: ArrayDataRef,
- value_offsets: RawPtrBox<i32>,
- value_data: RawPtrBox<u8>,
-}
-
-impl BinaryArray {
- /// Returns the element at index `i` as a byte slice.
- pub fn get_value(&self, i: usize) -> &[u8] {
- assert!(i < self.data.len(), "BinaryArray out of bounds access");
- let offset = i.checked_add(self.data.offset()).unwrap();
- unsafe {
- let pos = self.value_offset_at(offset);
- ::std::slice::from_raw_parts(
- self.value_data.get().offset(pos as isize),
- (self.value_offset_at(offset + 1) - pos) as usize,
- )
- }
- }
-
- /// 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: usize) -> 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: usize) -> i32 {
- self.value_offset_at(self.data.offset() + 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: usize) -> i32 {
- i += self.data.offset();
- self.value_offset_at(i + 1) - self.value_offset_at(i)
- }
-
- #[inline]
- fn value_offset_at(&self, i: usize) -> i32 {
- unsafe { *self.value_offsets.get().offset(i as isize) }
- }
-}
-
-impl From<ArrayDataRef> for BinaryArray {
- fn from(data: ArrayDataRef) -> Self {
- assert_eq!(
- data.buffers().len(),
- 2,
- "BinaryArray data should contain 2 buffers only (offsets and values)"
- );
- let raw_value_offsets = data.buffers()[0].raw_data();
- assert!(
- memory::is_aligned(raw_value_offsets, mem::align_of::<i32>()),
- "memory is not aligned"
- );
- let value_data = data.buffers()[1].raw_data();
- Self {
- data: data.clone(),
- value_offsets: RawPtrBox::new(raw_value_offsets as *const i32),
- value_data: RawPtrBox::new(value_data),
- }
- }
-}
-
-impl<'a> From<Vec<&'a str>> 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());
- }
- let array_data = ArrayData::builder(DataType::Utf8)
- .len(v.len())
- .add_buffer(Buffer::from(offsets.to_byte_slice()))
- .add_buffer(Buffer::from(&values[..]))
- .build();
- BinaryArray::from(array_data)
- }
-}
-
-/// Creates a `BinaryArray` from `List<u8>` array
-impl From<ListArray> for BinaryArray {
- fn from(v: ListArray) -> Self {
- assert_eq!(
- v.data().child_data()[0].child_data().len(),
- 0,
- "BinaryArray can only be created from list array of u8 values (i.e. List<PrimitiveArray<u8>>)."
- );
- assert_eq!(
- v.data().child_data()[0].data_type(),
- &DataType::UInt8,
- "BinaryArray can only be created from List<u8> arrays, mismatched data types."
- );
-
- let data = ArrayData::builder(DataType::Utf8)
- .len(v.len())
- .add_buffer(v.data().buffers()[0].clone())
- .add_buffer(v.data().child_data()[0].buffers()[0].clone())
- .build();
- Self::from(data)
- }
-}
-
-impl Array for BinaryArray {
- fn as_any(&self) -> &Any {
- self
- }
-
- fn data(&self) -> ArrayDataRef {
- self.data.clone()
- }
-
- fn data_ref(&self) -> &ArrayDataRef {
- &self.data
- }
-}
-
-/// A nested array type where each child (called *field*) is represented by a separate array.
-pub struct StructArray {
- data: ArrayDataRef,
- boxed_fields: Vec<ArrayRef>,
-}
-
-impl StructArray {
- /// Returns the field at `pos`.
- pub fn column(&self, pos: usize) -> &ArrayRef {
- &self.boxed_fields[pos]
- }
-}
-
-impl From<ArrayDataRef> 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, boxed_fields }
- }
-}
-
-impl Array for StructArray {
- fn as_any(&self) -> &Any {
- self
- }
-
- fn data(&self) -> ArrayDataRef {
- self.data.clone()
- }
-
- fn data_ref(&self) -> &ArrayDataRef {
- &self.data
- }
-
- /// Returns the length (i.e., number of elements) of this array
- fn len(&self) -> usize {
- self.boxed_fields[0].len()
- }
-}
-
-impl From<Vec<(Field, ArrayRef)>> for StructArray {
- fn from(v: Vec<(Field, ArrayRef)>) -> Self {
- let (field_types, field_values): (Vec<_>, Vec<_>) = v.into_iter().unzip();
-
- // Check the length of the child arrays
- let length = field_values[0].len();
- for i in 1..field_values.len() {
- assert_eq!(
- length,
- field_values[i].len(),
- "all child arrays of a StructArray must have the same length"
- );
- }
-
- let data = ArrayData::builder(DataType::Struct(field_types))
- .child_data(field_values.into_iter().map(|a| a.data()).collect())
- .build();
- Self::from(data)
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- use std::sync::Arc;
- use std::thread;
-
- use crate::array_data::ArrayData;
- use crate::buffer::Buffer;
- use crate::datatypes::{DataType, Field};
- use crate::memory;
-
- #[test]
- fn test_primitive_array_from_vec() {
- let buf = Buffer::from(&[0, 1, 2, 3, 4].to_byte_slice());
- let buf2 = buf.clone();
- let arr = Int32Array::new(5, buf, 0, 0);
- let slice = unsafe { ::std::slice::from_raw_parts(arr.raw_values(), 5) };
- assert_eq!(buf2, arr.values());
- assert_eq!(&[0, 1, 2, 3, 4], slice);
- assert_eq!(5, arr.len());
- assert_eq!(0, arr.offset());
- assert_eq!(0, arr.null_count());
- for i in 0..5 {
- assert!(!arr.is_null(i));
- assert!(arr.is_valid(i));
- assert_eq!(i as i32, arr.value(i));
- }
- }
-
- #[test]
- fn test_primitive_array_from_vec_option() {
- // Test building a primitive array with null values
- let arr = Int32Array::from(vec![Some(0), None, Some(2), None, Some(4)]);
- assert_eq!(5, arr.len());
- assert_eq!(0, arr.offset());
- assert_eq!(2, arr.null_count());
- for i in 0..5 {
- if i % 2 == 0 {
- assert!(!arr.is_null(i));
- assert!(arr.is_valid(i));
- assert_eq!(i as i32, arr.value(i));
- } else {
- assert!(arr.is_null(i));
- assert!(!arr.is_valid(i));
- }
- }
- }
-
- #[test]
- fn test_primitive_array_builder() {
- // Test building an primitive array with ArrayData builder and offset
- let buf = Buffer::from(&[0, 1, 2, 3, 4].to_byte_slice());
- let buf2 = buf.clone();
- let data = ArrayData::builder(DataType::Int32)
- .len(5)
- .offset(2)
- .add_buffer(buf)
- .build();
- let arr = Int32Array::from(data);
- assert_eq!(buf2, arr.values());
- assert_eq!(5, arr.len());
- assert_eq!(0, arr.null_count());
- for i in 0..3 {
- assert_eq!((i + 2) as i32, arr.value(i));
- }
- }
-
- #[test]
- #[should_panic(
- expected = "PrimitiveArray data should contain a single buffer only (values buffer)"
- )]
- fn test_primitive_array_invalid_buffer_len() {
- let data = ArrayData::builder(DataType::Int32).len(5).build();
- Int32Array::from(data);
- }
-
- #[test]
- fn test_boolean_array_new() {
- // 00000010 01001000
- let buf = Buffer::from([72_u8, 2_u8]);
- let buf2 = buf.clone();
- let arr = BooleanArray::new(10, buf, 0, 0);
- assert_eq!(buf2, arr.values());
- assert_eq!(10, arr.len());
- assert_eq!(0, arr.offset());
- assert_eq!(0, arr.null_count());
- for i in 0..10 {
- assert!(!arr.is_null(i));
- assert!(arr.is_valid(i));
- assert_eq!(i == 3 || i == 6 || i == 9, arr.value(i), "failed at {}", i)
- }
- }
-
- #[test]
- fn test_boolean_array_from_vec() {
- let buf = Buffer::from([10_u8]);
- let arr = BooleanArray::from(vec![false, true, false, true]);
- assert_eq!(buf, arr.values());
- assert_eq!(4, arr.len());
- assert_eq!(0, arr.offset());
- assert_eq!(0, arr.null_count());
- for i in 0..4 {
- assert!(!arr.is_null(i));
- assert!(arr.is_valid(i));
- assert_eq!(i == 1 || i == 3, arr.value(i), "failed at {}", i)
- }
- }
-
- #[test]
- fn test_boolean_array_from_vec_option() {
- let buf = Buffer::from([10_u8]);
- let arr = BooleanArray::from(vec![Some(false), Some(true), None, Some(true)]);
- assert_eq!(buf, arr.values());
- assert_eq!(4, arr.len());
- assert_eq!(0, arr.offset());
- assert_eq!(1, arr.null_count());
- for i in 0..4 {
- if i == 2 {
- assert!(arr.is_null(i));
- assert!(!arr.is_valid(i));
- } else {
- assert!(!arr.is_null(i));
- assert!(arr.is_valid(i));
- assert_eq!(i == 1 || i == 3, arr.value(i), "failed at {}", i)
- }
- }
- }
-
- #[test]
- fn test_boolean_array_builder() {
- // Test building a boolean array with ArrayData builder and offset
- // 000011011
- let buf = Buffer::from([27_u8]);
- let buf2 = buf.clone();
- let data = ArrayData::builder(DataType::Boolean)
- .len(5)
- .offset(2)
- .add_buffer(buf)
- .build();
- let arr = BooleanArray::from(data);
- assert_eq!(buf2, arr.values());
- assert_eq!(5, arr.len());
- assert_eq!(2, arr.offset());
- assert_eq!(0, arr.null_count());
- for i in 0..3 {
- assert_eq!(i != 0, arr.value(i), "failed at {}", i);
- }
- }
-
- #[test]
- #[should_panic(
- expected = "PrimitiveArray data should contain a single buffer only (values buffer)"
- )]
- fn test_boolean_array_invalid_buffer_len() {
- let data = ArrayData::builder(DataType::Boolean).len(5).build();
- BooleanArray::from(data);
- }
-
- #[test]
- fn test_list_array() {
- // Construct a value array
- let value_data = ArrayData::builder(DataType::Int32)
- .len(8)
- .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_offsets = Buffer::from(&[0, 3, 6, 8].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.clone())
- .len(3)
- .add_buffer(value_offsets.clone())
- .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!(3, list_array.len());
- assert_eq!(0, list_array.null_count());
- assert_eq!(6, list_array.value_offset(2));
- assert_eq!(2, list_array.value_length(2));
- for i in 0..3 {
- assert!(list_array.is_valid(i));
- assert!(!list_array.is_null(i));
- }
-
- // 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!(3, list_array.len());
- assert_eq!(0, list_array.null_count());
- assert_eq!(6, list_array.value_offset(1));
- assert_eq!(2, list_array.value_length(1));
- }
-
- #[test]
- #[should_panic(expected = "ListArray data should contain a single buffer only (value offsets)")]
- fn test_list_array_invalid_buffer_len() {
- let value_data = ArrayData::builder(DataType::Int32)
- .len(8)
- .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 = "ListArray should contain a single child array (values array)")]
- 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 = "offsets do not start at zero")]
- fn test_list_array_invalid_value_offset_start() {
- let value_data = ArrayData::builder(DataType::Int32)
- .len(8)
- .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 = "inconsistent offsets buffer and values array")]
- fn test_list_array_invalid_value_offset_end() {
- let value_data = ArrayData::builder(DataType::Int32)
- .len(8)
- .add_buffer(Buffer::from(&[0, 1, 2, 3, 4, 5, 6, 7].to_byte_slice()))
- .build();
-
- 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.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] = [
- 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];
-
- // Array data: ["hello", "", "parquet"]
- 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);
- 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));
- 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));
- for i in 0..3 {
- assert!(binary_array.is_valid(i));
- assert!(!binary_array.is_null(i));
- }
-
- // 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));
- assert_eq!(5, binary_array.value_offset(0));
- assert_eq!(0, binary_array.value_length(0));
- assert_eq!(5, binary_array.value_offset(1));
- assert_eq!(7, binary_array.value_length(1));
- }
-
- #[test]
- fn test_binary_array_from_list_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 values_data = ArrayData::builder(DataType::UInt8)
- .len(12)
- .add_buffer(Buffer::from(&values[..]))
- .build();
- let offsets: [i32; 4] = [0, 5, 5, 12];
-
- // Array data: ["hello", "", "parquet"]
- let array_data1 = ArrayData::builder(DataType::Utf8)
- .len(3)
- .add_buffer(Buffer::from(offsets.to_byte_slice()))
- .add_buffer(Buffer::from(&values[..]))
- .build();
- let binary_array1 = BinaryArray::from(array_data1);
-
- let array_data2 = ArrayData::builder(DataType::Utf8)
- .len(3)
- .add_buffer(Buffer::from(offsets.to_byte_slice()))
- .add_child_data(values_data)
- .build();
- let list_array = ListArray::from(array_data2);
- let binary_array2 = BinaryArray::from(list_array);
-
- assert_eq!(2, binary_array2.data().buffers().len());
- assert_eq!(0, binary_array2.data().child_data().len());
-
- assert_eq!(binary_array1.len(), binary_array2.len());
- assert_eq!(binary_array1.null_count(), binary_array2.null_count());
- for i in 0..binary_array1.len() {
- assert_eq!(binary_array1.get_value(i), binary_array2.get_value(i));
- assert_eq!(binary_array1.get_string(i), binary_array2.get_string(i));
- assert_eq!(binary_array1.value_offset(i), binary_array2.value_offset(i));
- assert_eq!(binary_array1.value_length(i), binary_array2.value_length(i));
- }
- }
-
- #[test]
- #[should_panic(
- expected = "BinaryArray can only be created from List<u8> arrays, mismatched data types."
- )]
- fn test_binary_array_from_incorrect_list_array_type() {
- let values: [u32; 12] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
- let values_data = ArrayData::builder(DataType::UInt32)
- .len(12)
- .add_buffer(Buffer::from(values[..].to_byte_slice()))
- .build();
- 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_child_data(values_data)
- .build();
- let list_array = ListArray::from(array_data);
- BinaryArray::from(list_array);
- }
-
- #[test]
- #[should_panic(
- expected = "BinaryArray can only be created from list array of u8 values (i.e. List<PrimitiveArray<u8>>)."
- )]
- fn test_binary_array_from_incorrect_list_array() {
- let values: [u32; 12] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
- let values_data = ArrayData::builder(DataType::UInt32)
- .len(12)
- .add_buffer(Buffer::from(values[..].to_byte_slice()))
- .add_child_data(ArrayData::builder(DataType::Boolean).build())
- .build();
- 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_child_data(values_data)
- .build();
- let list_array = ListArray::from(array_data);
- BinaryArray::from(list_array);
- }
-
- #[test]
- #[should_panic(expected = "BinaryArray out of bounds access")]
- 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_builder() {
- let boolean_data = ArrayData::builder(DataType::Boolean)
- .len(4)
- .add_buffer(Buffer::from([false, false, true, true].to_byte_slice()))
- .build();
- let int_data = ArrayData::builder(DataType::Int64)
- .len(4)
- .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));
- 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_struct_array_from() {
- let boolean_data = ArrayData::builder(DataType::Boolean)
- .len(4)
- .add_buffer(Buffer::from([12_u8]))
- .build();
- let int_data = ArrayData::builder(DataType::Int32)
- .len(4)
- .add_buffer(Buffer::from([42, 28, 19, 31].to_byte_slice()))
- .build();
- let struct_array = StructArray::from(vec![
- (
- Field::new("b", DataType::Boolean, false),
- Arc::new(BooleanArray::from(vec![false, false, true, true])) as Arc<Array>,
- ),
- (
- Field::new("c", DataType::Int32, false),
- Arc::new(Int32Array::from(vec![42, 28, 19, 31])),
- ),
- ]);
- assert_eq!(boolean_data, struct_array.column(0).data());
- assert_eq!(int_data, struct_array.column(1).data());
- }
-
- #[test]
- #[should_panic(expected = "all child arrays of a StructArray must have the same length")]
- fn test_invalid_struct_child_array_lengths() {
- StructArray::from(vec![
- (
- Field::new("b", DataType::Float32, false),
- Arc::new(Float32Array::from(vec![1.1])) as Arc<Array>,
- ),
- (
- Field::new("c", DataType::Float64, false),
- Arc::new(Float64Array::from(vec![2.2, 3.3])),
- ),
- ]);
- }
-
- #[test]
- #[should_panic(expected = "memory is not aligned")]
- 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();
- Int32Array::from(array_data);
- }
-
- #[test]
- #[should_panic(expected = "memory is not aligned")]
- 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 = "memory is not aligned")]
- 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_access_array_concurrently() {
- let a = Int32Array::from(vec![5, 6, 7, 8, 9]);
- 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
deleted file mode 100644
index 9ea01a402a..0000000000
--- a/rust/src/array_data.rs
+++ /dev/null
@@ -1,299 +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::sync::Arc;
-
-use crate::bitmap::Bitmap;
-use crate::buffer::Buffer;
-use crate::datatypes::DataType;
-use crate::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.,
-/// primitive, list, struct) are implemented in `Array`.
-#[derive(PartialEq, Debug)]
-pub struct ArrayData {
- /// The data type for this array data
- data_type: DataType,
-
- /// The number of elements in this array data
- len: usize,
-
- /// The number of null elements in this array data
- null_count: usize,
-
- /// The offset into this array data
- offset: usize,
-
- /// The buffers for this array data. Note that depending on the array types, this
- /// could hold different kinds of buffers (e.g., value buffer, value offset buffer)
- /// at different positions.
- buffers: Vec<Buffer>,
-
- /// The child(ren) of this array. Only non-empty for nested types, currently
- /// `ListArray` and `StructArray`.
- child_data: Vec<ArrayDataRef>,
-
- /// The null bitmap. A `None` value for this indicates all values are non-null in
- /// this array.
- null_bitmap: Option<Bitmap>,
-}
-
-pub type ArrayDataRef = Arc<ArrayData>;
-
-impl ArrayData {
- pub fn new(
- data_type: DataType,
- len: usize,
- null_count: Option<usize>,
- null_bit_buffer: Option<Buffer>,
- offset: usize,
- buffers: Vec<Buffer>,
- child_data: Vec<ArrayDataRef>,
- ) -> Self {
- let null_count = match null_count {
- None => {
- if let Some(ref buf) = null_bit_buffer {
- len.checked_sub(bit_util::count_set_bits_offset(buf.data(), offset))
- .unwrap()
- } else {
- 0
- }
- }
- Some(null_count) => null_count,
- };
- let null_bitmap = null_bit_buffer.map(Bitmap::from);
- Self {
- data_type,
- len,
- 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 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
- 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 a reference to the null bitmap of this array data
- pub fn null_bitmap(&self) -> &Option<Bitmap> {
- &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);
- }
- true
- }
-
- /// Returns the length (i.e., number of elements) of this array
- pub fn len(&self) -> usize {
- self.len
- }
-
- /// Returns the offset of this array
- pub fn offset(&self) -> usize {
- self.offset
- }
-
- /// Returns the total number of nulls in this array
- pub fn null_count(&self) -> usize {
- self.null_count
- }
-}
-
-/// Builder for `ArrayData` type
-pub struct ArrayDataBuilder {
- data_type: DataType,
- len: usize,
- null_count: Option<usize>,
- null_bit_buffer: Option<Buffer>,
- offset: usize,
- buffers: Vec<Buffer>,
- child_data: Vec<ArrayDataRef>,
-}
-
-impl ArrayDataBuilder {
- pub fn new(data_type: DataType) -> Self {
- Self {
- data_type,
- len: 0,
- null_count: None,
- null_bit_buffer: None,
- offset: 0,
- buffers: vec![],
- child_data: vec![],
- }
- }
-
- pub fn len(mut self, n: usize) -> Self {
- self.len = n;
- self
- }
-
- pub fn null_count(mut self, n: usize) -> Self {
- self.null_count = Some(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: usize) -> Self {
- self.offset = n;
- self
- }
-
- pub fn buffers(mut self, v: Vec<Buffer>) -> 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<ArrayDataRef>) -> 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.len,
- self.null_count,
- self.null_bit_buffer,
- self.offset,
- self.buffers,
- self.child_data,
- );
- Arc::new(data)
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- use std::sync::Arc;
-
- use crate::buffer::Buffer;
- use crate::util::bit_util;
-
- #[test]
- fn test_new() {
- let arr_data = ArrayData::new(DataType::Boolean, 10, Some(1), None, 2, vec![], vec![]);
- 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());
- 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,
- Some(0),
- None,
- 0,
- vec![],
- vec![],
- ));
- let b1 = Buffer::from(&v[..]);
- let arr_data = ArrayData::builder(DataType::Int32)
- .len(20)
- .null_count(10)
- .offset(5)
- .add_buffer(b1)
- .add_child_data(child_arr_data.clone())
- .build();
-
- 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());
- 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]);
- }
-
- #[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/array_ops.rs b/rust/src/array_ops.rs
deleted file mode 100644
index 517111ba76..0000000000
--- a/rust/src/array_ops.rs
+++ /dev/null
@@ -1,634 +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.
-
-//! Defines primitive computations on arrays
-
-use std::ops::{Add, Div, Mul, Sub};
-
-use num::Zero;
-
-use crate::array::{Array, BooleanArray, PrimitiveArray};
-use crate::builder::{ArrayBuilder, PrimitiveArrayBuilder};
-use crate::datatypes;
-use crate::datatypes::ArrowNumericType;
-use crate::error::{ArrowError, Result};
-
-/// Perform `left + right` operation on two arrays. If either left or right value is null then the result is also null.
-pub fn add<T>(left: &PrimitiveArray<T>, right: &PrimitiveArray<T>) -> Result<PrimitiveArray<T>>
-where
- T: datatypes::ArrowNumericType,
- T::Native: Add<Output = T::Native>
- + Sub<Output = T::Native>
- + Mul<Output = T::Native>
- + Div<Output = T::Native>
- + Zero,
-{
- math_op(left, right, |a, b| Ok(a + b))
-}
-
-/// Perform `left - right` operation on two arrays. If either left or right value is null then the result is also null.
-pub fn subtract<T>(left: &PrimitiveArray<T>, right: &PrimitiveArray<T>) -> Result<PrimitiveArray<T>>
-where
- T: datatypes::ArrowNumericType,
- T::Native: Add<Output = T::Native>
- + Sub<Output = T::Native>
- + Mul<Output = T::Native>
- + Div<Output = T::Native>
- + Zero,
-{
- math_op(left, right, |a, b| Ok(a - b))
-}
-
-/// Perform `left * right` operation on two arrays. If either left or right value is null then the result is also null.
-pub fn multiply<T>(left: &PrimitiveArray<T>, right: &PrimitiveArray<T>) -> Result<PrimitiveArray<T>>
-where
- T: datatypes::ArrowNumericType,
- T::Native: Add<Output = T::Native>
- + Sub<Output = T::Native>
- + Mul<Output = T::Native>
- + Div<Output = T::Native>
- + Zero,
-{
- math_op(left, right, |a, b| Ok(a * b))
-}
-
-/// Perform `left / right` operation on two arrays. If either left or right value is null then the result is also null.
-/// If any right hand value is zero then the result of this operation will be `Err(ArrowError::DivideByZero)`.
-pub fn divide<T>(left: &PrimitiveArray<T>, right: &PrimitiveArray<T>) -> Result<PrimitiveArray<T>>
-where
- T: datatypes::ArrowNumericType,
- T::Native: Add<Output = T::Native>
- + Sub<Output = T::Native>
- + Mul<Output = T::Native>
- + Div<Output = T::Native>
- + Zero,
-{
- math_op(left, right, |a, b| {
- if b.is_zero() {
- Err(ArrowError::DivideByZero)
- } else {
- Ok(a / b)
- }
- })
-}
-
-/// Helper function to perform math lambda function on values from two arrays. If either left or
-/// right value is null then the output value is also null, so `1 + null` is `null`.
-fn math_op<T, F>(
- left: &PrimitiveArray<T>,
- right: &PrimitiveArray<T>,
- op: F,
-) -> Result<PrimitiveArray<T>>
-where
- T: datatypes::ArrowNumericType,
- F: Fn(T::Native, T::Native) -> Result<T::Native>,
-{
- if left.len() != right.len() {
- return Err(ArrowError::ComputeError(
- "Cannot perform math operation on arrays of different length".to_string(),
- ));
- }
- let mut b = PrimitiveArrayBuilder::<T>::new(left.len());
- for i in 0..left.len() {
- let index = i;
- if left.is_null(i) || right.is_null(i) {
- b.push_null()?;
- } else {
- b.push(op(left.value(index), right.value(index))?)?;
- }
- }
- Ok(b.finish())
-}
-
-/// Returns the minimum value in the array, according to the natural order.
-pub fn min<T>(array: &PrimitiveArray<T>) -> Option<T::Native>
-where
- T: ArrowNumericType,
-{
- min_max_helper(array, |a, b| a < b)
-}
-
-/// Returns the maximum value in the array, according to the natural order.
-pub fn max<T>(array: &PrimitiveArray<T>) -> Option<T::Native>
-where
- T: ArrowNumericType,
-{
- min_max_helper(array, |a, b| a > b)
-}
-
-/// Helper function to perform min/max lambda function on values from a numeric array.
-fn min_max_helper<T, F>(array: &PrimitiveArray<T>, cmp: F) -> Option<T::Native>
-where
- T: ArrowNumericType,
- F: Fn(T::Native, T::Native) -> bool,
-{
- let mut n: Option<T::Native> = None;
- let data = array.data();
- for i in 0..data.len() {
- if data.is_null(i) {
- continue;
- }
- let m = array.value(i);
- match n {
- None => n = Some(m),
- Some(nn) => {
- if cmp(m, nn) {
- n = Some(m)
- }
- }
- }
- }
- n
-}
-
-/// Returns the sum of values in the array.
-///
-/// Returns `None` if the array is empty or only contains null values.
-pub fn sum<T>(array: &PrimitiveArray<T>) -> Option<T::Native>
-where
- T: ArrowNumericType,
- T::Native: Add<Output = T::Native>,
-{
- let mut n: T::Native = T::default_value();
- // iteratively track whether all values are null (or array is empty)
- let mut all_nulls = true;
- let data = array.data();
- for i in 0..data.len() {
- if data.is_null(i) {
- continue;
- }
- if all_nulls {
- all_nulls = false;
- }
- let m = array.value(i);
- n = n + m;
- }
- if all_nulls {
- None
- } else {
- Some(n)
- }
-}
-
-/// Perform `left == right` operation on two arrays.
-pub fn eq<T>(left: &PrimitiveArray<T>, right: &PrimitiveArray<T>) -> Result<BooleanArray>
-where
- T: ArrowNumericType,
-{
- bool_op(left, right, |a, b| a == b)
-}
-
-/// Perform `left != right` operation on two arrays.
-pub fn neq<T>(left: &PrimitiveArray<T>, right: &PrimitiveArray<T>) -> Result<BooleanArray>
-where
- T: ArrowNumericType,
-{
- bool_op(left, right, |a, b| a != b)
-}
-
-/// Perform `left < right` operation on two arrays. Null values are less than non-null values.
-pub fn lt<T>(left: &PrimitiveArray<T>, right: &PrimitiveArray<T>) -> Result<BooleanArray>
-where
- T: ArrowNumericType,
-{
- bool_op(left, right, |a, b| match (a, b) {
- (None, None) => false,
- (None, _) => true,
- (_, None) => false,
- (Some(aa), Some(bb)) => aa < bb,
- })
-}
-
-/// Perform `left <= right` operation on two arrays. Null values are less than non-null values.
-pub fn lt_eq<T>(left: &PrimitiveArray<T>, right: &PrimitiveArray<T>) -> Result<BooleanArray>
-where
- T: ArrowNumericType,
-{
- bool_op(left, right, |a, b| match (a, b) {
- (None, None) => true,
- (None, _) => true,
- (_, None) => false,
- (Some(aa), Some(bb)) => aa <= bb,
- })
-}
-
-/// Perform `left > right` operation on two arrays. Non-null values are greater than null values.
-pub fn gt<T>(left: &PrimitiveArray<T>, right: &PrimitiveArray<T>) -> Result<BooleanArray>
-where
- T: ArrowNumericType,
-{
- bool_op(left, right, |a, b| match (a, b) {
- (None, None) => false,
- (None, _) => false,
- (_, None) => true,
- (Some(aa), Some(bb)) => aa > bb,
- })
-}
-
-/// Perform `left >= right` operation on two arrays. Non-null values are greater than null values.
-pub fn gt_eq<T>(left: &PrimitiveArray<T>, right: &PrimitiveArray<T>) -> Result<BooleanArray>
-where
- T: ArrowNumericType,
-{
- bool_op(left, right, |a, b| match (a, b) {
- (None, None) => true,
- (None, _) => false,
- (_, None) => true,
- (Some(aa), Some(bb)) => aa >= bb,
- })
-}
-
-/// Helper function to perform boolean lambda function on values from two arrays.
-fn bool_op<T, F>(left: &PrimitiveArray<T>, right: &PrimitiveArray<T>, op: F) -> Result<BooleanArray>
-where
- T: ArrowNumericType,
- F: Fn(Option<T::Native>, Option<T::Native>) -> bool,
-{
- if left.len() != right.len() {
- return Err(ArrowError::ComputeError(
- "Cannot perform math operation on arrays of different length".to_string(),
- ));
- }
- let mut b = BooleanArray::builder(left.len());
- for i in 0..left.len() {
- let index = i;
- let l = if left.is_null(i) {
- None
- } else {
- Some(left.value(index))
- };
- let r = if right.is_null(i) {
- None
- } else {
- Some(right.value(index))
- };
- b.push(op(l, r))?;
- }
- Ok(b.finish())
-}
-
-/// Perform `AND` operation on two arrays. If either left or right value is null then the result is also null.
-pub fn and(left: &BooleanArray, right: &BooleanArray) -> Result<BooleanArray> {
- if left.len() != right.len() {
- return Err(ArrowError::ComputeError(
- "Cannot perform boolean operation on arrays of different length".to_string(),
- ));
- }
- let mut b = BooleanArray::builder(left.len());
- for i in 0..left.len() {
- if left.is_null(i) || right.is_null(i) {
- b.push_null()?;
- } else {
- b.push(left.value(i) && right.value(i))?;
- }
- }
- Ok(b.finish())
-}
-
-/// Perform `OR` operation on two arrays. If either left or right value is null then the result is also null.
-pub fn or(left: &BooleanArray, right: &BooleanArray) -> Result<BooleanArray> {
- if left.len() != right.len() {
- return Err(ArrowError::ComputeError(
- "Cannot perform boolean operation on arrays of different length".to_string(),
- ));
- }
- let mut b = BooleanArray::builder(left.len());
- for i in 0..left.len() {
- if left.is_null(i) || right.is_null(i) {
- b.push_null()?;
- } else {
- b.push(left.value(i) || right.value(i))?;
- }
- }
- Ok(b.finish())
-}
-
-/// Perform unary `NOT` operation on an arrays. If value is null then the result is also null.
-pub fn not(left: &BooleanArray) -> Result<BooleanArray> {
- let mut b = BooleanArray::builder(left.len());
- for i in 0..left.len() {
- if left.is_null(i) {
- b.push_null()?;
- } else {
- b.push(!left.value(i))?;
- }
- }
- Ok(b.finish())
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::array::{Float64Array, Int32Array};
-
- #[test]
- fn test_primitive_array_add() {
- let a = Int32Array::from(vec![5, 6, 7, 8, 9]);
- let b = Int32Array::from(vec![6, 7, 8, 9, 8]);
- let c = add(&a, &b).unwrap();
- assert_eq!(11, c.value(0));
- assert_eq!(13, c.value(1));
- assert_eq!(15, c.value(2));
- assert_eq!(17, c.value(3));
- assert_eq!(17, c.value(4));
- }
-
- #[test]
- fn test_primitive_array_add_mismatched_length() {
- let a = Int32Array::from(vec![5, 6, 7, 8, 9]);
- let b = Int32Array::from(vec![6, 7, 8]);
- let e = add(&a, &b)
- .err()
- .expect("should have failed due to different lengths");
- assert_eq!(
- "ComputeError(\"Cannot perform math operation on arrays of different length\")",
- format!("{:?}", e)
- );
- }
-
- #[test]
- fn test_primitive_array_subtract() {
- let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
- let b = Int32Array::from(vec![5, 4, 3, 2, 1]);
- let c = subtract(&a, &b).unwrap();
- assert_eq!(-4, c.value(0));
- assert_eq!(-2, c.value(1));
- assert_eq!(0, c.value(2));
- assert_eq!(2, c.value(3));
- assert_eq!(4, c.value(4));
- }
-
- #[test]
- fn test_primitive_array_multiply() {
- let a = Int32Array::from(vec![5, 6, 7, 8, 9]);
- let b = Int32Array::from(vec![6, 7, 8, 9, 8]);
- let c = multiply(&a, &b).unwrap();
- assert_eq!(30, c.value(0));
- assert_eq!(42, c.value(1));
- assert_eq!(56, c.value(2));
- assert_eq!(72, c.value(3));
- assert_eq!(72, c.value(4));
- }
-
- #[test]
- fn test_primitive_array_divide() {
- let a = Int32Array::from(vec![15, 15, 8, 1, 9]);
- let b = Int32Array::from(vec![5, 6, 8, 9, 1]);
- let c = divide(&a, &b).unwrap();
- assert_eq!(3, c.value(0));
- assert_eq!(2, c.value(1));
- assert_eq!(1, c.value(2));
- assert_eq!(0, c.value(3));
- assert_eq!(9, c.value(4));
- }
-
- #[test]
- fn test_primitive_array_divide_by_zero() {
- let a = Int32Array::from(vec![15]);
- let b = Int32Array::from(vec![0]);
- assert_eq!(
- ArrowError::DivideByZero,
- divide(&a, &b).err().expect("divide by zero should fail")
- );
- }
-
- #[test]
- fn test_primitive_array_divide_f64() {
- let a = Float64Array::from(vec![15.0, 15.0, 8.0]);
- let b = Float64Array::from(vec![5.0, 6.0, 8.0]);
- let c = divide(&a, &b).unwrap();
- assert_eq!(3.0, c.value(0));
- assert_eq!(2.5, c.value(1));
- assert_eq!(1.0, c.value(2));
- }
-
- #[test]
- fn test_primitive_array_add_with_nulls() {
- let a = Int32Array::from(vec![Some(5), None, Some(7), None]);
- let b = Int32Array::from(vec![None, None, Some(6), Some(7)]);
- let c = add(&a, &b).unwrap();
- assert_eq!(true, c.is_null(0));
- assert_eq!(true, c.is_null(1));
- assert_eq!(false, c.is_null(2));
- assert_eq!(true, c.is_null(3));
- assert_eq!(13, c.value(2));
- }
-
- #[test]
- fn test_primitive_array_sum() {
- let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
- assert_eq!(15, sum(&a).unwrap());
- }
-
- #[test]
- fn test_primitive_array_float_sum() {
- let a = Float64Array::from(vec![1.1, 2.2, 3.3, 4.4, 5.5]);
- assert_eq!(16.5, sum(&a).unwrap());
- }
-
- #[test]
- fn test_primitive_array_sum_with_nulls() {
- let a = Int32Array::from(vec![None, Some(2), Some(3), None, Some(5)]);
- assert_eq!(10, sum(&a).unwrap());
- }
-
- #[test]
- fn test_primitive_array_sum_all_nulls() {
- let a = Int32Array::from(vec![None, None, None]);
- assert_eq!(None, sum(&a));
- }
-
- #[test]
- fn test_primitive_array_eq() {
- let a = Int32Array::from(vec![8, 8, 8, 8, 8]);
- let b = Int32Array::from(vec![6, 7, 8, 9, 10]);
- let c = eq(&a, &b).unwrap();
- assert_eq!(false, c.value(0));
- assert_eq!(false, c.value(1));
- assert_eq!(true, c.value(2));
- assert_eq!(false, c.value(3));
- assert_eq!(false, c.value(4));
- }
-
- #[test]
- fn test_primitive_array_neq() {
- let a = Int32Array::from(vec![8, 8, 8, 8, 8]);
- let b = Int32Array::from(vec![6, 7, 8, 9, 10]);
- let c = neq(&a, &b).unwrap();
- assert_eq!(true, c.value(0));
- assert_eq!(true, c.value(1));
- assert_eq!(false, c.value(2));
- assert_eq!(true, c.value(3));
- assert_eq!(true, c.value(4));
- }
-
- #[test]
- fn test_primitive_array_lt() {
- let a = Int32Array::from(vec![8, 8, 8, 8, 8]);
- let b = Int32Array::from(vec![6, 7, 8, 9, 10]);
- let c = lt(&a, &b).unwrap();
- assert_eq!(false, c.value(0));
- assert_eq!(false, c.value(1));
- assert_eq!(false, c.value(2));
- assert_eq!(true, c.value(3));
- assert_eq!(true, c.value(4));
- }
-
- #[test]
- fn test_primitive_array_lt_nulls() {
- let a = Int32Array::from(vec![None, None, Some(1)]);
- let b = Int32Array::from(vec![None, Some(1), None]);
- let c = lt(&a, &b).unwrap();
- assert_eq!(false, c.value(0));
- assert_eq!(true, c.value(1));
- assert_eq!(false, c.value(2));
- }
-
- #[test]
- fn test_primitive_array_lt_eq() {
- let a = Int32Array::from(vec![8, 8, 8, 8, 8]);
- let b = Int32Array::from(vec![6, 7, 8, 9, 10]);
- let c = lt_eq(&a, &b).unwrap();
- assert_eq!(false, c.value(0));
- assert_eq!(false, c.value(1));
- assert_eq!(true, c.value(2));
- assert_eq!(true, c.value(3));
- assert_eq!(true, c.value(4));
- }
-
- #[test]
- fn test_primitive_array_lt_eq_nulls() {
- let a = Int32Array::from(vec![None, None, Some(1)]);
- let b = Int32Array::from(vec![None, Some(1), None]);
- let c = lt_eq(&a, &b).unwrap();
- assert_eq!(true, c.value(0));
- assert_eq!(true, c.value(1));
- assert_eq!(false, c.value(2));
- }
-
- #[test]
- fn test_primitive_array_gt() {
- let a = Int32Array::from(vec![8, 8, 8, 8, 8]);
- let b = Int32Array::from(vec![6, 7, 8, 9, 10]);
- let c = gt(&a, &b).unwrap();
- assert_eq!(true, c.value(0));
- assert_eq!(true, c.value(1));
- assert_eq!(false, c.value(2));
- assert_eq!(false, c.value(3));
- assert_eq!(false, c.value(4));
- }
-
- #[test]
- fn test_primitive_array_gt_nulls() {
- let a = Int32Array::from(vec![None, None, Some(1)]);
- let b = Int32Array::from(vec![None, Some(1), None]);
- let c = gt(&a, &b).unwrap();
- assert_eq!(false, c.value(0));
- assert_eq!(false, c.value(1));
- assert_eq!(true, c.value(2));
- }
-
- #[test]
- fn test_primitive_array_gt_eq() {
- let a = Int32Array::from(vec![8, 8, 8, 8, 8]);
- let b = Int32Array::from(vec![6, 7, 8, 9, 10]);
- let c = gt_eq(&a, &b).unwrap();
- assert_eq!(true, c.value(0));
- assert_eq!(true, c.value(1));
- assert_eq!(true, c.value(2));
- assert_eq!(false, c.value(3));
- assert_eq!(false, c.value(4));
- }
-
- #[test]
- fn test_primitive_array_gt_eq_nulls() {
- let a = Int32Array::from(vec![None, None, Some(1)]);
- let b = Int32Array::from(vec![None, Some(1), None]);
- let c = gt_eq(&a, &b).unwrap();
- assert_eq!(true, c.value(0));
- assert_eq!(false, c.value(1));
- assert_eq!(true, c.value(2));
- }
-
- #[test]
- fn test_buffer_array_min_max() {
- let a = Int32Array::from(vec![5, 6, 7, 8, 9]);
- assert_eq!(5, min(&a).unwrap());
- assert_eq!(9, max(&a).unwrap());
- }
-
- #[test]
- fn test_buffer_array_min_max_with_nulls() {
- let a = Int32Array::from(vec![Some(5), None, None, Some(8), Some(9)]);
- assert_eq!(5, min(&a).unwrap());
- assert_eq!(9, max(&a).unwrap());
- }
-
- #[test]
- fn test_bool_array_and() {
- let a = BooleanArray::from(vec![false, false, true, true]);
- let b = BooleanArray::from(vec![false, true, false, true]);
- let c = and(&a, &b).unwrap();
- assert_eq!(false, c.value(0));
- assert_eq!(false, c.value(1));
- assert_eq!(false, c.value(2));
- assert_eq!(true, c.value(3));
- }
-
- #[test]
- fn test_bool_array_or() {
- let a = BooleanArray::from(vec![false, false, true, true]);
- let b = BooleanArray::from(vec![false, true, false, true]);
- let c = or(&a, &b).unwrap();
- assert_eq!(false, c.value(0));
- assert_eq!(true, c.value(1));
- assert_eq!(true, c.value(2));
- assert_eq!(true, c.value(3));
- }
-
- #[test]
- fn test_bool_array_or_nulls() {
- let a = BooleanArray::from(vec![None, Some(false), None, Some(false)]);
- let b = BooleanArray::from(vec![None, None, Some(false), Some(false)]);
- let c = or(&a, &b).unwrap();
- assert_eq!(true, c.is_null(0));
- assert_eq!(true, c.is_null(1));
- assert_eq!(true, c.is_null(2));
- assert_eq!(false, c.is_null(3));
- }
-
- #[test]
- fn test_bool_array_not() {
- let a = BooleanArray::from(vec![false, false, true, true]);
- let c = not(&a).unwrap();
- assert_eq!(true, c.value(0));
- assert_eq!(true, c.value(1));
- assert_eq!(false, c.value(2));
- assert_eq!(false, c.value(3));
- }
-
- #[test]
- fn test_bool_array_and_nulls() {
- let a = BooleanArray::from(vec![None, Some(false), None, Some(false)]);
- let b = BooleanArray::from(vec![None, None, Some(false), Some(false)]);
- let c = and(&a, &b).unwrap();
- assert_eq!(true, c.is_null(0));
- assert_eq!(true, c.is_null(1));
- assert_eq!(true, c.is_null(2));
- assert_eq!(false, c.is_null(3));
- }
-}
diff --git a/rust/src/bitmap.rs b/rust/src/bitmap.rs
deleted file mode 100644
index 3d5a77f78a..0000000000
--- a/rust/src/bitmap.rs
+++ /dev/null
@@ -1,84 +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::buffer::Buffer;
-use crate::util::bit_util;
-
-#[derive(PartialEq, Debug)]
-pub struct Bitmap {
- bits: Buffer,
-}
-
-impl Bitmap {
- pub fn new(num_bits: usize) -> Self {
- let num_bytes = num_bits / 8 + if num_bits % 8 > 0 { 1 } else { 0 };
- let r = num_bytes % 64;
- let len = if r == 0 {
- num_bytes
- } else {
- num_bytes + 64 - r
- };
- let mut v = Vec::with_capacity(len);
- for _ in 0..len {
- v.push(255); // 1 is not null
- }
- Bitmap {
- bits: Buffer::from(&v[..]),
- }
- }
-
- pub fn len(&self) -> usize {
- self.bits.len()
- }
-
- pub fn is_set(&self, i: usize) -> bool {
- assert!(i < (self.bits.len() << 3));
- unsafe { bit_util::get_bit_raw(self.bits.raw_data(), i) }
- }
-}
-
-impl From<Buffer> for Bitmap {
- fn from(buf: Buffer) -> Self {
- Self { bits: buf }
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn test_bitmap_length() {
- assert_eq!(64, Bitmap::new(63 * 8).len());
- assert_eq!(64, Bitmap::new(64 * 8).len());
- assert_eq!(128, Bitmap::new(65 * 8).len());
- }
-
- #[test]
- 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
deleted file mode 100644
index b9c159f338..0000000000
--- a/rust/src/buffer.rs
+++ /dev/null
@@ -1,532 +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::cmp;
-use std::io::{Error as IoError, ErrorKind, Result as IoResult, Write};
-use std::mem;
-use std::sync::Arc;
-
-use crate::error::Result;
-use crate::memory;
-use crate::util::bit_util;
-
-/// 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: Arc<BufferData>,
-
- /// The offset into the buffer.
- offset: usize,
-}
-
-#[derive(Debug)]
-struct BufferData {
- /// The raw pointer into the buffer bytes
- ptr: *const u8,
-
- /// The length (num of bytes) of the buffer
- len: usize,
-}
-
-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) == 0 }
- }
-}
-
-/// Release the underlying memory when the current buffer goes out of scope
-impl Drop for BufferData {
- fn drop(&mut self) {
- memory::free_aligned(self.ptr);
- }
-}
-
-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), "memory not aligned");
- let buf_data = BufferData { ptr, len };
- Buffer {
- data: Arc::new(buf_data),
- offset: 0,
- }
- }
-
- /// Returns the number of bytes in the buffer
- pub fn len(&self) -> usize {
- self.data.len - self.offset
- }
-
- /// Returns whether the buffer is empty.
- pub fn is_empty(&self) -> bool {
- 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.raw_data(), self.len()) }
- }
-
- /// Returns a slice of this buffer, starting from `offset`.
- pub fn slice(&self, offset: usize) -> Self {
- assert!(
- self.offset + offset <= self.len(),
- "the offset of the new Buffer cannot exceed the existing length"
- );
- Self {
- data: self.data.clone(),
- offset: self.offset + offset,
- }
- }
-
- /// 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 {
- unsafe { self.data.ptr.offset(self.offset as isize) }
- }
-
- /// Returns an empty buffer.
- pub fn empty() -> Self {
- Self::from_raw_parts(::std::ptr::null(), 0)
- }
-}
-
-impl Clone for Buffer {
- fn clone(&self) -> Buffer {
- Buffer {
- data: self.data.clone(),
- offset: self.offset,
- }
- }
-}
-
-/// Creating a `Buffer` instance by copying the memory from a `AsRef<[u8]>` into a newly
-/// allocated memory region.
-impl<T: AsRef<[u8]>> From<T> for Buffer {
- fn from(p: T) -> Self {
- // allocate aligned memory buffer
- let slice = p.as_ref();
- let len = slice.len() * mem::size_of::<u8>();
- let buffer = memory::allocate_aligned(len).unwrap();
- unsafe {
- memory::memcpy(buffer, slice.as_ptr(), len);
- }
- Buffer::from_raw_parts(buffer, len)
- }
-}
-
-unsafe impl Sync for Buffer {}
-unsafe impl Send for Buffer {}
-
-/// Similar to `Buffer`, but is growable and can be mutated. A mutable buffer can be
-/// converted into a immutable buffer via the `freeze` method.
-#[derive(Debug)]
-pub struct MutableBuffer {
- data: *mut u8,
- len: usize,
- capacity: usize,
-}
-
-impl MutableBuffer {
- /// Allocate a new mutable buffer with initial capacity to be `capacity`.
- pub fn new(capacity: usize) -> Self {
- let new_capacity = bit_util::round_upto_multiple_of_64(capacity);
- let ptr = memory::allocate_aligned(new_capacity).unwrap();
- Self {
- data: ptr,
- len: 0,
- capacity: new_capacity,
- }
- }
-
- /// Set the bits in the range of `[0, end)` to 0 (if `val` is false), or 1 (if `val`
- /// is true). Also extend the length of this buffer to be `end`.
- ///
- /// This is useful when one wants to clear (or set) the bits and then manipulate
- /// the buffer directly (e.g., modifying the buffer by holding a mutable reference
- /// from `data_mut()`).
- pub fn with_bitset(mut self, end: usize, val: bool) -> Self {
- assert!(end <= self.capacity);
- let v = if val { 255 } else { 0 };
- unsafe {
- ::std::ptr::write_bytes(self.data, v, end);
- self.len = end;
- }
- self
- }
-
- /// Ensure that `count` bytes from `start` contain zero bits
- ///
- /// This is used to initialize the bits in a buffer, however, it has no impact on the `len`
- /// of the buffer and so can be used to initialize the memory region from `len` to `capacity`.
- pub fn set_null_bits(&mut self, start: usize, count: usize) {
- assert!(start + count <= self.capacity);
- unsafe {
- ::std::ptr::write_bytes(self.data.offset(start as isize), 0, count);
- }
- }
-
- /// Ensures that this buffer has at least `capacity` slots in this buffer. This will
- /// also ensure the new capacity will be a multiple of 64 bytes.
- ///
- /// Returns the new capacity for this buffer.
- pub fn reserve(&mut self, capacity: usize) -> Result<usize> {
- if capacity > self.capacity {
- let new_capacity = bit_util::round_upto_multiple_of_64(capacity);
- let new_capacity = cmp::max(new_capacity, self.capacity * 2);
- let new_data = memory::reallocate(self.capacity, new_capacity, self.data)?;
- self.data = new_data as *mut u8;
- self.capacity = new_capacity;
- }
- Ok(self.capacity)
- }
-
- /// Resizes the buffer so that the `len` will equal to the `new_len`.
- ///
- /// If `new_len` is greater than `len`, the buffer's length is simply adjusted to be
- /// the former, optionally extending the capacity. The data between `len` and
- /// `new_len` will remain unchanged.
- ///
- /// If `new_len` is less than `len`, the buffer will be truncated.
- pub fn resize(&mut self, new_len: usize) -> Result<()> {
- if new_len > self.len {
- self.reserve(new_len)?;
- } else {
- let new_capacity = bit_util::round_upto_multiple_of_64(new_len);
- if new_capacity < self.capacity {
- let new_data = memory::reallocate(self.capacity, new_capacity, self.data)?;
- self.data = new_data as *mut u8;
- self.capacity = new_capacity;
- }
- }
- self.len = new_len;
- Ok(())
- }
-
- /// Returns whether this buffer is empty or not.
- pub fn is_empty(&self) -> bool {
- self.len == 0
- }
-
- /// Returns the length (the number of bytes written) in this buffer.
- pub fn len(&self) -> usize {
- self.len
- }
-
- /// Returns the total capacity in this buffer.
- pub fn capacity(&self) -> usize {
- self.capacity
- }
-
- /// Clear all existing data from this buffer.
- pub fn clear(&mut self) {
- self.len = 0
- }
-
- /// Returns the data stored in this buffer as a slice.
- pub fn data(&self) -> &[u8] {
- unsafe { ::std::slice::from_raw_parts(self.raw_data(), self.len()) }
- }
-
- /// Returns the data stored in this buffer as a mutable slice.
- pub fn data_mut(&mut self) -> &mut [u8] {
- unsafe { ::std::slice::from_raw_parts_mut(self.raw_data() as *mut u8, self.len()) }
- }
-
- /// 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
- }
-
- /// Freezes this buffer and return an immutable version of it.
- pub fn freeze(self) -> Buffer {
- let buffer_data = BufferData {
- ptr: self.data,
- len: self.len,
- };
- ::std::mem::forget(self);
- Buffer {
- data: Arc::new(buffer_data),
- offset: 0,
- }
- }
-}
-
-impl Drop for MutableBuffer {
- fn drop(&mut self) {
- memory::free_aligned(self.data);
- }
-}
-
-impl PartialEq for MutableBuffer {
- fn eq(&self, other: &MutableBuffer) -> bool {
- if self.len != other.len {
- return false;
- }
- unsafe { memory::memcmp(self.data, other.data, self.len) == 0 }
- }
-}
-
-impl Write for MutableBuffer {
- fn write(&mut self, buf: &[u8]) -> IoResult<usize> {
- let remaining_capacity = self.capacity - self.len;
- if buf.len() > remaining_capacity {
- return Err(IoError::new(ErrorKind::Other, "Buffer not big enough"));
- }
- unsafe {
- memory::memcpy(self.data.offset(self.len as isize), buf.as_ptr(), buf.len());
- self.len += buf.len();
- Ok(buf.len())
- }
- }
-
- fn flush(&mut self) -> IoResult<()> {
- Ok(())
- }
-}
-
-unsafe impl Sync for MutableBuffer {}
-unsafe impl Send for MutableBuffer {}
-
-#[cfg(test)]
-mod tests {
- use crate::util::bit_util;
- use std::ptr::null_mut;
- use std::thread;
-
- use super::*;
-
- #[test]
- fn test_buffer_data_equality() {
- let buf1 = Buffer::from(&[0, 1, 2, 3, 4]);
- 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_ne!(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_ne!(buf1, buf2);
-
- // unequal because of different length
- buf2 = Buffer::from(&[0, 1, 2, 3]);
- assert_ne!(buf1, buf2);
- }
-
- #[test]
- 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());
- assert!(buf.raw_data().is_null());
-
- 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]
- fn test_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]
- fn test_copy() {
- let buf = Buffer::from(&[0, 1, 2, 3, 4]);
- let buf2 = buf.clone();
- assert_eq!(5, buf2.len());
- assert!(!buf2.raw_data().is_null());
- assert_eq!(&[0, 1, 2, 3, 4], buf2.data());
- }
-
- #[test]
- fn test_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 = "the offset of the new Buffer cannot exceed the existing length")]
- fn test_slice_offset_out_of_bound() {
- let buf = Buffer::from(&[2, 4, 6, 8, 10]);
- buf.slice(6);
- }
-
- #[test]
- fn test_with_bitset() {
- let mut_buf = MutableBuffer::new(64).with_bitset(64, false);
- let buf = mut_buf.freeze();
- assert_eq!(0, bit_util::count_set_bits(buf.data()));
-
- let mut_buf = MutableBuffer::new(64).with_bitset(64, true);
- let buf = mut_buf.freeze();
- assert_eq!(512, bit_util::count_set_bits(buf.data()));
- }
-
- #[test]
- fn test_set_null_bits() {
- let mut mut_buf = MutableBuffer::new(64).with_bitset(64, true);
- mut_buf.set_null_bits(0, 64);
- let buf = mut_buf.freeze();
- assert_eq!(0, bit_util::count_set_bits(buf.data()));
-
- let mut mut_buf = MutableBuffer::new(64).with_bitset(64, true);
- mut_buf.set_null_bits(32, 32);
- let buf = mut_buf.freeze();
- assert_eq!(256, bit_util::count_set_bits(buf.data()));
- }
-
- #[test]
- fn test_mutable_new() {
- let buf = MutableBuffer::new(63);
- assert_eq!(64, buf.capacity());
- assert_eq!(0, buf.len());
- assert!(buf.is_empty());
- }
-
- #[test]
- fn test_mutable_write() {
- let mut buf = MutableBuffer::new(100);
- buf.write("hello".as_bytes()).expect("Ok");
- assert_eq!(5, buf.len());
- assert_eq!("hello".as_bytes(), buf.data());
-
- buf.write(" world".as_bytes()).expect("Ok");
- assert_eq!(11, buf.len());
- assert_eq!("hello world".as_bytes(), buf.data());
-
- buf.clear();
- assert_eq!(0, buf.len());
- buf.write("hello arrow".as_bytes()).expect("Ok");
- assert_eq!(11, buf.len());
- assert_eq!("hello arrow".as_bytes(), buf.data());
- }
-
- #[test]
- #[should_panic(expected = "Buffer not big enough")]
- fn test_mutable_write_overflow() {
- let mut buf = MutableBuffer::new(1);
- assert_eq!(64, buf.capacity());
- for _ in 0..10 {
- buf.write(&[0, 0, 0, 0, 0, 0, 0, 0]).unwrap();
- }
- }
-
- #[test]
- fn test_mutable_reserve() {
- let mut buf = MutableBuffer::new(1);
- assert_eq!(64, buf.capacity());
-
- // Reserving a smaller capacity should have no effect.
- let mut new_cap = buf.reserve(10).expect("reserve should be OK");
- assert_eq!(64, new_cap);
- assert_eq!(64, buf.capacity());
-
- new_cap = buf.reserve(100).expect("reserve should be OK");
- assert_eq!(128, new_cap);
- assert_eq!(128, buf.capacity());
- }
-
- #[test]
- fn test_mutable_resize() {
- let mut buf = MutableBuffer::new(1);
- assert_eq!(64, buf.capacity());
- assert_eq!(0, buf.len());
-
- buf.resize(20).expect("resize should be OK");
- assert_eq!(64, buf.capacity());
- assert_eq!(20, buf.len());
-
- buf.resize(10).expect("resize should be OK");
- assert_eq!(64, buf.capacity());
- assert_eq!(10, buf.len());
-
- buf.resize(100).expect("resize should be OK");
- assert_eq!(128, buf.capacity());
- assert_eq!(100, buf.len());
-
- buf.resize(30).expect("resize should be OK");
- assert_eq!(64, buf.capacity());
- assert_eq!(30, buf.len());
-
- buf.resize(0).expect("resize should be OK");
- assert_eq!(0, buf.capacity());
- assert_eq!(0, buf.len());
- }
-
- #[test]
- fn test_mutable_freeze() {
- let mut buf = MutableBuffer::new(1);
- buf.write("aaaa bbbb cccc dddd".as_bytes())
- .expect("write should be OK");
- assert_eq!(19, buf.len());
- assert_eq!("aaaa bbbb cccc dddd".as_bytes(), buf.data());
-
- let immutable_buf = buf.freeze();
- assert_eq!(19, immutable_buf.len());
- assert_eq!("aaaa bbbb cccc dddd".as_bytes(), immutable_buf.data());
- }
-
- #[test]
- 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());
-
- let buffer_copy = thread::spawn(move || {
- // access buffer in another thread.
- buffer.clone()
- })
- .join();
-
- assert!(buffer_copy.is_ok());
- assert_eq!(buffer2, buffer_copy.ok().unwrap());
- }
-}
diff --git a/rust/src/builder.rs b/rust/src/builder.rs
deleted file mode 100644
index a4c8666233..0000000000
--- a/rust/src/builder.rs
+++ /dev/null
@@ -1,986 +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.
-
-//! Defines a `BufferBuilder` capable of creating a `Buffer` which can be used as an internal
-//! buffer in an `ArrayData` object.
-
-use std::any::Any;
-use std::io::Write;
-use std::marker::PhantomData;
-use std::mem;
-
-use crate::array::*;
-use crate::array_data::ArrayData;
-use crate::buffer::{Buffer, MutableBuffer};
-use crate::datatypes::*;
-use crate::error::{ArrowError, Result};
-use crate::util::bit_util;
-
-/// Buffer builder with zero-copy build method
-pub struct BufferBuilder<T: ArrowPrimitiveType> {
- buffer: MutableBuffer,
- len: usize,
- _marker: PhantomData<T>,
-}
-
-pub type BooleanBufferBuilder = BufferBuilder<BooleanType>;
-pub type Int8BufferBuilder = BufferBuilder<Int8Type>;
-pub type Int16BufferBuilder = BufferBuilder<Int16Type>;
-pub type Int32BufferBuilder = BufferBuilder<Int32Type>;
-pub type Int64BufferBuilder = BufferBuilder<Int64Type>;
-pub type UInt8BufferBuilder = BufferBuilder<UInt8Type>;
-pub type UInt16BufferBuilder = BufferBuilder<UInt16Type>;
-pub type UInt32BufferBuilder = BufferBuilder<UInt32Type>;
-pub type UInt64BufferBuilder = BufferBuilder<UInt64Type>;
-pub type Float32BufferBuilder = BufferBuilder<Float32Type>;
-pub type Float64BufferBuilder = BufferBuilder<Float64Type>;
-
-// Trait for buffer builder. This is used mainly to offer separate implementations for
-// numeric types and boolean types, while still be able to call methods on buffer builder
-// with generic primitive type.
-pub trait BufferBuilderTrait<T: ArrowPrimitiveType> {
- fn new(capacity: usize) -> Self;
- fn len(&self) -> usize;
- fn capacity(&self) -> usize;
- fn advance(&mut self, i: usize) -> Result<()>;
- fn reserve(&mut self, n: usize) -> Result<()>;
- fn push(&mut self, v: T::Native) -> Result<()>;
- fn push_slice(&mut self, slice: &[T::Native]) -> Result<()>;
- fn finish(&mut self) -> Buffer;
-}
-
-impl<T: ArrowPrimitiveType> BufferBuilderTrait<T> for BufferBuilder<T> {
- /// Creates a builder with a fixed initial capacity
- default fn new(capacity: usize) -> Self {
- let buffer = MutableBuffer::new(capacity * mem::size_of::<T::Native>());
- Self {
- buffer,
- len: 0,
- _marker: PhantomData,
- }
- }
-
- /// Returns the number of array elements (slots) in the builder
- fn len(&self) -> usize {
- self.len
- }
-
- /// Returns the current capacity of the builder (number of elements)
- fn capacity(&self) -> usize {
- let bit_capacity = self.buffer.capacity() * 8;
- (bit_capacity / T::get_bit_width())
- }
-
- // Advances the `len` of the underlying `Buffer` by `i` slots of type T
- default fn advance(&mut self, i: usize) -> Result<()> {
- let new_buffer_len = (self.len + i) * mem::size_of::<T::Native>();
- self.buffer.resize(new_buffer_len)?;
- self.len += i;
- Ok(())
- }
-
- /// Reserves memory for `n` elements of type `T`.
- default fn reserve(&mut self, n: usize) -> Result<()> {
- let new_capacity = self.len + n;
- let byte_capacity = mem::size_of::<T::Native>() * new_capacity;
- self.buffer.reserve(byte_capacity)?;
- Ok(())
- }
-
- /// Pushes a value into the builder, growing the internal buffer as needed.
- default fn push(&mut self, v: T::Native) -> Result<()> {
- self.reserve(1)?;
- self.write_bytes(v.to_byte_slice(), 1)
- }
-
- /// Pushes a slice of type `T`, growing the internal buffer as needed.
- default fn push_slice(&mut self, slice: &[T::Native]) -> Result<()> {
- let array_slots = slice.len();
- self.reserve(array_slots)?;
- self.write_bytes(slice.to_byte_slice(), array_slots)
- }
-
- /// Reset this builder and returns an immutable `Buffer`.
- default fn finish(&mut self) -> Buffer {
- let buf = ::std::mem::replace(&mut self.buffer, MutableBuffer::new(0));
- self.len = 0;
- buf.freeze()
- }
-}
-
-impl<T: ArrowPrimitiveType> BufferBuilder<T> {
- /// Writes a byte slice to the underlying buffer and updates the `len`, i.e. the number array
- /// elements in the builder. Also, converts the `io::Result` required by the `Write` trait
- /// to the Arrow `Result` type.
- fn write_bytes(&mut self, bytes: &[u8], len_added: usize) -> Result<()> {
- let write_result = self.buffer.write(bytes);
- // `io::Result` has many options one of which we use, so pattern matching is overkill here
- if write_result.is_err() {
- Err(ArrowError::MemoryError(
- "Could not write to Buffer, not big enough".to_string(),
- ))
- } else {
- self.len += len_added;
- Ok(())
- }
- }
-}
-
-impl BufferBuilderTrait<BooleanType> for BufferBuilder<BooleanType> {
- /// Creates a builder with a fixed initial capacity.
- fn new(capacity: usize) -> Self {
- let byte_capacity = bit_util::ceil(capacity, 8);
- let actual_capacity = bit_util::round_upto_multiple_of_64(byte_capacity);
- let mut buffer = MutableBuffer::new(actual_capacity);
- buffer.set_null_bits(0, actual_capacity);
- Self {
- buffer,
- len: 0,
- _marker: PhantomData,
- }
- }
-
- // Advances the `len` of the underlying `Buffer` by `i` slots of type T
- fn advance(&mut self, i: usize) -> Result<()> {
- let new_buffer_len = bit_util::ceil(self.len + i, 8);
- self.buffer.resize(new_buffer_len)?;
- self.len += i;
- Ok(())
- }
-
- /// Pushes a value into the builder, growing the internal buffer as needed.
- fn push(&mut self, v: bool) -> Result<()> {
- self.reserve(1)?;
- if v {
- // For performance the `len` of the buffer is not updated on each push but
- // is updated in the `freeze` method instead.
- unsafe {
- bit_util::set_bit_raw(self.buffer.raw_data() as *mut u8, self.len);
- }
- }
- self.len += 1;
- Ok(())
- }
-
- /// Pushes a slice of type `T`, growing the internal buffer as needed.
- fn push_slice(&mut self, slice: &[bool]) -> Result<()> {
- let array_slots = slice.len();
- for i in 0..array_slots {
- self.push(slice[i])?;
- }
- Ok(())
- }
-
- /// Reserves memory for `n` elements of type `T`.
- fn reserve(&mut self, n: usize) -> Result<()> {
- let new_capacity = self.len + n;
- if new_capacity > self.capacity() {
- let new_byte_capacity = bit_util::ceil(new_capacity, 8);
- let existing_capacity = self.buffer.capacity();
- let new_capacity = self.buffer.reserve(new_byte_capacity)?;
- self.buffer
- .set_null_bits(existing_capacity, new_capacity - existing_capacity);
- }
- Ok(())
- }
-
- /// Reset this builder and returns an immutable `Buffer`.
- fn finish(&mut self) -> Buffer {
- // `push` does not update the buffer's `len` so do it before `freeze` is called.
- let new_buffer_len = bit_util::ceil(self.len, 8);
- debug_assert!(new_buffer_len >= self.buffer.len());
- let mut buf = ::std::mem::replace(&mut self.buffer, MutableBuffer::new(0));
- self.len = 0;
- buf.resize(new_buffer_len).unwrap();
- buf.freeze()
- }
-}
-
-/// Trait for dealing with different array builders at runtime
-pub trait ArrayBuilder {
- /// The type of array that this builder creates
- type ArrayType: Array;
-
- /// Returns the number of array slots in the builder
- fn len(&self) -> usize;
-
- /// Builds the array
- fn finish(&mut self) -> Self::ArrayType;
-
- /// Returns the builder as an non-mutable `Any` reference.
- ///
- /// This is most useful when one wants to call non-mutable APIs on a specific builder
- /// type. In this case, one can first cast this into a `Any`, and then use
- /// `downcast_ref` to get a reference on the specific builder.
- fn as_any(&self) -> &Any;
-
- /// Returns the builder as an mutable `Any` reference.
- ///
- /// This is most useful when one wants to call mutable APIs on a specific builder
- /// type. In this case, one can first cast this into a `Any`, and then use
- /// `downcast_mut` to get a reference on the specific builder.
- fn as_any_mut(&mut self) -> &mut Any;
-}
-
-/// Array builder for fixed-width primitive types
-pub struct PrimitiveArrayBuilder<T: ArrowPrimitiveType> {
- values_builder: BufferBuilder<T>,
- bitmap_builder: BooleanBufferBuilder,
-}
-
-pub type BooleanBuilder = PrimitiveArrayBuilder<BooleanType>;
-pub type Int8Builder = PrimitiveArrayBuilder<Int8Type>;
-pub type Int16Builder = PrimitiveArrayBuilder<Int16Type>;
-pub type Int32Builder = PrimitiveArrayBuilder<Int32Type>;
-pub type Int64Builder = PrimitiveArrayBuilder<Int64Type>;
-pub type UInt8Builder = PrimitiveArrayBuilder<UInt8Type>;
-pub type UInt16Builder = PrimitiveArrayBuilder<UInt16Type>;
-pub type UInt32Builder = PrimitiveArrayBuilder<UInt32Type>;
-pub type UInt64Builder = PrimitiveArrayBuilder<UInt64Type>;
-pub type Float32Builder = PrimitiveArrayBuilder<Float32Type>;
-pub type Float64Builder = PrimitiveArrayBuilder<Float64Type>;
-
-impl<T: ArrowPrimitiveType> ArrayBuilder for PrimitiveArrayBuilder<T> {
- type ArrayType = PrimitiveArray<T>;
-
- /// Returns the builder as an non-mutable `Any` reference.
- fn as_any(&self) -> &Any {
- self
- }
-
- /// Returns the builder as an mutable `Any` reference.
- fn as_any_mut(&mut self) -> &mut Any {
- self
- }
-
- /// Returns the number of array slots in the builder
- fn len(&self) -> usize {
- self.values_builder.len
- }
-
- /// Builds the `PrimitiveArray` and reset this builder.
- fn finish(&mut self) -> PrimitiveArray<T> {
- let len = self.len();
- let null_bit_buffer = self.bitmap_builder.finish();
- let data = ArrayData::builder(T::get_data_type())
- .len(len)
- .null_count(len - bit_util::count_set_bits(null_bit_buffer.data()))
- .add_buffer(self.values_builder.finish())
- .null_bit_buffer(null_bit_buffer)
- .build();
- PrimitiveArray::<T>::from(data)
- }
-}
-
-impl<T: ArrowPrimitiveType> PrimitiveArrayBuilder<T> {
- /// Creates a new primitive array builder
- pub fn new(capacity: usize) -> Self {
- Self {
- values_builder: BufferBuilder::<T>::new(capacity),
- bitmap_builder: BooleanBufferBuilder::new(capacity),
- }
- }
-
- /// Returns the capacity of this builder measured in slots of type `T`
- pub fn capacity(&self) -> usize {
- self.values_builder.capacity()
- }
-
- /// Pushes a value of type `T` into the builder
- pub fn push(&mut self, v: T::Native) -> Result<()> {
- self.bitmap_builder.push(true)?;
- self.values_builder.push(v)?;
- Ok(())
- }
-
- /// Pushes a null slot into the builder
- pub fn push_null(&mut self) -> Result<()> {
- self.bitmap_builder.push(false)?;
- self.values_builder.advance(1)?;
- Ok(())
- }
-
- /// Pushes an `Option<T>` into the builder
- pub fn push_option(&mut self, v: Option<T::Native>) -> Result<()> {
- match v {
- None => self.push_null()?,
- Some(v) => self.push(v)?,
- };
- Ok(())
- }
-
- /// Pushes a slice of type `T` into the builder
- pub fn push_slice(&mut self, v: &[T::Native]) -> Result<()> {
- self.bitmap_builder.push_slice(&vec![true; v.len()][..])?;
- self.values_builder.push_slice(v)?;
- Ok(())
- }
-}
-
-/// Array builder for `ListArray`
-pub struct ListArrayBuilder<T: ArrayBuilder> {
- offsets_builder: Int32BufferBuilder,
- bitmap_builder: BooleanBufferBuilder,
- values_builder: T,
- len: usize,
-}
-
-impl<T: ArrayBuilder> ListArrayBuilder<T> {
- /// Creates a new `ListArrayBuilder` from a given values array builder
- pub fn new(values_builder: T) -> Self {
- let mut offsets_builder = Int32BufferBuilder::new(values_builder.len() + 1);
- offsets_builder.push(0).unwrap();
- Self {
- offsets_builder,
- bitmap_builder: BooleanBufferBuilder::new(values_builder.len()),
- values_builder,
- len: 0,
- }
- }
-}
-
-impl<T: ArrayBuilder> ArrayBuilder for ListArrayBuilder<T>
-where
- T: 'static,
-{
- type ArrayType = ListArray;
-
- /// Returns the builder as an non-mutable `Any` reference.
- fn as_any(&self) -> &Any {
- self
- }
-
- /// Returns the builder as an mutable `Any` reference.
- fn as_any_mut(&mut self) -> &mut Any {
- self
- }
-
- /// Returns the number of array slots in the builder
- fn len(&self) -> usize {
- self.len
- }
-
- /// Builds the `ListArray` and reset this builder.
- fn finish(&mut self) -> ListArray {
- let len = self.len();
- self.len = 0;
- let values_arr = self
- .values_builder
- .as_any_mut()
- .downcast_mut::<T>()
- .unwrap()
- .finish();
- let values_data = values_arr.data();
-
- let offset_buffer = self.offsets_builder.finish();
- let null_bit_buffer = self.bitmap_builder.finish();
- self.offsets_builder.push(0).unwrap();
- let data = ArrayData::builder(DataType::List(Box::new(values_data.data_type().clone())))
- .len(len)
- .null_count(len - bit_util::count_set_bits(null_bit_buffer.data()))
- .add_buffer(offset_buffer)
- .add_child_data(values_data)
- .null_bit_buffer(null_bit_buffer)
- .build();
-
- ListArray::from(data)
- }
-}
-
-impl<T: ArrayBuilder> ListArrayBuilder<T> {
- /// Returns the child array builder as a mutable reference.
- ///
- /// This mutable reference can be used to push values into the child array builder,
- /// but you must call `append` to delimit each distinct list value.
- pub fn values(&mut self) -> &mut T {
- &mut self.values_builder
- }
-
- /// Finish the current variable-length list array slot
- pub fn append(&mut self, is_valid: bool) -> Result<()> {
- self.offsets_builder
- .push(self.values_builder.len() as i32)?;
- self.bitmap_builder.push(is_valid)?;
- self.len += 1;
- Ok(())
- }
-}
-
-/// Array builder for `BinaryArray`
-pub struct BinaryArrayBuilder {
- builder: ListArrayBuilder<UInt8Builder>,
-}
-
-impl ArrayBuilder for BinaryArrayBuilder {
- type ArrayType = BinaryArray;
-
- /// Returns the builder as an non-mutable `Any` reference.
- fn as_any(&self) -> &Any {
- self
- }
-
- /// Returns the builder as an mutable `Any` reference.
- fn as_any_mut(&mut self) -> &mut Any {
- self
- }
-
- /// Returns the number of array slots in the builder
- fn len(&self) -> usize {
- self.builder.len()
- }
-
- /// Builds the `BinaryArray` and reset this builder.
- fn finish(&mut self) -> BinaryArray {
- BinaryArray::from(self.builder.finish())
- }
-}
-
-impl BinaryArrayBuilder {
- /// Creates a new `BinaryArrayBuilder`, `capacity` is the number of bytes in the values array
- pub fn new(capacity: usize) -> Self {
- let values_builder = UInt8Builder::new(capacity);
- Self {
- builder: ListArrayBuilder::new(values_builder),
- }
- }
-
- /// Pushes a single byte value into the builder's values array.
- ///
- /// Note, when pushing individual byte values you must call `append` to delimit each
- /// distinct list value.
- pub fn push(&mut self, value: u8) -> Result<()> {
- self.builder.values().push(value)?;
- Ok(())
- }
-
- /// Pushes a `&String` or `&str` into the builder.
- ///
- /// Automatically calls the `append` method to delimit the string pushed in as a distinct
- /// array element.
- pub fn push_string(&mut self, value: &str) -> Result<()> {
- self.builder.values().push_slice(value.as_bytes())?;
- self.builder.append(true)?;
- Ok(())
- }
-
- /// Finish the current variable-length list array slot.
- pub fn append(&mut self, is_valid: bool) -> Result<()> {
- self.builder.append(is_valid)
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- use crate::array::Array;
-
- #[test]
- fn test_builder_i32_empty() {
- let mut b = Int32BufferBuilder::new(5);
- assert_eq!(0, b.len());
- assert_eq!(16, b.capacity());
- let a = b.finish();
- assert_eq!(0, a.len());
- }
-
- #[test]
- fn test_builder_i32_alloc_zero_bytes() {
- let mut b = Int32BufferBuilder::new(0);
- b.push(123).unwrap();
- let a = b.finish();
- assert_eq!(4, a.len());
- }
-
- #[test]
- fn test_builder_i32() {
- let mut b = Int32BufferBuilder::new(5);
- for i in 0..5 {
- b.push(i).unwrap();
- }
- assert_eq!(16, b.capacity());
- let a = b.finish();
- assert_eq!(20, a.len());
- }
-
- #[test]
- fn test_builder_i32_grow_buffer() {
- let mut b = Int32BufferBuilder::new(2);
- assert_eq!(16, b.capacity());
- for i in 0..20 {
- b.push(i).unwrap();
- }
- assert_eq!(32, b.capacity());
- let a = b.finish();
- assert_eq!(80, a.len());
- }
-
- #[test]
- fn test_builder_finish() {
- let mut b = Int32BufferBuilder::new(5);
- assert_eq!(16, b.capacity());
- for i in 0..10 {
- b.push(i).unwrap();
- }
- let mut a = b.finish();
- assert_eq!(40, a.len());
- assert_eq!(0, b.len());
- assert_eq!(0, b.capacity());
-
- // Try build another buffer after cleaning up.
- for i in 0..20 {
- b.push(i).unwrap()
- }
- assert_eq!(32, b.capacity());
- a = b.finish();
- assert_eq!(80, a.len());
- }
-
- #[test]
- fn test_reserve() {
- let mut b = UInt8BufferBuilder::new(2);
- assert_eq!(64, b.capacity());
- b.reserve(64).unwrap();
- assert_eq!(64, b.capacity());
- b.reserve(65).unwrap();
- assert_eq!(128, b.capacity());
-
- let mut b = Int32BufferBuilder::new(2);
- assert_eq!(16, b.capacity());
- b.reserve(16).unwrap();
- assert_eq!(16, b.capacity());
- b.reserve(17).unwrap();
- assert_eq!(32, b.capacity());
- }
-
- #[test]
- fn test_push_slice() {
- let mut b = UInt8BufferBuilder::new(0);
- b.push_slice("Hello, ".as_bytes()).unwrap();
- b.push_slice("World!".as_bytes()).unwrap();
- let buffer = b.finish();
- assert_eq!(13, buffer.len());
-
- let mut b = Int32BufferBuilder::new(0);
- b.push_slice(&[32, 54]).unwrap();
- let buffer = b.finish();
- assert_eq!(8, buffer.len());
- }
-
- #[test]
- fn test_write_bytes() {
- let mut b = BooleanBufferBuilder::new(4);
- b.push(false).unwrap();
- b.push(true).unwrap();
- b.push(false).unwrap();
- b.push(true).unwrap();
- assert_eq!(4, b.len());
- assert_eq!(512, b.capacity());
- let buffer = b.finish();
- assert_eq!(1, buffer.len());
-
- let mut b = BooleanBufferBuilder::new(4);
- b.push_slice(&[false, true, false, true]).unwrap();
- assert_eq!(4, b.len());
- assert_eq!(512, b.capacity());
- let buffer = b.finish();
- assert_eq!(1, buffer.len());
- }
-
- #[test]
- fn test_write_bytes_i32() {
- let mut b = Int32BufferBuilder::new(4);
- let bytes = [8, 16, 32, 64].to_byte_slice();
- b.write_bytes(bytes, 4).unwrap();
- assert_eq!(4, b.len());
- assert_eq!(16, b.capacity());
- let buffer = b.finish();
- assert_eq!(16, buffer.len());
- }
-
- #[test]
- #[should_panic(expected = "Could not write to Buffer, not big enough")]
- fn test_write_too_many_bytes() {
- let mut b = Int32BufferBuilder::new(0);
- let bytes = [8, 16, 32, 64].to_byte_slice();
- b.write_bytes(bytes, 4).unwrap();
- }
-
- #[test]
- fn test_boolean_builder_increases_buffer_len() {
- // 00000010 01001000
- let buf = Buffer::from([72_u8, 2_u8]);
- let mut builder = BooleanBufferBuilder::new(8);
-
- for i in 0..10 {
- if i == 3 || i == 6 || i == 9 {
- builder.push(true).unwrap();
- } else {
- builder.push(false).unwrap();
- }
- }
- let buf2 = builder.finish();
-
- assert_eq!(buf.len(), buf2.len());
- assert_eq!(buf.data(), buf2.data());
- }
-
- #[test]
- fn test_primitive_array_builder_i32() {
- let mut builder = Int32Array::builder(5);
- for i in 0..5 {
- builder.push(i).unwrap();
- }
- let arr = builder.finish();
- assert_eq!(5, arr.len());
- assert_eq!(0, arr.offset());
- assert_eq!(0, arr.null_count());
- for i in 0..5 {
- assert!(!arr.is_null(i));
- assert!(arr.is_valid(i));
- assert_eq!(i as i32, arr.value(i));
- }
- }
-
- #[test]
- fn test_primitive_array_builder_bool() {
- // 00000010 01001000
- let buf = Buffer::from([72_u8, 2_u8]);
- let mut builder = BooleanArray::builder(10);
- for i in 0..10 {
- if i == 3 || i == 6 || i == 9 {
- builder.push(true).unwrap();
- } else {
- builder.push(false).unwrap();
- }
- }
-
- let arr = builder.finish();
- assert_eq!(buf, arr.values());
- assert_eq!(10, arr.len());
- assert_eq!(0, arr.offset());
- assert_eq!(0, arr.null_count());
- for i in 0..10 {
- assert!(!arr.is_null(i));
- assert!(arr.is_valid(i));
- assert_eq!(i == 3 || i == 6 || i == 9, arr.value(i), "failed at {}", i)
- }
- }
-
- #[test]
- fn test_primitive_array_builder_push_option() {
- let arr1 = Int32Array::from(vec![Some(0), None, Some(2), None, Some(4)]);
-
- let mut builder = Int32Array::builder(5);
- builder.push_option(Some(0)).unwrap();
- builder.push_option(None).unwrap();
- builder.push_option(Some(2)).unwrap();
- builder.push_option(None).unwrap();
- builder.push_option(Some(4)).unwrap();
- let arr2 = builder.finish();
-
- assert_eq!(arr1.len(), arr2.len());
- assert_eq!(arr1.offset(), arr2.offset());
- assert_eq!(arr1.null_count(), arr2.null_count());
- for i in 0..5 {
- assert_eq!(arr1.is_null(i), arr2.is_null(i));
- assert_eq!(arr1.is_valid(i), arr2.is_valid(i));
- if arr1.is_valid(i) {
- assert_eq!(arr1.value(i), arr2.value(i));
- }
- }
- }
-
- #[test]
- fn test_primitive_array_builder_push_null() {
- let arr1 = Int32Array::from(vec![Some(0), Some(2), None, None, Some(4)]);
-
- let mut builder = Int32Array::builder(5);
- builder.push(0).unwrap();
- builder.push(2).unwrap();
- builder.push_null().unwrap();
- builder.push_null().unwrap();
- builder.push(4).unwrap();
- let arr2 = builder.finish();
-
- assert_eq!(arr1.len(), arr2.len());
- assert_eq!(arr1.offset(), arr2.offset());
- assert_eq!(arr1.null_count(), arr2.null_count());
- for i in 0..5 {
- assert_eq!(arr1.is_null(i), arr2.is_null(i));
- assert_eq!(arr1.is_valid(i), arr2.is_valid(i));
- if arr1.is_valid(i) {
- assert_eq!(arr1.value(i), arr2.value(i));
- }
- }
- }
-
- #[test]
- fn test_primitive_array_builder_push_slice() {
- let arr1 = Int32Array::from(vec![Some(0), Some(2), None, None, Some(4)]);
-
- let mut builder = Int32Array::builder(5);
- builder.push_slice(&[0, 2]).unwrap();
- builder.push_null().unwrap();
- builder.push_null().unwrap();
- builder.push(4).unwrap();
- let arr2 = builder.finish();
-
- assert_eq!(arr1.len(), arr2.len());
- assert_eq!(arr1.offset(), arr2.offset());
- assert_eq!(arr1.null_count(), arr2.null_count());
- for i in 0..5 {
- assert_eq!(arr1.is_null(i), arr2.is_null(i));
- assert_eq!(arr1.is_valid(i), arr2.is_valid(i));
- if arr1.is_valid(i) {
- assert_eq!(arr1.value(i), arr2.value(i));
- }
- }
- }
-
- #[test]
- fn test_primitive_array_builder_finish() {
- let mut builder = Int32Builder::new(5);
- builder.push_slice(&[2, 4, 6, 8]).unwrap();
- let mut arr = builder.finish();
- assert_eq!(4, arr.len());
- assert_eq!(0, builder.len());
-
- builder.push_slice(&[1, 3, 5, 7, 9]).unwrap();
- arr = builder.finish();
- assert_eq!(5, arr.len());
- assert_eq!(0, builder.len());
- }
-
- #[test]
- fn test_list_array_builder() {
- let values_builder = Int32Builder::new(10);
- let mut builder = ListArrayBuilder::new(values_builder);
-
- // [[0, 1, 2], [3, 4, 5], [6, 7]]
- builder.values().push(0).unwrap();
- builder.values().push(1).unwrap();
- builder.values().push(2).unwrap();
- builder.append(true).unwrap();
- builder.values().push(3).unwrap();
- builder.values().push(4).unwrap();
- builder.values().push(5).unwrap();
- builder.append(true).unwrap();
- builder.values().push(6).unwrap();
- builder.values().push(7).unwrap();
- builder.append(true).unwrap();
- let list_array = builder.finish();
-
- let values = list_array.values().data().buffers()[0].clone();
- assert_eq!(
- Buffer::from(&[0, 1, 2, 3, 4, 5, 6, 7].to_byte_slice()),
- values
- );
- assert_eq!(
- Buffer::from(&[0, 3, 6, 8].to_byte_slice()),
- list_array.data().buffers()[0].clone()
- );
- assert_eq!(DataType::Int32, list_array.value_type());
- assert_eq!(3, list_array.len());
- assert_eq!(0, list_array.null_count());
- assert_eq!(6, list_array.value_offset(2));
- assert_eq!(2, list_array.value_length(2));
- for i in 0..3 {
- assert!(list_array.is_valid(i));
- assert!(!list_array.is_null(i));
- }
- }
-
- #[test]
- fn test_list_array_builder_nulls() {
- let values_builder = Int32Builder::new(10);
- let mut builder = ListArrayBuilder::new(values_builder);
-
- // [[0, 1, 2], null, [3, null, 5], [6, 7]]
- builder.values().push(0).unwrap();
- builder.values().push(1).unwrap();
- builder.values().push(2).unwrap();
- builder.append(true).unwrap();
- builder.append(false).unwrap();
- builder.values().push(3).unwrap();
- builder.values().push_null().unwrap();
- builder.values().push(5).unwrap();
- builder.append(true).unwrap();
- builder.values().push(6).unwrap();
- builder.values().push(7).unwrap();
- builder.append(true).unwrap();
- let list_array = builder.finish();
-
- assert_eq!(DataType::Int32, list_array.value_type());
- assert_eq!(4, list_array.len());
- assert_eq!(1, list_array.null_count());
- assert_eq!(3, list_array.value_offset(2));
- assert_eq!(3, list_array.value_length(2));
- }
-
- #[test]
- fn test_list_array_builder_finish() {
- let values_builder = Int32Array::builder(5);
- let mut builder = ListArrayBuilder::new(values_builder);
-
- builder.values().push_slice(&[1, 2, 3]).unwrap();
- builder.append(true).unwrap();
- builder.values().push_slice(&[4, 5, 6]).unwrap();
- builder.append(true).unwrap();
-
- let mut arr = builder.finish();
- assert_eq!(2, arr.len());
- assert_eq!(0, builder.len());
-
- builder.values().push_slice(&[7, 8, 9]).unwrap();
- builder.append(true).unwrap();
- arr = builder.finish();
- assert_eq!(1, arr.len());
- assert_eq!(0, builder.len());
- }
-
- #[test]
- fn test_list_list_array_builder() {
- let primitive_builder = Int32Builder::new(10);
- let values_builder = ListArrayBuilder::new(primitive_builder);
- let mut builder = ListArrayBuilder::new(values_builder);
-
- // [[[1, 2], [3, 4]], [[5, 6, 7], null, [8]], null, [[9, 10]]]
- builder.values().values().push(1).unwrap();
- builder.values().values().push(2).unwrap();
- builder.values().append(true).unwrap();
- builder.values().values().push(3).unwrap();
- builder.values().values().push(4).unwrap();
- builder.values().append(true).unwrap();
- builder.append(true).unwrap();
-
- builder.values().values().push(5).unwrap();
- builder.values().values().push(6).unwrap();
- builder.values().values().push(7).unwrap();
- builder.values().append(true).unwrap();
- builder.values().append(false).unwrap();
- builder.values().values().push(8).unwrap();
- builder.values().append(true).unwrap();
- builder.append(true).unwrap();
-
- builder.append(false).unwrap();
-
- builder.values().values().push(9).unwrap();
- builder.values().values().push(10).unwrap();
- builder.values().append(true).unwrap();
- builder.append(true).unwrap();
-
- let list_array = builder.finish();
-
- assert_eq!(4, list_array.len());
- assert_eq!(1, list_array.null_count());
- assert_eq!(
- Buffer::from(&[0, 2, 5, 5, 6].to_byte_slice()),
- list_array.data().buffers()[0].clone()
- );
-
- assert_eq!(6, list_array.values().data().len());
- assert_eq!(1, list_array.values().data().null_count());
- assert_eq!(
- Buffer::from(&[0, 2, 4, 7, 7, 8, 10].to_byte_slice()),
- list_array.values().data().buffers()[0].clone()
- );
-
- assert_eq!(10, list_array.values().data().child_data()[0].len());
- assert_eq!(0, list_array.values().data().child_data()[0].null_count());
- assert_eq!(
- Buffer::from(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].to_byte_slice()),
- list_array.values().data().child_data()[0].buffers()[0].clone()
- );
- }
-
- #[test]
- fn test_binary_array_builder() {
- let mut builder = BinaryArrayBuilder::new(20);
-
- builder.push(b'h').unwrap();
- builder.push(b'e').unwrap();
- builder.push(b'l').unwrap();
- builder.push(b'l').unwrap();
- builder.push(b'o').unwrap();
- builder.append(true).unwrap();
- builder.append(true).unwrap();
- builder.push(b'w').unwrap();
- builder.push(b'o').unwrap();
- builder.push(b'r').unwrap();
- builder.push(b'l').unwrap();
- builder.push(b'd').unwrap();
- builder.append(true).unwrap();
-
- let array = builder.finish();
-
- let binary_array = BinaryArray::from(array);
-
- 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));
- assert_eq!("", binary_array.get_string(1));
- assert_eq!([b'w', b'o', b'r', b'l', b'd'], binary_array.get_value(2));
- assert_eq!("world", binary_array.get_string(2));
- assert_eq!(5, binary_array.value_offset(2));
- assert_eq!(5, binary_array.value_length(2));
- }
-
- #[test]
- fn test_binary_array_builder_finish() {
- let mut builder = BinaryArrayBuilder::new(10);
-
- builder.push_string("hello").unwrap();
- builder.push_string("world").unwrap();
-
- let mut arr = builder.finish();
- assert_eq!(2, arr.len());
- assert_eq!(0, builder.len());
-
- builder.push_string("arrow").unwrap();
- arr = builder.finish();
- assert_eq!(1, arr.len());
- assert_eq!(0, builder.len());
- }
-
- #[test]
- fn test_binary_array_builder_push_string() {
- let mut builder = BinaryArrayBuilder::new(20);
-
- let var = "hello".to_owned();
- builder.push_string(&var).unwrap();
- builder.append(true).unwrap();
- builder.push_string("world").unwrap();
-
- let array = builder.finish();
-
- let binary_array = BinaryArray::from(array);
-
- 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));
- assert_eq!("", binary_array.get_string(1));
- assert_eq!([b'w', b'o', b'r', b'l', b'd'], binary_array.get_value(2));
- assert_eq!("world", binary_array.get_string(2));
- assert_eq!(5, binary_array.value_offset(2));
- assert_eq!(5, binary_array.value_length(2));
- }
-}
diff --git a/rust/src/csv/mod.rs b/rust/src/csv/mod.rs
deleted file mode 100644
index 9f2bd1db69..0000000000
--- a/rust/src/csv/mod.rs
+++ /dev/null
@@ -1,20 +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.
-
-pub mod reader;
-
-pub use self::reader::Reader;
diff --git a/rust/src/csv/reader.rs b/rust/src/csv/reader.rs
deleted file mode 100644
index b9c46fc321..0000000000
--- a/rust/src/csv/reader.rs
+++ /dev/null
@@ -1,281 +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.
-
-//! CSV Reader
-//!
-//! This CSV reader allows CSV files to be read into the Arrow memory model. Records are loaded in
-//! batches and are then converted from row-based data to columnar data.
-//!
-//! Example:
-//!
-//! ```
-//! use arrow::csv;
-//! use arrow::datatypes::{DataType, Field, Schema};
-//! use std::fs::File;
-//! use std::sync::Arc;
-//!
-//! let schema = Schema::new(vec![
-//! Field::new("city", DataType::Utf8, false),
-//! Field::new("lat", DataType::Float64, false),
-//! Field::new("lng", DataType::Float64, false),
-//! ]);
-//!
-//! let file = File::open("test/data/uk_cities.csv").unwrap();
-//!
-//! let mut csv = csv::Reader::new(file, Arc::new(schema), false, 1024, None);
-//! let batch = csv.next().unwrap().unwrap();
-//! ```
-
-use std::fs::File;
-use std::io::BufReader;
-use std::sync::Arc;
-
-use csv as csv_crate;
-
-use crate::array::{ArrayRef, BinaryArray};
-use crate::builder::*;
-use crate::datatypes::*;
-use crate::error::{ArrowError, Result};
-use crate::record_batch::RecordBatch;
-
-use self::csv_crate::{StringRecord, StringRecordsIntoIter};
-
-/// CSV file reader
-pub struct Reader {
- /// Explicit schema for the CSV file
- schema: Arc<Schema>,
- /// Optional projection for which columns to load (zero-based column indices)
- projection: Option<Vec<usize>>,
- /// File reader
- record_iter: StringRecordsIntoIter<BufReader<File>>,
- /// Batch size (number of records to load each time)
- batch_size: usize,
-}
-
-impl Reader {
- /// Create a new CsvReader
- pub fn new(
- file: File,
- schema: Arc<Schema>,
- has_headers: bool,
- batch_size: usize,
- projection: Option<Vec<usize>>,
- ) -> Self {
- let csv_reader = csv::ReaderBuilder::new()
- .has_headers(has_headers)
- .from_reader(BufReader::new(file));
-
- let record_iter = csv_reader.into_records();
- Reader {
- schema: schema.clone(),
- projection,
- record_iter,
- batch_size,
- }
- }
-
- /// Read the next batch of rows
- pub fn next(&mut self) -> Result<Option<RecordBatch>> {
- // read a batch of rows into memory
- let mut rows: Vec<StringRecord> = Vec::with_capacity(self.batch_size);
- for _ in 0..self.batch_size {
- match self.record_iter.next() {
- Some(Ok(r)) => {
- rows.push(r);
- }
- Some(Err(_)) => {
- return Err(ArrowError::ParseError("Error reading CSV file".to_string()));
- }
- None => break,
- }
- }
-
- // return early if no data was loaded
- if rows.is_empty() {
- return Ok(None);
- }
-
- let projection: Vec<usize> = match self.projection {
- Some(ref v) => v.clone(),
- None => self
- .schema
- .fields()
- .iter()
- .enumerate()
- .map(|(i, _)| i)
- .collect(),
- };
-
- let rows = &rows[..];
- let arrays: Result<Vec<ArrayRef>> = projection
- .iter()
- .map(|i| {
- let field = self.schema.field(*i);
- match field.data_type() {
- &DataType::Boolean => self.build_primitive_array::<BooleanType>(rows, i),
- &DataType::Int8 => self.build_primitive_array::<Int8Type>(rows, i),
- &DataType::Int16 => self.build_primitive_array::<Int16Type>(rows, i),
- &DataType::Int32 => self.build_primitive_array::<Int32Type>(rows, i),
- &DataType::Int64 => self.build_primitive_array::<Int64Type>(rows, i),
- &DataType::UInt8 => self.build_primitive_array::<UInt8Type>(rows, i),
- &DataType::UInt16 => self.build_primitive_array::<UInt16Type>(rows, i),
- &DataType::UInt32 => self.build_primitive_array::<UInt32Type>(rows, i),
- &DataType::UInt64 => self.build_primitive_array::<UInt64Type>(rows, i),
- &DataType::Float32 => self.build_primitive_array::<Float32Type>(rows, i),
- &DataType::Float64 => self.build_primitive_array::<Float64Type>(rows, i),
- &DataType::Utf8 => {
- let values_builder: UInt8Builder = UInt8Builder::new(rows.len());
- let mut list_builder = ListArrayBuilder::new(values_builder);
- for row_index in 0..rows.len() {
- match rows[row_index].get(*i) {
- Some(s) => {
- list_builder.values().push_slice(s.as_bytes()).unwrap();
- list_builder.append(true).unwrap();
- }
- _ => {
- list_builder.append(false).unwrap();
- }
- }
- }
- Ok(Arc::new(BinaryArray::from(list_builder.finish())) as ArrayRef)
- }
- other => Err(ArrowError::ParseError(format!(
- "Unsupported data type {:?}",
- other
- ))),
- }
- })
- .collect();
-
- match arrays {
- Ok(arr) => Ok(Some(RecordBatch::new(self.schema.clone(), arr))),
- Err(e) => Err(e),
- }
- }
-
- fn build_primitive_array<T: ArrowPrimitiveType>(
- &self,
- rows: &[StringRecord],
- col_idx: &usize,
- ) -> Result<ArrayRef> {
- let mut builder = PrimitiveArrayBuilder::<T>::new(rows.len());
- let is_boolean_type = *self.schema.field(*col_idx).data_type() == DataType::Boolean;
- for row_index in 0..rows.len() {
- match rows[row_index].get(*col_idx) {
- Some(s) if s.len() > 0 => {
- let t = if is_boolean_type {
- s.to_lowercase().parse::<T::Native>()
- } else {
- s.parse::<T::Native>()
- };
- match t {
- Ok(v) => builder.push(v)?,
- Err(_) => {
- // TODO: we should surface the underlying error here.
- return Err(ArrowError::ParseError(format!(
- "Error while parsing value {}",
- s
- )));
- }
- }
- }
- _ => builder.push_null()?,
- }
- }
- Ok(Arc::new(builder.finish()) as ArrayRef)
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- use crate::array::*;
- use crate::datatypes::Field;
-
- #[test]
- fn test_csv() {
- let schema = Schema::new(vec![
- Field::new("city", DataType::Utf8, false),
- Field::new("lat", DataType::Float64, false),
- Field::new("lng", DataType::Float64, false),
- ]);
-
- let file = File::open("test/data/uk_cities.csv").unwrap();
-
- let mut csv = Reader::new(file, Arc::new(schema), false, 1024, None);
- let batch = csv.next().unwrap().unwrap();
- assert_eq!(37, batch.num_rows());
- assert_eq!(3, batch.num_columns());
-
- // access data from a primitive array
- let lat = batch
- .column(1)
- .as_any()
- .downcast_ref::<Float64Array>()
- .unwrap();
- assert_eq!(57.653484, lat.value(0));
-
- // access data from a string array (ListArray<u8>)
- let city = batch
- .column(0)
- .as_any()
- .downcast_ref::<BinaryArray>()
- .unwrap();
-
- let city_name: String = String::from_utf8(city.get_value(13).to_vec()).unwrap();
-
- assert_eq!("Aberdeen, Aberdeen City, UK", city_name);
- }
-
- #[test]
- fn test_csv_with_projection() {
- let schema = Schema::new(vec![
- Field::new("city", DataType::Utf8, false),
- Field::new("lat", DataType::Float64, false),
- Field::new("lng", DataType::Float64, false),
- ]);
-
- let file = File::open("test/data/uk_cities.csv").unwrap();
-
- let mut csv = Reader::new(file, Arc::new(schema), false, 1024, Some(vec![0, 1]));
- let batch = csv.next().unwrap().unwrap();
- assert_eq!(37, batch.num_rows());
- assert_eq!(2, batch.num_columns());
- }
-
- #[test]
- fn test_nulls() {
- let schema = Schema::new(vec![
- Field::new("c_int", DataType::UInt64, false),
- Field::new("c_float", DataType::Float32, false),
- Field::new("c_string", DataType::Utf8, false),
- ]);
-
- let file = File::open("test/data/null_test.csv").unwrap();
-
- let mut csv = Reader::new(file, Arc::new(schema), true, 1024, None);
- let batch = csv.next().unwrap().unwrap();
-
- assert_eq!(false, batch.column(1).is_null(0));
- assert_eq!(false, batch.column(1).is_null(1));
- assert_eq!(true, batch.column(1).is_null(2));
- assert_eq!(false, batch.column(1).is_null(3));
- assert_eq!(false, batch.column(1).is_null(4));
- }
-
-}
diff --git a/rust/src/datatypes.rs b/rust/src/datatypes.rs
deleted file mode 100644
index 49e06eb096..0000000000
--- a/rust/src/datatypes.rs
+++ /dev/null
@@ -1,572 +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.
-
-//! Defines the data-types of Arrow arrays.
-//!
-//! For an overview of the terminology used within the arrow project and more general information
-//! regarding data-types and memory layouts see
-//! [here](https://arrow.apache.org/docs/memory_layout.html).
-
-use std::fmt;
-use std::mem::size_of;
-use std::slice::from_raw_parts;
-use std::str::FromStr;
-
-use serde_derive::{Deserialize, Serialize};
-use serde_json::{json, Value};
-
-use crate::error::{ArrowError, Result};
-
-/// The possible relative types that are supported.
-///
-/// The variants of this enum include primitive fixed size types as well as parametric or nested
-/// types.
-/// Currently the Rust implementation supports the following nested types:
-/// - `List<T>`
-/// - `Struct<T, U, V, ...>`
-///
-/// Nested types can themselves be nested within other arrays.
-/// For more information on these types please see
-/// [here](https://arrow.apache.org/docs/memory_layout.html).
-#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
-pub enum DataType {
- Boolean,
- Int8,
- Int16,
- Int32,
- Int64,
- UInt8,
- UInt16,
- UInt32,
- UInt64,
- Float16,
- Float32,
- Float64,
- Utf8,
- List(Box<DataType>),
- Struct(Vec<Field>),
-}
-
-/// Contains the meta-data for a single relative type.
-///
-/// The `Schema` object is an ordered collection of `Field` objects.
-#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
-pub struct Field {
- name: String,
- data_type: DataType,
- nullable: bool,
-}
-
-pub trait ArrowNativeType: Send + Sync + Copy + PartialOrd + FromStr + 'static {}
-
-/// Trait indicating a primitive fixed-width type (bool, ints and floats).
-pub trait ArrowPrimitiveType: 'static {
- /// Corresponding Rust native type for the primitive type.
- type Native: ArrowNativeType;
-
- /// Returns the corresponding Arrow data type of this primitive type.
- fn get_data_type() -> DataType;
-
- /// Returns the bit width of this primitive type.
- fn get_bit_width() -> usize;
-
- /// Returns a default value of this primitive type.
- ///
- /// This is useful for aggregate array ops like `sum()`, `mean()`.
- fn default_value() -> Self::Native;
-}
-
-macro_rules! make_type {
- ($name:ident, $native_ty:ty, $data_ty:path, $bit_width:expr, $default_val:expr) => {
- impl ArrowNativeType for $native_ty {}
-
- pub struct $name {}
-
- impl ArrowPrimitiveType for $name {
- type Native = $native_ty;
-
- fn get_data_type() -> DataType {
- $data_ty
- }
-
- fn get_bit_width() -> usize {
- $bit_width
- }
-
- fn default_value() -> Self::Native {
- $default_val
- }
- }
- };
-}
-
-make_type!(BooleanType, bool, DataType::Boolean, 1, false);
-make_type!(Int8Type, i8, DataType::Int8, 8, 0i8);
-make_type!(Int16Type, i16, DataType::Int16, 16, 0i16);
-make_type!(Int32Type, i32, DataType::Int32, 32, 0i32);
-make_type!(Int64Type, i64, DataType::Int64, 64, 0i64);
-make_type!(UInt8Type, u8, DataType::UInt8, 8, 0u8);
-make_type!(UInt16Type, u16, DataType::UInt16, 16, 0u16);
-make_type!(UInt32Type, u32, DataType::UInt32, 32, 0u32);
-make_type!(UInt64Type, u64, DataType::UInt64, 64, 0u64);
-make_type!(Float32Type, f32, DataType::Float32, 32, 0.0f32);
-make_type!(Float64Type, f64, DataType::Float64, 64, 0.0f64);
-
-/// A subtype of primitive type that represents numeric values.
-pub trait ArrowNumericType: ArrowPrimitiveType {}
-
-impl ArrowNumericType for Int8Type {}
-impl ArrowNumericType for Int16Type {}
-impl ArrowNumericType for Int32Type {}
-impl ArrowNumericType for Int64Type {}
-impl ArrowNumericType for UInt8Type {}
-impl ArrowNumericType for UInt16Type {}
-impl ArrowNumericType for UInt32Type {}
-impl ArrowNumericType for UInt64Type {}
-impl ArrowNumericType for Float32Type {}
-impl ArrowNumericType for Float64Type {}
-
-/// Allows conversion from supported Arrow types to a byte slice.
-pub trait ToByteSlice {
- /// Converts this instance into a byte slice
- fn to_byte_slice(&self) -> &[u8];
-}
-
-impl<T: ArrowNativeType> ToByteSlice for [T] {
- 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::<T>()) }
- }
-}
-
-impl<T: ArrowNativeType> ToByteSlice for T {
- fn to_byte_slice(&self) -> &[u8] {
- let raw_ptr = self as *const T as *const u8;
- unsafe { from_raw_parts(raw_ptr, size_of::<T>()) }
- }
-}
-
-impl DataType {
- /// Parse a data type from a JSON representation
- fn from(json: &Value) -> Result<DataType> {
- match *json {
- Value::Object(ref map) => match map.get("name") {
- Some(s) if s == "bool" => Ok(DataType::Boolean),
- Some(s) if s == "utf8" => Ok(DataType::Utf8),
- Some(s) if s == "floatingpoint" => match map.get("precision") {
- Some(p) if p == "HALF" => Ok(DataType::Float16),
- Some(p) if p == "SINGLE" => Ok(DataType::Float32),
- Some(p) if p == "DOUBLE" => Ok(DataType::Float64),
- _ => Err(ArrowError::ParseError(
- "floatingpoint precision missing or invalid".to_string(),
- )),
- },
- Some(s) if s == "int" => match map.get("isSigned") {
- Some(&Value::Bool(true)) => match map.get("bitWidth") {
- Some(&Value::Number(ref n)) => match n.as_u64() {
- Some(8) => Ok(DataType::Int8),
- Some(16) => Ok(DataType::Int16),
- Some(32) => Ok(DataType::Int32),
- Some(64) => Ok(DataType::Int32),
- _ => Err(ArrowError::ParseError(
- "int bitWidth missing or invalid".to_string(),
- )),
- },
- _ => Err(ArrowError::ParseError(
- "int bitWidth missing or invalid".to_string(),
- )),
- },
- Some(&Value::Bool(false)) => match map.get("bitWidth") {
- Some(&Value::Number(ref n)) => match n.as_u64() {
- Some(8) => Ok(DataType::UInt8),
- Some(16) => Ok(DataType::UInt16),
- Some(32) => Ok(DataType::UInt32),
- Some(64) => Ok(DataType::UInt64),
- _ => Err(ArrowError::ParseError(
- "int bitWidth missing or invalid".to_string(),
- )),
- },
- _ => Err(ArrowError::ParseError(
- "int bitWidth missing or invalid".to_string(),
- )),
- },
- _ => Err(ArrowError::ParseError(
- "int signed missing or invalid".to_string(),
- )),
- },
- Some(other) => Err(ArrowError::ParseError(format!(
- "invalid type name: {}",
- other
- ))),
- None => match map.get("fields") {
- Some(&Value::Array(ref fields_array)) => {
- let fields = fields_array
- .iter()
- .map(|f| Field::from(f))
- .collect::<Result<Vec<Field>>>();
- Ok(DataType::Struct(fields?))
- }
- _ => Err(ArrowError::ParseError("empty type".to_string())),
- },
- },
- _ => Err(ArrowError::ParseError(
- "invalid json value type".to_string(),
- )),
- }
- }
-
- /// Generate a JSON representation of the data type
- pub fn to_json(&self) -> Value {
- match *self {
- DataType::Boolean => json!({"name": "bool"}),
- DataType::Int8 => json!({"name": "int", "bitWidth": 8, "isSigned": true}),
- DataType::Int16 => json!({"name": "int", "bitWidth": 16, "isSigned": true}),
- DataType::Int32 => json!({"name": "int", "bitWidth": 32, "isSigned": true}),
- DataType::Int64 => json!({"name": "int", "bitWidth": 64, "isSigned": true}),
- DataType::UInt8 => json!({"name": "int", "bitWidth": 8, "isSigned": false}),
- DataType::UInt16 => json!({"name": "int", "bitWidth": 16, "isSigned": false}),
- DataType::UInt32 => json!({"name": "int", "bitWidth": 32, "isSigned": false}),
- DataType::UInt64 => json!({"name": "int", "bitWidth": 64, "isSigned": false}),
- DataType::Float16 => json!({"name": "floatingpoint", "precision": "HALF"}),
- DataType::Float32 => json!({"name": "floatingpoint", "precision": "SINGLE"}),
- DataType::Float64 => json!({"name": "floatingpoint", "precision": "DOUBLE"}),
- DataType::Utf8 => json!({"name": "utf8"}),
- DataType::Struct(ref fields) => {
- let field_json_array =
- Value::Array(fields.iter().map(|f| f.to_json()).collect::<Vec<Value>>());
- json!({ "fields": field_json_array })
- }
- DataType::List(ref t) => {
- let child_json = t.to_json();
- json!({ "name": "list", "children": child_json })
- }
- }
- }
-}
-
-impl Field {
- /// Creates a new field
- pub fn new(name: &str, data_type: DataType, nullable: bool) -> Self {
- Field {
- name: name.to_string(),
- data_type,
- nullable,
- }
- }
-
- /// Returns an immutable reference to the `Field`'s name
- pub fn name(&self) -> &String {
- &self.name
- }
-
- /// Returns an immutable reference to the `Field`'s data-type
- pub fn data_type(&self) -> &DataType {
- &self.data_type
- }
-
- /// Indicates whether this `Field` supports null values
- pub fn is_nullable(&self) -> bool {
- self.nullable
- }
-
- /// Parse a `Field` definition from a JSON representation
- pub fn from(json: &Value) -> Result<Self> {
- match *json {
- Value::Object(ref map) => {
- let name = match map.get("name") {
- Some(&Value::String(ref name)) => name.to_string(),
- _ => {
- return Err(ArrowError::ParseError(
- "Field missing 'name' attribute".to_string(),
- ));
- }
- };
- let nullable = match map.get("nullable") {
- Some(&Value::Bool(b)) => b,
- _ => {
- return Err(ArrowError::ParseError(
- "Field missing 'nullable' attribute".to_string(),
- ));
- }
- };
- let data_type = match map.get("type") {
- Some(t) => DataType::from(t)?,
- _ => {
- return Err(ArrowError::ParseError(
- "Field missing 'type' attribute".to_string(),
- ));
- }
- };
- Ok(Field {
- name,
- nullable,
- data_type,
- })
- }
- _ => Err(ArrowError::ParseError(
- "Invalid json value type for field".to_string(),
- )),
- }
- }
-
- /// Generate a JSON representation of the `Field`
- pub fn to_json(&self) -> Value {
- json!({
- "name": self.name,
- "nullable": self.nullable,
- "type": self.data_type.to_json(),
- })
- }
-
- /// Converts to a `String` representation of the the `Field`
- pub fn to_string(&self) -> String {
- format!("{}: {:?}", self.name, self.data_type)
- }
-}
-
-impl fmt::Display for Field {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(f, "{}", self.to_string())
- }
-}
-
-/// Describes the meta-data of an ordered sequence of relative types.
-///
-/// Note that this information is only part of the meta-data and not part of the physical memory
-/// layout.
-#[derive(Serialize, Deserialize, Debug, Clone)]
-pub struct Schema {
- fields: Vec<Field>,
-}
-
-impl Schema {
- /// Creates an empty `Schema`
- pub fn empty() -> Self {
- Self { fields: vec![] }
- }
-
- /// Creates a new `Schema` from a sequence of `Field` values
- ///
- /// # Example
- ///
- /// ```
- /// # extern crate arrow;
- /// # use arrow::datatypes::{Field, DataType, Schema};
- /// let field_a = Field::new("a", DataType::Int64, false);
- /// let field_b = Field::new("b", DataType::Boolean, false);
- ///
- /// let schema = Schema::new(vec![field_a, field_b]);
- /// ```
- pub fn new(fields: Vec<Field>) -> Self {
- Self { fields }
- }
-
- /// Returns an immutable reference of the vector of `Field` instances
- pub fn fields(&self) -> &Vec<Field> {
- &self.fields
- }
-
- /// Returns an immutable reference of a specific `Field` instance selected using an offset
- /// within the internal `fields` vector
- pub fn field(&self, i: usize) -> &Field {
- &self.fields[i]
- }
-
- /// Look up a column by name and return a immutable reference to the column along with
- /// it's index
- pub fn column_with_name(&self, name: &str) -> Option<(usize, &Field)> {
- self.fields
- .iter()
- .enumerate()
- .find(|&(_, c)| c.name == name)
- }
-}
-
-impl fmt::Display for Schema {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- f.write_str(
- &self
- .fields
- .iter()
- .map(|c| c.to_string())
- .collect::<Vec<String>>()
- .join(", "),
- )
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use serde_json;
-
- #[test]
- fn create_struct_type() {
- let _person = DataType::Struct(vec![
- Field::new("first_name", DataType::Utf8, false),
- Field::new("last_name", DataType::Utf8, false),
- Field::new(
- "address",
- DataType::Struct(vec![
- Field::new("street", DataType::Utf8, false),
- Field::new("zip", DataType::UInt16, false),
- ]),
- false,
- ),
- ]);
- }
-
- #[test]
- fn serde_struct_type() {
- let person = DataType::Struct(vec![
- Field::new("first_name", DataType::Utf8, false),
- Field::new("last_name", DataType::Utf8, false),
- Field::new(
- "address",
- DataType::Struct(vec![
- Field::new("street", DataType::Utf8, false),
- Field::new("zip", DataType::UInt16, false),
- ]),
- false,
- ),
- ]);
-
- let serialized = serde_json::to_string(&person).unwrap();
-
- // NOTE that this is testing the default (derived) serialization format, not the
- // JSON format specified in metadata.md
-
- assert_eq!(
- "{\"Struct\":[\
- {\"name\":\"first_name\",\"data_type\":\"Utf8\",\"nullable\":false},\
- {\"name\":\"last_name\",\"data_type\":\"Utf8\",\"nullable\":false},\
- {\"name\":\"address\",\"data_type\":{\"Struct\":\
- [{\"name\":\"street\",\"data_type\":\"Utf8\",\"nullable\":false},\
- {\"name\":\"zip\",\"data_type\":\"UInt16\",\"nullable\":false}\
- ]},\"nullable\":false}]}",
- serialized
- );
-
- let deserialized = serde_json::from_str(&serialized).unwrap();
-
- assert_eq!(person, deserialized);
- }
-
- #[test]
- fn struct_field_to_json() {
- let f = Field::new(
- "address",
- DataType::Struct(vec![
- Field::new("street", DataType::Utf8, false),
- Field::new("zip", DataType::UInt16, false),
- ]),
- false,
- );
- assert_eq!(
- "{\"name\":\"address\",\"nullable\":false,\"type\":{\"fields\":[\
- {\"name\":\"street\",\"nullable\":false,\"type\":{\"name\":\"utf8\"}},\
- {\"name\":\"zip\",\"nullable\":false,\"type\":{\"bitWidth\":16,\"isSigned\":false,\"name\":\"int\"}}]}}",
- f.to_json().to_string()
- );
- }
-
- #[test]
- fn primitive_field_to_json() {
- let f = Field::new("first_name", DataType::Utf8, false);
- assert_eq!(
- "{\"name\":\"first_name\",\"nullable\":false,\"type\":{\"name\":\"utf8\"}}",
- f.to_json().to_string()
- );
- }
- #[test]
- fn parse_struct_from_json() {
- let json = "{\"name\":\"address\",\"nullable\":false,\"type\":{\"fields\":[\
- {\"name\":\"street\",\"nullable\":false,\"type\":{\"name\":\"utf8\"}},\
- {\"name\":\"zip\",\"nullable\":false,\"type\":{\"bitWidth\":16,\"isSigned\":false,\"name\":\"int\"}}]}}";
- let value: Value = serde_json::from_str(json).unwrap();
- let dt = Field::from(&value).unwrap();
-
- let expected = Field::new(
- "address",
- DataType::Struct(vec![
- Field::new("street", DataType::Utf8, false),
- Field::new("zip", DataType::UInt16, false),
- ]),
- false,
- );
-
- assert_eq!(expected, dt);
- }
-
- #[test]
- fn parse_utf8_from_json() {
- let json = "{\"name\":\"utf8\"}";
- let value: Value = serde_json::from_str(json).unwrap();
- let dt = DataType::from(&value).unwrap();
- assert_eq!(DataType::Utf8, dt);
- }
-
- #[test]
- fn parse_int32_from_json() {
- let json = "{\"name\": \"int\", \"isSigned\": true, \"bitWidth\": 32}";
- let value: Value = serde_json::from_str(json).unwrap();
- let dt = DataType::from(&value).unwrap();
- assert_eq!(DataType::Int32, dt);
- }
-
- #[test]
- fn create_schema_string() {
- let _person = Schema::new(vec![
- Field::new("first_name", DataType::Utf8, false),
- Field::new("last_name", DataType::Utf8, false),
- Field::new(
- "address",
- DataType::Struct(vec![
- Field::new("street", DataType::Utf8, false),
- Field::new("zip", DataType::UInt16, false),
- ]),
- false,
- ),
- ]);
- assert_eq!(_person.to_string(), "first_name: Utf8, last_name: Utf8, address: Struct([Field { name: \"street\", data_type: Utf8, nullable: false }, Field { name: \"zip\", data_type: UInt16, nullable: false }])")
- }
-
- #[test]
- fn schema_field_accessors() {
- let _person = Schema::new(vec![
- Field::new("first_name", DataType::Utf8, false),
- Field::new("last_name", DataType::Utf8, false),
- Field::new(
- "address",
- DataType::Struct(vec![
- Field::new("street", DataType::Utf8, false),
- Field::new("zip", DataType::UInt16, false),
- ]),
- false,
- ),
- ]);
-
- // test schema accessors
- assert_eq!(_person.fields().len(), 3);
-
- // test field accessors
- assert_eq!(_person.fields()[0].name(), "first_name");
- assert_eq!(_person.fields()[0].data_type(), &DataType::Utf8);
- assert_eq!(_person.fields()[0].is_nullable(), false);
- }
-
-}
diff --git a/rust/src/error.rs b/rust/src/error.rs
deleted file mode 100644
index 559b2d7205..0000000000
--- a/rust/src/error.rs
+++ /dev/null
@@ -1,26 +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.
-
-#[derive(Debug, Clone, PartialEq)]
-pub enum ArrowError {
- MemoryError(String),
- ParseError(String),
- ComputeError(String),
- DivideByZero,
-}
-
-pub type Result<T> = ::std::result::Result<T, ArrowError>;
diff --git a/rust/src/lib.rs b/rust/src/lib.rs
deleted file mode 100644
index 199159e369..0000000000
--- a/rust/src/lib.rs
+++ /dev/null
@@ -1,37 +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.
-
-#![feature(type_ascription)]
-#![feature(rustc_private)]
-#![feature(specialization)]
-#![feature(try_from)]
-#![allow(dead_code)]
-#![allow(non_camel_case_types)]
-
-pub mod array;
-pub mod array_data;
-pub mod array_ops;
-pub mod bitmap;
-pub mod buffer;
-pub mod builder;
-pub mod csv;
-pub mod datatypes;
-pub mod error;
-pub mod memory;
-pub mod record_batch;
-pub mod tensor;
-pub mod util;
diff --git a/rust/src/memory.rs b/rust/src/memory.rs
deleted file mode 100644
index 763cb48f50..0000000000
--- a/rust/src/memory.rs
+++ /dev/null
@@ -1,128 +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 libc;
-use std::cmp;
-use std::mem;
-
-use crate::error::{ArrowError, Result};
-
-const ALIGNMENT: usize = 64;
-
-#[cfg(windows)]
-#[link(name = "msvcrt")]
-extern "C" {
- fn _aligned_malloc(size: libc::size_t, alignment: libc::size_t) -> libc::size_t;
- fn _aligned_free(prt: *const u8);
-}
-
-#[cfg(windows)]
-pub fn allocate_aligned(size: usize) -> Result<*mut u8> {
- 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::<libc::size_t, *mut u8>(page) }),
- }
-}
-
-#[cfg(not(windows))]
-pub fn allocate_aligned(size: usize) -> Result<*mut u8> {
- unsafe {
- let mut page: *mut libc::c_void = mem::uninitialized();
- let result = libc::posix_memalign(&mut page, ALIGNMENT, size);
- match result {
- 0 => Ok(mem::transmute::<*mut libc::c_void, *mut u8>(page)),
- _ => Err(ArrowError::MemoryError(
- "Failed to allocate memory".to_string(),
- )),
- }
- }
-}
-
-#[cfg(windows)]
-pub fn free_aligned(p: *const u8) {
- unsafe {
- _aligned_free(p);
- }
-}
-
-#[cfg(not(windows))]
-pub fn free_aligned(p: *const u8) {
- unsafe {
- libc::free(mem::transmute::<*const u8, *mut libc::c_void>(p));
- }
-}
-
-pub fn reallocate(old_size: usize, new_size: usize, pointer: *const u8) -> Result<*const u8> {
- unsafe {
- let old_src = mem::transmute::<*const u8, *mut libc::c_void>(pointer);
- let result = allocate_aligned(new_size)?;
- let dst = mem::transmute::<*const u8, *mut libc::c_void>(result);
- libc::memcpy(dst, old_src, cmp::min(old_size, new_size));
- free_aligned(pointer);
- Ok(result)
- }
-}
-
-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" {
- #[inline]
- 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<T>(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::*;
-
- #[test]
- fn test_allocate() {
- for _ in 0..10 {
- let p = allocate_aligned(1024).unwrap();
- // make sure this is 64-byte aligned
- assert_eq!(0, (p as usize) % 64);
- }
- }
-
- #[test]
- fn test_is_aligned() {
- // allocate memory aligned to 64-byte
- let mut ptr = allocate_aligned(10).unwrap();
- assert_eq!(true, is_aligned::<u8>(ptr, 1));
- assert_eq!(true, is_aligned::<u8>(ptr, 2));
- assert_eq!(true, is_aligned::<u8>(ptr, 4));
-
- // now make the memory aligned to 63-byte
- ptr = unsafe { ptr.offset(1) };
- assert_eq!(true, is_aligned::<u8>(ptr, 1));
- assert_eq!(false, is_aligned::<u8>(ptr, 2));
- assert_eq!(false, is_aligned::<u8>(ptr, 4));
- }
-}
diff --git a/rust/src/mod.rs b/rust/src/mod.rs
deleted file mode 100644
index b9fa43ab81..0000000000
--- a/rust/src/mod.rs
+++ /dev/null
@@ -1,28 +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.
-
-pub mod array;
-pub mod array_data;
-pub mod bitmap;
-pub mod buffer;
-pub mod builder;
-pub mod csv;
-pub mod datatypes;
-pub mod error;
-pub mod memory;
-pub mod record_batch;
-pub mod tensor;
diff --git a/rust/src/record_batch.rs b/rust/src/record_batch.rs
deleted file mode 100644
index e6a8e79500..0000000000
--- a/rust/src/record_batch.rs
+++ /dev/null
@@ -1,107 +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::sync::Arc;
-
-use crate::array::*;
-use crate::datatypes::*;
-
-/// A batch of column-oriented data
-pub struct RecordBatch {
- schema: Arc<Schema>,
- columns: Vec<Arc<Array>>,
-}
-
-impl RecordBatch {
- pub fn new(schema: Arc<Schema>, columns: Vec<ArrayRef>) -> Self {
- // assert that there are some columns
- assert!(
- columns.len() > 0,
- "at least one column must be defined to create a record batch"
- );
- // assert that all columns have the same row count
- let len = columns[0].data().len();
- for i in 1..columns.len() {
- assert_eq!(
- len,
- columns[i].len(),
- "all columns in a record batch must have the same length"
- );
- }
- RecordBatch { schema, columns }
- }
-
- pub fn schema(&self) -> &Arc<Schema> {
- &self.schema
- }
-
- pub fn num_columns(&self) -> usize {
- self.columns.len()
- }
-
- pub fn num_rows(&self) -> usize {
- self.columns[0].data().len()
- }
-
- pub fn column(&self, i: usize) -> &ArrayRef {
- &self.columns[i]
- }
-}
-
-unsafe impl Send for RecordBatch {}
-unsafe impl Sync for RecordBatch {}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- use crate::array_data::*;
- use crate::buffer::*;
-
- #[test]
- fn create_record_batch() {
- let schema = Schema::new(vec![
- Field::new("a", DataType::Int32, false),
- Field::new("b", DataType::Utf8, false),
- ]);
-
- let v = vec![1, 2, 3, 4, 5];
- let array_data = ArrayData::builder(DataType::Int32)
- .len(5)
- .add_buffer(Buffer::from(v.to_byte_slice()))
- .build();
- let a = Int32Array::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)
- .len(5)
- .add_buffer(Buffer::from(offset_data.to_byte_slice()))
- .add_buffer(Buffer::from(v.to_byte_slice()))
- .build();
- let b = BinaryArray::from(array_data);
-
- let record_batch = RecordBatch::new(Arc::new(schema), vec![Arc::new(a), Arc::new(b)]);
-
- assert_eq!(5, record_batch.num_rows());
- assert_eq!(2, record_batch.num_columns());
- assert_eq!(&DataType::Int32, record_batch.schema().field(0).data_type());
- assert_eq!(&DataType::Utf8, record_batch.schema().field(1).data_type());
- assert_eq!(5, record_batch.column(0).data().len());
- assert_eq!(5, record_batch.column(1).data().len());
- }
-}
diff --git a/rust/src/tensor.rs b/rust/src/tensor.rs
deleted file mode 100644
index 7272a2cf14..0000000000
--- a/rust/src/tensor.rs
+++ /dev/null
@@ -1,375 +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.
-
-//! Arrow Tensor Type
-use std::marker::PhantomData;
-use std::mem;
-
-use crate::buffer::Buffer;
-use crate::datatypes::*;
-
-/// Computes the strides required assuming a row major memory layout
-fn compute_row_major_strides<T: ArrowPrimitiveType>(shape: &Vec<usize>) -> Vec<usize> {
- let mut remaining_bytes = mem::size_of::<T::Native>();
- for i in shape {
- remaining_bytes = remaining_bytes
- .checked_mul(*i)
- .expect("Overflow occurred when computing row major strides.");
- }
-
- let mut strides = Vec::<usize>::new();
- for i in shape {
- remaining_bytes /= *i;
- strides.push(remaining_bytes);
- }
- strides
-}
-
-/// Computes the strides required assuming a column major memory layout
-fn compute_column_major_strides<T: ArrowPrimitiveType>(shape: &Vec<usize>) -> Vec<usize> {
- let mut remaining_bytes = mem::size_of::<T::Native>();
- let mut strides = Vec::<usize>::new();
- for i in shape {
- strides.push(remaining_bytes);
- remaining_bytes = remaining_bytes
- .checked_mul(*i)
- .expect("Overflow occurred when computing column major strides.");
- }
- strides
-}
-
-/// Tensor of primitive types
-pub struct Tensor<'a, T: ArrowPrimitiveType> {
- data_type: DataType,
- buffer: Buffer,
- shape: Option<Vec<usize>>,
- strides: Option<Vec<usize>>,
- names: Option<Vec<&'a str>>,
- _marker: PhantomData<T>,
-}
-
-pub type BooleanTensor<'a> = Tensor<'a, BooleanType>;
-pub type Int8Tensor<'a> = Tensor<'a, Int8Type>;
-pub type Int16Tensor<'a> = Tensor<'a, Int16Type>;
-pub type Int32Tensor<'a> = Tensor<'a, Int32Type>;
-pub type Int64Tensor<'a> = Tensor<'a, Int64Type>;
-pub type UInt8Tensor<'a> = Tensor<'a, UInt8Type>;
-pub type UInt16Tensor<'a> = Tensor<'a, UInt16Type>;
-pub type UInt32Tensor<'a> = Tensor<'a, UInt32Type>;
-pub type UInt64Tensor<'a> = Tensor<'a, UInt64Type>;
-pub type Float32Tensor<'a> = Tensor<'a, Float32Type>;
-pub type Float64Tensor<'a> = Tensor<'a, Float64Type>;
-
-impl<'a, T: ArrowPrimitiveType> Tensor<'a, T> {
- /// Creates a new `Tensor`
- pub fn new(
- buffer: Buffer,
- shape: Option<Vec<usize>>,
- strides: Option<Vec<usize>>,
- names: Option<Vec<&'a str>>,
- ) -> Self {
- match &shape {
- None => {
- assert_eq!(
- buffer.len(),
- mem::size_of::<T::Native>(),
- "underlying buffer should only contain a single tensor element"
- );
- assert_eq!(None, strides);
- assert_eq!(None, names);
- }
- Some(ref s) => {
- strides
- .iter()
- .map(|i| assert_eq!(s.len(), i.len(), "shape and stride dimensions differ"))
- .next();
- names
- .iter()
- .map(|i| {
- assert_eq!(
- s.len(),
- i.len(),
- "number of dimensions and number of dimension names differ"
- )
- })
- .next();
- }
- };
- Self {
- data_type: T::get_data_type(),
- buffer,
- shape,
- strides,
- names,
- _marker: PhantomData,
- }
- }
-
- /// Creates a new Tensor using row major memory layout
- pub fn new_row_major(
- buffer: Buffer,
- shape: Option<Vec<usize>>,
- names: Option<Vec<&'a str>>,
- ) -> Self {
- let strides = match &shape {
- None => None,
- Some(ref s) => Some(compute_row_major_strides::<T>(&s)),
- };
- Self::new(buffer, shape, strides, names)
- }
-
- /// Creates a new Tensor using column major memory layout
- pub fn new_column_major(
- buffer: Buffer,
- shape: Option<Vec<usize>>,
- names: Option<Vec<&'a str>>,
- ) -> Self {
- let strides = match &shape {
- None => None,
- Some(ref s) => Some(compute_column_major_strides::<T>(&s)),
- };
- Self::new(buffer, shape, strides, names)
- }
-
- /// The data type of the `Tensor`
- pub fn data_type(&self) -> &DataType {
- &self.data_type
- }
-
- /// The sizes of the dimensions
- pub fn shape(&self) -> Option<&Vec<usize>> {
- self.shape.as_ref()
- }
-
- /// Returns a reference to the underlying `Buffer`
- pub fn data(&self) -> &Buffer {
- &self.buffer
- }
-
- /// The number of bytes between elements in each dimension
- pub fn strides(&self) -> Option<&Vec<usize>> {
- self.strides.as_ref()
- }
-
- /// The names of the dimensions
- pub fn names(&self) -> Option<&Vec<&'a str>> {
- self.names.as_ref()
- }
-
- /// The number of dimensions
- pub fn ndim(&self) -> usize {
- match &self.shape {
- None => 0,
- Some(v) => v.len(),
- }
- }
-
- /// The name of dimension i
- pub fn dim_name(&self, i: usize) -> Option<&'a str> {
- match &self.names {
- None => None,
- Some(ref names) => Some(&names[i]),
- }
- }
-
- /// The total number of elements in the `Tensor`
- pub fn size(&self) -> usize {
- (self.buffer.len() / mem::size_of::<T::Native>())
- }
-
- /// Indicates if the data is laid out contiguously in memory
- pub fn is_contiguous(&self) -> bool {
- self.is_row_major() || self.is_column_major()
- }
-
- /// Indicates if the memory layout row major
- pub fn is_row_major(&self) -> bool {
- match self.shape {
- None => false,
- Some(ref s) => Some(compute_row_major_strides::<T>(s)) == self.strides,
- }
- }
-
- /// Indicates if the memory layout column major
- pub fn is_column_major(&self) -> bool {
- match self.shape {
- None => false,
- Some(ref s) => Some(compute_column_major_strides::<T>(s)) == self.strides,
- }
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- use crate::buffer::Buffer;
- use crate::builder::*;
-
- #[test]
- fn test_compute_row_major_strides() {
- assert_eq!(
- vec![48, 8],
- compute_row_major_strides::<Int64Type>(&vec![4_usize, 6])
- );
- assert_eq!(
- vec![24, 4],
- compute_row_major_strides::<Int32Type>(&vec![4_usize, 6])
- );
- assert_eq!(
- vec![6, 1],
- compute_row_major_strides::<Int8Type>(&vec![4_usize, 6])
- );
- }
-
- #[test]
- fn test_compute_column_major_strides() {
- assert_eq!(
- vec![8, 32],
- compute_column_major_strides::<Int64Type>(&vec![4_usize, 6])
- );
- assert_eq!(
- vec![4, 16],
- compute_column_major_strides::<Int32Type>(&vec![4_usize, 6])
- );
- assert_eq!(
- vec![1, 4],
- compute_column_major_strides::<Int8Type>(&vec![4_usize, 6])
- );
- }
-
- #[test]
- fn test_zero_dim() {
- let buf = Buffer::from(&[1]);
- let tensor = UInt8Tensor::new(buf, None, None, None);
- assert_eq!(1, tensor.size());
- assert_eq!(None, tensor.shape());
- assert_eq!(None, tensor.names());
- assert_eq!(0, tensor.ndim());
- assert_eq!(false, tensor.is_row_major());
- assert_eq!(false, tensor.is_column_major());
- assert_eq!(false, tensor.is_contiguous());
-
- let buf = Buffer::from(&[1, 2, 2, 2]);
- let tensor = Int32Tensor::new(buf, None, None, None);
- assert_eq!(1, tensor.size());
- assert_eq!(None, tensor.shape());
- assert_eq!(None, tensor.names());
- assert_eq!(0, tensor.ndim());
- assert_eq!(false, tensor.is_row_major());
- assert_eq!(false, tensor.is_column_major());
- assert_eq!(false, tensor.is_contiguous());
- }
-
- #[test]
- fn test_tensor() {
- let mut builder = Int32BufferBuilder::new(16);
- for i in 0..16 {
- builder.push(i).unwrap();
- }
- let buf = builder.finish();
- let tensor = Int32Tensor::new(buf, Some(vec![2, 8]), None, None);
- assert_eq!(16, tensor.size());
- assert_eq!(Some(vec![2_usize, 8]).as_ref(), tensor.shape());
- assert_eq!(None, tensor.strides());
- assert_eq!(2, tensor.ndim());
- assert_eq!(None, tensor.names());
- }
-
- #[test]
- fn test_new_row_major() {
- let mut builder = Int32BufferBuilder::new(16);
- for i in 0..16 {
- builder.push(i).unwrap();
- }
- let buf = builder.finish();
- let tensor = Int32Tensor::new_row_major(buf, Some(vec![2, 8]), None);
- assert_eq!(16, tensor.size());
- assert_eq!(Some(vec![2_usize, 8]).as_ref(), tensor.shape());
- assert_eq!(Some(vec![32_usize, 4]).as_ref(), tensor.strides());
- assert_eq!(None, tensor.names());
- assert_eq!(2, tensor.ndim());
- assert_eq!(true, tensor.is_row_major());
- assert_eq!(false, tensor.is_column_major());
- assert_eq!(true, tensor.is_contiguous());
- }
-
- #[test]
- fn test_new_column_major() {
- let mut builder = Int32BufferBuilder::new(16);
- for i in 0..16 {
- builder.push(i).unwrap();
- }
- let buf = builder.finish();
- let tensor = Int32Tensor::new_column_major(buf, Some(vec![2, 8]), None);
- assert_eq!(16, tensor.size());
- assert_eq!(Some(vec![2_usize, 8]).as_ref(), tensor.shape());
- assert_eq!(Some(vec![4_usize, 8]).as_ref(), tensor.strides());
- assert_eq!(None, tensor.names());
- assert_eq!(2, tensor.ndim());
- assert_eq!(false, tensor.is_row_major());
- assert_eq!(true, tensor.is_column_major());
- assert_eq!(true, tensor.is_contiguous());
- }
-
- #[test]
- fn test_with_names() {
- let mut builder = Int64BufferBuilder::new(8);
- for i in 0..8 {
- builder.push(i).unwrap();
- }
- let buf = builder.finish();
- let names = vec!["Dim 1", "Dim 2"];
- let tensor = Int64Tensor::new_column_major(buf, Some(vec![2, 4]), Some(names));
- assert_eq!(8, tensor.size());
- assert_eq!(Some(vec![2_usize, 4]).as_ref(), tensor.shape());
- assert_eq!(Some(vec![8_usize, 16]).as_ref(), tensor.strides());
- assert_eq!("Dim 1", tensor.dim_name(0).unwrap());
- assert_eq!("Dim 2", tensor.dim_name(1).unwrap());
- assert_eq!(2, tensor.ndim());
- assert_eq!(false, tensor.is_row_major());
- assert_eq!(true, tensor.is_column_major());
- assert_eq!(true, tensor.is_contiguous());
- }
-
- #[test]
- #[should_panic(expected = "shape and stride dimensions differ")]
- fn test_inconsistent_strides() {
- let mut builder = Int32BufferBuilder::new(16);
- for i in 0..16 {
- builder.push(i).unwrap();
- }
- let buf = builder.finish();
- Int32Tensor::new(buf, Some(vec![2, 8]), Some(vec![2, 8, 1]), None);
- }
-
- #[test]
- #[should_panic(expected = "number of dimensions and number of dimension names differ")]
- fn test_inconsistent_names() {
- let mut builder = Int32BufferBuilder::new(16);
- for i in 0..16 {
- builder.push(i).unwrap();
- }
- let buf = builder.finish();
- Int32Tensor::new(
- buf,
- Some(vec![2, 8]),
- Some(vec![4, 8]),
- Some(vec!["1", "2", "3"]),
- );
- }
-}
diff --git a/rust/src/util/bit_util.rs b/rust/src/util/bit_util.rs
deleted file mode 100644
index 3f7f4cb573..0000000000
--- a/rust/src/util/bit_util.rs
+++ /dev/null
@@ -1,269 +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.
-
-static BIT_MASK: [u8; 8] = [1, 2, 4, 8, 16, 32, 64, 128];
-
-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,
- 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
-#[inline]
-pub fn round_upto_multiple_of_64(num: usize) -> usize {
- 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: usize, factor: usize) -> usize {
- debug_assert!(factor > 0 && (factor & (factor - 1)) == 0);
- (num + (factor - 1)) & !(factor - 1)
-}
-
-/// Returns whether bit at position `i` in `data` is set or not
-#[inline]
-pub fn get_bit(data: &[u8], i: usize) -> bool {
- (data[i >> 3] & BIT_MASK[i & 7]) != 0
-}
-
-/// Returns whether bit at position `i` in `data` is set or not.
-///
-/// Note this doesn't do any bound checking, for performance reason. The caller is
-/// responsible to guarantee that `i` is within bounds.
-#[inline]
-pub unsafe fn get_bit_raw(data: *const u8, i: usize) -> bool {
- (*data.offset((i >> 3) as isize) & BIT_MASK[i & 7]) != 0
-}
-
-/// Sets bit at position `i` for `data`
-#[inline]
-pub fn set_bit(data: &mut [u8], i: usize) {
- data[i >> 3] |= BIT_MASK[i & 7]
-}
-
-/// Sets bit at position `i` for `data`
-///
-/// Note this doesn't do any bound checking, for performance reason. The caller is
-/// responsible to guarantee that `i` is within bounds.
-#[inline]
-pub unsafe fn set_bit_raw(data: *mut u8, i: usize) {
- *data.offset((i >> 3) as isize) |= BIT_MASK[i & 7]
-}
-
-/// Returns the number of 1-bits in `data`
-#[inline]
-pub fn count_set_bits(data: &[u8]) -> usize {
- let mut count: usize = 0;
- for u in data {
- count += POPCOUNT_TABLE[*u as usize] as usize;
- }
- count
-}
-
-/// Returns the number of 1-bits in `data`, starting from `offset`.
-#[inline]
-pub fn count_set_bits_offset(data: &[u8], offset: usize) -> usize {
- debug_assert!(offset <= (data.len() << 3));
-
- let start_byte_pos = offset >> 3;
- let start_bit_pos = offset & 7;
-
- 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) {
- result += 1;
- }
- }
- result
- }
-}
-
-/// Returns the ceil of `value`/`divisor`
-#[inline]
-pub fn ceil(value: usize, divisor: usize) -> usize {
- let mut result = value / divisor;
- if value % divisor != 0 {
- result += 1
- };
- result
-}
-
-#[cfg(test)]
-mod tests {
- use rand::{thread_rng, Rng};
- use std::collections::HashSet;
-
- 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!(192, round_upto_multiple_of_64(129));
- }
-
- #[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_get_bit_raw() {
- const NUM_BYTE: usize = 10;
- let mut buf = vec![0; NUM_BYTE];
- let mut expected = vec![];
- let mut rng = thread_rng();
- for i in 0..8 * NUM_BYTE {
- let b = rng.gen_bool(0.5);
- expected.push(b);
- if b {
- set_bit(&mut buf[..], i)
- }
- }
-
- let raw_ptr = buf.as_ptr();
- for (i, b) in expected.iter().enumerate() {
- unsafe {
- assert_eq!(*b, get_bit_raw(raw_ptr, i));
- }
- }
- }
-
- #[test]
- fn test_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_set_bit_raw() {
- const NUM_BYTE: usize = 10;
- let mut buf = vec![0; NUM_BYTE];
- let mut expected = vec![];
- let mut rng = thread_rng();
- for i in 0..8 * NUM_BYTE {
- let b = rng.gen_bool(0.5);
- expected.push(b);
- if b {
- unsafe {
- set_bit_raw(buf.as_mut_ptr(), i);
- }
- }
- }
-
- let raw_ptr = buf.as_ptr();
- for (i, b) in expected.iter().enumerate() {
- unsafe {
- assert_eq!(*b, get_bit_raw(raw_ptr, i));
- }
- }
- }
-
- #[test]
- fn test_get_set_bit_roundtrip() {
- const NUM_BYTES: usize = 10;
- const NUM_SETS: usize = 10;
-
- 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 {
- 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]));
- assert_eq!(8, count_set_bits(&[0b11111111]));
- 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));
- }
-
- #[test]
- fn test_ceil() {
- assert_eq!(ceil(0, 1), 0);
- assert_eq!(ceil(1, 1), 1);
- assert_eq!(ceil(1, 2), 1);
- assert_eq!(ceil(1, 8), 1);
- assert_eq!(ceil(7, 8), 1);
- assert_eq!(ceil(8, 8), 1);
- assert_eq!(ceil(9, 8), 2);
- assert_eq!(ceil(9, 9), 1);
- assert_eq!(ceil(10000000000, 10), 1000000000);
- assert_eq!(ceil(10, 10000000000), 1);
- assert_eq!(ceil(10000000000, 1000000000), 10);
- }
-}
diff --git a/rust/src/util/mod.rs b/rust/src/util/mod.rs
deleted file mode 100644
index c20abba180..0000000000
--- a/rust/src/util/mod.rs
+++ /dev/null
@@ -1,19 +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.
-
-pub mod bit_util;
-pub mod test_util;
diff --git a/rust/src/util/test_util.rs b/rust/src/util/test_util.rs
deleted file mode 100644
index 4ef48e6003..0000000000
--- a/rust/src/util/test_util.rs
+++ /dev/null
@@ -1,28 +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 rand::{thread_rng, Rng};
-
-/// Returns a vector of size `n`, filled with randomly generated bytes.
-pub fn random_bytes(n: usize) -> Vec<u8> {
- let mut result = vec![];
- let mut rng = thread_rng();
- for _ in 0..n {
- result.push(rng.gen_range(0, 255) & 0xFF);
- }
- result
-}
diff --git a/rust/test/data/null_test.csv b/rust/test/data/null_test.csv
deleted file mode 100644
index 7e0dde5371..0000000000
--- a/rust/test/data/null_test.csv
+++ /dev/null
@@ -1,6 +0,0 @@
-c_int,c_float,c_string,c_bool
-1,1.1,"1.11",True
-2,2.2,"2.22",TRUE
-3,,"3.33",true
-4,4.4,,False
-5,6.6,"",FALSE
\ No newline at end of file
diff --git a/rust/test/data/uk_cities.csv b/rust/test/data/uk_cities.csv
deleted file mode 100644
index db9e6da8c7..0000000000
--- a/rust/test/data/uk_cities.csv
+++ /dev/null
@@ -1,37 +0,0 @@
-"Elgin, Scotland, the UK",57.653484,-3.335724
-"Stoke-on-Trent, Staffordshire, the UK",53.002666,-2.179404
-"Solihull, Birmingham, UK",52.412811,-1.778197
-"Cardiff, Cardiff county, UK",51.481583,-3.179090
-"Eastbourne, East Sussex, UK",50.768036,0.290472
-"Oxford, Oxfordshire, UK",51.752022,-1.257677
-"London, UK",51.509865,-0.118092
-"Swindon, Swindon, UK",51.568535,-1.772232
-"Gravesend, Kent, UK",51.441883,0.370759
-"Northampton, Northamptonshire, UK",52.240479,-0.902656
-"Rugby, Warwickshire, UK",52.370876,-1.265032
-"Sutton Coldfield, West Midlands, UK",52.570385,-1.824042
-"Harlow, Essex, UK",51.772938,0.102310
-"Aberdeen, Aberdeen City, UK",57.149651,-2.099075
-"Swansea, Swansea, UK",51.621441,-3.943646
-"Chesterfield, Derbyshire, UK",53.235046,-1.421629
-"Londonderry, Derry, UK",55.006763,-7.318268
-"Salisbury, Wiltshire, UK",51.068787,-1.794472
-"Weymouth, Dorset, UK",50.614429,-2.457621
-"Wolverhampton, West Midlands, UK",52.591370,-2.110748
-"Preston, Lancashire, UK",53.765762,-2.692337
-"Bournemouth, UK",50.720806,-1.904755
-"Doncaster, South Yorkshire, UK",53.522820,-1.128462
-"Ayr, South Ayrshire, UK",55.458565,-4.629179
-"Hastings, East Sussex, UK",50.854259,0.573453
-"Bedford, UK",52.136436,-0.460739
-"Basildon, Essex, UK",51.572376,0.470009
-"Chippenham, Wiltshire, UK",51.458057,-2.116074
-"Belfast, UK",54.607868,-5.926437
-"Uckfield, East Sussex, UK",50.967941,0.085831
-"Worthing, West Sussex, UK",50.825024,-0.383835
-"Leeds, West Yorkshire, UK",53.801277,-1.548567
-"Kendal, Cumbria, UK",54.328506,-2.743870
-"Plymouth, UK",50.376289,-4.143841
-"Haverhill, Suffolk, UK",52.080875,0.444517
-"Frankton, Warwickshire, UK",52.328415,-1.377561
-"Inverness, the UK",57.477772,-4.224721
\ No newline at end of file