Apache DataFusion SQL Query Engine
ARROW-4028: [Rust] Merge parquet-rs codebase
Chao Sunc7dc47a30286
diff --git a/ci/rust-build-main.bat b/ci/rust-build-main.batindex c8a51fef6e..e338f7e172 100644--- a/ci/rust-build-main.bat+++ b/ci/rust-build-main.bat@@ -17,6 +17,9 @@@rem The "main" Rust build script for Windows CI+@rem Retrieve git submodules, configure env var for Parquet unit tests+git submodule update --init || exit /B+set PARQUET_TEST_DATA=%CD%\cpp\submodules\parquet-testing\datapushd rust@echo ===================================diff --git a/ci/travis_script_rust.sh b/ci/travis_script_rust.shindex 55cce8f354..4b09bc22e4 100755--- a/ci/travis_script_rust.sh+++ b/ci/travis_script_rust.sh@@ -19,6 +19,8 @@set -e+source $TRAVIS_BUILD_DIR/ci/travis_env_common.sh+RUST_DIR=${TRAVIS_BUILD_DIR}/rustpushd $RUST_DIRdiff --git a/docker-compose.yml b/docker-compose.ymlindex 0a01a7cbe9..b61511ee56 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -152,6 +152,8 @@ services:build:context: .dockerfile: rust/Dockerfile+ environment:+ PARQUET_TEST_DATA: /arrow/cpp/submodules/parquet-testing/datavolumes: *ubuntu-volumesr:diff --git a/rust/Cargo.toml b/rust/Cargo.tomlindex aa23815f74..49e8a9d9c8 100644--- a/rust/Cargo.toml+++ b/rust/Cargo.toml@@ -42,10 +42,22 @@ serde_derive = "1.0.80"serde_json = "1.0.13"rand = "0.5"csv = "1.0.0"+parquet-format = "2.5.0"+quick-error = "1.2.2"+byteorder = "1"+thrift = "0.0.4"+snap = "0.2"+brotli = "2.5"+flate2 = "1.0.2"+lz4 = "1.23"+zstd = "0.4"+chrono = "0.4"+num-bigint = "0.2"num = "0.2"[dev-dependencies]criterion = "0.2"+lazy_static = "1"[[bench]]name = "array_from_vec"diff --git a/rust/benches/array_from_vec.rs b/rust/benches/array_from_vec.rsindex 669b88eaa4..f935714092 100644--- a/rust/benches/array_from_vec.rs+++ b/rust/benches/array_from_vec.rs@@ -17,7 +17,6 @@#[macro_use]extern crate criterion;-use criterion::Criterion;extern crate arrow;diff --git a/rust/benches/builder.rs b/rust/benches/builder.rsindex 04f8a33b5b..90fd75a0da 100644--- a/rust/benches/builder.rs+++ b/rust/benches/builder.rs@@ -19,11 +19,13 @@ extern crate arrow;extern crate criterion;extern crate rand;-use arrow::builder::*;+use std::mem::size_of;+use criterion::*;use rand::distributions::Standard;use rand::{thread_rng, Rng};-use std::mem::size_of;++use arrow::builder::*;// Build arrays with 512k elements.const BATCH_SIZE: usize = 8 << 10;diff --git a/rust/build.rs b/rust/build.rsnew file mode 100644index 0000000000..b42b2a4bab--- /dev/null+++ b/rust/build.rs@@ -0,0 +1,43 @@+// 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::process::Command;++fn main() {+ // Set Parquet version, build hash and "created by" string.+ let version = env!("CARGO_PKG_VERSION");+ let mut created_by = format!("parquet-rs version {}", version);+ if let Ok(git_hash) = run(Command::new("git").arg("rev-parse").arg("HEAD")) {+ created_by.push_str(format!(" (build {})", git_hash).as_str());+ println!("cargo:rustc-env=PARQUET_BUILD={}", git_hash);+ }+ println!("cargo:rustc-env=PARQUET_VERSION={}", version);+ println!("cargo:rustc-env=PARQUET_CREATED_BY={}", created_by);+}++/// Runs command and returns either content of stdout for successful execution,+/// or an error message otherwise.+fn run(command: &mut Command) -> Result<String, String> {+ println!("Running: `{:?}`", command);+ match command.output() {+ Ok(ref output) if output.status.success() => {+ Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())+ }+ Ok(ref output) => Err(format!("Failed: `{:?}` ({})", command, output.status)),+ Err(error) => Err(format!("Failed: `{:?}` ({})", command, error)),+ }+}diff --git a/rust/examples/read_csv.rs b/rust/examples/read_csv.rsindex df66a8112e..147d2f9c23 100644--- a/rust/examples/read_csv.rs+++ b/rust/examples/read_csv.rs@@ -17,11 +17,12 @@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};-use std::fs::File;-use std::sync::Arc;fn main() {let schema = Schema::new(vec![diff --git a/rust/rustfmt.toml b/rust/rustfmt.tomlnew file mode 100644index 0000000000..72eeee0af1--- /dev/null+++ b/rust/rustfmt.toml@@ -0,0 +1,18 @@+# 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.++format_doc_comments = true\ No newline at end of filediff --git a/rust/src/array.rs b/rust/src/array.rsindex 11e732a126..251dd35eea 100644--- a/rust/src/array.rs+++ b/rust/src/array.rs@@ -657,12 +657,14 @@ impl From<Vec<(Field, ArrayRef)>> for StructArray {#[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, ToByteSlice};+ use crate::datatypes::{DataType, Field};use crate::memory;- use std::sync::Arc;- use std::thread;#[test]fn test_primitive_array_from_vec() {diff --git a/rust/src/array_data.rs b/rust/src/array_data.rsindex 36a817ee57..9ea01a402a 100644--- a/rust/src/array_data.rs+++ b/rust/src/array_data.rs@@ -225,9 +225,10 @@ impl ArrayDataBuilder {#[cfg(test)]mod tests {+ use super::*;+use std::sync::Arc;- use super::{ArrayData, DataType};use crate::buffer::Buffer;use crate::util::bit_util;diff --git a/rust/src/builder.rs b/rust/src/builder.rsindex fc781ffa50..d5d222d006 100644--- a/rust/src/builder.rs+++ b/rust/src/builder.rs@@ -456,10 +456,10 @@ impl BinaryArrayBuilder {#[cfg(test)]mod tests {- use crate::array::Array;-use super::*;+ use crate::array::Array;+#[test]fn test_builder_i32_empty() {let b = Int32BufferBuilder::new(5);@@ -825,7 +825,6 @@ mod tests {#[test]fn test_binary_array_builder() {- use crate::array::BinaryArray;let mut builder = BinaryArrayBuilder::new(20);builder.push(b'h').unwrap();@@ -860,7 +859,6 @@ mod tests {#[test]fn test_binary_array_builder_push_string() {- use crate::array::BinaryArray;let mut builder = BinaryArrayBuilder::new(20);let var = "hello".to_owned();diff --git a/rust/src/csv/reader.rs b/rust/src/csv/reader.rsindex 956408e4a4..632aa7ae79 100644--- a/rust/src/csv/reader.rs+++ b/rust/src/csv/reader.rs@@ -29,16 +29,16 @@//! 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),+//! 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;@@ -195,8 +195,8 @@ impl Reader {#[cfg(test)]mod tests {-use super::*;+use crate::array::*;use crate::datatypes::Field;diff --git a/rust/src/lib.rs b/rust/src/lib.rsindex f41d08f142..d5708b1050 100644--- a/rust/src/lib.rs+++ b/rust/src/lib.rs@@ -15,7 +15,12 @@// 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;@@ -27,6 +32,7 @@ pub mod csv;pub mod datatypes;pub mod error;pub mod memory;+pub mod parquet;pub mod record_batch;pub mod tensor;pub mod util;diff --git a/rust/src/mod.rs b/rust/src/mod.rsnew file mode 100644index 0000000000..b9fa43ab81--- /dev/null+++ b/rust/src/mod.rs@@ -0,0 +1,28 @@+// 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/parquet/basic.rs b/rust/src/parquet/basic.rsnew file mode 100644index 0000000000..22e16347dc--- /dev/null+++ b/rust/src/parquet/basic.rs@@ -0,0 +1,1497 @@+// 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.++//! Contains Rust mappings for Thrift definition.+//! Refer to `parquet.thrift` file to see raw definitions.++use std::{convert, fmt, result, str};++use parquet_format as parquet;++use crate::parquet::errors::ParquetError;++// ----------------------------------------------------------------------+// Types from the Thrift definition++// ----------------------------------------------------------------------+// Mirrors `parquet::Type`++/// Types supported by Parquet.+/// These physical types are intended to be used in combination with the encodings to+/// control the on disk storage format.+/// For example INT16 is not included as a type since a good encoding of INT32+/// would handle this.+#[derive(Debug, Clone, Copy, PartialEq)]+pub enum Type {+ BOOLEAN,+ INT32,+ INT64,+ INT96,+ FLOAT,+ DOUBLE,+ BYTE_ARRAY,+ FIXED_LEN_BYTE_ARRAY,+}++// ----------------------------------------------------------------------+// Mirrors `parquet::ConvertedType`++/// Common types (logical types) used by frameworks when using Parquet.+/// This helps map between types in those frameworks to the base types in Parquet.+/// This is only metadata and not needed to read or write the data.+#[derive(Debug, Clone, Copy, PartialEq)]+pub enum LogicalType {+ NONE,+ /// A BYTE_ARRAY actually contains UTF8 encoded chars.+ UTF8,++ /// A map is converted as an optional field containing a repeated key/value pair.+ MAP,++ /// A key/value pair is converted into a group of two fields.+ MAP_KEY_VALUE,++ /// A list is converted into an optional field containing a repeated field for its+ /// values.+ LIST,++ /// An enum is converted into a binary field+ ENUM,++ /// A decimal value.+ /// This may be used to annotate binary or fixed primitive types. The+ /// underlying byte array stores the unscaled value encoded as two's+ /// complement using big-endian byte order (the most significant byte is the+ /// zeroth element).+ ///+ /// This must be accompanied by a (maximum) precision and a scale in the+ /// SchemaElement. The precision specifies the number of digits in the decimal+ /// and the scale stores the location of the decimal point. For example 1.23+ /// would have precision 3 (3 total digits) and scale 2 (the decimal point is+ /// 2 digits over).+ DECIMAL,++ /// A date stored as days since Unix epoch, encoded as the INT32 physical type.+ DATE,++ /// The total number of milliseconds since midnight. The value is stored as an INT32+ /// physical type.+ TIME_MILLIS,++ /// The total number of microseconds since midnight. The value is stored as an INT64+ /// physical type.+ TIME_MICROS,++ /// Date and time recorded as milliseconds since the Unix epoch.+ /// Recorded as a physical type of INT64.+ TIMESTAMP_MILLIS,++ /// Date and time recorded as microseconds since the Unix epoch.+ /// The value is stored as an INT64 physical type.+ TIMESTAMP_MICROS,++ /// An unsigned 8 bit integer value stored as INT32 physical type.+ UINT_8,++ /// An unsigned 16 bit integer value stored as INT32 physical type.+ UINT_16,++ /// An unsigned 32 bit integer value stored as INT32 physical type.+ UINT_32,++ /// An unsigned 64 bit integer value stored as INT64 physical type.+ UINT_64,++ /// A signed 8 bit integer value stored as INT32 physical type.+ INT_8,++ /// A signed 16 bit integer value stored as INT32 physical type.+ INT_16,++ /// A signed 32 bit integer value stored as INT32 physical type.+ INT_32,++ /// A signed 64 bit integer value stored as INT64 physical type.+ INT_64,++ /// A JSON document embedded within a single UTF8 column.+ JSON,++ /// A BSON document embedded within a single BINARY column.+ BSON,++ /// An interval of time.+ ///+ /// This type annotates data stored as a FIXED_LEN_BYTE_ARRAY of length 12.+ /// This data is composed of three separate little endian unsigned integers.+ /// Each stores a component of a duration of time. The first integer identifies+ /// the number of months associated with the duration, the second identifies+ /// the number of days associated with the duration and the third identifies+ /// the number of milliseconds associated with the provided duration.+ /// This duration of time is independent of any particular timezone or date.+ INTERVAL,+}++// ----------------------------------------------------------------------+// Mirrors `parquet::FieldRepetitionType`++/// Representation of field types in schema.+#[derive(Debug, Clone, Copy, PartialEq)]+pub enum Repetition {+ /// Field is required (can not be null) and each record has exactly 1 value.+ REQUIRED,+ /// Field is optional (can be null) and each record has 0 or 1 values.+ OPTIONAL,+ /// Field is repeated and can contain 0 or more values.+ REPEATED,+}++// ----------------------------------------------------------------------+// Mirrors `parquet::Encoding`++/// Encodings supported by Parquet.+/// Not all encodings are valid for all types. These enums are also used to specify the+/// encoding of definition and repetition levels.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub enum Encoding {+ /// Default byte encoding.+ /// - BOOLEAN - 1 bit per value, 0 is false; 1 is true.+ /// - INT32 - 4 bytes per value, stored as little-endian.+ /// - INT64 - 8 bytes per value, stored as little-endian.+ /// - FLOAT - 4 bytes per value, stored as little-endian.+ /// - DOUBLE - 8 bytes per value, stored as little-endian.+ /// - BYTE_ARRAY - 4 byte length stored as little endian, followed by bytes.+ /// - FIXED_LEN_BYTE_ARRAY - just the bytes are stored.+ PLAIN,++ /// **Deprecated** dictionary encoding.+ ///+ /// The values in the dictionary are encoded using PLAIN encoding.+ /// Since it is deprecated, RLE_DICTIONARY encoding is used for a data page, and PLAIN+ /// encoding is used for dictionary page.+ PLAIN_DICTIONARY,++ /// Group packed run length encoding.+ ///+ /// Usable for definition/repetition levels encoding and boolean values.+ RLE,++ /// Bit packed encoding.+ ///+ /// This can only be used if the data has a known max width.+ /// Usable for definition/repetition levels encoding.+ BIT_PACKED,++ /// Delta encoding for integers, either INT32 or INT64.+ ///+ /// Works best on sorted data.+ DELTA_BINARY_PACKED,++ /// Encoding for byte arrays to separate the length values and the data.+ ///+ /// The lengths are encoded using DELTA_BINARY_PACKED encoding.+ DELTA_LENGTH_BYTE_ARRAY,++ /// Incremental encoding for byte arrays.+ ///+ /// Prefix lengths are encoded using DELTA_BINARY_PACKED encoding.+ /// Suffixes are stored using DELTA_LENGTH_BYTE_ARRAY encoding.+ DELTA_BYTE_ARRAY,++ /// Dictionary encoding.+ ///+ /// The ids are encoded using the RLE encoding.+ RLE_DICTIONARY,+}++// ----------------------------------------------------------------------+// Mirrors `parquet::CompressionCodec`++/// Supported compression algorithms.+#[derive(Debug, Clone, Copy, PartialEq)]+pub enum Compression {+ UNCOMPRESSED,+ SNAPPY,+ GZIP,+ LZO,+ BROTLI,+ LZ4,+ ZSTD,+}++// ----------------------------------------------------------------------+// Mirrors `parquet::PageType`++/// Available data pages for Parquet file format.+/// Note that some of the page types may not be supported.+#[derive(Debug, Clone, Copy, PartialEq)]+pub enum PageType {+ DATA_PAGE,+ INDEX_PAGE,+ DICTIONARY_PAGE,+ DATA_PAGE_V2,+}++// ----------------------------------------------------------------------+// Mirrors `parquet::ColumnOrder`++/// Sort order for page and column statistics.+///+/// Types are associated with sort orders and column stats are aggregated using a sort+/// order, and a sort order should be considered when comparing values with statistics+/// min/max.+///+/// See reference in+/// https://github.com/apache/parquet-cpp/blob/master/src/parquet/types.h+#[derive(Debug, Clone, Copy, PartialEq)]+pub enum SortOrder {+ /// Signed (either value or legacy byte-wise) comparison.+ SIGNED,+ /// Unsigned (depending on physical type either value or byte-wise) comparison.+ UNSIGNED,+ /// Comparison is undefined.+ UNDEFINED,+}++/// Column order that specifies what method was used to aggregate min/max values for+/// statistics.+///+/// If column order is undefined, then it is the legacy behaviour and all values should+/// be compared as signed values/bytes.+#[derive(Debug, Clone, Copy, PartialEq)]+pub enum ColumnOrder {+ /// Column uses the order defined by its logical or physical type+ /// (if there is no logical type), parquet-format 2.4.0+.+ TYPE_DEFINED_ORDER(SortOrder),+ /// Undefined column order, means legacy behaviour before parquet-format 2.4.0.+ /// Sort order is always SIGNED.+ UNDEFINED,+}++impl ColumnOrder {+ /// Returns sort order for a physical/logical type.+ pub fn get_sort_order(logical_type: LogicalType, physical_type: Type) -> SortOrder {+ match logical_type {+ // Unsigned byte-wise comparison.+ LogicalType::UTF8 | LogicalType::JSON | LogicalType::BSON | LogicalType::ENUM => {+ SortOrder::UNSIGNED+ }++ LogicalType::INT_8+ | LogicalType::INT_16+ | LogicalType::INT_32+ | LogicalType::INT_64 => SortOrder::SIGNED,++ LogicalType::UINT_8+ | LogicalType::UINT_16+ | LogicalType::UINT_32+ | LogicalType::UINT_64 => SortOrder::UNSIGNED,++ // Signed comparison of the represented value.+ LogicalType::DECIMAL => SortOrder::SIGNED,++ LogicalType::DATE => SortOrder::SIGNED,++ LogicalType::TIME_MILLIS+ | LogicalType::TIME_MICROS+ | LogicalType::TIMESTAMP_MILLIS+ | LogicalType::TIMESTAMP_MICROS => SortOrder::SIGNED,++ LogicalType::INTERVAL => SortOrder::UNSIGNED,++ LogicalType::LIST | LogicalType::MAP | LogicalType::MAP_KEY_VALUE => {+ SortOrder::UNDEFINED+ }++ // Fall back to physical type.+ LogicalType::NONE => Self::get_default_sort_order(physical_type),+ }+ }++ /// Returns default sort order based on physical type.+ fn get_default_sort_order(physical_type: Type) -> SortOrder {+ match physical_type {+ // Order: false, true+ Type::BOOLEAN => SortOrder::UNSIGNED,+ Type::INT32 | Type::INT64 => SortOrder::SIGNED,+ Type::INT96 => SortOrder::UNDEFINED,+ // Notes to remember when comparing float/double values:+ // If the min is a NaN, it should be ignored.+ // If the max is a NaN, it should be ignored.+ // If the min is +0, the row group may contain -0 values as well.+ // If the max is -0, the row group may contain +0 values as well.+ // When looking for NaN values, min and max should be ignored.+ Type::FLOAT | Type::DOUBLE => SortOrder::SIGNED,+ // unsigned byte-wise comparison+ Type::BYTE_ARRAY | Type::FIXED_LEN_BYTE_ARRAY => SortOrder::UNSIGNED,+ }+ }++ /// Returns sort order associated with this column order.+ pub fn sort_order(&self) -> SortOrder {+ match *self {+ ColumnOrder::TYPE_DEFINED_ORDER(order) => order,+ ColumnOrder::UNDEFINED => SortOrder::SIGNED,+ }+ }+}++impl fmt::Display for Type {+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {+ write!(f, "{:?}", self)+ }+}++impl fmt::Display for LogicalType {+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {+ write!(f, "{:?}", self)+ }+}++impl fmt::Display for Repetition {+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {+ write!(f, "{:?}", self)+ }+}++impl fmt::Display for Encoding {+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {+ write!(f, "{:?}", self)+ }+}++impl fmt::Display for Compression {+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {+ write!(f, "{:?}", self)+ }+}++impl fmt::Display for PageType {+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {+ write!(f, "{:?}", self)+ }+}++impl fmt::Display for SortOrder {+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {+ write!(f, "{:?}", self)+ }+}++impl fmt::Display for ColumnOrder {+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {+ write!(f, "{:?}", self)+ }+}++// ----------------------------------------------------------------------+// parquet::Type <=> Type conversion++impl convert::From<parquet::Type> for Type {+ fn from(value: parquet::Type) -> Self {+ match value {+ parquet::Type::BOOLEAN => Type::BOOLEAN,+ parquet::Type::INT32 => Type::INT32,+ parquet::Type::INT64 => Type::INT64,+ parquet::Type::INT96 => Type::INT96,+ parquet::Type::FLOAT => Type::FLOAT,+ parquet::Type::DOUBLE => Type::DOUBLE,+ parquet::Type::BYTE_ARRAY => Type::BYTE_ARRAY,+ parquet::Type::FIXED_LEN_BYTE_ARRAY => Type::FIXED_LEN_BYTE_ARRAY,+ }+ }+}++impl convert::From<Type> for parquet::Type {+ fn from(value: Type) -> Self {+ match value {+ Type::BOOLEAN => parquet::Type::BOOLEAN,+ Type::INT32 => parquet::Type::INT32,+ Type::INT64 => parquet::Type::INT64,+ Type::INT96 => parquet::Type::INT96,+ Type::FLOAT => parquet::Type::FLOAT,+ Type::DOUBLE => parquet::Type::DOUBLE,+ Type::BYTE_ARRAY => parquet::Type::BYTE_ARRAY,+ Type::FIXED_LEN_BYTE_ARRAY => parquet::Type::FIXED_LEN_BYTE_ARRAY,+ }+ }+}++// ----------------------------------------------------------------------+// parquet::ConvertedType <=> LogicalType conversion++impl convert::From<Option<parquet::ConvertedType>> for LogicalType {+ fn from(option: Option<parquet::ConvertedType>) -> Self {+ match option {+ None => LogicalType::NONE,+ Some(value) => match value {+ parquet::ConvertedType::UTF8 => LogicalType::UTF8,+ parquet::ConvertedType::MAP => LogicalType::MAP,+ parquet::ConvertedType::MAP_KEY_VALUE => LogicalType::MAP_KEY_VALUE,+ parquet::ConvertedType::LIST => LogicalType::LIST,+ parquet::ConvertedType::ENUM => LogicalType::ENUM,+ parquet::ConvertedType::DECIMAL => LogicalType::DECIMAL,+ parquet::ConvertedType::DATE => LogicalType::DATE,+ parquet::ConvertedType::TIME_MILLIS => LogicalType::TIME_MILLIS,+ parquet::ConvertedType::TIME_MICROS => LogicalType::TIME_MICROS,+ parquet::ConvertedType::TIMESTAMP_MILLIS => LogicalType::TIMESTAMP_MILLIS,+ parquet::ConvertedType::TIMESTAMP_MICROS => LogicalType::TIMESTAMP_MICROS,+ parquet::ConvertedType::UINT_8 => LogicalType::UINT_8,+ parquet::ConvertedType::UINT_16 => LogicalType::UINT_16,+ parquet::ConvertedType::UINT_32 => LogicalType::UINT_32,+ parquet::ConvertedType::UINT_64 => LogicalType::UINT_64,+ parquet::ConvertedType::INT_8 => LogicalType::INT_8,+ parquet::ConvertedType::INT_16 => LogicalType::INT_16,+ parquet::ConvertedType::INT_32 => LogicalType::INT_32,+ parquet::ConvertedType::INT_64 => LogicalType::INT_64,+ parquet::ConvertedType::JSON => LogicalType::JSON,+ parquet::ConvertedType::BSON => LogicalType::BSON,+ parquet::ConvertedType::INTERVAL => LogicalType::INTERVAL,+ },+ }+ }+}++impl convert::From<LogicalType> for Option<parquet::ConvertedType> {+ fn from(value: LogicalType) -> Self {+ match value {+ LogicalType::NONE => None,+ LogicalType::UTF8 => Some(parquet::ConvertedType::UTF8),+ LogicalType::MAP => Some(parquet::ConvertedType::MAP),+ LogicalType::MAP_KEY_VALUE => Some(parquet::ConvertedType::MAP_KEY_VALUE),+ LogicalType::LIST => Some(parquet::ConvertedType::LIST),+ LogicalType::ENUM => Some(parquet::ConvertedType::ENUM),+ LogicalType::DECIMAL => Some(parquet::ConvertedType::DECIMAL),+ LogicalType::DATE => Some(parquet::ConvertedType::DATE),+ LogicalType::TIME_MILLIS => Some(parquet::ConvertedType::TIME_MILLIS),+ LogicalType::TIME_MICROS => Some(parquet::ConvertedType::TIME_MICROS),+ LogicalType::TIMESTAMP_MILLIS => Some(parquet::ConvertedType::TIMESTAMP_MILLIS),+ LogicalType::TIMESTAMP_MICROS => Some(parquet::ConvertedType::TIMESTAMP_MICROS),+ LogicalType::UINT_8 => Some(parquet::ConvertedType::UINT_8),+ LogicalType::UINT_16 => Some(parquet::ConvertedType::UINT_16),+ LogicalType::UINT_32 => Some(parquet::ConvertedType::UINT_32),+ LogicalType::UINT_64 => Some(parquet::ConvertedType::UINT_64),+ LogicalType::INT_8 => Some(parquet::ConvertedType::INT_8),+ LogicalType::INT_16 => Some(parquet::ConvertedType::INT_16),+ LogicalType::INT_32 => Some(parquet::ConvertedType::INT_32),+ LogicalType::INT_64 => Some(parquet::ConvertedType::INT_64),+ LogicalType::JSON => Some(parquet::ConvertedType::JSON),+ LogicalType::BSON => Some(parquet::ConvertedType::BSON),+ LogicalType::INTERVAL => Some(parquet::ConvertedType::INTERVAL),+ }+ }+}++// ----------------------------------------------------------------------+// parquet::FieldRepetitionType <=> Repetition conversion++impl convert::From<parquet::FieldRepetitionType> for Repetition {+ fn from(value: parquet::FieldRepetitionType) -> Self {+ match value {+ parquet::FieldRepetitionType::REQUIRED => Repetition::REQUIRED,+ parquet::FieldRepetitionType::OPTIONAL => Repetition::OPTIONAL,+ parquet::FieldRepetitionType::REPEATED => Repetition::REPEATED,+ }+ }+}++impl convert::From<Repetition> for parquet::FieldRepetitionType {+ fn from(value: Repetition) -> Self {+ match value {+ Repetition::REQUIRED => parquet::FieldRepetitionType::REQUIRED,+ Repetition::OPTIONAL => parquet::FieldRepetitionType::OPTIONAL,+ Repetition::REPEATED => parquet::FieldRepetitionType::REPEATED,+ }+ }+}++// ----------------------------------------------------------------------+// parquet::Encoding <=> Encoding conversion++impl convert::From<parquet::Encoding> for Encoding {+ fn from(value: parquet::Encoding) -> Self {+ match value {+ parquet::Encoding::PLAIN => Encoding::PLAIN,+ parquet::Encoding::PLAIN_DICTIONARY => Encoding::PLAIN_DICTIONARY,+ parquet::Encoding::RLE => Encoding::RLE,+ parquet::Encoding::BIT_PACKED => Encoding::BIT_PACKED,+ parquet::Encoding::DELTA_BINARY_PACKED => Encoding::DELTA_BINARY_PACKED,+ parquet::Encoding::DELTA_LENGTH_BYTE_ARRAY => Encoding::DELTA_LENGTH_BYTE_ARRAY,+ parquet::Encoding::DELTA_BYTE_ARRAY => Encoding::DELTA_BYTE_ARRAY,+ parquet::Encoding::RLE_DICTIONARY => Encoding::RLE_DICTIONARY,+ }+ }+}++impl convert::From<Encoding> for parquet::Encoding {+ fn from(value: Encoding) -> Self {+ match value {+ Encoding::PLAIN => parquet::Encoding::PLAIN,+ Encoding::PLAIN_DICTIONARY => parquet::Encoding::PLAIN_DICTIONARY,+ Encoding::RLE => parquet::Encoding::RLE,+ Encoding::BIT_PACKED => parquet::Encoding::BIT_PACKED,+ Encoding::DELTA_BINARY_PACKED => parquet::Encoding::DELTA_BINARY_PACKED,+ Encoding::DELTA_LENGTH_BYTE_ARRAY => parquet::Encoding::DELTA_LENGTH_BYTE_ARRAY,+ Encoding::DELTA_BYTE_ARRAY => parquet::Encoding::DELTA_BYTE_ARRAY,+ Encoding::RLE_DICTIONARY => parquet::Encoding::RLE_DICTIONARY,+ }+ }+}++// ----------------------------------------------------------------------+// parquet::CompressionCodec <=> Compression conversion++impl convert::From<parquet::CompressionCodec> for Compression {+ fn from(value: parquet::CompressionCodec) -> Self {+ match value {+ parquet::CompressionCodec::UNCOMPRESSED => Compression::UNCOMPRESSED,+ parquet::CompressionCodec::SNAPPY => Compression::SNAPPY,+ parquet::CompressionCodec::GZIP => Compression::GZIP,+ parquet::CompressionCodec::LZO => Compression::LZO,+ parquet::CompressionCodec::BROTLI => Compression::BROTLI,+ parquet::CompressionCodec::LZ4 => Compression::LZ4,+ parquet::CompressionCodec::ZSTD => Compression::ZSTD,+ }+ }+}++impl convert::From<Compression> for parquet::CompressionCodec {+ fn from(value: Compression) -> Self {+ match value {+ Compression::UNCOMPRESSED => parquet::CompressionCodec::UNCOMPRESSED,+ Compression::SNAPPY => parquet::CompressionCodec::SNAPPY,+ Compression::GZIP => parquet::CompressionCodec::GZIP,+ Compression::LZO => parquet::CompressionCodec::LZO,+ Compression::BROTLI => parquet::CompressionCodec::BROTLI,+ Compression::LZ4 => parquet::CompressionCodec::LZ4,+ Compression::ZSTD => parquet::CompressionCodec::ZSTD,+ }+ }+}++// ----------------------------------------------------------------------+// parquet::PageType <=> PageType conversion++impl convert::From<parquet::PageType> for PageType {+ fn from(value: parquet::PageType) -> Self {+ match value {+ parquet::PageType::DATA_PAGE => PageType::DATA_PAGE,+ parquet::PageType::INDEX_PAGE => PageType::INDEX_PAGE,+ parquet::PageType::DICTIONARY_PAGE => PageType::DICTIONARY_PAGE,+ parquet::PageType::DATA_PAGE_V2 => PageType::DATA_PAGE_V2,+ }+ }+}++impl convert::From<PageType> for parquet::PageType {+ fn from(value: PageType) -> Self {+ match value {+ PageType::DATA_PAGE => parquet::PageType::DATA_PAGE,+ PageType::INDEX_PAGE => parquet::PageType::INDEX_PAGE,+ PageType::DICTIONARY_PAGE => parquet::PageType::DICTIONARY_PAGE,+ PageType::DATA_PAGE_V2 => parquet::PageType::DATA_PAGE_V2,+ }+ }+}++// ----------------------------------------------------------------------+// String conversions for schema parsing.++impl str::FromStr for Repetition {+ type Err = ParquetError;++ fn from_str(s: &str) -> result::Result<Self, Self::Err> {+ match s {+ "REQUIRED" => Ok(Repetition::REQUIRED),+ "OPTIONAL" => Ok(Repetition::OPTIONAL),+ "REPEATED" => Ok(Repetition::REPEATED),+ other => Err(general_err!("Invalid repetition {}", other)),+ }+ }+}++impl str::FromStr for Type {+ type Err = ParquetError;++ fn from_str(s: &str) -> result::Result<Self, Self::Err> {+ match s {+ "BOOLEAN" => Ok(Type::BOOLEAN),+ "INT32" => Ok(Type::INT32),+ "INT64" => Ok(Type::INT64),+ "INT96" => Ok(Type::INT96),+ "FLOAT" => Ok(Type::FLOAT),+ "DOUBLE" => Ok(Type::DOUBLE),+ "BYTE_ARRAY" | "BINARY" => Ok(Type::BYTE_ARRAY),+ "FIXED_LEN_BYTE_ARRAY" => Ok(Type::FIXED_LEN_BYTE_ARRAY),+ other => Err(general_err!("Invalid type {}", other)),+ }+ }+}++impl str::FromStr for LogicalType {+ type Err = ParquetError;++ fn from_str(s: &str) -> result::Result<Self, Self::Err> {+ match s {+ "NONE" => Ok(LogicalType::NONE),+ "UTF8" => Ok(LogicalType::UTF8),+ "MAP" => Ok(LogicalType::MAP),+ "MAP_KEY_VALUE" => Ok(LogicalType::MAP_KEY_VALUE),+ "LIST" => Ok(LogicalType::LIST),+ "ENUM" => Ok(LogicalType::ENUM),+ "DECIMAL" => Ok(LogicalType::DECIMAL),+ "DATE" => Ok(LogicalType::DATE),+ "TIME_MILLIS" => Ok(LogicalType::TIME_MILLIS),+ "TIME_MICROS" => Ok(LogicalType::TIME_MICROS),+ "TIMESTAMP_MILLIS" => Ok(LogicalType::TIMESTAMP_MILLIS),+ "TIMESTAMP_MICROS" => Ok(LogicalType::TIMESTAMP_MICROS),+ "UINT_8" => Ok(LogicalType::UINT_8),+ "UINT_16" => Ok(LogicalType::UINT_16),+ "UINT_32" => Ok(LogicalType::UINT_32),+ "UINT_64" => Ok(LogicalType::UINT_64),+ "INT_8" => Ok(LogicalType::INT_8),+ "INT_16" => Ok(LogicalType::INT_16),+ "INT_32" => Ok(LogicalType::INT_32),+ "INT_64" => Ok(LogicalType::INT_64),+ "JSON" => Ok(LogicalType::JSON),+ "BSON" => Ok(LogicalType::BSON),+ "INTERVAL" => Ok(LogicalType::INTERVAL),+ other => Err(general_err!("Invalid logical type {}", other)),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_display_type() {+ assert_eq!(Type::BOOLEAN.to_string(), "BOOLEAN");+ assert_eq!(Type::INT32.to_string(), "INT32");+ assert_eq!(Type::INT64.to_string(), "INT64");+ assert_eq!(Type::INT96.to_string(), "INT96");+ assert_eq!(Type::FLOAT.to_string(), "FLOAT");+ assert_eq!(Type::DOUBLE.to_string(), "DOUBLE");+ assert_eq!(Type::BYTE_ARRAY.to_string(), "BYTE_ARRAY");+ assert_eq!(+ Type::FIXED_LEN_BYTE_ARRAY.to_string(),+ "FIXED_LEN_BYTE_ARRAY"+ );+ }++ #[test]+ fn test_from_type() {+ assert_eq!(Type::from(parquet::Type::BOOLEAN), Type::BOOLEAN);+ assert_eq!(Type::from(parquet::Type::INT32), Type::INT32);+ assert_eq!(Type::from(parquet::Type::INT64), Type::INT64);+ assert_eq!(Type::from(parquet::Type::INT96), Type::INT96);+ assert_eq!(Type::from(parquet::Type::FLOAT), Type::FLOAT);+ assert_eq!(Type::from(parquet::Type::DOUBLE), Type::DOUBLE);+ assert_eq!(Type::from(parquet::Type::BYTE_ARRAY), Type::BYTE_ARRAY);+ assert_eq!(+ Type::from(parquet::Type::FIXED_LEN_BYTE_ARRAY),+ Type::FIXED_LEN_BYTE_ARRAY+ );+ }++ #[test]+ fn test_into_type() {+ assert_eq!(parquet::Type::BOOLEAN, Type::BOOLEAN.into());+ assert_eq!(parquet::Type::INT32, Type::INT32.into());+ assert_eq!(parquet::Type::INT64, Type::INT64.into());+ assert_eq!(parquet::Type::INT96, Type::INT96.into());+ assert_eq!(parquet::Type::FLOAT, Type::FLOAT.into());+ assert_eq!(parquet::Type::DOUBLE, Type::DOUBLE.into());+ assert_eq!(parquet::Type::BYTE_ARRAY, Type::BYTE_ARRAY.into());+ assert_eq!(+ parquet::Type::FIXED_LEN_BYTE_ARRAY,+ Type::FIXED_LEN_BYTE_ARRAY.into()+ );+ }++ #[test]+ fn test_from_string_into_type() {+ assert_eq!(+ Type::BOOLEAN.to_string().parse::<Type>().unwrap(),+ Type::BOOLEAN+ );+ assert_eq!(+ Type::INT32.to_string().parse::<Type>().unwrap(),+ Type::INT32+ );+ assert_eq!(+ Type::INT64.to_string().parse::<Type>().unwrap(),+ Type::INT64+ );+ assert_eq!(+ Type::INT96.to_string().parse::<Type>().unwrap(),+ Type::INT96+ );+ assert_eq!(+ Type::FLOAT.to_string().parse::<Type>().unwrap(),+ Type::FLOAT+ );+ assert_eq!(+ Type::DOUBLE.to_string().parse::<Type>().unwrap(),+ Type::DOUBLE+ );+ assert_eq!(+ Type::BYTE_ARRAY.to_string().parse::<Type>().unwrap(),+ Type::BYTE_ARRAY+ );+ assert_eq!("BINARY".parse::<Type>().unwrap(), Type::BYTE_ARRAY);+ assert_eq!(+ Type::FIXED_LEN_BYTE_ARRAY+ .to_string()+ .parse::<Type>()+ .unwrap(),+ Type::FIXED_LEN_BYTE_ARRAY+ );+ }++ #[test]+ fn test_display_logical_type() {+ assert_eq!(LogicalType::NONE.to_string(), "NONE");+ assert_eq!(LogicalType::UTF8.to_string(), "UTF8");+ assert_eq!(LogicalType::MAP.to_string(), "MAP");+ assert_eq!(LogicalType::MAP_KEY_VALUE.to_string(), "MAP_KEY_VALUE");+ assert_eq!(LogicalType::LIST.to_string(), "LIST");+ assert_eq!(LogicalType::ENUM.to_string(), "ENUM");+ assert_eq!(LogicalType::DECIMAL.to_string(), "DECIMAL");+ assert_eq!(LogicalType::DATE.to_string(), "DATE");+ assert_eq!(LogicalType::TIME_MILLIS.to_string(), "TIME_MILLIS");+ assert_eq!(LogicalType::DATE.to_string(), "DATE");+ assert_eq!(LogicalType::TIME_MICROS.to_string(), "TIME_MICROS");+ assert_eq!(+ LogicalType::TIMESTAMP_MILLIS.to_string(),+ "TIMESTAMP_MILLIS"+ );+ assert_eq!(+ LogicalType::TIMESTAMP_MICROS.to_string(),+ "TIMESTAMP_MICROS"+ );+ assert_eq!(LogicalType::UINT_8.to_string(), "UINT_8");+ assert_eq!(LogicalType::UINT_16.to_string(), "UINT_16");+ assert_eq!(LogicalType::UINT_32.to_string(), "UINT_32");+ assert_eq!(LogicalType::UINT_64.to_string(), "UINT_64");+ assert_eq!(LogicalType::INT_8.to_string(), "INT_8");+ assert_eq!(LogicalType::INT_16.to_string(), "INT_16");+ assert_eq!(LogicalType::INT_32.to_string(), "INT_32");+ assert_eq!(LogicalType::INT_64.to_string(), "INT_64");+ assert_eq!(LogicalType::JSON.to_string(), "JSON");+ assert_eq!(LogicalType::BSON.to_string(), "BSON");+ assert_eq!(LogicalType::INTERVAL.to_string(), "INTERVAL");+ }++ #[test]+ fn test_from_logical_type() {+ assert_eq!(LogicalType::from(None), LogicalType::NONE);+ assert_eq!(+ LogicalType::from(Some(parquet::ConvertedType::UTF8)),+ LogicalType::UTF8+ );+ assert_eq!(+ LogicalType::from(Some(parquet::ConvertedType::MAP)),+ LogicalType::MAP+ );+ assert_eq!(+ LogicalType::from(Some(parquet::ConvertedType::MAP_KEY_VALUE)),+ LogicalType::MAP_KEY_VALUE+ );+ assert_eq!(+ LogicalType::from(Some(parquet::ConvertedType::LIST)),+ LogicalType::LIST+ );+ assert_eq!(+ LogicalType::from(Some(parquet::ConvertedType::ENUM)),+ LogicalType::ENUM+ );+ assert_eq!(+ LogicalType::from(Some(parquet::ConvertedType::DECIMAL)),+ LogicalType::DECIMAL+ );+ assert_eq!(+ LogicalType::from(Some(parquet::ConvertedType::DATE)),+ LogicalType::DATE+ );+ assert_eq!(+ LogicalType::from(Some(parquet::ConvertedType::TIME_MILLIS)),+ LogicalType::TIME_MILLIS+ );+ assert_eq!(+ LogicalType::from(Some(parquet::ConvertedType::TIME_MICROS)),+ LogicalType::TIME_MICROS+ );+ assert_eq!(+ LogicalType::from(Some(parquet::ConvertedType::TIMESTAMP_MILLIS)),+ LogicalType::TIMESTAMP_MILLIS+ );+ assert_eq!(+ LogicalType::from(Some(parquet::ConvertedType::TIMESTAMP_MICROS)),+ LogicalType::TIMESTAMP_MICROS+ );+ assert_eq!(+ LogicalType::from(Some(parquet::ConvertedType::UINT_8)),+ LogicalType::UINT_8+ );+ assert_eq!(+ LogicalType::from(Some(parquet::ConvertedType::UINT_16)),+ LogicalType::UINT_16+ );+ assert_eq!(+ LogicalType::from(Some(parquet::ConvertedType::UINT_32)),+ LogicalType::UINT_32+ );+ assert_eq!(+ LogicalType::from(Some(parquet::ConvertedType::UINT_64)),+ LogicalType::UINT_64+ );+ assert_eq!(+ LogicalType::from(Some(parquet::ConvertedType::INT_8)),+ LogicalType::INT_8+ );+ assert_eq!(+ LogicalType::from(Some(parquet::ConvertedType::INT_16)),+ LogicalType::INT_16+ );+ assert_eq!(+ LogicalType::from(Some(parquet::ConvertedType::INT_32)),+ LogicalType::INT_32+ );+ assert_eq!(+ LogicalType::from(Some(parquet::ConvertedType::INT_64)),+ LogicalType::INT_64+ );+ assert_eq!(+ LogicalType::from(Some(parquet::ConvertedType::JSON)),+ LogicalType::JSON+ );+ assert_eq!(+ LogicalType::from(Some(parquet::ConvertedType::BSON)),+ LogicalType::BSON+ );+ assert_eq!(+ LogicalType::from(Some(parquet::ConvertedType::INTERVAL)),+ LogicalType::INTERVAL+ );+ }++ #[test]+ fn test_into_logical_type() {+ let converted_type: Option<parquet::ConvertedType> = None;+ assert_eq!(converted_type, LogicalType::NONE.into());+ assert_eq!(Some(parquet::ConvertedType::UTF8), LogicalType::UTF8.into());+ assert_eq!(Some(parquet::ConvertedType::MAP), LogicalType::MAP.into());+ assert_eq!(+ Some(parquet::ConvertedType::MAP_KEY_VALUE),+ LogicalType::MAP_KEY_VALUE.into()+ );+ assert_eq!(Some(parquet::ConvertedType::LIST), LogicalType::LIST.into());+ assert_eq!(Some(parquet::ConvertedType::ENUM), LogicalType::ENUM.into());+ assert_eq!(+ Some(parquet::ConvertedType::DECIMAL),+ LogicalType::DECIMAL.into()+ );+ assert_eq!(Some(parquet::ConvertedType::DATE), LogicalType::DATE.into());+ assert_eq!(+ Some(parquet::ConvertedType::TIME_MILLIS),+ LogicalType::TIME_MILLIS.into()+ );+ assert_eq!(+ Some(parquet::ConvertedType::TIME_MICROS),+ LogicalType::TIME_MICROS.into()+ );+ assert_eq!(+ Some(parquet::ConvertedType::TIMESTAMP_MILLIS),+ LogicalType::TIMESTAMP_MILLIS.into()+ );+ assert_eq!(+ Some(parquet::ConvertedType::TIMESTAMP_MICROS),+ LogicalType::TIMESTAMP_MICROS.into()+ );+ assert_eq!(+ Some(parquet::ConvertedType::UINT_8),+ LogicalType::UINT_8.into()+ );+ assert_eq!(+ Some(parquet::ConvertedType::UINT_16),+ LogicalType::UINT_16.into()+ );+ assert_eq!(+ Some(parquet::ConvertedType::UINT_32),+ LogicalType::UINT_32.into()+ );+ assert_eq!(+ Some(parquet::ConvertedType::UINT_64),+ LogicalType::UINT_64.into()+ );+ assert_eq!(+ Some(parquet::ConvertedType::INT_8),+ LogicalType::INT_8.into()+ );+ assert_eq!(+ Some(parquet::ConvertedType::INT_16),+ LogicalType::INT_16.into()+ );+ assert_eq!(+ Some(parquet::ConvertedType::INT_32),+ LogicalType::INT_32.into()+ );+ assert_eq!(+ Some(parquet::ConvertedType::INT_64),+ LogicalType::INT_64.into()+ );+ assert_eq!(Some(parquet::ConvertedType::JSON), LogicalType::JSON.into());+ assert_eq!(Some(parquet::ConvertedType::BSON), LogicalType::BSON.into());+ assert_eq!(+ Some(parquet::ConvertedType::INTERVAL),+ LogicalType::INTERVAL.into()+ );+ }++ #[test]+ fn test_from_string_into_logical_type() {+ assert_eq!(+ LogicalType::NONE+ .to_string()+ .parse::<LogicalType>()+ .unwrap(),+ LogicalType::NONE+ );+ assert_eq!(+ LogicalType::UTF8+ .to_string()+ .parse::<LogicalType>()+ .unwrap(),+ LogicalType::UTF8+ );+ assert_eq!(+ LogicalType::MAP.to_string().parse::<LogicalType>().unwrap(),+ LogicalType::MAP+ );+ assert_eq!(+ LogicalType::MAP_KEY_VALUE+ .to_string()+ .parse::<LogicalType>()+ .unwrap(),+ LogicalType::MAP_KEY_VALUE+ );+ assert_eq!(+ LogicalType::LIST+ .to_string()+ .parse::<LogicalType>()+ .unwrap(),+ LogicalType::LIST+ );+ assert_eq!(+ LogicalType::ENUM+ .to_string()+ .parse::<LogicalType>()+ .unwrap(),+ LogicalType::ENUM+ );+ assert_eq!(+ LogicalType::DECIMAL+ .to_string()+ .parse::<LogicalType>()+ .unwrap(),+ LogicalType::DECIMAL+ );+ assert_eq!(+ LogicalType::DATE+ .to_string()+ .parse::<LogicalType>()+ .unwrap(),+ LogicalType::DATE+ );+ assert_eq!(+ LogicalType::TIME_MILLIS+ .to_string()+ .parse::<LogicalType>()+ .unwrap(),+ LogicalType::TIME_MILLIS+ );+ assert_eq!(+ LogicalType::TIME_MICROS+ .to_string()+ .parse::<LogicalType>()+ .unwrap(),+ LogicalType::TIME_MICROS+ );+ assert_eq!(+ LogicalType::TIMESTAMP_MILLIS+ .to_string()+ .parse::<LogicalType>()+ .unwrap(),+ LogicalType::TIMESTAMP_MILLIS+ );+ assert_eq!(+ LogicalType::TIMESTAMP_MICROS+ .to_string()+ .parse::<LogicalType>()+ .unwrap(),+ LogicalType::TIMESTAMP_MICROS+ );+ assert_eq!(+ LogicalType::UINT_8+ .to_string()+ .parse::<LogicalType>()+ .unwrap(),+ LogicalType::UINT_8+ );+ assert_eq!(+ LogicalType::UINT_16+ .to_string()+ .parse::<LogicalType>()+ .unwrap(),+ LogicalType::UINT_16+ );+ assert_eq!(+ LogicalType::UINT_32+ .to_string()+ .parse::<LogicalType>()+ .unwrap(),+ LogicalType::UINT_32+ );+ assert_eq!(+ LogicalType::UINT_64+ .to_string()+ .parse::<LogicalType>()+ .unwrap(),+ LogicalType::UINT_64+ );+ assert_eq!(+ LogicalType::INT_8+ .to_string()+ .parse::<LogicalType>()+ .unwrap(),+ LogicalType::INT_8+ );+ assert_eq!(+ LogicalType::INT_16+ .to_string()+ .parse::<LogicalType>()+ .unwrap(),+ LogicalType::INT_16+ );+ assert_eq!(+ LogicalType::INT_32+ .to_string()+ .parse::<LogicalType>()+ .unwrap(),+ LogicalType::INT_32+ );+ assert_eq!(+ LogicalType::INT_64+ .to_string()+ .parse::<LogicalType>()+ .unwrap(),+ LogicalType::INT_64+ );+ assert_eq!(+ LogicalType::JSON+ .to_string()+ .parse::<LogicalType>()+ .unwrap(),+ LogicalType::JSON+ );+ assert_eq!(+ LogicalType::BSON+ .to_string()+ .parse::<LogicalType>()+ .unwrap(),+ LogicalType::BSON+ );+ assert_eq!(+ LogicalType::INTERVAL+ .to_string()+ .parse::<LogicalType>()+ .unwrap(),+ LogicalType::INTERVAL+ );+ }++ #[test]+ fn test_display_repetition() {+ assert_eq!(Repetition::REQUIRED.to_string(), "REQUIRED");+ assert_eq!(Repetition::OPTIONAL.to_string(), "OPTIONAL");+ assert_eq!(Repetition::REPEATED.to_string(), "REPEATED");+ }++ #[test]+ fn test_from_repetition() {+ assert_eq!(+ Repetition::from(parquet::FieldRepetitionType::REQUIRED),+ Repetition::REQUIRED+ );+ assert_eq!(+ Repetition::from(parquet::FieldRepetitionType::OPTIONAL),+ Repetition::OPTIONAL+ );+ assert_eq!(+ Repetition::from(parquet::FieldRepetitionType::REPEATED),+ Repetition::REPEATED+ );+ }++ #[test]+ fn test_into_repetition() {+ assert_eq!(+ parquet::FieldRepetitionType::REQUIRED,+ Repetition::REQUIRED.into()+ );+ assert_eq!(+ parquet::FieldRepetitionType::OPTIONAL,+ Repetition::OPTIONAL.into()+ );+ assert_eq!(+ parquet::FieldRepetitionType::REPEATED,+ Repetition::REPEATED.into()+ );+ }++ #[test]+ fn test_from_string_into_repetition() {+ assert_eq!(+ Repetition::REQUIRED+ .to_string()+ .parse::<Repetition>()+ .unwrap(),+ Repetition::REQUIRED+ );+ assert_eq!(+ Repetition::OPTIONAL+ .to_string()+ .parse::<Repetition>()+ .unwrap(),+ Repetition::OPTIONAL+ );+ assert_eq!(+ Repetition::REPEATED+ .to_string()+ .parse::<Repetition>()+ .unwrap(),+ Repetition::REPEATED+ );+ }++ #[test]+ fn test_display_encoding() {+ assert_eq!(Encoding::PLAIN.to_string(), "PLAIN");+ assert_eq!(Encoding::PLAIN_DICTIONARY.to_string(), "PLAIN_DICTIONARY");+ assert_eq!(Encoding::RLE.to_string(), "RLE");+ assert_eq!(Encoding::BIT_PACKED.to_string(), "BIT_PACKED");+ assert_eq!(+ Encoding::DELTA_BINARY_PACKED.to_string(),+ "DELTA_BINARY_PACKED"+ );+ assert_eq!(+ Encoding::DELTA_LENGTH_BYTE_ARRAY.to_string(),+ "DELTA_LENGTH_BYTE_ARRAY"+ );+ assert_eq!(Encoding::DELTA_BYTE_ARRAY.to_string(), "DELTA_BYTE_ARRAY");+ assert_eq!(Encoding::RLE_DICTIONARY.to_string(), "RLE_DICTIONARY");+ }++ #[test]+ fn test_from_encoding() {+ assert_eq!(Encoding::from(parquet::Encoding::PLAIN), Encoding::PLAIN);+ assert_eq!(+ Encoding::from(parquet::Encoding::PLAIN_DICTIONARY),+ Encoding::PLAIN_DICTIONARY+ );+ assert_eq!(Encoding::from(parquet::Encoding::RLE), Encoding::RLE);+ assert_eq!(+ Encoding::from(parquet::Encoding::BIT_PACKED),+ Encoding::BIT_PACKED+ );+ assert_eq!(+ Encoding::from(parquet::Encoding::DELTA_BINARY_PACKED),+ Encoding::DELTA_BINARY_PACKED+ );+ assert_eq!(+ Encoding::from(parquet::Encoding::DELTA_LENGTH_BYTE_ARRAY),+ Encoding::DELTA_LENGTH_BYTE_ARRAY+ );+ assert_eq!(+ Encoding::from(parquet::Encoding::DELTA_BYTE_ARRAY),+ Encoding::DELTA_BYTE_ARRAY+ );+ }++ #[test]+ fn test_into_encoding() {+ assert_eq!(parquet::Encoding::PLAIN, Encoding::PLAIN.into());+ assert_eq!(+ parquet::Encoding::PLAIN_DICTIONARY,+ Encoding::PLAIN_DICTIONARY.into()+ );+ assert_eq!(parquet::Encoding::RLE, Encoding::RLE.into());+ assert_eq!(parquet::Encoding::BIT_PACKED, Encoding::BIT_PACKED.into());+ assert_eq!(+ parquet::Encoding::DELTA_BINARY_PACKED,+ Encoding::DELTA_BINARY_PACKED.into()+ );+ assert_eq!(+ parquet::Encoding::DELTA_LENGTH_BYTE_ARRAY,+ Encoding::DELTA_LENGTH_BYTE_ARRAY.into()+ );+ assert_eq!(+ parquet::Encoding::DELTA_BYTE_ARRAY,+ Encoding::DELTA_BYTE_ARRAY.into()+ );+ }++ #[test]+ fn test_display_compression() {+ assert_eq!(Compression::UNCOMPRESSED.to_string(), "UNCOMPRESSED");+ assert_eq!(Compression::SNAPPY.to_string(), "SNAPPY");+ assert_eq!(Compression::GZIP.to_string(), "GZIP");+ assert_eq!(Compression::LZO.to_string(), "LZO");+ assert_eq!(Compression::BROTLI.to_string(), "BROTLI");+ assert_eq!(Compression::LZ4.to_string(), "LZ4");+ assert_eq!(Compression::ZSTD.to_string(), "ZSTD");+ }++ #[test]+ fn test_from_compression() {+ assert_eq!(+ Compression::from(parquet::CompressionCodec::UNCOMPRESSED),+ Compression::UNCOMPRESSED+ );+ assert_eq!(+ Compression::from(parquet::CompressionCodec::SNAPPY),+ Compression::SNAPPY+ );+ assert_eq!(+ Compression::from(parquet::CompressionCodec::GZIP),+ Compression::GZIP+ );+ assert_eq!(+ Compression::from(parquet::CompressionCodec::LZO),+ Compression::LZO+ );+ assert_eq!(+ Compression::from(parquet::CompressionCodec::BROTLI),+ Compression::BROTLI+ );+ assert_eq!(+ Compression::from(parquet::CompressionCodec::LZ4),+ Compression::LZ4+ );+ assert_eq!(+ Compression::from(parquet::CompressionCodec::ZSTD),+ Compression::ZSTD+ );+ }++ #[test]+ fn test_into_compression() {+ assert_eq!(+ parquet::CompressionCodec::UNCOMPRESSED,+ Compression::UNCOMPRESSED.into()+ );+ assert_eq!(+ parquet::CompressionCodec::SNAPPY,+ Compression::SNAPPY.into()+ );+ assert_eq!(parquet::CompressionCodec::GZIP, Compression::GZIP.into());+ assert_eq!(parquet::CompressionCodec::LZO, Compression::LZO.into());+ assert_eq!(+ parquet::CompressionCodec::BROTLI,+ Compression::BROTLI.into()+ );+ assert_eq!(parquet::CompressionCodec::LZ4, Compression::LZ4.into());+ assert_eq!(parquet::CompressionCodec::ZSTD, Compression::ZSTD.into());+ }++ #[test]+ fn test_display_page_type() {+ assert_eq!(PageType::DATA_PAGE.to_string(), "DATA_PAGE");+ assert_eq!(PageType::INDEX_PAGE.to_string(), "INDEX_PAGE");+ assert_eq!(PageType::DICTIONARY_PAGE.to_string(), "DICTIONARY_PAGE");+ assert_eq!(PageType::DATA_PAGE_V2.to_string(), "DATA_PAGE_V2");+ }++ #[test]+ fn test_from_page_type() {+ assert_eq!(+ PageType::from(parquet::PageType::DATA_PAGE),+ PageType::DATA_PAGE+ );+ assert_eq!(+ PageType::from(parquet::PageType::INDEX_PAGE),+ PageType::INDEX_PAGE+ );+ assert_eq!(+ PageType::from(parquet::PageType::DICTIONARY_PAGE),+ PageType::DICTIONARY_PAGE+ );+ assert_eq!(+ PageType::from(parquet::PageType::DATA_PAGE_V2),+ PageType::DATA_PAGE_V2+ );+ }++ #[test]+ fn test_into_page_type() {+ assert_eq!(parquet::PageType::DATA_PAGE, PageType::DATA_PAGE.into());+ assert_eq!(parquet::PageType::INDEX_PAGE, PageType::INDEX_PAGE.into());+ assert_eq!(+ parquet::PageType::DICTIONARY_PAGE,+ PageType::DICTIONARY_PAGE.into()+ );+ assert_eq!(+ parquet::PageType::DATA_PAGE_V2,+ PageType::DATA_PAGE_V2.into()+ );+ }++ #[test]+ fn test_display_sort_order() {+ assert_eq!(SortOrder::SIGNED.to_string(), "SIGNED");+ assert_eq!(SortOrder::UNSIGNED.to_string(), "UNSIGNED");+ assert_eq!(SortOrder::UNDEFINED.to_string(), "UNDEFINED");+ }++ #[test]+ fn test_display_column_order() {+ assert_eq!(+ ColumnOrder::TYPE_DEFINED_ORDER(SortOrder::SIGNED).to_string(),+ "TYPE_DEFINED_ORDER(SIGNED)"+ );+ assert_eq!(+ ColumnOrder::TYPE_DEFINED_ORDER(SortOrder::UNSIGNED).to_string(),+ "TYPE_DEFINED_ORDER(UNSIGNED)"+ );+ assert_eq!(+ ColumnOrder::TYPE_DEFINED_ORDER(SortOrder::UNDEFINED).to_string(),+ "TYPE_DEFINED_ORDER(UNDEFINED)"+ );+ assert_eq!(ColumnOrder::UNDEFINED.to_string(), "UNDEFINED");+ }++ #[test]+ fn test_column_order_get_sort_order() {+ // Helper to check the order in a list of values.+ // Only logical type is checked.+ fn check_sort_order(types: Vec<LogicalType>, expected_order: SortOrder) {+ for tpe in types {+ assert_eq!(+ ColumnOrder::get_sort_order(tpe, Type::BYTE_ARRAY),+ expected_order+ );+ }+ }++ // Unsigned comparison (physical type does not matter)+ let unsigned = vec![+ LogicalType::UTF8,+ LogicalType::JSON,+ LogicalType::BSON,+ LogicalType::ENUM,+ LogicalType::UINT_8,+ LogicalType::UINT_16,+ LogicalType::UINT_32,+ LogicalType::UINT_64,+ LogicalType::INTERVAL,+ ];+ check_sort_order(unsigned, SortOrder::UNSIGNED);++ // Signed comparison (physical type does not matter)+ let signed = vec![+ LogicalType::INT_8,+ LogicalType::INT_16,+ LogicalType::INT_32,+ LogicalType::INT_64,+ LogicalType::DECIMAL,+ LogicalType::DATE,+ LogicalType::TIME_MILLIS,+ LogicalType::TIME_MICROS,+ LogicalType::TIMESTAMP_MILLIS,+ LogicalType::TIMESTAMP_MICROS,+ ];+ check_sort_order(signed, SortOrder::SIGNED);++ // Undefined comparison+ let undefined = vec![+ LogicalType::LIST,+ LogicalType::MAP,+ LogicalType::MAP_KEY_VALUE,+ ];+ check_sort_order(undefined, SortOrder::UNDEFINED);++ // Check None logical type+ // This should return a sort order for byte array type.+ check_sort_order(vec![LogicalType::NONE], SortOrder::UNSIGNED);+ }++ #[test]+ fn test_column_order_get_default_sort_order() {+ // Comparison based on physical type+ assert_eq!(+ ColumnOrder::get_default_sort_order(Type::BOOLEAN),+ SortOrder::UNSIGNED+ );+ assert_eq!(+ ColumnOrder::get_default_sort_order(Type::INT32),+ SortOrder::SIGNED+ );+ assert_eq!(+ ColumnOrder::get_default_sort_order(Type::INT64),+ SortOrder::SIGNED+ );+ assert_eq!(+ ColumnOrder::get_default_sort_order(Type::INT96),+ SortOrder::UNDEFINED+ );+ assert_eq!(+ ColumnOrder::get_default_sort_order(Type::FLOAT),+ SortOrder::SIGNED+ );+ assert_eq!(+ ColumnOrder::get_default_sort_order(Type::DOUBLE),+ SortOrder::SIGNED+ );+ assert_eq!(+ ColumnOrder::get_default_sort_order(Type::BYTE_ARRAY),+ SortOrder::UNSIGNED+ );+ assert_eq!(+ ColumnOrder::get_default_sort_order(Type::FIXED_LEN_BYTE_ARRAY),+ SortOrder::UNSIGNED+ );+ }++ #[test]+ fn test_column_order_sort_order() {+ assert_eq!(+ ColumnOrder::TYPE_DEFINED_ORDER(SortOrder::SIGNED).sort_order(),+ SortOrder::SIGNED+ );+ assert_eq!(+ ColumnOrder::TYPE_DEFINED_ORDER(SortOrder::UNSIGNED).sort_order(),+ SortOrder::UNSIGNED+ );+ assert_eq!(+ ColumnOrder::TYPE_DEFINED_ORDER(SortOrder::UNDEFINED).sort_order(),+ SortOrder::UNDEFINED+ );+ assert_eq!(ColumnOrder::UNDEFINED.sort_order(), SortOrder::SIGNED);+ }+}diff --git a/rust/src/parquet/column/mod.rs b/rust/src/parquet/column/mod.rsnew file mode 100644index 0000000000..09c4bde51f--- /dev/null+++ b/rust/src/parquet/column/mod.rs@@ -0,0 +1,124 @@+// 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.++//! Low level column reader and writer APIs.+//!+//! This API is designed for reading and writing column values, definition and repetition+//! levels directly.+//!+//! # Example of writing and reading data+//!+//! Data has the following format:+//! ```text+//! +---------------++//! | values|+//! +---------------++//! |[1, 2] |+//! |[3, null, null]|+//! +---------------++//! ```+//!+//! The example uses column writer and reader APIs to write raw values, definition and+//! repetition levels and read them to verify write/read correctness.+//!+//! ```rust+//! use std::{fs, path::Path, rc::Rc};+//!+//! use arrow::parquet::{+//! column::{reader::ColumnReader, writer::ColumnWriter},+//! file::{+//! properties::WriterProperties,+//! reader::{FileReader, SerializedFileReader},+//! writer::{FileWriter, SerializedFileWriter},+//! },+//! schema::parser::parse_message_type,+//! };+//!+//! let path = Path::new("target/debug/examples/column_sample.parquet");+//!+//! // Writing data using column writer API.+//!+//! let message_type = "+//! message schema {+//! optional group values (LIST) {+//! repeated group list {+//! optional INT32 element;+//! }+//! }+//! }+//! ";+//! let schema = Rc::new(parse_message_type(message_type).unwrap());+//! let props = Rc::new(WriterProperties::builder().build());+//! let file = fs::File::create(path).unwrap();+//! let mut writer = SerializedFileWriter::new(file, schema, props).unwrap();+//! let mut row_group_writer = writer.next_row_group().unwrap();+//! while let Some(mut col_writer) = row_group_writer.next_column().unwrap() {+//! match col_writer {+//! // You can also use `get_typed_column_writer` method to extract typed writer.+//! ColumnWriter::Int32ColumnWriter(ref mut typed_writer) => {+//! typed_writer+//! .write_batch(&[1, 2, 3], Some(&[3, 3, 3, 2, 2]), Some(&[0, 1, 0, 1, 1]))+//! .unwrap();+//! }+//! _ => {}+//! }+//! row_group_writer.close_column(col_writer).unwrap();+//! }+//! writer.close_row_group(row_group_writer).unwrap();+//! writer.close().unwrap();+//!+//! // Reading data using column reader API.+//!+//! let file = fs::File::open(path).unwrap();+//! let reader = SerializedFileReader::new(file).unwrap();+//! let metadata = reader.metadata();+//!+//! let mut res = Ok((0, 0));+//! let mut values = vec![0; 8];+//! let mut def_levels = vec![0; 8];+//! let mut rep_levels = vec![0; 8];+//!+//! for i in 0..metadata.num_row_groups() {+//! let row_group_reader = reader.get_row_group(i).unwrap();+//! let row_group_metadata = metadata.row_group(i);+//!+//! for j in 0..row_group_metadata.num_columns() {+//! let mut column_reader = row_group_reader.get_column_reader(j).unwrap();+//! match column_reader {+//! // You can also use `get_typed_column_reader` method to extract typed reader.+//! ColumnReader::Int32ColumnReader(ref mut typed_reader) => {+//! res = typed_reader.read_batch(+//! 8, // batch size+//! Some(&mut def_levels),+//! Some(&mut rep_levels),+//! &mut values,+//! );+//! }+//! _ => {}+//! }+//! }+//! }+//!+//! assert_eq!(res, Ok((3, 5)));+//! assert_eq!(values, vec![1, 2, 3, 0, 0, 0, 0, 0]);+//! assert_eq!(def_levels, vec![3, 3, 3, 2, 2, 0, 0, 0]);+//! assert_eq!(rep_levels, vec![0, 1, 0, 1, 1, 0, 0, 0]);+//! ```++pub mod page;+pub mod reader;+pub mod writer;diff --git a/rust/src/parquet/column/page.rs b/rust/src/parquet/column/page.rsnew file mode 100644index 0000000000..115037cba0--- /dev/null+++ b/rust/src/parquet/column/page.rs@@ -0,0 +1,296 @@+// 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.++//! Contains Parquet Page definitions and page reader interface.++use crate::parquet::basic::{Encoding, PageType};+use crate::parquet::errors::Result;+use crate::parquet::file::{metadata::ColumnChunkMetaData, statistics::Statistics};+use crate::parquet::util::memory::ByteBufferPtr;++/// Parquet Page definition.+///+/// List of supported pages.+/// These are 1-to-1 mapped from the equivalent Thrift definitions, except `buf` which+/// used to store uncompressed bytes of the page.+pub enum Page {+ DataPage {+ buf: ByteBufferPtr,+ num_values: u32,+ encoding: Encoding,+ def_level_encoding: Encoding,+ rep_level_encoding: Encoding,+ statistics: Option<Statistics>,+ },+ DataPageV2 {+ buf: ByteBufferPtr,+ num_values: u32,+ encoding: Encoding,+ num_nulls: u32,+ num_rows: u32,+ def_levels_byte_len: u32,+ rep_levels_byte_len: u32,+ is_compressed: bool,+ statistics: Option<Statistics>,+ },+ DictionaryPage {+ buf: ByteBufferPtr,+ num_values: u32,+ encoding: Encoding,+ is_sorted: bool,+ },+}++impl Page {+ /// Returns [`PageType`](`::basic::PageType`) for this page.+ pub fn page_type(&self) -> PageType {+ match self {+ &Page::DataPage { .. } => PageType::DATA_PAGE,+ &Page::DataPageV2 { .. } => PageType::DATA_PAGE_V2,+ &Page::DictionaryPage { .. } => PageType::DICTIONARY_PAGE,+ }+ }++ /// Returns internal byte buffer reference for this page.+ pub fn buffer(&self) -> &ByteBufferPtr {+ match self {+ &Page::DataPage { ref buf, .. } => &buf,+ &Page::DataPageV2 { ref buf, .. } => &buf,+ &Page::DictionaryPage { ref buf, .. } => &buf,+ }+ }++ /// Returns number of values in this page.+ pub fn num_values(&self) -> u32 {+ match self {+ &Page::DataPage { num_values, .. } => num_values,+ &Page::DataPageV2 { num_values, .. } => num_values,+ &Page::DictionaryPage { num_values, .. } => num_values,+ }+ }++ /// Returns this page [`Encoding`](`::basic::Encoding`).+ pub fn encoding(&self) -> Encoding {+ match self {+ &Page::DataPage { encoding, .. } => encoding,+ &Page::DataPageV2 { encoding, .. } => encoding,+ &Page::DictionaryPage { encoding, .. } => encoding,+ }+ }++ /// Returns optional [`Statistics`](`::file::metadata::Statistics`).+ pub fn statistics(&self) -> Option<&Statistics> {+ match self {+ &Page::DataPage { ref statistics, .. } => statistics.as_ref(),+ &Page::DataPageV2 { ref statistics, .. } => statistics.as_ref(),+ &Page::DictionaryPage { .. } => None,+ }+ }+}++/// Helper struct to represent pages with potentially compressed buffer (data page v1) or+/// compressed and concatenated buffer (def levels + rep levels + compressed values for+/// data page v2).+///+/// The difference with `Page` is that `Page` buffer is always uncompressed.+pub struct CompressedPage {+ compressed_page: Page,+ uncompressed_size: usize,+}++impl CompressedPage {+ /// Creates `CompressedPage` from a page with potentially compressed buffer and+ /// uncompressed size.+ pub fn new(compressed_page: Page, uncompressed_size: usize) -> Self {+ Self {+ compressed_page,+ uncompressed_size,+ }+ }++ /// Returns page type.+ pub fn page_type(&self) -> PageType {+ self.compressed_page.page_type()+ }++ /// Returns underlying page with potentially compressed buffer.+ pub fn compressed_page(&self) -> &Page {+ &self.compressed_page+ }++ /// Returns uncompressed size in bytes.+ pub fn uncompressed_size(&self) -> usize {+ self.uncompressed_size+ }++ /// Returns compressed size in bytes.+ ///+ /// Note that it is assumed that buffer is compressed, but it may not be. In this+ /// case compressed size will be equal to uncompressed size.+ pub fn compressed_size(&self) -> usize {+ self.compressed_page.buffer().len()+ }++ /// Number of values in page.+ pub fn num_values(&self) -> u32 {+ self.compressed_page.num_values()+ }++ /// Returns encoding for values in page.+ pub fn encoding(&self) -> Encoding {+ self.compressed_page.encoding()+ }++ /// Returns slice of compressed buffer in the page.+ pub fn data(&self) -> &[u8] {+ self.compressed_page.buffer().data()+ }+}++/// Contains page write metrics.+pub struct PageWriteSpec {+ pub page_type: PageType,+ pub uncompressed_size: usize,+ pub compressed_size: usize,+ pub num_values: u32,+ pub offset: u64,+ pub bytes_written: u64,+}++impl PageWriteSpec {+ /// Creates new spec with default page write metrics.+ pub fn new() -> Self {+ Self {+ page_type: PageType::DATA_PAGE,+ uncompressed_size: 0,+ compressed_size: 0,+ num_values: 0,+ offset: 0,+ bytes_written: 0,+ }+ }+}++/// API for reading pages from a column chunk.+/// This offers a iterator like API to get the next page.+pub trait PageReader {+ /// Gets the next page in the column chunk associated with this reader.+ /// Returns `None` if there are no pages left.+ fn get_next_page(&mut self) -> Result<Option<Page>>;+}++/// API for writing pages in a column chunk.+///+/// It is reasonable to assume that all pages will be written in the correct order, e.g.+/// dictionary page followed by data pages, or a set of data pages, etc.+pub trait PageWriter {+ /// Writes a page into the output stream/sink.+ /// Returns `PageWriteSpec` that contains information about written page metrics,+ /// including number of bytes, size, number of values, offset, etc.+ ///+ /// This method is called for every compressed page we write into underlying buffer,+ /// either data page or dictionary page.+ fn write_page(&mut self, page: CompressedPage) -> Result<PageWriteSpec>;++ /// Writes column chunk metadata into the output stream/sink.+ ///+ /// This method is called once before page writer is closed, normally when writes are+ /// finalised in column writer.+ fn write_metadata(&mut self, metadata: &ColumnChunkMetaData) -> Result<()>;++ /// Closes resources and flushes underlying sink.+ /// Page writer should not be used after this method is called.+ fn close(&mut self) -> Result<()>;+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_page() {+ let data_page = Page::DataPage {+ buf: ByteBufferPtr::new(vec![0, 1, 2]),+ num_values: 10,+ encoding: Encoding::PLAIN,+ def_level_encoding: Encoding::RLE,+ rep_level_encoding: Encoding::RLE,+ statistics: Some(Statistics::int32(Some(1), Some(2), None, 1, true)),+ };+ assert_eq!(data_page.page_type(), PageType::DATA_PAGE);+ assert_eq!(data_page.buffer().data(), vec![0, 1, 2].as_slice());+ assert_eq!(data_page.num_values(), 10);+ assert_eq!(data_page.encoding(), Encoding::PLAIN);+ assert_eq!(+ data_page.statistics(),+ Some(&Statistics::int32(Some(1), Some(2), None, 1, true))+ );++ let data_page_v2 = Page::DataPageV2 {+ buf: ByteBufferPtr::new(vec![0, 1, 2]),+ num_values: 10,+ encoding: Encoding::PLAIN,+ num_nulls: 5,+ num_rows: 20,+ def_levels_byte_len: 30,+ rep_levels_byte_len: 40,+ is_compressed: false,+ statistics: Some(Statistics::int32(Some(1), Some(2), None, 1, true)),+ };+ assert_eq!(data_page_v2.page_type(), PageType::DATA_PAGE_V2);+ assert_eq!(data_page_v2.buffer().data(), vec![0, 1, 2].as_slice());+ assert_eq!(data_page_v2.num_values(), 10);+ assert_eq!(data_page_v2.encoding(), Encoding::PLAIN);+ assert_eq!(+ data_page_v2.statistics(),+ Some(&Statistics::int32(Some(1), Some(2), None, 1, true))+ );++ let dict_page = Page::DictionaryPage {+ buf: ByteBufferPtr::new(vec![0, 1, 2]),+ num_values: 10,+ encoding: Encoding::PLAIN,+ is_sorted: false,+ };+ assert_eq!(dict_page.page_type(), PageType::DICTIONARY_PAGE);+ assert_eq!(dict_page.buffer().data(), vec![0, 1, 2].as_slice());+ assert_eq!(dict_page.num_values(), 10);+ assert_eq!(dict_page.encoding(), Encoding::PLAIN);+ assert_eq!(dict_page.statistics(), None);+ }++ #[test]+ fn test_compressed_page() {+ let data_page = Page::DataPage {+ buf: ByteBufferPtr::new(vec![0, 1, 2]),+ num_values: 10,+ encoding: Encoding::PLAIN,+ def_level_encoding: Encoding::RLE,+ rep_level_encoding: Encoding::RLE,+ statistics: Some(Statistics::int32(Some(1), Some(2), None, 1, true)),+ };++ let cpage = CompressedPage::new(data_page, 5);++ assert_eq!(cpage.page_type(), PageType::DATA_PAGE);+ assert_eq!(cpage.uncompressed_size(), 5);+ assert_eq!(cpage.compressed_size(), 3);+ assert_eq!(cpage.num_values(), 10);+ assert_eq!(cpage.encoding(), Encoding::PLAIN);+ assert_eq!(cpage.data(), &[0, 1, 2]);+ }+}diff --git a/rust/src/parquet/column/reader.rs b/rust/src/parquet/column/reader.rsnew file mode 100644index 0000000000..f3dde31ab9--- /dev/null+++ b/rust/src/parquet/column/reader.rs@@ -0,0 +1,1576 @@+// 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.++//! Contains column reader API.++use std::{+ cmp::{max, min},+ collections::HashMap,+ mem,+};++use super::page::{Page, PageReader};+use crate::parquet::basic::*;+use crate::parquet::data_type::*;+use crate::parquet::encodings::{+ decoding::{get_decoder, Decoder, DictDecoder, PlainDecoder},+ levels::LevelDecoder,+};+use crate::parquet::errors::{ParquetError, Result};+use crate::parquet::schema::types::ColumnDescPtr;+use crate::parquet::util::memory::ByteBufferPtr;++/// Column reader for a Parquet type.+pub enum ColumnReader {+ BoolColumnReader(ColumnReaderImpl<BoolType>),+ Int32ColumnReader(ColumnReaderImpl<Int32Type>),+ Int64ColumnReader(ColumnReaderImpl<Int64Type>),+ Int96ColumnReader(ColumnReaderImpl<Int96Type>),+ FloatColumnReader(ColumnReaderImpl<FloatType>),+ DoubleColumnReader(ColumnReaderImpl<DoubleType>),+ ByteArrayColumnReader(ColumnReaderImpl<ByteArrayType>),+ FixedLenByteArrayColumnReader(ColumnReaderImpl<FixedLenByteArrayType>),+}++/// Gets a specific column reader corresponding to column descriptor `col_descr`. The+/// column reader will read from pages in `col_page_reader`.+pub fn get_column_reader(+ col_descr: ColumnDescPtr,+ col_page_reader: Box<PageReader>,+) -> ColumnReader {+ match col_descr.physical_type() {+ Type::BOOLEAN => {+ ColumnReader::BoolColumnReader(ColumnReaderImpl::new(col_descr, col_page_reader))+ }+ Type::INT32 => {+ ColumnReader::Int32ColumnReader(ColumnReaderImpl::new(col_descr, col_page_reader))+ }+ Type::INT64 => {+ ColumnReader::Int64ColumnReader(ColumnReaderImpl::new(col_descr, col_page_reader))+ }+ Type::INT96 => {+ ColumnReader::Int96ColumnReader(ColumnReaderImpl::new(col_descr, col_page_reader))+ }+ Type::FLOAT => {+ ColumnReader::FloatColumnReader(ColumnReaderImpl::new(col_descr, col_page_reader))+ }+ Type::DOUBLE => {+ ColumnReader::DoubleColumnReader(ColumnReaderImpl::new(col_descr, col_page_reader))+ }+ Type::BYTE_ARRAY => {+ ColumnReader::ByteArrayColumnReader(ColumnReaderImpl::new(col_descr, col_page_reader))+ }+ Type::FIXED_LEN_BYTE_ARRAY => ColumnReader::FixedLenByteArrayColumnReader(+ ColumnReaderImpl::new(col_descr, col_page_reader),+ ),+ }+}++/// Gets a typed column reader for the specific type `T`, by "up-casting" `col_reader` of+/// non-generic type to a generic column reader type `ColumnReaderImpl`.+///+/// NOTE: the caller MUST guarantee that the actual enum value for `col_reader` matches+/// the type `T`. Otherwise, disastrous consequence could happen.+pub fn get_typed_column_reader<T: DataType>(col_reader: ColumnReader) -> ColumnReaderImpl<T> {+ match col_reader {+ ColumnReader::BoolColumnReader(r) => unsafe { mem::transmute(r) },+ ColumnReader::Int32ColumnReader(r) => unsafe { mem::transmute(r) },+ ColumnReader::Int64ColumnReader(r) => unsafe { mem::transmute(r) },+ ColumnReader::Int96ColumnReader(r) => unsafe { mem::transmute(r) },+ ColumnReader::FloatColumnReader(r) => unsafe { mem::transmute(r) },+ ColumnReader::DoubleColumnReader(r) => unsafe { mem::transmute(r) },+ ColumnReader::ByteArrayColumnReader(r) => unsafe { mem::transmute(r) },+ ColumnReader::FixedLenByteArrayColumnReader(r) => unsafe { mem::transmute(r) },+ }+}++/// Typed value reader for a particular primitive column.+pub struct ColumnReaderImpl<T: DataType> {+ descr: ColumnDescPtr,+ def_level_decoder: Option<LevelDecoder>,+ rep_level_decoder: Option<LevelDecoder>,+ page_reader: Box<PageReader>,+ current_encoding: Option<Encoding>,++ // The total number of values stored in the data page.+ num_buffered_values: u32,++ // The number of values from the current data page that has been decoded into memory+ // so far.+ num_decoded_values: u32,++ // Cache of decoders for existing encodings+ decoders: HashMap<Encoding, Box<Decoder<T>>>,+}++impl<T: DataType> ColumnReaderImpl<T> {+ /// Creates new column reader based on column descriptor and page reader.+ pub fn new(descr: ColumnDescPtr, page_reader: Box<PageReader>) -> Self {+ Self {+ descr,+ def_level_decoder: None,+ rep_level_decoder: None,+ page_reader,+ current_encoding: None,+ num_buffered_values: 0,+ num_decoded_values: 0,+ decoders: HashMap::new(),+ }+ }++ /// Reads a batch of values of at most `batch_size`.+ ///+ /// This will try to read from the row group, and fills up at most `batch_size` values+ /// for `def_levels`, `rep_levels` and `values`. It will stop either when the row group+ /// is depleted or `batch_size` values has been read, or there is no space in the input+ /// slices (values/definition levels/repetition levels).+ ///+ /// Note that in case the field being read is not required, `values` could contain less+ /// values than `def_levels`. Also note that this will skip reading def / rep levels if+ /// the field is required / not repeated, respectively.+ ///+ /// If `def_levels` or `rep_levels` is `None`, this will also skip reading the+ /// respective levels. This is useful when the caller of this function knows in advance+ /// that the field is required and non-repeated, therefore can avoid allocating memory+ /// for the levels data. Note that if field has definition levels, but caller provides+ /// None, there might be inconsistency between levels/values (see comments below).+ ///+ /// Returns a tuple where the first element is the actual number of values read,+ /// and the second element is the actual number of levels read.+ #[inline]+ pub fn read_batch(+ &mut self,+ batch_size: usize,+ mut def_levels: Option<&mut [i16]>,+ mut rep_levels: Option<&mut [i16]>,+ values: &mut [T::T],+ ) -> Result<(usize, usize)> {+ let mut values_read = 0;+ let mut levels_read = 0;++ // Compute the smallest batch size we can read based on provided slices+ let mut batch_size = min(batch_size, values.len());+ if let Some(ref levels) = def_levels {+ batch_size = min(batch_size, levels.len());+ }+ if let Some(ref levels) = rep_levels {+ batch_size = min(batch_size, levels.len());+ }++ // Read exhaustively all pages until we read all batch_size values/levels+ // or there are no more values/levels to read.+ while max(values_read, levels_read) < batch_size {+ if !self.has_next()? {+ break;+ }++ // Batch size for the current iteration+ let iter_batch_size = {+ // Compute approximate value based on values decoded so far+ let mut adjusted_size = min(+ batch_size,+ (self.num_buffered_values - self.num_decoded_values) as usize,+ );++ // Adjust batch size by taking into account how much space is left in values+ // slice or levels slices (if available)+ adjusted_size = min(adjusted_size, values.len() - values_read);+ if let Some(ref levels) = def_levels {+ adjusted_size = min(adjusted_size, levels.len() - levels_read);+ }+ if let Some(ref levels) = rep_levels {+ adjusted_size = min(adjusted_size, levels.len() - levels_read);+ }++ adjusted_size+ };++ let mut values_to_read = 0;+ let mut num_def_levels = 0;+ let mut num_rep_levels = 0;++ // If the field is required and non-repeated, there are no definition levels+ if self.descr.max_def_level() > 0 && def_levels.as_ref().is_some() {+ if let Some(ref mut levels) = def_levels {+ num_def_levels = self+ .read_def_levels(&mut levels[levels_read..levels_read + iter_batch_size])?;+ for i in levels_read..levels_read + num_def_levels {+ if levels[i] == self.descr.max_def_level() {+ values_to_read += 1;+ }+ }+ }+ } else {+ // If max definition level == 0, then it is REQUIRED field, read all values.+ // If definition levels are not provided, we still read all values.+ values_to_read = iter_batch_size;+ }++ if self.descr.max_rep_level() > 0 && rep_levels.is_some() {+ if let Some(ref mut levels) = rep_levels {+ num_rep_levels = self+ .read_rep_levels(&mut levels[levels_read..levels_read + iter_batch_size])?;++ // If definition levels are defined, check that rep levels == def levels+ if def_levels.is_some() {+ assert_eq!(+ num_def_levels, num_rep_levels,+ "Number of decoded rep / def levels did not match"+ );+ }+ }+ }++ // At this point we have read values, definition and repetition levels.+ // If both definition and repetition levels are defined, their counts+ // should be equal. Values count is always less or equal to definition levels.+ //+ // Note that if field is not required, but no definition levels are provided,+ // we would read values of batch size and (if provided, of course) repetition+ // levels of batch size - [!] they will not be synced, because only definition+ // levels enforce number of non-null values to read.++ let curr_values_read =+ self.read_values(&mut values[values_read..values_read + values_to_read])?;++ // Update all "return" counters and internal state.++ // This is to account for when def or rep levels are not provided+ let curr_levels_read = max(num_def_levels, num_rep_levels);+ self.num_decoded_values += max(curr_levels_read, curr_values_read) as u32;+ levels_read += curr_levels_read;+ values_read += curr_values_read;+ }++ Ok((values_read, levels_read))+ }++ /// Reads a new page and set up the decoders for levels, values or dictionary.+ /// Returns false if there's no page left.+ fn read_new_page(&mut self) -> Result<bool> {+ #[allow(while_true)]+ while true {+ match self.page_reader.get_next_page()? {+ // No more page to read+ None => return Ok(false),+ Some(current_page) => {+ match current_page {+ // 1. Dictionary page: configure dictionary for this page.+ p @ Page::DictionaryPage { .. } => {+ self.configure_dictionary(p)?;+ continue;+ }+ // 2. Data page v1+ Page::DataPage {+ buf,+ num_values,+ encoding,+ def_level_encoding,+ rep_level_encoding,+ statistics: _,+ } => {+ self.num_buffered_values = num_values;+ self.num_decoded_values = 0;++ let mut buffer_ptr = buf;++ if self.descr.max_rep_level() > 0 {+ let mut rep_decoder = LevelDecoder::v1(+ rep_level_encoding,+ self.descr.max_rep_level(),+ );+ let total_bytes = rep_decoder+ .set_data(self.num_buffered_values as usize, buffer_ptr.all());+ buffer_ptr = buffer_ptr.start_from(total_bytes);+ self.rep_level_decoder = Some(rep_decoder);+ }++ if self.descr.max_def_level() > 0 {+ let mut def_decoder = LevelDecoder::v1(+ def_level_encoding,+ self.descr.max_def_level(),+ );+ let total_bytes = def_decoder+ .set_data(self.num_buffered_values as usize, buffer_ptr.all());+ buffer_ptr = buffer_ptr.start_from(total_bytes);+ self.def_level_decoder = Some(def_decoder);+ }++ // Data page v1 does not have offset, all content of buffer should be passed+ self.set_current_page_encoding(+ encoding,+ &buffer_ptr,+ 0,+ num_values as usize,+ )?;+ return Ok(true);+ }+ // 3. Data page v2+ Page::DataPageV2 {+ buf,+ num_values,+ encoding,+ num_nulls: _,+ num_rows: _,+ def_levels_byte_len,+ rep_levels_byte_len,+ is_compressed: _,+ statistics: _,+ } => {+ self.num_buffered_values = num_values;+ self.num_decoded_values = 0;++ let mut offset = 0;++ // DataPage v2 only supports RLE encoding for repetition levels+ if self.descr.max_rep_level() > 0 {+ let mut rep_decoder = LevelDecoder::v2(self.descr.max_rep_level());+ let bytes_read = rep_decoder.set_data_range(+ self.num_buffered_values as usize,+ &buf,+ offset,+ rep_levels_byte_len as usize,+ );+ offset += bytes_read;+ self.rep_level_decoder = Some(rep_decoder);+ }++ // DataPage v2 only supports RLE encoding for definition levels+ if self.descr.max_def_level() > 0 {+ let mut def_decoder = LevelDecoder::v2(self.descr.max_def_level());+ let bytes_read = def_decoder.set_data_range(+ self.num_buffered_values as usize,+ &buf,+ offset,+ def_levels_byte_len as usize,+ );+ offset += bytes_read;+ self.def_level_decoder = Some(def_decoder);+ }++ self.set_current_page_encoding(+ encoding,+ &buf,+ offset,+ num_values as usize,+ )?;+ return Ok(true);+ }+ };+ }+ }+ }++ Ok(true)+ }++ /// Resolves and updates encoding and set decoder for the current page+ fn set_current_page_encoding(+ &mut self,+ mut encoding: Encoding,+ buffer_ptr: &ByteBufferPtr,+ offset: usize,+ len: usize,+ ) -> Result<()> {+ if encoding == Encoding::PLAIN_DICTIONARY {+ encoding = Encoding::RLE_DICTIONARY;+ }++ let decoder = if encoding == Encoding::RLE_DICTIONARY {+ self.decoders+ .get_mut(&encoding)+ .expect("Decoder for dict should have been set")+ } else {+ // Search cache for data page decoder+ if !self.decoders.contains_key(&encoding) {+ // Initialize decoder for this page+ let data_decoder = get_decoder::<T>(self.descr.clone(), encoding)?;+ self.decoders.insert(encoding, data_decoder);+ }+ self.decoders.get_mut(&encoding).unwrap()+ };++ decoder.set_data(buffer_ptr.start_from(offset), len as usize)?;+ self.current_encoding = Some(encoding);+ Ok(())+ }++ #[inline]+ fn has_next(&mut self) -> Result<bool> {+ if self.num_buffered_values == 0 || self.num_buffered_values == self.num_decoded_values {+ // TODO: should we return false if read_new_page() = true and+ // num_buffered_values = 0?+ if !self.read_new_page()? {+ Ok(false)+ } else {+ Ok(self.num_buffered_values != 0)+ }+ } else {+ Ok(true)+ }+ }++ #[inline]+ fn read_rep_levels(&mut self, buffer: &mut [i16]) -> Result<usize> {+ let level_decoder = self+ .rep_level_decoder+ .as_mut()+ .expect("rep_level_decoder be set");+ level_decoder.get(buffer)+ }++ #[inline]+ fn read_def_levels(&mut self, buffer: &mut [i16]) -> Result<usize> {+ let level_decoder = self+ .def_level_decoder+ .as_mut()+ .expect("def_level_decoder be set");+ level_decoder.get(buffer)+ }++ #[inline]+ fn read_values(&mut self, buffer: &mut [T::T]) -> Result<usize> {+ let encoding = self+ .current_encoding+ .expect("current_encoding should be set");+ let current_decoder = self+ .decoders+ .get_mut(&encoding)+ .expect(format!("decoder for encoding {} should be set", encoding).as_str());+ current_decoder.get(buffer)+ }++ #[inline]+ fn configure_dictionary(&mut self, page: Page) -> Result<bool> {+ let mut encoding = page.encoding();+ if encoding == Encoding::PLAIN || encoding == Encoding::PLAIN_DICTIONARY {+ encoding = Encoding::RLE_DICTIONARY+ }++ if self.decoders.contains_key(&encoding) {+ return Err(general_err!("Column cannot have more than one dictionary"));+ }++ if encoding == Encoding::RLE_DICTIONARY {+ let mut dictionary = PlainDecoder::<T>::new(self.descr.type_length());+ let num_values = page.num_values();+ dictionary.set_data(page.buffer().clone(), num_values as usize)?;++ let mut decoder = DictDecoder::new();+ decoder.set_dict(Box::new(dictionary))?;+ self.decoders.insert(encoding, Box::new(decoder));+ Ok(true)+ } else {+ Err(nyi_err!(+ "Invalid/Unsupported encoding type for dictionary: {}",+ encoding+ ))+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ use rand::distributions::range::SampleRange;+ use std::{collections::VecDeque, rc::Rc, vec::IntoIter};++ use crate::parquet::basic::Type as PhysicalType;+ use crate::parquet::column::page::Page;+ use crate::parquet::encodings::{+ encoding::{get_encoder, DictEncoder, Encoder},+ levels::{max_buffer_size, LevelEncoder},+ };+ use crate::parquet::schema::types::{ColumnDescriptor, ColumnPath, Type as SchemaType};+ use crate::parquet::util::{+ memory::{ByteBufferPtr, MemTracker, MemTrackerPtr},+ test_common::random_numbers_range,+ };++ const NUM_LEVELS: usize = 128;+ const NUM_PAGES: usize = 2;+ const MAX_DEF_LEVEL: i16 = 5;+ const MAX_REP_LEVEL: i16 = 5;++ // Macro to generate test cases+ macro_rules! test {+ // branch for generating i32 cases+ ($test_func:ident, i32, $func:ident, $def_level:expr, $rep_level:expr,+ $num_pages:expr, $num_levels:expr, $batch_size:expr, $min:expr, $max:expr) => {+ test_internal!(+ $test_func,+ Int32Type,+ get_test_int32_type,+ $func,+ $def_level,+ $rep_level,+ $num_pages,+ $num_levels,+ $batch_size,+ $min,+ $max+ );+ };+ // branch for generating i64 cases+ ($test_func:ident, i64, $func:ident, $def_level:expr, $rep_level:expr,+ $num_pages:expr, $num_levels:expr, $batch_size:expr, $min:expr, $max:expr) => {+ test_internal!(+ $test_func,+ Int64Type,+ get_test_int64_type,+ $func,+ $def_level,+ $rep_level,+ $num_pages,+ $num_levels,+ $batch_size,+ $min,+ $max+ );+ };+ }++ macro_rules! test_internal {+ ($test_func:ident, $ty:ident, $pty:ident, $func:ident, $def_level:expr,+ $rep_level:expr, $num_pages:expr, $num_levels:expr, $batch_size:expr,+ $min:expr, $max:expr) => {+ #[test]+ fn $test_func() {+ let desc = Rc::new(ColumnDescriptor::new(+ Rc::new($pty()),+ None,+ $def_level,+ $rep_level,+ ColumnPath::new(Vec::new()),+ ));+ let mut tester = ColumnReaderTester::<$ty>::new();+ tester.$func(desc, $num_pages, $num_levels, $batch_size, $min, $max);+ }+ };+ }++ test!(+ test_read_plain_v1_int32,+ i32,+ plain_v1,+ MAX_DEF_LEVEL,+ MAX_REP_LEVEL,+ NUM_PAGES,+ NUM_LEVELS,+ 16,+ ::std::i32::MIN,+ ::std::i32::MAX+ );+ test!(+ test_read_plain_v2_int32,+ i32,+ plain_v2,+ MAX_DEF_LEVEL,+ MAX_REP_LEVEL,+ NUM_PAGES,+ NUM_LEVELS,+ 16,+ ::std::i32::MIN,+ ::std::i32::MAX+ );++ test!(+ test_read_plain_v1_int32_uneven,+ i32,+ plain_v1,+ MAX_DEF_LEVEL,+ MAX_REP_LEVEL,+ NUM_PAGES,+ NUM_LEVELS,+ 17,+ ::std::i32::MIN,+ ::std::i32::MAX+ );+ test!(+ test_read_plain_v2_int32_uneven,+ i32,+ plain_v2,+ MAX_DEF_LEVEL,+ MAX_REP_LEVEL,+ NUM_PAGES,+ NUM_LEVELS,+ 17,+ ::std::i32::MIN,+ ::std::i32::MAX+ );++ test!(+ test_read_plain_v1_int32_multi_page,+ i32,+ plain_v1,+ MAX_DEF_LEVEL,+ MAX_REP_LEVEL,+ NUM_PAGES,+ NUM_LEVELS,+ 512,+ ::std::i32::MIN,+ ::std::i32::MAX+ );+ test!(+ test_read_plain_v2_int32_multi_page,+ i32,+ plain_v2,+ MAX_DEF_LEVEL,+ MAX_REP_LEVEL,+ NUM_PAGES,+ NUM_LEVELS,+ 512,+ ::std::i32::MIN,+ ::std::i32::MAX+ );++ // test cases when column descriptor has MAX_DEF_LEVEL = 0 and MAX_REP_LEVEL = 0+ test!(+ test_read_plain_v1_int32_required_non_repeated,+ i32,+ plain_v1,+ 0,+ 0,+ NUM_PAGES,+ NUM_LEVELS,+ 16,+ ::std::i32::MIN,+ ::std::i32::MAX+ );+ test!(+ test_read_plain_v2_int32_required_non_repeated,+ i32,+ plain_v2,+ 0,+ 0,+ NUM_PAGES,+ NUM_LEVELS,+ 16,+ ::std::i32::MIN,+ ::std::i32::MAX+ );++ test!(+ test_read_plain_v1_int64,+ i64,+ plain_v1,+ 1,+ 1,+ NUM_PAGES,+ NUM_LEVELS,+ 16,+ ::std::i64::MIN,+ ::std::i64::MAX+ );+ test!(+ test_read_plain_v2_int64,+ i64,+ plain_v2,+ 1,+ 1,+ NUM_PAGES,+ NUM_LEVELS,+ 16,+ ::std::i64::MIN,+ ::std::i64::MAX+ );++ test!(+ test_read_plain_v1_int64_uneven,+ i64,+ plain_v1,+ 1,+ 1,+ NUM_PAGES,+ NUM_LEVELS,+ 17,+ ::std::i64::MIN,+ ::std::i64::MAX+ );+ test!(+ test_read_plain_v2_int64_uneven,+ i64,+ plain_v2,+ 1,+ 1,+ NUM_PAGES,+ NUM_LEVELS,+ 17,+ ::std::i64::MIN,+ ::std::i64::MAX+ );++ test!(+ test_read_plain_v1_int64_multi_page,+ i64,+ plain_v1,+ 1,+ 1,+ NUM_PAGES,+ NUM_LEVELS,+ 512,+ ::std::i64::MIN,+ ::std::i64::MAX+ );+ test!(+ test_read_plain_v2_int64_multi_page,+ i64,+ plain_v2,+ 1,+ 1,+ NUM_PAGES,+ NUM_LEVELS,+ 512,+ ::std::i64::MIN,+ ::std::i64::MAX+ );++ // test cases when column descriptor has MAX_DEF_LEVEL = 0 and MAX_REP_LEVEL = 0+ test!(+ test_read_plain_v1_int64_required_non_repeated,+ i64,+ plain_v1,+ 0,+ 0,+ NUM_PAGES,+ NUM_LEVELS,+ 16,+ ::std::i64::MIN,+ ::std::i64::MAX+ );+ test!(+ test_read_plain_v2_int64_required_non_repeated,+ i64,+ plain_v2,+ 0,+ 0,+ NUM_PAGES,+ NUM_LEVELS,+ 16,+ ::std::i64::MIN,+ ::std::i64::MAX+ );++ test!(+ test_read_dict_v1_int32_small,+ i32,+ dict_v1,+ MAX_DEF_LEVEL,+ MAX_REP_LEVEL,+ 2,+ 2,+ 16,+ 0,+ 3+ );+ test!(+ test_read_dict_v2_int32_small,+ i32,+ dict_v2,+ MAX_DEF_LEVEL,+ MAX_REP_LEVEL,+ 2,+ 2,+ 16,+ 0,+ 3+ );++ test!(+ test_read_dict_v1_int32,+ i32,+ dict_v1,+ MAX_DEF_LEVEL,+ MAX_REP_LEVEL,+ NUM_PAGES,+ NUM_LEVELS,+ 16,+ 0,+ 3+ );+ test!(+ test_read_dict_v2_int32,+ i32,+ dict_v2,+ MAX_DEF_LEVEL,+ MAX_REP_LEVEL,+ NUM_PAGES,+ NUM_LEVELS,+ 16,+ 0,+ 3+ );++ test!(+ test_read_dict_v1_int32_uneven,+ i32,+ dict_v1,+ MAX_DEF_LEVEL,+ MAX_REP_LEVEL,+ NUM_PAGES,+ NUM_LEVELS,+ 17,+ 0,+ 3+ );+ test!(+ test_read_dict_v2_int32_uneven,+ i32,+ dict_v2,+ MAX_DEF_LEVEL,+ MAX_REP_LEVEL,+ NUM_PAGES,+ NUM_LEVELS,+ 17,+ 0,+ 3+ );++ test!(+ test_read_dict_v1_int32_multi_page,+ i32,+ dict_v1,+ MAX_DEF_LEVEL,+ MAX_REP_LEVEL,+ NUM_PAGES,+ NUM_LEVELS,+ 512,+ 0,+ 3+ );+ test!(+ test_read_dict_v2_int32_multi_page,+ i32,+ dict_v2,+ MAX_DEF_LEVEL,+ MAX_REP_LEVEL,+ NUM_PAGES,+ NUM_LEVELS,+ 512,+ 0,+ 3+ );++ test!(+ test_read_dict_v1_int64,+ i64,+ dict_v1,+ MAX_DEF_LEVEL,+ MAX_REP_LEVEL,+ NUM_PAGES,+ NUM_LEVELS,+ 16,+ 0,+ 3+ );+ test!(+ test_read_dict_v2_int64,+ i64,+ dict_v2,+ MAX_DEF_LEVEL,+ MAX_REP_LEVEL,+ NUM_PAGES,+ NUM_LEVELS,+ 16,+ 0,+ 3+ );++ #[test]+ fn test_read_batch_values_only() {+ test_read_batch_int32(16, &mut vec![0; 10], None, None); // < batch_size+ test_read_batch_int32(16, &mut vec![0; 16], None, None); // == batch_size+ test_read_batch_int32(16, &mut vec![0; 51], None, None); // > batch_size+ }++ #[test]+ fn test_read_batch_values_def_levels() {+ test_read_batch_int32(16, &mut vec![0; 10], Some(&mut vec![0; 10]), None);+ test_read_batch_int32(16, &mut vec![0; 16], Some(&mut vec![0; 16]), None);+ test_read_batch_int32(16, &mut vec![0; 51], Some(&mut vec![0; 51]), None);+ }++ #[test]+ fn test_read_batch_values_rep_levels() {+ test_read_batch_int32(16, &mut vec![0; 10], None, Some(&mut vec![0; 10]));+ test_read_batch_int32(16, &mut vec![0; 16], None, Some(&mut vec![0; 16]));+ test_read_batch_int32(16, &mut vec![0; 51], None, Some(&mut vec![0; 51]));+ }++ #[test]+ fn test_read_batch_different_buf_sizes() {+ test_read_batch_int32(+ 16,+ &mut vec![0; 8],+ Some(&mut vec![0; 9]),+ Some(&mut vec![0; 7]),+ );+ test_read_batch_int32(+ 16,+ &mut vec![0; 1],+ Some(&mut vec![0; 9]),+ Some(&mut vec![0; 3]),+ );+ }++ #[test]+ fn test_read_batch_values_def_rep_levels() {+ test_read_batch_int32(+ 128,+ &mut vec![0; 128],+ Some(&mut vec![0; 128]),+ Some(&mut vec![0; 128]),+ );+ }++ #[test]+ fn test_read_batch_adjust_after_buffering_page() {+ // This test covers scenario when buffering new page results in setting number+ // of decoded values to 0, resulting on reading `batch_size` of values, but it is+ // larger than we can insert into slice (affects values and levels).+ //+ // Note: values are chosen to reproduce the issue.+ //+ let primitive_type = get_test_int32_type();+ let desc = Rc::new(ColumnDescriptor::new(+ Rc::new(primitive_type),+ None,+ 1,+ 1,+ ColumnPath::new(Vec::new()),+ ));++ let num_pages = 2;+ let num_levels = 4;+ let batch_size = 5;+ let values = &mut vec![0; 7];+ let def_levels = &mut vec![0; 7];+ let rep_levels = &mut vec![0; 7];++ let mut tester = ColumnReaderTester::<Int32Type>::new();+ tester.test_read_batch(+ desc,+ Encoding::RLE_DICTIONARY,+ num_pages,+ num_levels,+ batch_size,+ ::std::i32::MIN,+ ::std::i32::MAX,+ values,+ Some(def_levels),+ Some(rep_levels),+ false,+ );+ }++ // ----------------------------------------------------------------------+ // Helper methods to make pages and test+ //+ // # Overview+ //+ // Most of the test functionality is implemented in `ColumnReaderTester`, which+ // provides some general data page test methods:+ // - `test_read_batch_general`+ // - `test_read_batch`+ //+ // There are also some high level wrappers that are part of `ColumnReaderTester`:+ // - `plain_v1` -> call `test_read_batch_general` with data page v1 and plain encoding+ // - `plain_v2` -> call `test_read_batch_general` with data page v2 and plain encoding+ // - `dict_v1` -> call `test_read_batch_general` with data page v1 + dictionary page+ // - `dict_v2` -> call `test_read_batch_general` with data page v2 + dictionary page+ //+ // And even higher level wrappers that simplify testing of almost the same test cases:+ // - `get_test_int32_type`, provides dummy schema type+ // - `get_test_int64_type`, provides dummy schema type+ // - `test_read_batch_int32`, wrapper for `read_batch` tests, since they are basically+ // the same, just different def/rep levels and batch size.+ //+ // # Page assembly+ //+ // Page construction and generation of values, definition and repetition levels happens+ // in `make_pages` function.+ // All values are randomly generated based on provided min/max, levels are calculated+ // based on provided max level for column descriptor (which is basically either int32+ // or int64 type in tests) and `levels_per_page` variable.+ //+ // We use `DataPageBuilder` and its implementation `DataPageBuilderImpl` to actually+ // turn values, definition and repetition levels into data pages (either v1 or v2).+ //+ // Those data pages are then stored as part of `TestPageReader` (we just pass vector+ // of generated pages directly), which implements `PageReader` interface.+ //+ // # Comparison+ //+ // This allows us to pass test page reader into column reader, so we can test+ // functionality of column reader - see `test_read_batch`, where we create column+ // reader -> typed column reader, buffer values in `read_batch` method and compare+ // output with generated data.++ // Returns dummy Parquet `Type` for primitive field, because most of our tests use+ // INT32 physical type.+ fn get_test_int32_type() -> SchemaType {+ SchemaType::primitive_type_builder("a", PhysicalType::INT32)+ .with_repetition(Repetition::REQUIRED)+ .with_logical_type(LogicalType::INT_32)+ .with_length(-1)+ .build()+ .expect("build() should be OK")+ }++ // Returns dummy Parquet `Type` for INT64 physical type.+ fn get_test_int64_type() -> SchemaType {+ SchemaType::primitive_type_builder("a", PhysicalType::INT64)+ .with_repetition(Repetition::REQUIRED)+ .with_logical_type(LogicalType::INT_64)+ .with_length(-1)+ .build()+ .expect("build() should be OK")+ }++ // Tests `read_batch()` functionality for INT32.+ //+ // This is a high level wrapper on `ColumnReaderTester` that allows us to specify some+ // boilerplate code for setting up definition/repetition levels and column descriptor.+ fn test_read_batch_int32(+ batch_size: usize,+ values: &mut [i32],+ def_levels: Option<&mut [i16]>,+ rep_levels: Option<&mut [i16]>,+ ) {+ let primitive_type = get_test_int32_type();+ // make field is required based on provided slices of levels+ let max_def_level = if def_levels.is_some() {+ MAX_DEF_LEVEL+ } else {+ 0+ };+ let max_rep_level = if def_levels.is_some() {+ MAX_REP_LEVEL+ } else {+ 0+ };++ let desc = Rc::new(ColumnDescriptor::new(+ Rc::new(primitive_type),+ None,+ max_def_level,+ max_rep_level,+ ColumnPath::new(Vec::new()),+ ));+ let mut tester = ColumnReaderTester::<Int32Type>::new();+ tester.test_read_batch(+ desc,+ Encoding::RLE_DICTIONARY,+ NUM_PAGES,+ NUM_LEVELS,+ batch_size,+ ::std::i32::MIN,+ ::std::i32::MAX,+ values,+ def_levels,+ rep_levels,+ false,+ );+ }++ struct ColumnReaderTester<T: DataType>+ where+ T::T: PartialOrd + SampleRange + Copy,+ {+ rep_levels: Vec<i16>,+ def_levels: Vec<i16>,+ values: Vec<T::T>,+ }++ impl<T: DataType> ColumnReaderTester<T>+ where+ T::T: PartialOrd + SampleRange + Copy,+ {+ pub fn new() -> Self {+ Self {+ rep_levels: Vec::new(),+ def_levels: Vec::new(),+ values: Vec::new(),+ }+ }++ // Method to generate and test data pages v1+ fn plain_v1(+ &mut self,+ desc: ColumnDescPtr,+ num_pages: usize,+ num_levels: usize,+ batch_size: usize,+ min: T::T,+ max: T::T,+ ) {+ self.test_read_batch_general(+ desc,+ Encoding::PLAIN,+ num_pages,+ num_levels,+ batch_size,+ min,+ max,+ false,+ );+ }++ // Method to generate and test data pages v2+ fn plain_v2(+ &mut self,+ desc: ColumnDescPtr,+ num_pages: usize,+ num_levels: usize,+ batch_size: usize,+ min: T::T,+ max: T::T,+ ) {+ self.test_read_batch_general(+ desc,+ Encoding::PLAIN,+ num_pages,+ num_levels,+ batch_size,+ min,+ max,+ true,+ );+ }++ // Method to generate and test dictionary page + data pages v1+ fn dict_v1(+ &mut self,+ desc: ColumnDescPtr,+ num_pages: usize,+ num_levels: usize,+ batch_size: usize,+ min: T::T,+ max: T::T,+ ) {+ self.test_read_batch_general(+ desc,+ Encoding::RLE_DICTIONARY,+ num_pages,+ num_levels,+ batch_size,+ min,+ max,+ false,+ );+ }++ // Method to generate and test dictionary page + data pages v2+ fn dict_v2(+ &mut self,+ desc: ColumnDescPtr,+ num_pages: usize,+ num_levels: usize,+ batch_size: usize,+ min: T::T,+ max: T::T,+ ) {+ self.test_read_batch_general(+ desc,+ Encoding::RLE_DICTIONARY,+ num_pages,+ num_levels,+ batch_size,+ min,+ max,+ true,+ );+ }++ // Helper function for the general case of `read_batch()` where `values`,+ // `def_levels` and `rep_levels` are always provided with enough space.+ fn test_read_batch_general(+ &mut self,+ desc: ColumnDescPtr,+ encoding: Encoding,+ num_pages: usize,+ num_levels: usize,+ batch_size: usize,+ min: T::T,+ max: T::T,+ use_v2: bool,+ ) {+ let mut def_levels = vec![0; num_levels * num_pages];+ let mut rep_levels = vec![0; num_levels * num_pages];+ let mut values = vec![T::T::default(); num_levels * num_pages];+ self.test_read_batch(+ desc,+ encoding,+ num_pages,+ num_levels,+ batch_size,+ min,+ max,+ &mut values,+ Some(&mut def_levels),+ Some(&mut rep_levels),+ use_v2,+ );+ }++ // Helper function to test `read_batch()` method with custom buffers for values,+ // definition and repetition levels.+ fn test_read_batch(+ &mut self,+ desc: ColumnDescPtr,+ encoding: Encoding,+ num_pages: usize,+ num_levels: usize,+ batch_size: usize,+ min: T::T,+ max: T::T,+ values: &mut [T::T],+ mut def_levels: Option<&mut [i16]>,+ mut rep_levels: Option<&mut [i16]>,+ use_v2: bool,+ ) {+ let mut pages = VecDeque::new();+ make_pages::<T>(+ desc.clone(),+ encoding,+ num_pages,+ num_levels,+ min,+ max,+ &mut self.def_levels,+ &mut self.rep_levels,+ &mut self.values,+ &mut pages,+ use_v2,+ );+ let max_def_level = desc.max_def_level();+ let page_reader = TestPageReader::new(Vec::from(pages));+ let column_reader: ColumnReader = get_column_reader(desc, Box::new(page_reader));+ let mut typed_column_reader = get_typed_column_reader::<T>(column_reader);++ let mut curr_values_read = 0;+ let mut curr_levels_read = 0;+ let mut done = false;+ while !done {+ let actual_def_levels = match &mut def_levels {+ Some(ref mut vec) => Some(&mut vec[curr_levels_read..]),+ None => None,+ };+ let actual_rep_levels = match rep_levels {+ Some(ref mut vec) => Some(&mut vec[curr_levels_read..]),+ None => None,+ };++ let (values_read, levels_read) = typed_column_reader+ .read_batch(+ batch_size,+ actual_def_levels,+ actual_rep_levels,+ &mut values[curr_values_read..],+ )+ .expect("read_batch() should be OK");++ if values_read == 0 && levels_read == 0 {+ done = true;+ }++ curr_values_read += values_read;+ curr_levels_read += levels_read;+ }++ assert!(+ values.len() >= curr_values_read,+ "values.len() >= values_read"+ );+ assert_eq!(+ &values[0..curr_values_read],+ &self.values[0..curr_values_read],+ "values content doesn't match"+ );++ if let Some(ref levels) = def_levels {+ assert!(+ levels.len() >= curr_levels_read,+ "def_levels.len() >= levels_read"+ );+ assert_eq!(+ &levels[0..curr_levels_read],+ &self.def_levels[0..curr_levels_read],+ "definition levels content doesn't match"+ );+ }++ if let Some(ref levels) = rep_levels {+ assert!(+ levels.len() >= curr_levels_read,+ "rep_levels.len() >= levels_read"+ );+ assert_eq!(+ &levels[0..curr_levels_read],+ &self.rep_levels[0..curr_levels_read],+ "repetition levels content doesn't match"+ );+ }++ if def_levels.is_none() && rep_levels.is_none() {+ assert!(+ curr_levels_read == 0,+ "expected to read 0 levels, found {}",+ curr_levels_read+ );+ } else if def_levels.is_some() && max_def_level > 0 {+ assert!(+ curr_levels_read >= curr_values_read,+ "expected levels read to be greater than values read"+ );+ }+ }+ }++ struct TestPageReader {+ pages: IntoIter<Page>,+ }++ impl TestPageReader {+ pub fn new(pages: Vec<Page>) -> Self {+ Self {+ pages: pages.into_iter(),+ }+ }+ }++ impl PageReader for TestPageReader {+ fn get_next_page(&mut self) -> Result<Option<Page>> {+ Ok(self.pages.next())+ }+ }++ // ----------------------------------------------------------------------+ // Utility functions for generating testing pages++ trait DataPageBuilder {+ fn add_rep_levels(&mut self, max_level: i16, rep_levels: &[i16]);+ fn add_def_levels(&mut self, max_level: i16, def_levels: &[i16]);+ fn add_values<T: DataType>(&mut self, encoding: Encoding, values: &[T::T]);+ fn add_indices(&mut self, indices: ByteBufferPtr);+ fn consume(self) -> Page;+ }++ /// A utility struct for building data pages (v1 or v2). Callers must call:+ /// - add_rep_levels()+ /// - add_def_levels()+ /// - add_values() for normal data page / add_indices() for dictionary data page+ /// - consume()+ /// in order to populate and obtain a data page.+ struct DataPageBuilderImpl {+ desc: ColumnDescPtr,+ encoding: Option<Encoding>,+ mem_tracker: MemTrackerPtr,+ num_values: u32,+ buffer: Vec<u8>,+ rep_levels_byte_len: u32,+ def_levels_byte_len: u32,+ datapage_v2: bool,+ }++ impl DataPageBuilderImpl {+ // `num_values` is the number of non-null values to put in the data page.+ // `datapage_v2` flag is used to indicate if the generated data page should use V2+ // format or not.+ fn new(desc: ColumnDescPtr, num_values: u32, datapage_v2: bool) -> Self {+ DataPageBuilderImpl {+ desc,+ encoding: None,+ mem_tracker: Rc::new(MemTracker::new()),+ num_values,+ buffer: vec![],+ rep_levels_byte_len: 0,+ def_levels_byte_len: 0,+ datapage_v2,+ }+ }++ // Adds levels to the buffer and return number of encoded bytes+ fn add_levels(&mut self, max_level: i16, levels: &[i16]) -> u32 {+ let size = max_buffer_size(Encoding::RLE, max_level, levels.len());+ let mut level_encoder = LevelEncoder::v1(Encoding::RLE, max_level, vec![0; size]);+ level_encoder.put(levels).expect("put() should be OK");+ let encoded_levels = level_encoder.consume().expect("consume() should be OK");+ // Actual encoded bytes (without length offset)+ let encoded_bytes = &encoded_levels[mem::size_of::<i32>()..];+ if self.datapage_v2 {+ // Level encoder always initializes with offset of i32, where it stores length of+ // encoded data; for data page v2 we explicitly store length, therefore we should+ // skip i32 bytes.+ self.buffer.extend_from_slice(encoded_bytes);+ } else {+ self.buffer.extend_from_slice(encoded_levels.as_slice());+ }+ encoded_bytes.len() as u32+ }+ }++ impl DataPageBuilder for DataPageBuilderImpl {+ fn add_rep_levels(&mut self, max_levels: i16, rep_levels: &[i16]) {+ self.num_values = rep_levels.len() as u32;+ self.rep_levels_byte_len = self.add_levels(max_levels, rep_levels);+ }++ fn add_def_levels(&mut self, max_levels: i16, def_levels: &[i16]) {+ assert!(+ self.num_values == def_levels.len() as u32,+ "Must call `add_rep_levels() first!`"+ );++ self.def_levels_byte_len = self.add_levels(max_levels, def_levels);+ }++ fn add_values<T: DataType>(&mut self, encoding: Encoding, values: &[T::T]) {+ assert!(+ self.num_values >= values.len() as u32,+ "num_values: {}, values.len(): {}",+ self.num_values,+ values.len()+ );+ self.encoding = Some(encoding);+ let mut encoder: Box<Encoder<T>> =+ get_encoder::<T>(self.desc.clone(), encoding, self.mem_tracker.clone())+ .expect("get_encoder() should be OK");+ encoder.put(values).expect("put() should be OK");+ let encoded_values = encoder+ .flush_buffer()+ .expect("consume_buffer() should be OK");+ self.buffer.extend_from_slice(encoded_values.data());+ }++ fn add_indices(&mut self, indices: ByteBufferPtr) {+ self.encoding = Some(Encoding::RLE_DICTIONARY);+ self.buffer.extend_from_slice(indices.data());+ }++ fn consume(self) -> Page {+ if self.datapage_v2 {+ Page::DataPageV2 {+ buf: ByteBufferPtr::new(self.buffer),+ num_values: self.num_values,+ encoding: self.encoding.unwrap(),+ num_nulls: 0, // set to dummy value - don't need this when reading data page+ num_rows: self.num_values, // also don't need this when reading data page+ def_levels_byte_len: self.def_levels_byte_len,+ rep_levels_byte_len: self.rep_levels_byte_len,+ is_compressed: false,+ statistics: None, // set to None, we do not need statistics for tests+ }+ } else {+ Page::DataPage {+ buf: ByteBufferPtr::new(self.buffer),+ num_values: self.num_values,+ encoding: self.encoding.unwrap(),+ def_level_encoding: Encoding::RLE,+ rep_level_encoding: Encoding::RLE,+ statistics: None, // set to None, we do not need statistics for tests+ }+ }+ }+ }++ fn make_pages<T: DataType>(+ desc: ColumnDescPtr,+ encoding: Encoding,+ num_pages: usize,+ levels_per_page: usize,+ min: T::T,+ max: T::T,+ def_levels: &mut Vec<i16>,+ rep_levels: &mut Vec<i16>,+ values: &mut Vec<T::T>,+ pages: &mut VecDeque<Page>,+ use_v2: bool,+ ) where+ T::T: PartialOrd + SampleRange + Copy,+ {+ let mut num_values = 0;+ let max_def_level = desc.max_def_level();+ let max_rep_level = desc.max_rep_level();++ let mem_tracker = Rc::new(MemTracker::new());+ let mut dict_encoder = DictEncoder::<T>::new(desc.clone(), mem_tracker);++ for i in 0..num_pages {+ let mut num_values_cur_page = 0;+ let level_range = i * levels_per_page..(i + 1) * levels_per_page;++ if max_def_level > 0 {+ random_numbers_range(levels_per_page, 0, max_def_level + 1, def_levels);+ for dl in &def_levels[level_range.clone()] {+ if *dl == max_def_level {+ num_values_cur_page += 1;+ }+ }+ } else {+ num_values_cur_page = levels_per_page;+ }+ if max_rep_level > 0 {+ random_numbers_range(levels_per_page, 0, max_rep_level + 1, rep_levels);+ }+ random_numbers_range(num_values_cur_page, min, max, values);++ // Generate the current page++ let mut pb = DataPageBuilderImpl::new(desc.clone(), num_values_cur_page as u32, use_v2);+ if max_rep_level > 0 {+ pb.add_rep_levels(max_rep_level, &rep_levels[level_range.clone()]);+ }+ if max_def_level > 0 {+ pb.add_def_levels(max_def_level, &def_levels[level_range]);+ }++ let value_range = num_values..num_values + num_values_cur_page;+ match encoding {+ Encoding::PLAIN_DICTIONARY | Encoding::RLE_DICTIONARY => {+ let _ = dict_encoder.put(&values[value_range.clone()]);+ let indices = dict_encoder+ .write_indices()+ .expect("write_indices() should be OK");+ pb.add_indices(indices);+ }+ Encoding::PLAIN => {+ pb.add_values::<T>(encoding, &values[value_range]);+ }+ enc @ _ => panic!("Unexpected encoding {}", enc),+ }++ let data_page = pb.consume();+ pages.push_back(data_page);+ num_values += num_values_cur_page;+ }++ if encoding == Encoding::PLAIN_DICTIONARY || encoding == Encoding::RLE_DICTIONARY {+ let dict = dict_encoder+ .write_dict()+ .expect("write_dict() should be OK");+ let dict_page = Page::DictionaryPage {+ buf: dict,+ num_values: dict_encoder.num_entries() as u32,+ encoding: Encoding::RLE_DICTIONARY,+ is_sorted: false,+ };+ pages.push_front(dict_page);+ }+ }+}diff --git a/rust/src/parquet/column/writer.rs b/rust/src/parquet/column/writer.rsnew file mode 100644index 0000000000..4798d9ad17--- /dev/null+++ b/rust/src/parquet/column/writer.rs@@ -0,0 +1,1617 @@+// 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.++//! Contains column writer API.++use std::{cmp, collections::VecDeque, mem, rc::Rc};++use crate::parquet::basic::{Compression, Encoding, PageType, Type};+use crate::parquet::column::page::{CompressedPage, Page, PageWriteSpec, PageWriter};+use crate::parquet::compression::{create_codec, Codec};+use crate::parquet::data_type::*;+use crate::parquet::encodings::{+ encoding::{get_encoder, DictEncoder, Encoder},+ levels::{max_buffer_size, LevelEncoder},+};+use crate::parquet::errors::{ParquetError, Result};+use crate::parquet::file::{+ metadata::ColumnChunkMetaData,+ properties::{WriterProperties, WriterPropertiesPtr, WriterVersion},+};+use crate::parquet::schema::types::ColumnDescPtr;+use crate::parquet::util::memory::{ByteBufferPtr, MemTracker};++/// Column writer for a Parquet type.+pub enum ColumnWriter {+ BoolColumnWriter(ColumnWriterImpl<BoolType>),+ Int32ColumnWriter(ColumnWriterImpl<Int32Type>),+ Int64ColumnWriter(ColumnWriterImpl<Int64Type>),+ Int96ColumnWriter(ColumnWriterImpl<Int96Type>),+ FloatColumnWriter(ColumnWriterImpl<FloatType>),+ DoubleColumnWriter(ColumnWriterImpl<DoubleType>),+ ByteArrayColumnWriter(ColumnWriterImpl<ByteArrayType>),+ FixedLenByteArrayColumnWriter(ColumnWriterImpl<FixedLenByteArrayType>),+}++/// Gets a specific column writer corresponding to column descriptor `descr`.+pub fn get_column_writer(+ descr: ColumnDescPtr,+ props: WriterPropertiesPtr,+ page_writer: Box<PageWriter>,+) -> ColumnWriter {+ match descr.physical_type() {+ Type::BOOLEAN => {+ ColumnWriter::BoolColumnWriter(ColumnWriterImpl::new(descr, props, page_writer))+ }+ Type::INT32 => {+ ColumnWriter::Int32ColumnWriter(ColumnWriterImpl::new(descr, props, page_writer))+ }+ Type::INT64 => {+ ColumnWriter::Int64ColumnWriter(ColumnWriterImpl::new(descr, props, page_writer))+ }+ Type::INT96 => {+ ColumnWriter::Int96ColumnWriter(ColumnWriterImpl::new(descr, props, page_writer))+ }+ Type::FLOAT => {+ ColumnWriter::FloatColumnWriter(ColumnWriterImpl::new(descr, props, page_writer))+ }+ Type::DOUBLE => {+ ColumnWriter::DoubleColumnWriter(ColumnWriterImpl::new(descr, props, page_writer))+ }+ Type::BYTE_ARRAY => {+ ColumnWriter::ByteArrayColumnWriter(ColumnWriterImpl::new(descr, props, page_writer))+ }+ Type::FIXED_LEN_BYTE_ARRAY => ColumnWriter::FixedLenByteArrayColumnWriter(+ ColumnWriterImpl::new(descr, props, page_writer),+ ),+ }+}++/// Gets a typed column writer for the specific type `T`, by "up-casting" `col_writer` of+/// non-generic type to a generic column writer type `ColumnWriterImpl`.+///+/// NOTE: the caller MUST guarantee that the actual enum value for `col_writer` matches+/// the type `T`. Otherwise, disastrous consequence could happen.+pub fn get_typed_column_writer<T: DataType>(col_writer: ColumnWriter) -> ColumnWriterImpl<T> {+ match col_writer {+ ColumnWriter::BoolColumnWriter(r) => unsafe { mem::transmute(r) },+ ColumnWriter::Int32ColumnWriter(r) => unsafe { mem::transmute(r) },+ ColumnWriter::Int64ColumnWriter(r) => unsafe { mem::transmute(r) },+ ColumnWriter::Int96ColumnWriter(r) => unsafe { mem::transmute(r) },+ ColumnWriter::FloatColumnWriter(r) => unsafe { mem::transmute(r) },+ ColumnWriter::DoubleColumnWriter(r) => unsafe { mem::transmute(r) },+ ColumnWriter::ByteArrayColumnWriter(r) => unsafe { mem::transmute(r) },+ ColumnWriter::FixedLenByteArrayColumnWriter(r) => unsafe { mem::transmute(r) },+ }+}++/// Typed column writer for a primitive column.+pub struct ColumnWriterImpl<T: DataType> {+ // Column writer properties+ descr: ColumnDescPtr,+ props: WriterPropertiesPtr,+ page_writer: Box<PageWriter>,+ has_dictionary: bool,+ dict_encoder: Option<DictEncoder<T>>,+ encoder: Box<Encoder<T>>,+ codec: Compression,+ compressor: Option<Box<Codec>>,+ // Metrics per page+ num_buffered_values: u32,+ num_buffered_encoded_values: u32,+ num_buffered_rows: u32,+ // Metrics per column writer+ total_bytes_written: u64,+ total_rows_written: u64,+ total_uncompressed_size: u64,+ total_compressed_size: u64,+ total_num_values: u64,+ dictionary_page_offset: Option<u64>,+ data_page_offset: Option<u64>,+ // Reused buffers+ def_levels_sink: Vec<i16>,+ rep_levels_sink: Vec<i16>,+ data_pages: VecDeque<CompressedPage>,+}++impl<T: DataType> ColumnWriterImpl<T> {+ pub fn new(+ descr: ColumnDescPtr,+ props: WriterPropertiesPtr,+ page_writer: Box<PageWriter>,+ ) -> Self {+ let codec = props.compression(descr.path());+ let compressor = create_codec(codec).unwrap();++ // Optionally set dictionary encoder.+ let dict_encoder =+ if props.dictionary_enabled(descr.path()) && Self::has_dictionary_support(&props) {+ Some(DictEncoder::new(descr.clone(), Rc::new(MemTracker::new())))+ } else {+ None+ };++ // Whether or not this column writer has a dictionary encoding.+ let has_dictionary = dict_encoder.is_some();++ // Set either main encoder or fallback encoder.+ let fallback_encoder = get_encoder(+ descr.clone(),+ props+ .encoding(descr.path())+ .unwrap_or(Self::fallback_encoding(&props)),+ Rc::new(MemTracker::new()),+ )+ .unwrap();++ Self {+ descr,+ props,+ page_writer,+ has_dictionary,+ dict_encoder,+ encoder: fallback_encoder,+ codec,+ compressor,+ num_buffered_values: 0,+ num_buffered_encoded_values: 0,+ num_buffered_rows: 0,+ total_bytes_written: 0,+ total_rows_written: 0,+ total_uncompressed_size: 0,+ total_compressed_size: 0,+ total_num_values: 0,+ dictionary_page_offset: None,+ data_page_offset: None,+ def_levels_sink: vec![],+ rep_levels_sink: vec![],+ data_pages: VecDeque::new(),+ }+ }++ /// Writes batch of values, definition levels and repetition levels.+ /// Returns number of values processed (written).+ ///+ /// If definition and repetition levels are provided, we write fully those levels and+ /// select how many values to write (this number will be returned), since number of+ /// actual written values may be smaller than provided values.+ ///+ /// If only values are provided, then all values are written and the length of+ /// of the values buffer is returned.+ ///+ /// Definition and/or repetition levels can be omitted, if values are+ /// non-nullable and/or non-repeated.+ pub fn write_batch(+ &mut self,+ values: &[T::T],+ def_levels: Option<&[i16]>,+ rep_levels: Option<&[i16]>,+ ) -> Result<usize> {+ // We check for DataPage limits only after we have inserted the values. If a user+ // writes a large number of values, the DataPage size can be well above the limit.+ //+ // The purpose of this chunking is to bound this. Even if a user writes large number+ // of values, the chunking will ensure that we add data page at a reasonable pagesize+ // limit.++ // TODO: find out why we don't account for size of levels when we estimate page size.++ // Find out the minimal length to prevent index out of bound errors.+ let mut min_len = values.len();+ if let Some(levels) = def_levels {+ min_len = cmp::min(min_len, levels.len());+ }+ if let Some(levels) = rep_levels {+ min_len = cmp::min(min_len, levels.len());+ }++ // Find out number of batches to process.+ let write_batch_size = self.props.write_batch_size();+ let num_batches = min_len / write_batch_size;++ let mut values_offset = 0;+ let mut levels_offset = 0;++ for _ in 0..num_batches {+ values_offset += self.write_mini_batch(+ &values[values_offset..values_offset + write_batch_size],+ def_levels.map(|lv| &lv[levels_offset..levels_offset + write_batch_size]),+ rep_levels.map(|lv| &lv[levels_offset..levels_offset + write_batch_size]),+ )?;+ levels_offset += write_batch_size;+ }++ values_offset += self.write_mini_batch(+ &values[values_offset..],+ def_levels.map(|lv| &lv[levels_offset..]),+ rep_levels.map(|lv| &lv[levels_offset..]),+ )?;++ // Return total number of values processed.+ Ok(values_offset)+ }++ /// Returns total number of bytes written by this column writer so far.+ /// This value is also returned when column writer is closed.+ pub fn get_total_bytes_written(&self) -> u64 {+ self.total_bytes_written+ }++ /// Returns total number of rows written by this column writer so far.+ /// This value is also returned when column writer is closed.+ pub fn get_total_rows_written(&self) -> u64 {+ self.total_rows_written+ }++ /// Finalises writes and closes the column writer.+ /// Returns total bytes written, total rows written and column chunk metadata.+ pub fn close(mut self) -> Result<(u64, u64, ColumnChunkMetaData)> {+ if self.dict_encoder.is_some() {+ self.write_dictionary_page()?;+ }+ self.flush_data_pages()?;+ let metadata = self.write_column_metadata()?;+ self.dict_encoder = None;+ self.page_writer.close()?;++ Ok((self.total_bytes_written, self.total_rows_written, metadata))+ }++ /// Writes mini batch of values, definition and repetition levels.+ /// This allows fine-grained processing of values and maintaining a reasonable+ /// page size.+ fn write_mini_batch(+ &mut self,+ values: &[T::T],+ def_levels: Option<&[i16]>,+ rep_levels: Option<&[i16]>,+ ) -> Result<usize> {+ let num_values;+ let mut values_to_write = 0;++ // Check if number of definition levels is the same as number of repetition levels.+ if def_levels.is_some() && rep_levels.is_some() {+ let def = def_levels.unwrap();+ let rep = rep_levels.unwrap();+ if def.len() != rep.len() {+ return Err(general_err!(+ "Inconsistent length of definition and repetition levels: {} != {}",+ def.len(),+ rep.len()+ ));+ }+ }++ // Process definition levels and determine how many values to write.+ if self.descr.max_def_level() > 0 {+ if def_levels.is_none() {+ return Err(general_err!(+ "Definition levels are required, because max definition level = {}",+ self.descr.max_def_level()+ ));+ }++ let levels = def_levels.unwrap();+ num_values = levels.len();+ for &level in levels {+ values_to_write += (level == self.descr.max_def_level()) as usize;+ }++ self.write_definition_levels(levels);+ } else {+ values_to_write = values.len();+ num_values = values_to_write;+ }++ // Process repetition levels and determine how many rows we are about to process.+ if self.descr.max_rep_level() > 0 {+ // A row could contain more than one value.+ if rep_levels.is_none() {+ return Err(general_err!(+ "Repetition levels are required, because max repetition level = {}",+ self.descr.max_rep_level()+ ));+ }++ // Count the occasions where we start a new row+ let levels = rep_levels.unwrap();+ for &level in levels {+ self.num_buffered_rows += (level == 0) as u32+ }++ self.write_repetition_levels(levels);+ } else {+ // Each value is exactly one row.+ // Equals to the number of values, we count nulls as well.+ self.num_buffered_rows += num_values as u32;+ }++ // Check that we have enough values to write.+ if values.len() < values_to_write {+ return Err(general_err!(+ "Expected to write {} values, but have only {}",+ values_to_write,+ values.len()+ ));+ }++ // TODO: update page statistics++ self.write_values(&values[0..values_to_write])?;++ self.num_buffered_values += num_values as u32;+ self.num_buffered_encoded_values += values_to_write as u32;++ if self.should_add_data_page() {+ self.add_data_page()?;+ }++ if self.should_dict_fallback() {+ self.dict_fallback()?;+ }++ Ok(values_to_write)+ }++ #[inline]+ fn write_definition_levels(&mut self, def_levels: &[i16]) {+ self.def_levels_sink.extend_from_slice(def_levels);+ }++ #[inline]+ fn write_repetition_levels(&mut self, rep_levels: &[i16]) {+ self.rep_levels_sink.extend_from_slice(rep_levels);+ }++ #[inline]+ fn write_values(&mut self, values: &[T::T]) -> Result<()> {+ match self.dict_encoder {+ Some(ref mut encoder) => encoder.put(values),+ None => self.encoder.put(values),+ }+ }++ /// Returns true if we need to fall back to non-dictionary encoding.+ ///+ /// We can only fall back if dictionary encoder is set and we have exceeded dictionary+ /// size.+ #[inline]+ fn should_dict_fallback(&self) -> bool {+ match self.dict_encoder {+ Some(ref encoder) => {+ encoder.dict_encoded_size() >= self.props.dictionary_pagesize_limit()+ }+ None => false,+ }+ }++ /// Returns true if there is enough data for a data page, false otherwise.+ #[inline]+ fn should_add_data_page(&self) -> bool {+ self.encoder.estimated_data_encoded_size() >= self.props.data_pagesize_limit()+ }++ /// Performs dictionary fallback.+ /// Prepares and writes dictionary and all data pages into page writer.+ fn dict_fallback(&mut self) -> Result<()> {+ // At this point we know that we need to fall back.+ self.write_dictionary_page()?;+ self.flush_data_pages()?;+ self.dict_encoder = None;+ Ok(())+ }++ /// Adds data page.+ /// Data page is either buffered in case of dictionary encoding or written directly.+ fn add_data_page(&mut self) -> Result<()> {+ // Extract encoded values+ let value_bytes = match self.dict_encoder {+ Some(ref mut encoder) => encoder.write_indices()?,+ None => self.encoder.flush_buffer()?,+ };++ // Select encoding based on current encoder and writer version (v1 or v2).+ let encoding = if self.dict_encoder.is_some() {+ self.props.dictionary_data_page_encoding()+ } else {+ self.encoder.encoding()+ };++ let max_def_level = self.descr.max_def_level();+ let max_rep_level = self.descr.max_rep_level();++ let compressed_page = match self.props.writer_version() {+ WriterVersion::PARQUET_1_0 => {+ let mut buffer = vec![];++ if max_rep_level > 0 {+ buffer.extend_from_slice(+ &self.encode_levels_v1(+ Encoding::RLE,+ &self.rep_levels_sink[..],+ max_rep_level,+ )?[..],+ );+ }++ if max_def_level > 0 {+ buffer.extend_from_slice(+ &self.encode_levels_v1(+ Encoding::RLE,+ &self.def_levels_sink[..],+ max_def_level,+ )?[..],+ );+ }++ buffer.extend_from_slice(value_bytes.data());+ let uncompressed_size = buffer.len();++ if let Some(ref mut cmpr) = self.compressor {+ let mut compressed_buf = Vec::with_capacity(value_bytes.data().len());+ cmpr.compress(&buffer[..], &mut compressed_buf)?;+ buffer = compressed_buf;+ }++ let data_page = Page::DataPage {+ buf: ByteBufferPtr::new(buffer),+ num_values: self.num_buffered_values,+ encoding,+ def_level_encoding: Encoding::RLE,+ rep_level_encoding: Encoding::RLE,+ // TODO: process statistics+ statistics: None,+ };++ CompressedPage::new(data_page, uncompressed_size)+ }+ WriterVersion::PARQUET_2_0 => {+ let mut rep_levels_byte_len = 0;+ let mut def_levels_byte_len = 0;+ let mut buffer = vec![];++ if max_rep_level > 0 {+ let levels = self.encode_levels_v2(&self.rep_levels_sink[..], max_rep_level)?;+ rep_levels_byte_len = levels.len();+ buffer.extend_from_slice(&levels[..]);+ }++ if max_def_level > 0 {+ let levels = self.encode_levels_v2(&self.def_levels_sink[..], max_def_level)?;+ def_levels_byte_len = levels.len();+ buffer.extend_from_slice(&levels[..]);+ }++ let uncompressed_size =+ rep_levels_byte_len + def_levels_byte_len + value_bytes.len();++ // Data Page v2 compresses values only.+ match self.compressor {+ Some(ref mut cmpr) => {+ let mut compressed_buf = Vec::with_capacity(value_bytes.data().len());+ cmpr.compress(value_bytes.data(), &mut compressed_buf)?;+ buffer.extend_from_slice(&compressed_buf[..]);+ }+ None => {+ buffer.extend_from_slice(value_bytes.data());+ }+ }++ let data_page = Page::DataPageV2 {+ buf: ByteBufferPtr::new(buffer),+ num_values: self.num_buffered_values,+ encoding,+ num_nulls: self.num_buffered_values - self.num_buffered_encoded_values,+ num_rows: self.num_buffered_rows,+ def_levels_byte_len: def_levels_byte_len as u32,+ rep_levels_byte_len: rep_levels_byte_len as u32,+ is_compressed: self.compressor.is_some(),+ // TODO: process statistics+ statistics: None,+ };++ CompressedPage::new(data_page, uncompressed_size)+ }+ };++ // Check if we need to buffer data page or flush it to the sink directly.+ if self.dict_encoder.is_some() {+ self.data_pages.push_back(compressed_page);+ } else {+ self.write_data_page(compressed_page)?;+ }++ // Update total number of rows.+ self.total_rows_written += self.num_buffered_rows as u64;++ // Reset state.+ self.rep_levels_sink.clear();+ self.def_levels_sink.clear();+ self.num_buffered_values = 0;+ self.num_buffered_encoded_values = 0;+ self.num_buffered_rows = 0;++ Ok(())+ }++ /// Finalises any outstanding data pages and flushes buffered data pages from+ /// dictionary encoding into underlying sink.+ #[inline]+ fn flush_data_pages(&mut self) -> Result<()> {+ // Write all outstanding data to a new page.+ if self.num_buffered_values > 0 {+ self.add_data_page()?;+ }++ while let Some(page) = self.data_pages.pop_front() {+ self.write_data_page(page)?;+ }++ Ok(())+ }++ /// Assembles and writes column chunk metadata.+ fn write_column_metadata(&mut self) -> Result<ColumnChunkMetaData> {+ let total_compressed_size = self.total_compressed_size as i64;+ let total_uncompressed_size = self.total_uncompressed_size as i64;+ let num_values = self.total_num_values as i64;+ let dict_page_offset = self.dictionary_page_offset.map(|v| v as i64);+ // If data page offset is not set, then no pages have been written+ let data_page_offset = self.data_page_offset.unwrap_or(0) as i64;++ let file_offset;+ let mut encodings = Vec::new();++ if self.has_dictionary {+ assert!(dict_page_offset.is_some(), "Dictionary offset is not set");+ file_offset = dict_page_offset.unwrap() + total_compressed_size;+ // NOTE: This should be in sync with writing dictionary pages.+ encodings.push(self.props.dictionary_page_encoding());+ encodings.push(self.props.dictionary_data_page_encoding());+ // Fallback to alternative encoding, add it to the list.+ if self.dict_encoder.is_none() {+ encodings.push(self.encoder.encoding());+ }+ } else {+ file_offset = data_page_offset + total_compressed_size;+ encodings.push(self.encoder.encoding());+ }+ // We use only RLE level encoding for data page v1 and data page v2.+ encodings.push(Encoding::RLE);++ let metadata = ColumnChunkMetaData::builder(self.descr.clone())+ .set_compression(self.codec)+ .set_encodings(encodings)+ .set_file_offset(file_offset)+ .set_total_compressed_size(total_compressed_size)+ .set_total_uncompressed_size(total_uncompressed_size)+ .set_num_values(num_values)+ .set_data_page_offset(data_page_offset)+ .set_dictionary_page_offset(dict_page_offset)+ .build()?;++ self.page_writer.write_metadata(&metadata)?;++ Ok(metadata)+ }++ /// Encodes definition or repetition levels for Data Page v1.+ #[inline]+ fn encode_levels_v1(+ &self,+ encoding: Encoding,+ levels: &[i16],+ max_level: i16,+ ) -> Result<Vec<u8>> {+ let size = max_buffer_size(encoding, max_level, levels.len());+ let mut encoder = LevelEncoder::v1(encoding, max_level, vec![0; size]);+ encoder.put(&levels)?;+ encoder.consume()+ }++ /// Encodes definition or repetition levels for Data Page v2.+ /// Encoding is always RLE.+ #[inline]+ fn encode_levels_v2(&self, levels: &[i16], max_level: i16) -> Result<Vec<u8>> {+ let size = max_buffer_size(Encoding::RLE, max_level, levels.len());+ let mut encoder = LevelEncoder::v2(max_level, vec![0; size]);+ encoder.put(&levels)?;+ encoder.consume()+ }++ /// Writes compressed data page into underlying sink and updates global metrics.+ #[inline]+ fn write_data_page(&mut self, page: CompressedPage) -> Result<()> {+ let page_spec = self.page_writer.write_page(page)?;+ self.update_metrics_for_page(page_spec);+ Ok(())+ }++ /// Writes dictionary page into underlying sink.+ #[inline]+ fn write_dictionary_page(&mut self) -> Result<()> {+ if self.dict_encoder.is_none() {+ return Err(general_err!("Dictionary encoder is not set"));+ }++ let compressed_page = {+ let encoder = self.dict_encoder.as_ref().unwrap();+ let is_sorted = encoder.is_sorted();+ let num_values = encoder.num_entries();+ let mut values_buf = encoder.write_dict()?;+ let uncompressed_size = values_buf.len();++ if let Some(ref mut cmpr) = self.compressor {+ let mut output_buf = Vec::with_capacity(uncompressed_size);+ cmpr.compress(values_buf.data(), &mut output_buf)?;+ values_buf = ByteBufferPtr::new(output_buf);+ }++ let dict_page = Page::DictionaryPage {+ buf: values_buf,+ num_values: num_values as u32,+ encoding: self.props.dictionary_page_encoding(),+ is_sorted,+ };+ CompressedPage::new(dict_page, uncompressed_size)+ };++ let page_spec = self.page_writer.write_page(compressed_page)?;+ self.update_metrics_for_page(page_spec);+ Ok(())+ }++ /// Updates column writer metrics with each page metadata.+ #[inline]+ fn update_metrics_for_page(&mut self, page_spec: PageWriteSpec) {+ self.total_uncompressed_size += page_spec.uncompressed_size as u64;+ self.total_compressed_size += page_spec.compressed_size as u64;+ self.total_num_values += page_spec.num_values as u64;+ self.total_bytes_written += page_spec.bytes_written;++ match page_spec.page_type {+ PageType::DATA_PAGE | PageType::DATA_PAGE_V2 => {+ if self.data_page_offset.is_none() {+ self.data_page_offset = Some(page_spec.offset);+ }+ }+ PageType::DICTIONARY_PAGE => {+ assert!(+ self.dictionary_page_offset.is_none(),+ "Dictionary offset is already set"+ );+ self.dictionary_page_offset = Some(page_spec.offset);+ }+ _ => {}+ }+ }++ /// Returns reference to the underlying page writer.+ /// This method is intended to use in tests only.+ fn get_page_writer_ref(&self) -> &Box<PageWriter> {+ &self.page_writer+ }+}++// ----------------------------------------------------------------------+// Encoding support for column writer.+// This mirrors parquet-mr default encodings for writes. See:+// https://github.com/apache/parquet-mr/blob/master/parquet-column/src/main/java/org/apache/parquet/column/values/factory/DefaultV1ValuesWriterFactory.java+// https://github.com/apache/parquet-mr/blob/master/parquet-column/src/main/java/org/apache/parquet/column/values/factory/DefaultV2ValuesWriterFactory.java++/// Trait to define default encoding for types, including whether or not the type+/// supports dictionary encoding.+trait EncodingWriteSupport {+ /// Returns encoding for a column when no other encoding is provided in writer+ /// properties.+ fn fallback_encoding(props: &WriterProperties) -> Encoding;++ /// Returns true if dictionary is supported for column writer, false otherwise.+ fn has_dictionary_support(props: &WriterProperties) -> bool;+}++// Basic implementation, always falls back to PLAIN and supports dictionary.+impl<T: DataType> EncodingWriteSupport for ColumnWriterImpl<T> {+ default fn fallback_encoding(_props: &WriterProperties) -> Encoding {+ Encoding::PLAIN+ }++ default fn has_dictionary_support(_props: &WriterProperties) -> bool {+ true+ }+}++impl EncodingWriteSupport for ColumnWriterImpl<BoolType> {+ fn fallback_encoding(props: &WriterProperties) -> Encoding {+ match props.writer_version() {+ WriterVersion::PARQUET_1_0 => Encoding::PLAIN,+ WriterVersion::PARQUET_2_0 => Encoding::RLE,+ }+ }++ // Boolean column does not support dictionary encoding and should fall back to+ // whatever fallback encoding is defined.+ fn has_dictionary_support(_props: &WriterProperties) -> bool {+ false+ }+}++impl EncodingWriteSupport for ColumnWriterImpl<Int32Type> {+ fn fallback_encoding(props: &WriterProperties) -> Encoding {+ match props.writer_version() {+ WriterVersion::PARQUET_1_0 => Encoding::PLAIN,+ WriterVersion::PARQUET_2_0 => Encoding::DELTA_BINARY_PACKED,+ }+ }+}++impl EncodingWriteSupport for ColumnWriterImpl<Int64Type> {+ fn fallback_encoding(props: &WriterProperties) -> Encoding {+ match props.writer_version() {+ WriterVersion::PARQUET_1_0 => Encoding::PLAIN,+ WriterVersion::PARQUET_2_0 => Encoding::DELTA_BINARY_PACKED,+ }+ }+}++impl EncodingWriteSupport for ColumnWriterImpl<ByteArrayType> {+ fn fallback_encoding(props: &WriterProperties) -> Encoding {+ match props.writer_version() {+ WriterVersion::PARQUET_1_0 => Encoding::PLAIN,+ WriterVersion::PARQUET_2_0 => Encoding::DELTA_BYTE_ARRAY,+ }+ }+}++impl EncodingWriteSupport for ColumnWriterImpl<FixedLenByteArrayType> {+ fn fallback_encoding(props: &WriterProperties) -> Encoding {+ match props.writer_version() {+ WriterVersion::PARQUET_1_0 => Encoding::PLAIN,+ WriterVersion::PARQUET_2_0 => Encoding::DELTA_BYTE_ARRAY,+ }+ }++ fn has_dictionary_support(props: &WriterProperties) -> bool {+ match props.writer_version() {+ // Dictionary encoding was not enabled in PARQUET 1.0+ WriterVersion::PARQUET_1_0 => false,+ WriterVersion::PARQUET_2_0 => true,+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ use std::error::Error;++ use rand::distributions::range::SampleRange;++ use crate::parquet::column::{+ page::PageReader,+ reader::{get_column_reader, get_typed_column_reader, ColumnReaderImpl},+ };+ use crate::parquet::file::{+ properties::WriterProperties, reader::SerializedPageReader, writer::SerializedPageWriter,+ };+ use crate::parquet::schema::types::{ColumnDescriptor, ColumnPath, Type as SchemaType};+ use crate::parquet::util::{+ io::{FileSink, FileSource},+ test_common::{get_temp_file, random_numbers_range},+ };++ #[test]+ fn test_column_writer_inconsistent_def_rep_length() {+ let page_writer = get_test_page_writer();+ let props = Rc::new(WriterProperties::builder().build());+ let mut writer = get_test_column_writer::<Int32Type>(page_writer, 1, 1, props);+ let res = writer.write_batch(&[1, 2, 3, 4], Some(&[1, 1, 1]), Some(&[0, 0]));+ assert!(res.is_err());+ if let Err(err) = res {+ assert_eq!(+ err.description(),+ "Inconsistent length of definition and repetition levels: 3 != 2"+ );+ }+ }++ #[test]+ fn test_column_writer_invalid_def_levels() {+ let page_writer = get_test_page_writer();+ let props = Rc::new(WriterProperties::builder().build());+ let mut writer = get_test_column_writer::<Int32Type>(page_writer, 1, 0, props);+ let res = writer.write_batch(&[1, 2, 3, 4], None, None);+ assert!(res.is_err());+ if let Err(err) = res {+ assert_eq!(+ err.description(),+ "Definition levels are required, because max definition level = 1"+ );+ }+ }++ #[test]+ fn test_column_writer_invalid_rep_levels() {+ let page_writer = get_test_page_writer();+ let props = Rc::new(WriterProperties::builder().build());+ let mut writer = get_test_column_writer::<Int32Type>(page_writer, 0, 1, props);+ let res = writer.write_batch(&[1, 2, 3, 4], None, None);+ assert!(res.is_err());+ if let Err(err) = res {+ assert_eq!(+ err.description(),+ "Repetition levels are required, because max repetition level = 1"+ );+ }+ }++ #[test]+ fn test_column_writer_not_enough_values_to_write() {+ let page_writer = get_test_page_writer();+ let props = Rc::new(WriterProperties::builder().build());+ let mut writer = get_test_column_writer::<Int32Type>(page_writer, 1, 0, props);+ let res = writer.write_batch(&[1, 2], Some(&[1, 1, 1, 1]), None);+ assert!(res.is_err());+ if let Err(err) = res {+ assert_eq!(+ err.description(),+ "Expected to write 4 values, but have only 2"+ );+ }+ }++ #[test]+ #[should_panic(expected = "Dictionary offset is already set")]+ fn test_column_writer_write_only_one_dictionary_page() {+ let page_writer = get_test_page_writer();+ let props = Rc::new(WriterProperties::builder().build());+ let mut writer = get_test_column_writer::<Int32Type>(page_writer, 0, 0, props);+ writer.write_batch(&[1, 2, 3, 4], None, None).unwrap();+ // First page should be correctly written.+ let res = writer.write_dictionary_page();+ assert!(res.is_ok());+ writer.write_dictionary_page().unwrap();+ }++ #[test]+ fn test_column_writer_error_when_writing_disabled_dictionary() {+ let page_writer = get_test_page_writer();+ let props = Rc::new(+ WriterProperties::builder()+ .set_dictionary_enabled(false)+ .build(),+ );+ let mut writer = get_test_column_writer::<Int32Type>(page_writer, 0, 0, props);+ writer.write_batch(&[1, 2, 3, 4], None, None).unwrap();+ let res = writer.write_dictionary_page();+ assert!(res.is_err());+ if let Err(err) = res {+ assert_eq!(err.description(), "Dictionary encoder is not set");+ }+ }++ #[test]+ fn test_column_writer_boolean_type_does_not_support_dictionary() {+ let page_writer = get_test_page_writer();+ let props = Rc::new(+ WriterProperties::builder()+ .set_dictionary_enabled(true)+ .build(),+ );+ let mut writer = get_test_column_writer::<BoolType>(page_writer, 0, 0, props);+ writer+ .write_batch(&[true, false, true, false], None, None)+ .unwrap();++ let (bytes_written, rows_written, metadata) = writer.close().unwrap();+ // PlainEncoder uses bit writer to write boolean values, which all fit into 1 byte.+ assert_eq!(bytes_written, 1);+ assert_eq!(rows_written, 4);+ assert_eq!(metadata.encodings(), &vec![Encoding::PLAIN, Encoding::RLE]);+ assert_eq!(metadata.num_values(), 4); // just values+ assert_eq!(metadata.dictionary_page_offset(), None);+ }++ #[test]+ fn test_column_writer_default_encoding_support_bool() {+ check_encoding_write_support::<BoolType>(+ WriterVersion::PARQUET_1_0,+ true,+ &[true, false],+ None,+ &[Encoding::PLAIN, Encoding::RLE],+ );+ check_encoding_write_support::<BoolType>(+ WriterVersion::PARQUET_1_0,+ false,+ &[true, false],+ None,+ &[Encoding::PLAIN, Encoding::RLE],+ );+ check_encoding_write_support::<BoolType>(+ WriterVersion::PARQUET_2_0,+ true,+ &[true, false],+ None,+ &[Encoding::RLE, Encoding::RLE],+ );+ check_encoding_write_support::<BoolType>(+ WriterVersion::PARQUET_2_0,+ false,+ &[true, false],+ None,+ &[Encoding::RLE, Encoding::RLE],+ );+ }++ #[test]+ fn test_column_writer_default_encoding_support_int32() {+ check_encoding_write_support::<Int32Type>(+ WriterVersion::PARQUET_1_0,+ true,+ &[1, 2],+ Some(0),+ &[Encoding::PLAIN, Encoding::RLE_DICTIONARY, Encoding::RLE],+ );+ check_encoding_write_support::<Int32Type>(+ WriterVersion::PARQUET_1_0,+ false,+ &[1, 2],+ None,+ &[Encoding::PLAIN, Encoding::RLE],+ );+ check_encoding_write_support::<Int32Type>(+ WriterVersion::PARQUET_2_0,+ true,+ &[1, 2],+ Some(0),+ &[Encoding::PLAIN, Encoding::RLE_DICTIONARY, Encoding::RLE],+ );+ check_encoding_write_support::<Int32Type>(+ WriterVersion::PARQUET_2_0,+ false,+ &[1, 2],+ None,+ &[Encoding::DELTA_BINARY_PACKED, Encoding::RLE],+ );+ }++ #[test]+ fn test_column_writer_default_encoding_support_int64() {+ check_encoding_write_support::<Int64Type>(+ WriterVersion::PARQUET_1_0,+ true,+ &[1, 2],+ Some(0),+ &[Encoding::PLAIN, Encoding::RLE_DICTIONARY, Encoding::RLE],+ );+ check_encoding_write_support::<Int64Type>(+ WriterVersion::PARQUET_1_0,+ false,+ &[1, 2],+ None,+ &[Encoding::PLAIN, Encoding::RLE],+ );+ check_encoding_write_support::<Int64Type>(+ WriterVersion::PARQUET_2_0,+ true,+ &[1, 2],+ Some(0),+ &[Encoding::PLAIN, Encoding::RLE_DICTIONARY, Encoding::RLE],+ );+ check_encoding_write_support::<Int64Type>(+ WriterVersion::PARQUET_2_0,+ false,+ &[1, 2],+ None,+ &[Encoding::DELTA_BINARY_PACKED, Encoding::RLE],+ );+ }++ #[test]+ fn test_column_writer_default_encoding_support_int96() {+ check_encoding_write_support::<Int96Type>(+ WriterVersion::PARQUET_1_0,+ true,+ &[Int96::from(vec![1, 2, 3])],+ Some(0),+ &[Encoding::PLAIN, Encoding::RLE_DICTIONARY, Encoding::RLE],+ );+ check_encoding_write_support::<Int96Type>(+ WriterVersion::PARQUET_1_0,+ false,+ &[Int96::from(vec![1, 2, 3])],+ None,+ &[Encoding::PLAIN, Encoding::RLE],+ );+ check_encoding_write_support::<Int96Type>(+ WriterVersion::PARQUET_2_0,+ true,+ &[Int96::from(vec![1, 2, 3])],+ Some(0),+ &[Encoding::PLAIN, Encoding::RLE_DICTIONARY, Encoding::RLE],+ );+ check_encoding_write_support::<Int96Type>(+ WriterVersion::PARQUET_2_0,+ false,+ &[Int96::from(vec![1, 2, 3])],+ None,+ &[Encoding::PLAIN, Encoding::RLE],+ );+ }++ #[test]+ fn test_column_writer_default_encoding_support_float() {+ check_encoding_write_support::<FloatType>(+ WriterVersion::PARQUET_1_0,+ true,+ &[1.0, 2.0],+ Some(0),+ &[Encoding::PLAIN, Encoding::RLE_DICTIONARY, Encoding::RLE],+ );+ check_encoding_write_support::<FloatType>(+ WriterVersion::PARQUET_1_0,+ false,+ &[1.0, 2.0],+ None,+ &[Encoding::PLAIN, Encoding::RLE],+ );+ check_encoding_write_support::<FloatType>(+ WriterVersion::PARQUET_2_0,+ true,+ &[1.0, 2.0],+ Some(0),+ &[Encoding::PLAIN, Encoding::RLE_DICTIONARY, Encoding::RLE],+ );+ check_encoding_write_support::<FloatType>(+ WriterVersion::PARQUET_2_0,+ false,+ &[1.0, 2.0],+ None,+ &[Encoding::PLAIN, Encoding::RLE],+ );+ }++ #[test]+ fn test_column_writer_default_encoding_support_double() {+ check_encoding_write_support::<DoubleType>(+ WriterVersion::PARQUET_1_0,+ true,+ &[1.0, 2.0],+ Some(0),+ &[Encoding::PLAIN, Encoding::RLE_DICTIONARY, Encoding::RLE],+ );+ check_encoding_write_support::<DoubleType>(+ WriterVersion::PARQUET_1_0,+ false,+ &[1.0, 2.0],+ None,+ &[Encoding::PLAIN, Encoding::RLE],+ );+ check_encoding_write_support::<DoubleType>(+ WriterVersion::PARQUET_2_0,+ true,+ &[1.0, 2.0],+ Some(0),+ &[Encoding::PLAIN, Encoding::RLE_DICTIONARY, Encoding::RLE],+ );+ check_encoding_write_support::<DoubleType>(+ WriterVersion::PARQUET_2_0,+ false,+ &[1.0, 2.0],+ None,+ &[Encoding::PLAIN, Encoding::RLE],+ );+ }++ #[test]+ fn test_column_writer_default_encoding_support_byte_array() {+ check_encoding_write_support::<ByteArrayType>(+ WriterVersion::PARQUET_1_0,+ true,+ &[ByteArray::from(vec![1u8])],+ Some(0),+ &[Encoding::PLAIN, Encoding::RLE_DICTIONARY, Encoding::RLE],+ );+ check_encoding_write_support::<ByteArrayType>(+ WriterVersion::PARQUET_1_0,+ false,+ &[ByteArray::from(vec![1u8])],+ None,+ &[Encoding::PLAIN, Encoding::RLE],+ );+ check_encoding_write_support::<ByteArrayType>(+ WriterVersion::PARQUET_2_0,+ true,+ &[ByteArray::from(vec![1u8])],+ Some(0),+ &[Encoding::PLAIN, Encoding::RLE_DICTIONARY, Encoding::RLE],+ );+ check_encoding_write_support::<ByteArrayType>(+ WriterVersion::PARQUET_2_0,+ false,+ &[ByteArray::from(vec![1u8])],+ None,+ &[Encoding::DELTA_BYTE_ARRAY, Encoding::RLE],+ );+ }++ #[test]+ fn test_column_writer_default_encoding_support_fixed_len_byte_array() {+ check_encoding_write_support::<FixedLenByteArrayType>(+ WriterVersion::PARQUET_1_0,+ true,+ &[ByteArray::from(vec![1u8])],+ None,+ &[Encoding::PLAIN, Encoding::RLE],+ );+ check_encoding_write_support::<FixedLenByteArrayType>(+ WriterVersion::PARQUET_1_0,+ false,+ &[ByteArray::from(vec![1u8])],+ None,+ &[Encoding::PLAIN, Encoding::RLE],+ );+ check_encoding_write_support::<FixedLenByteArrayType>(+ WriterVersion::PARQUET_2_0,+ true,+ &[ByteArray::from(vec![1u8])],+ Some(0),+ &[Encoding::PLAIN, Encoding::RLE_DICTIONARY, Encoding::RLE],+ );+ check_encoding_write_support::<FixedLenByteArrayType>(+ WriterVersion::PARQUET_2_0,+ false,+ &[ByteArray::from(vec![1u8])],+ None,+ &[Encoding::DELTA_BYTE_ARRAY, Encoding::RLE],+ );+ }++ #[test]+ fn test_column_writer_check_metadata() {+ let page_writer = get_test_page_writer();+ let props = Rc::new(WriterProperties::builder().build());+ let mut writer = get_test_column_writer::<Int32Type>(page_writer, 0, 0, props);+ writer.write_batch(&[1, 2, 3, 4], None, None).unwrap();++ let (bytes_written, rows_written, metadata) = writer.close().unwrap();+ assert_eq!(bytes_written, 20);+ assert_eq!(rows_written, 4);+ assert_eq!(+ metadata.encodings(),+ &vec![Encoding::PLAIN, Encoding::RLE_DICTIONARY, Encoding::RLE]+ );+ assert_eq!(metadata.num_values(), 8); // dictionary + value indexes+ assert_eq!(metadata.compressed_size(), 20);+ assert_eq!(metadata.uncompressed_size(), 20);+ assert_eq!(metadata.data_page_offset(), 0);+ assert_eq!(metadata.dictionary_page_offset(), Some(0));+ }++ #[test]+ fn test_column_writer_empty_column_roundtrip() {+ let props = WriterProperties::builder().build();+ column_roundtrip::<Int32Type>("test_col_writer_rnd_1", props, &[], None, None);+ }++ #[test]+ fn test_column_writer_non_nullable_values_roundtrip() {+ let props = WriterProperties::builder().build();+ column_roundtrip_random::<Int32Type>(+ "test_col_writer_rnd_2",+ props,+ 1024,+ ::std::i32::MIN,+ ::std::i32::MAX,+ 0,+ 0,+ );+ }++ #[test]+ fn test_column_writer_nullable_non_repeated_values_roundtrip() {+ let props = WriterProperties::builder().build();+ column_roundtrip_random::<Int32Type>(+ "test_column_writer_nullable_non_repeated_values_roundtrip",+ props,+ 1024,+ ::std::i32::MIN,+ ::std::i32::MAX,+ 10,+ 0,+ );+ }++ #[test]+ fn test_column_writer_nullable_repeated_values_roundtrip() {+ let props = WriterProperties::builder().build();+ column_roundtrip_random::<Int32Type>(+ "test_col_writer_rnd_3",+ props,+ 1024,+ ::std::i32::MIN,+ ::std::i32::MAX,+ 10,+ 10,+ );+ }++ #[test]+ fn test_column_writer_dictionary_fallback_small_data_page() {+ let props = WriterProperties::builder()+ .set_dictionary_pagesize_limit(32)+ .set_data_pagesize_limit(32)+ .build();+ column_roundtrip_random::<Int32Type>(+ "test_col_writer_rnd_4",+ props,+ 1024,+ ::std::i32::MIN,+ ::std::i32::MAX,+ 10,+ 10,+ );+ }++ #[test]+ fn test_column_writer_small_write_batch_size() {+ for i in vec![1, 2, 5, 10, 11, 1023] {+ let props = WriterProperties::builder().set_write_batch_size(i).build();++ column_roundtrip_random::<Int32Type>(+ "test_col_writer_rnd_5",+ props,+ 1024,+ ::std::i32::MIN,+ ::std::i32::MAX,+ 10,+ 10,+ );+ }+ }++ #[test]+ fn test_column_writer_dictionary_disabled_v1() {+ let props = WriterProperties::builder()+ .set_writer_version(WriterVersion::PARQUET_1_0)+ .set_dictionary_enabled(false)+ .build();+ column_roundtrip_random::<Int32Type>(+ "test_col_writer_rnd_6",+ props,+ 1024,+ ::std::i32::MIN,+ ::std::i32::MAX,+ 10,+ 10,+ );+ }++ #[test]+ fn test_column_writer_dictionary_disabled_v2() {+ let props = WriterProperties::builder()+ .set_writer_version(WriterVersion::PARQUET_2_0)+ .set_dictionary_enabled(false)+ .build();+ column_roundtrip_random::<Int32Type>(+ "test_col_writer_rnd_7",+ props,+ 1024,+ ::std::i32::MIN,+ ::std::i32::MAX,+ 10,+ 10,+ );+ }++ #[test]+ fn test_column_writer_compression_v1() {+ let props = WriterProperties::builder()+ .set_writer_version(WriterVersion::PARQUET_1_0)+ .set_compression(Compression::SNAPPY)+ .build();+ column_roundtrip_random::<Int32Type>(+ "test_col_writer_rnd_8",+ props,+ 2048,+ ::std::i32::MIN,+ ::std::i32::MAX,+ 10,+ 10,+ );+ }++ #[test]+ fn test_column_writer_compression_v2() {+ let props = WriterProperties::builder()+ .set_writer_version(WriterVersion::PARQUET_2_0)+ .set_compression(Compression::SNAPPY)+ .build();+ column_roundtrip_random::<Int32Type>(+ "test_col_writer_rnd_9",+ props,+ 2048,+ ::std::i32::MIN,+ ::std::i32::MAX,+ 10,+ 10,+ );+ }++ /// Performs write-read roundtrip with randomly generated values and levels.+ /// `max_size` is maximum number of values or levels (if `max_def_level` > 0) to write+ /// for a column.+ fn column_roundtrip_random<'a, T: DataType>(+ file_name: &'a str,+ props: WriterProperties,+ max_size: usize,+ min_value: T::T,+ max_value: T::T,+ max_def_level: i16,+ max_rep_level: i16,+ ) where+ T::T: PartialOrd + SampleRange + Copy,+ {+ let mut num_values: usize = 0;++ let mut buf: Vec<i16> = Vec::new();+ let def_levels = if max_def_level > 0 {+ random_numbers_range(max_size, 0, max_def_level + 1, &mut buf);+ for &dl in &buf[..] {+ if dl == max_def_level {+ num_values += 1;+ }+ }+ Some(&buf[..])+ } else {+ num_values = max_size;+ None+ };++ let mut buf: Vec<i16> = Vec::new();+ let rep_levels = if max_rep_level > 0 {+ random_numbers_range(max_size, 0, max_rep_level + 1, &mut buf);+ Some(&buf[..])+ } else {+ None+ };++ let mut values: Vec<T::T> = Vec::new();+ random_numbers_range(num_values, min_value, max_value, &mut values);++ column_roundtrip::<T>(file_name, props, &values[..], def_levels, rep_levels);+ }++ /// Performs write-read roundtrip and asserts written values and levels.+ fn column_roundtrip<'a, T: DataType>(+ file_name: &'a str,+ props: WriterProperties,+ values: &[T::T],+ def_levels: Option<&[i16]>,+ rep_levels: Option<&[i16]>,+ ) {+ let file = get_temp_file(file_name, &[]);+ let sink = FileSink::new(&file);+ let page_writer = Box::new(SerializedPageWriter::new(sink));++ let max_def_level = match def_levels {+ Some(buf) => *buf.iter().max().unwrap_or(&0i16),+ None => 0i16,+ };++ let max_rep_level = match rep_levels {+ Some(buf) => *buf.iter().max().unwrap_or(&0i16),+ None => 0i16,+ };++ let mut max_batch_size = values.len();+ if let Some(levels) = def_levels {+ max_batch_size = cmp::max(max_batch_size, levels.len());+ }+ if let Some(levels) = rep_levels {+ max_batch_size = cmp::max(max_batch_size, levels.len());+ }++ let mut writer =+ get_test_column_writer::<T>(page_writer, max_def_level, max_rep_level, Rc::new(props));++ let values_written = writer.write_batch(values, def_levels, rep_levels).unwrap();+ assert_eq!(values_written, values.len());+ let (bytes_written, rows_written, column_metadata) = writer.close().unwrap();++ let source = FileSource::new(&file, 0, bytes_written as usize);+ let page_reader = Box::new(+ SerializedPageReader::new(+ source,+ column_metadata.num_values(),+ column_metadata.compression(),+ T::get_physical_type(),+ )+ .unwrap(),+ );+ let reader = get_test_column_reader::<T>(page_reader, max_def_level, max_rep_level);++ let mut actual_values = vec![T::T::default(); max_batch_size];+ let mut actual_def_levels = match def_levels {+ Some(_) => Some(vec![0i16; max_batch_size]),+ None => None,+ };+ let mut actual_rep_levels = match rep_levels {+ Some(_) => Some(vec![0i16; max_batch_size]),+ None => None,+ };++ let (values_read, levels_read) = read_fully(+ reader,+ max_batch_size,+ actual_def_levels.as_mut(),+ actual_rep_levels.as_mut(),+ actual_values.as_mut_slice(),+ );++ // Assert values, definition and repetition levels.++ assert_eq!(&actual_values[..values_read], values);+ match actual_def_levels {+ Some(ref vec) => assert_eq!(Some(&vec[..levels_read]), def_levels),+ None => assert_eq!(None, def_levels),+ }+ match actual_rep_levels {+ Some(ref vec) => assert_eq!(Some(&vec[..levels_read]), rep_levels),+ None => assert_eq!(None, rep_levels),+ }++ // Assert written rows.++ if let Some(levels) = actual_rep_levels {+ let mut actual_rows_written = 0;+ for l in levels {+ if l == 0 {+ actual_rows_written += 1;+ }+ }+ assert_eq!(actual_rows_written, rows_written);+ } else if actual_def_levels.is_some() {+ assert_eq!(levels_read as u64, rows_written);+ } else {+ assert_eq!(values_read as u64, rows_written);+ }+ }++ /// Performs write of provided values and returns column metadata of those values.+ /// Used to test encoding support for column writer.+ fn column_write_and_get_metadata<T: DataType>(+ props: WriterProperties,+ values: &[T::T],+ ) -> ColumnChunkMetaData {+ let page_writer = get_test_page_writer();+ let props = Rc::new(props);+ let mut writer = get_test_column_writer::<T>(page_writer, 0, 0, props);+ writer.write_batch(values, None, None).unwrap();+ let (_, _, metadata) = writer.close().unwrap();+ metadata+ }++ // Function to use in tests for EncodingWriteSupport. This checks that dictionary+ // offset and encodings to make sure that column writer uses provided by trait+ // encodings.+ fn check_encoding_write_support<T: DataType>(+ version: WriterVersion,+ dict_enabled: bool,+ data: &[T::T],+ dictionary_page_offset: Option<i64>,+ encodings: &[Encoding],+ ) {+ let props = WriterProperties::builder()+ .set_writer_version(version)+ .set_dictionary_enabled(dict_enabled)+ .build();+ let meta = column_write_and_get_metadata::<T>(props, data);+ assert_eq!(meta.dictionary_page_offset(), dictionary_page_offset);+ assert_eq!(meta.encodings(), &encodings);+ }++ /// Reads one batch of data, considering that batch is large enough to capture all of+ /// the values and levels.+ fn read_fully<T: DataType>(+ mut reader: ColumnReaderImpl<T>,+ batch_size: usize,+ mut def_levels: Option<&mut Vec<i16>>,+ mut rep_levels: Option<&mut Vec<i16>>,+ values: &mut [T::T],+ ) -> (usize, usize) {+ let actual_def_levels = match &mut def_levels {+ Some(ref mut vec) => Some(&mut vec[..]),+ None => None,+ };+ let actual_rep_levels = match rep_levels {+ Some(ref mut vec) => Some(&mut vec[..]),+ None => None,+ };+ reader+ .read_batch(batch_size, actual_def_levels, actual_rep_levels, values)+ .unwrap()+ }++ /// Returns column writer.+ fn get_test_column_writer<T: DataType>(+ page_writer: Box<PageWriter>,+ max_def_level: i16,+ max_rep_level: i16,+ props: WriterPropertiesPtr,+ ) -> ColumnWriterImpl<T> {+ let descr = Rc::new(get_test_column_descr::<T>(max_def_level, max_rep_level));+ let column_writer = get_column_writer(descr, props, page_writer);+ get_typed_column_writer::<T>(column_writer)+ }++ /// Returns column reader.+ fn get_test_column_reader<T: DataType>(+ page_reader: Box<PageReader>,+ max_def_level: i16,+ max_rep_level: i16,+ ) -> ColumnReaderImpl<T> {+ let descr = Rc::new(get_test_column_descr::<T>(max_def_level, max_rep_level));+ let column_reader = get_column_reader(descr, page_reader);+ get_typed_column_reader::<T>(column_reader)+ }++ /// Returns descriptor for primitive column.+ fn get_test_column_descr<T: DataType>(+ max_def_level: i16,+ max_rep_level: i16,+ ) -> ColumnDescriptor {+ let path = ColumnPath::from("col");+ let tpe = SchemaType::primitive_type_builder("col", T::get_physical_type())+ // length is set for "encoding support" tests for FIXED_LEN_BYTE_ARRAY type,+ // it should be no-op for other types+ .with_length(1)+ .build()+ .unwrap();+ ColumnDescriptor::new(Rc::new(tpe), None, max_def_level, max_rep_level, path)+ }++ /// Returns page writer that collects pages without serializing them.+ fn get_test_page_writer() -> Box<PageWriter> {+ Box::new(TestPageWriter {})+ }++ struct TestPageWriter {}++ impl PageWriter for TestPageWriter {+ fn write_page(&mut self, page: CompressedPage) -> Result<PageWriteSpec> {+ let mut res = PageWriteSpec::new();+ res.page_type = page.page_type();+ res.uncompressed_size = page.uncompressed_size();+ res.compressed_size = page.compressed_size();+ res.num_values = page.num_values();+ res.offset = 0;+ res.bytes_written = page.data().len() as u64;+ Ok(res)+ }++ fn write_metadata(&mut self, _metadata: &ColumnChunkMetaData) -> Result<()> {+ Ok(())+ }++ fn close(&mut self) -> Result<()> {+ Ok(())+ }+ }+}diff --git a/rust/src/parquet/compression.rs b/rust/src/parquet/compression.rsnew file mode 100644index 0000000000..3690cca032--- /dev/null+++ b/rust/src/parquet/compression.rs@@ -0,0 +1,321 @@+// 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.++//! Contains codec interface and supported codec implementations.+//!+//! See [`Compression`](`::basic::Compression`) enum for all available compression+//! algorithms.+//!+//! # Example+//!+//! ```rust+//! use arrow::parquet::{basic::Compression, compression::create_codec};+//!+//! let mut codec = match create_codec(Compression::SNAPPY) {+//! Ok(Some(codec)) => codec,+//! _ => panic!(),+//! };+//!+//! let data = vec![b'p', b'a', b'r', b'q', b'u', b'e', b't'];+//! let mut compressed = vec![];+//! codec.compress(&data[..], &mut compressed).unwrap();+//!+//! let mut output = vec![];+//! codec.decompress(&compressed[..], &mut output).unwrap();+//!+//! assert_eq!(output, data);+//! ```++use std::io::{self, Read, Write};++use brotli;+use flate2::{read, write, Compression};+use lz4;+use snap::{decompress_len, max_compress_len, Decoder, Encoder};+use zstd;++use crate::parquet::basic::Compression as CodecType;+use crate::parquet::errors::{ParquetError, Result};++/// Parquet compression codec interface.+pub trait Codec {+ /// Compresses data stored in slice `input_buf` and writes the compressed result+ /// to `output_buf`.+ /// Note that you'll need to call `clear()` before reusing the same `output_buf` across+ /// different `compress` calls.+ fn compress(&mut self, input_buf: &[u8], output_buf: &mut Vec<u8>) -> Result<()>;++ /// Decompresses data stored in slice `input_buf` and writes output to `output_buf`.+ /// Returns the total number of bytes written.+ fn decompress(&mut self, input_buf: &[u8], output_buf: &mut Vec<u8>) -> Result<usize>;+}++/// Given the compression type `codec`, returns a codec used to compress and decompress+/// bytes for the compression type.+/// This returns `None` if the codec type is `UNCOMPRESSED`.+pub fn create_codec(codec: CodecType) -> Result<Option<Box<Codec>>> {+ match codec {+ CodecType::BROTLI => Ok(Some(Box::new(BrotliCodec::new()))),+ CodecType::GZIP => Ok(Some(Box::new(GZipCodec::new()))),+ CodecType::SNAPPY => Ok(Some(Box::new(SnappyCodec::new()))),+ CodecType::LZ4 => Ok(Some(Box::new(LZ4Codec::new()))),+ CodecType::ZSTD => Ok(Some(Box::new(ZSTDCodec::new()))),+ CodecType::UNCOMPRESSED => Ok(None),+ _ => Err(nyi_err!("The codec type {} is not supported yet", codec)),+ }+}++/// Codec for Snappy compression format.+pub struct SnappyCodec {+ decoder: Decoder,+ encoder: Encoder,+}++impl SnappyCodec {+ /// Creates new Snappy compression codec.+ fn new() -> Self {+ Self {+ decoder: Decoder::new(),+ encoder: Encoder::new(),+ }+ }+}++impl Codec for SnappyCodec {+ fn decompress(&mut self, input_buf: &[u8], output_buf: &mut Vec<u8>) -> Result<usize> {+ let len = decompress_len(input_buf)?;+ output_buf.resize(len, 0);+ self.decoder+ .decompress(input_buf, output_buf)+ .map_err(|e| e.into())+ }++ fn compress(&mut self, input_buf: &[u8], output_buf: &mut Vec<u8>) -> Result<()> {+ let required_len = max_compress_len(input_buf.len());+ if output_buf.len() < required_len {+ output_buf.resize(required_len, 0);+ }+ let n = self.encoder.compress(input_buf, &mut output_buf[..])?;+ output_buf.truncate(n);+ Ok(())+ }+}++/// Codec for GZIP compression algorithm.+pub struct GZipCodec {}++impl GZipCodec {+ /// Creates new GZIP compression codec.+ fn new() -> Self {+ Self {}+ }+}++impl Codec for GZipCodec {+ fn decompress(&mut self, input_buf: &[u8], output_buf: &mut Vec<u8>) -> Result<usize> {+ let mut decoder = read::GzDecoder::new(input_buf);+ decoder.read_to_end(output_buf).map_err(|e| e.into())+ }++ fn compress(&mut self, input_buf: &[u8], output_buf: &mut Vec<u8>) -> Result<()> {+ let mut encoder = write::GzEncoder::new(output_buf, Compression::default());+ encoder.write_all(input_buf)?;+ encoder.try_finish().map_err(|e| e.into())+ }+}++const BROTLI_DEFAULT_BUFFER_SIZE: usize = 4096;+const BROTLI_DEFAULT_COMPRESSION_QUALITY: u32 = 1; // supported levels 0-9+const BROTLI_DEFAULT_LG_WINDOW_SIZE: u32 = 22; // recommended between 20-22++/// Codec for Brotli compression algorithm.+pub struct BrotliCodec {}++impl BrotliCodec {+ /// Creates new Brotli compression codec.+ fn new() -> Self {+ Self {}+ }+}++impl Codec for BrotliCodec {+ fn decompress(&mut self, input_buf: &[u8], output_buf: &mut Vec<u8>) -> Result<usize> {+ brotli::Decompressor::new(input_buf, BROTLI_DEFAULT_BUFFER_SIZE)+ .read_to_end(output_buf)+ .map_err(|e| e.into())+ }++ fn compress(&mut self, input_buf: &[u8], output_buf: &mut Vec<u8>) -> Result<()> {+ let mut encoder = brotli::CompressorWriter::new(+ output_buf,+ BROTLI_DEFAULT_BUFFER_SIZE,+ BROTLI_DEFAULT_COMPRESSION_QUALITY,+ BROTLI_DEFAULT_LG_WINDOW_SIZE,+ );+ encoder.write_all(&input_buf[..])?;+ encoder.flush().map_err(|e| e.into())+ }+}++const LZ4_BUFFER_SIZE: usize = 4096;++/// Codec for LZ4 compression algorithm.+pub struct LZ4Codec {}++impl LZ4Codec {+ /// Creates new LZ4 compression codec.+ fn new() -> Self {+ Self {}+ }+}++impl Codec for LZ4Codec {+ fn decompress(&mut self, input_buf: &[u8], output_buf: &mut Vec<u8>) -> Result<usize> {+ let mut decoder = lz4::Decoder::new(input_buf)?;+ let mut buffer: [u8; LZ4_BUFFER_SIZE] = [0; LZ4_BUFFER_SIZE];+ let mut total_len = 0;+ loop {+ let len = decoder.read(&mut buffer)?;+ if len == 0 {+ break;+ }+ total_len += len;+ output_buf.write_all(&buffer[0..len])?;+ }+ Ok(total_len)+ }++ fn compress(&mut self, input_buf: &[u8], output_buf: &mut Vec<u8>) -> Result<()> {+ let mut encoder = lz4::EncoderBuilder::new().build(output_buf)?;+ let mut from = 0;+ loop {+ let to = ::std::cmp::min(from + LZ4_BUFFER_SIZE, input_buf.len());+ encoder.write_all(&input_buf[from..to])?;+ from += LZ4_BUFFER_SIZE;+ if from >= input_buf.len() {+ break;+ }+ }+ encoder.finish().1.map_err(|e| e.into())+ }+}++/// Codec for Zstandard compression algorithm.+pub struct ZSTDCodec {}++impl ZSTDCodec {+ /// Creates new Zstandard compression codec.+ fn new() -> Self {+ Self {}+ }+}++/// Compression level (1-21) for ZSTD. Choose 1 here for better compression speed.+const ZSTD_COMPRESSION_LEVEL: i32 = 1;++impl Codec for ZSTDCodec {+ fn decompress(&mut self, input_buf: &[u8], output_buf: &mut Vec<u8>) -> Result<usize> {+ let mut decoder = zstd::Decoder::new(input_buf)?;+ match io::copy(&mut decoder, output_buf) {+ Ok(n) => Ok(n as usize),+ Err(e) => Err(e.into()),+ }+ }++ fn compress(&mut self, input_buf: &[u8], output_buf: &mut Vec<u8>) -> Result<()> {+ let mut encoder = zstd::Encoder::new(output_buf, ZSTD_COMPRESSION_LEVEL)?;+ encoder.write_all(&input_buf[..])?;+ match encoder.finish() {+ Ok(_) => Ok(()),+ Err(e) => Err(e.into()),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ use crate::parquet::util::test_common::*;++ fn test_roundtrip(c: CodecType, data: &Vec<u8>) {+ let mut c1 = create_codec(c).unwrap().unwrap();+ let mut c2 = create_codec(c).unwrap().unwrap();++ // Compress with c1+ let mut compressed = Vec::new();+ let mut decompressed = Vec::new();+ c1.compress(data.as_slice(), &mut compressed)+ .expect("Error when compressing");++ // Decompress with c2+ let mut decompressed_size = c2+ .decompress(compressed.as_slice(), &mut decompressed)+ .expect("Error when decompressing");+ assert_eq!(data.len(), decompressed_size);+ decompressed.truncate(decompressed_size);+ assert_eq!(*data, decompressed);++ compressed.clear();++ // Compress with c2+ c2.compress(data.as_slice(), &mut compressed)+ .expect("Error when compressing");++ // Decompress with c1+ decompressed_size = c1+ .decompress(compressed.as_slice(), &mut decompressed)+ .expect("Error when decompressing");+ assert_eq!(data.len(), decompressed_size);+ decompressed.truncate(decompressed_size);+ assert_eq!(*data, decompressed);+ }++ fn test_codec(c: CodecType) {+ let sizes = vec![100, 10000, 100000];+ for size in sizes {+ let mut data = random_bytes(size);+ test_roundtrip(c, &mut data);+ }+ }++ #[test]+ fn test_codec_snappy() {+ test_codec(CodecType::SNAPPY);+ }++ #[test]+ fn test_codec_gzip() {+ test_codec(CodecType::GZIP);+ }++ #[test]+ fn test_codec_brotli() {+ test_codec(CodecType::BROTLI);+ }++ #[test]+ fn test_codec_lz4() {+ test_codec(CodecType::LZ4);+ }++ #[test]+ fn test_codec_zstd() {+ test_codec(CodecType::ZSTD);+ }++}diff --git a/rust/src/parquet/data_type.rs b/rust/src/parquet/data_type.rsnew file mode 100644index 0000000000..26bdebd71b--- /dev/null+++ b/rust/src/parquet/data_type.rs@@ -0,0 +1,463 @@+// 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.++//! Data types that connect Parquet physical types with their Rust-specific+//! representations.++use std::mem;++use byteorder::{BigEndian, ByteOrder};++use crate::parquet::basic::Type;+use crate::parquet::util::memory::{ByteBuffer, ByteBufferPtr};++/// Rust representation for logical type INT96, value is backed by an array of `u32`.+/// The type only takes 12 bytes, without extra padding.+#[derive(Clone, Debug)]+pub struct Int96 {+ value: Option<[u32; 3]>,+}++impl Int96 {+ /// Creates new INT96 type struct with no data set.+ pub fn new() -> Self {+ Self { value: None }+ }++ /// Returns underlying data as slice of [`u32`].+ pub fn data(&self) -> &[u32] {+ assert!(self.value.is_some());+ self.value.as_ref().unwrap()+ }++ /// Sets data for this INT96 type.+ pub fn set_data(&mut self, elem0: u32, elem1: u32, elem2: u32) {+ self.value = Some([elem0, elem1, elem2]);+ }+}++impl Default for Int96 {+ fn default() -> Self {+ Self { value: None }+ }+}++impl PartialEq for Int96 {+ fn eq(&self, other: &Int96) -> bool {+ self.data() == other.data()+ }+}++impl From<Vec<u32>> for Int96 {+ fn from(buf: Vec<u32>) -> Self {+ assert_eq!(buf.len(), 3);+ let mut result = Self::new();+ result.set_data(buf[0], buf[1], buf[2]);+ result+ }+}++/// Rust representation for BYTE_ARRAY and FIXED_LEN_BYTE_ARRAY Parquet physical types.+/// Value is backed by a byte buffer.+#[derive(Clone, Debug)]+pub struct ByteArray {+ data: Option<ByteBufferPtr>,+}++impl ByteArray {+ /// Creates new byte array with no data set.+ pub fn new() -> Self {+ ByteArray { data: None }+ }++ /// Gets length of the underlying byte buffer.+ pub fn len(&self) -> usize {+ assert!(self.data.is_some());+ self.data.as_ref().unwrap().len()+ }++ /// Returns slice of data.+ pub fn data(&self) -> &[u8] {+ assert!(self.data.is_some());+ self.data.as_ref().unwrap().as_ref()+ }++ /// Set data from another byte buffer.+ pub fn set_data(&mut self, data: ByteBufferPtr) {+ self.data = Some(data);+ }++ /// Returns `ByteArray` instance with slice of values for a data.+ pub fn slice(&self, start: usize, len: usize) -> Self {+ assert!(self.data.is_some());+ Self::from(self.data.as_ref().unwrap().range(start, len))+ }+}++impl From<Vec<u8>> for ByteArray {+ fn from(buf: Vec<u8>) -> ByteArray {+ Self {+ data: Some(ByteBufferPtr::new(buf)),+ }+ }+}++impl<'a> From<&'a str> for ByteArray {+ fn from(s: &'a str) -> ByteArray {+ let mut v = Vec::new();+ v.extend_from_slice(s.as_bytes());+ Self {+ data: Some(ByteBufferPtr::new(v)),+ }+ }+}++impl From<ByteBufferPtr> for ByteArray {+ fn from(ptr: ByteBufferPtr) -> ByteArray {+ Self { data: Some(ptr) }+ }+}++impl From<ByteBuffer> for ByteArray {+ fn from(mut buf: ByteBuffer) -> ByteArray {+ Self {+ data: Some(buf.consume()),+ }+ }+}++impl Default for ByteArray {+ fn default() -> Self {+ ByteArray { data: None }+ }+}++impl PartialEq for ByteArray {+ fn eq(&self, other: &ByteArray) -> bool {+ self.data() == other.data()+ }+}++/// Rust representation for Decimal values.+///+/// This is not a representation of Parquet physical type, but rather a wrapper for+/// DECIMAL logical type, and serves as container for raw parts of decimal values:+/// unscaled value in bytes, precision and scale.+#[derive(Clone, Debug)]+pub enum Decimal {+ /// Decimal backed by `i32`.+ Int32 {+ value: [u8; 4],+ precision: i32,+ scale: i32,+ },+ /// Decimal backed by `i64`.+ Int64 {+ value: [u8; 8],+ precision: i32,+ scale: i32,+ },+ /// Decimal backed by byte array.+ Bytes {+ value: ByteArray,+ precision: i32,+ scale: i32,+ },+}++impl Decimal {+ /// Creates new decimal value from `i32`.+ pub fn from_i32(value: i32, precision: i32, scale: i32) -> Self {+ let mut bytes = [0; 4];+ BigEndian::write_i32(&mut bytes, value);+ Decimal::Int32 {+ value: bytes,+ precision,+ scale,+ }+ }++ /// Creates new decimal value from `i64`.+ pub fn from_i64(value: i64, precision: i32, scale: i32) -> Self {+ let mut bytes = [0; 8];+ BigEndian::write_i64(&mut bytes, value);+ Decimal::Int64 {+ value: bytes,+ precision,+ scale,+ }+ }++ /// Creates new decimal value from `ByteArray`.+ pub fn from_bytes(value: ByteArray, precision: i32, scale: i32) -> Self {+ Decimal::Bytes {+ value,+ precision,+ scale,+ }+ }++ /// Returns bytes of unscaled value.+ pub fn data(&self) -> &[u8] {+ match *self {+ Decimal::Int32 { ref value, .. } => value,+ Decimal::Int64 { ref value, .. } => value,+ Decimal::Bytes { ref value, .. } => value.data(),+ }+ }++ /// Returns decimal precision.+ pub fn precision(&self) -> i32 {+ match *self {+ Decimal::Int32 { precision, .. } => precision,+ Decimal::Int64 { precision, .. } => precision,+ Decimal::Bytes { precision, .. } => precision,+ }+ }++ /// Returns decimal scale.+ pub fn scale(&self) -> i32 {+ match *self {+ Decimal::Int32 { scale, .. } => scale,+ Decimal::Int64 { scale, .. } => scale,+ Decimal::Bytes { scale, .. } => scale,+ }+ }+}++impl Default for Decimal {+ fn default() -> Self {+ Self::from_i32(0, 0, 0)+ }+}++impl PartialEq for Decimal {+ fn eq(&self, other: &Decimal) -> bool {+ self.precision() == other.precision()+ && self.scale() == other.scale()+ && self.data() == other.data()+ }+}++/// Converts an instance of data type to a slice of bytes as `u8`.+pub trait AsBytes {+ /// Returns slice of bytes for this data type.+ fn as_bytes(&self) -> &[u8];+}++macro_rules! gen_as_bytes {+ ($source_ty:ident) => {+ impl AsBytes for $source_ty {+ fn as_bytes(&self) -> &[u8] {+ unsafe {+ ::std::slice::from_raw_parts(+ self as *const $source_ty as *const u8,+ ::std::mem::size_of::<$source_ty>(),+ )+ }+ }+ }+ };+}++gen_as_bytes!(bool);+gen_as_bytes!(u8);+gen_as_bytes!(i32);+gen_as_bytes!(u32);+gen_as_bytes!(i64);+gen_as_bytes!(f32);+gen_as_bytes!(f64);++impl AsBytes for Int96 {+ fn as_bytes(&self) -> &[u8] {+ unsafe { ::std::slice::from_raw_parts(self.data() as *const [u32] as *const u8, 12) }+ }+}++impl AsBytes for ByteArray {+ fn as_bytes(&self) -> &[u8] {+ self.data()+ }+}++impl AsBytes for Decimal {+ fn as_bytes(&self) -> &[u8] {+ self.data()+ }+}++impl AsBytes for Vec<u8> {+ fn as_bytes(&self) -> &[u8] {+ self.as_slice()+ }+}++impl<'a> AsBytes for &'a str {+ fn as_bytes(&self) -> &[u8] {+ (self as &str).as_bytes()+ }+}++impl AsBytes for str {+ fn as_bytes(&self) -> &[u8] {+ (self as &str).as_bytes()+ }+}++/// Contains the Parquet physical type information as well as the Rust primitive type+/// presentation.+pub trait DataType: 'static {+ type T: ::std::cmp::PartialEq+ + ::std::fmt::Debug+ + ::std::default::Default+ + ::std::clone::Clone+ + AsBytes;++ /// Returns Parquet physical type.+ fn get_physical_type() -> Type;++ /// Returns size in bytes for Rust representation of the physical type.+ fn get_type_size() -> usize;+}++macro_rules! make_type {+ ($name:ident, $physical_ty:path, $native_ty:ty, $size:expr) => {+ pub struct $name {}++ impl DataType for $name {+ type T = $native_ty;++ fn get_physical_type() -> Type {+ $physical_ty+ }++ fn get_type_size() -> usize {+ $size+ }+ }+ };+}++/// Generate struct definitions for all physical types++make_type!(BoolType, Type::BOOLEAN, bool, 1);+make_type!(Int32Type, Type::INT32, i32, 4);+make_type!(Int64Type, Type::INT64, i64, 8);+make_type!(Int96Type, Type::INT96, Int96, mem::size_of::<Int96>());+make_type!(FloatType, Type::FLOAT, f32, 4);+make_type!(DoubleType, Type::DOUBLE, f64, 8);+make_type!(+ ByteArrayType,+ Type::BYTE_ARRAY,+ ByteArray,+ mem::size_of::<ByteArray>()+);+make_type!(+ FixedLenByteArrayType,+ Type::FIXED_LEN_BYTE_ARRAY,+ ByteArray,+ mem::size_of::<ByteArray>()+);++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_as_bytes() {+ assert_eq!(false.as_bytes(), &[0]);+ assert_eq!(true.as_bytes(), &[1]);+ assert_eq!((7 as i32).as_bytes(), &[7, 0, 0, 0]);+ assert_eq!((555 as i32).as_bytes(), &[43, 2, 0, 0]);+ assert_eq!((555 as u32).as_bytes(), &[43, 2, 0, 0]);+ assert_eq!(i32::max_value().as_bytes(), &[255, 255, 255, 127]);+ assert_eq!(i32::min_value().as_bytes(), &[0, 0, 0, 128]);+ assert_eq!((7 as i64).as_bytes(), &[7, 0, 0, 0, 0, 0, 0, 0]);+ assert_eq!((555 as i64).as_bytes(), &[43, 2, 0, 0, 0, 0, 0, 0]);+ assert_eq!(+ (i64::max_value()).as_bytes(),+ &[255, 255, 255, 255, 255, 255, 255, 127]+ );+ assert_eq!((i64::min_value()).as_bytes(), &[0, 0, 0, 0, 0, 0, 0, 128]);+ assert_eq!((3.14 as f32).as_bytes(), &[195, 245, 72, 64]);+ assert_eq!(+ (3.14 as f64).as_bytes(),+ &[31, 133, 235, 81, 184, 30, 9, 64]+ );+ assert_eq!("hello".as_bytes(), &[b'h', b'e', b'l', b'l', b'o']);+ assert_eq!(+ Vec::from("hello".as_bytes()).as_bytes(),+ &[b'h', b'e', b'l', b'l', b'o']+ );++ // Test Int96+ let i96 = Int96::from(vec![1, 2, 3]);+ assert_eq!(i96.as_bytes(), &[1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0]);++ // Test ByteArray+ let ba = ByteArray::from(vec![1, 2, 3]);+ assert_eq!(ba.as_bytes(), &[1, 2, 3]);++ // Test Decimal+ let decimal = Decimal::from_i32(123, 5, 2);+ assert_eq!(decimal.as_bytes(), &[0, 0, 0, 123]);+ let decimal = Decimal::from_i64(123, 5, 2);+ assert_eq!(decimal.as_bytes(), &[0, 0, 0, 0, 0, 0, 0, 123]);+ let decimal = Decimal::from_bytes(ByteArray::from(vec![1, 2, 3]), 5, 2);+ assert_eq!(decimal.as_bytes(), &[1, 2, 3]);+ }++ #[test]+ fn test_int96_from() {+ assert_eq!(+ Int96::from(vec![1, 12345, 1234567890]).data(),+ &[1, 12345, 1234567890]+ );+ }++ #[test]+ fn test_byte_array_from() {+ assert_eq!(+ ByteArray::from(vec![b'A', b'B', b'C']).data(),+ &[b'A', b'B', b'C']+ );+ assert_eq!(ByteArray::from("ABC").data(), &[b'A', b'B', b'C']);+ assert_eq!(+ ByteArray::from(ByteBufferPtr::new(vec![1u8, 2u8, 3u8, 4u8, 5u8])).data(),+ &[1u8, 2u8, 3u8, 4u8, 5u8]+ );+ let mut buf = ByteBuffer::new();+ buf.set_data(vec![6u8, 7u8, 8u8, 9u8, 10u8]);+ assert_eq!(ByteArray::from(buf).data(), &[6u8, 7u8, 8u8, 9u8, 10u8]);+ }++ #[test]+ fn test_decimal_partial_eq() {+ assert_eq!(Decimal::default(), Decimal::from_i32(0, 0, 0));+ assert_eq!(Decimal::from_i32(222, 5, 2), Decimal::from_i32(222, 5, 2));+ assert_eq!(+ Decimal::from_bytes(ByteArray::from(vec![0, 0, 0, 3]), 5, 2),+ Decimal::from_i32(3, 5, 2)+ );++ assert!(Decimal::from_i32(222, 5, 2) != Decimal::from_i32(111, 5, 2));+ assert!(Decimal::from_i32(222, 5, 2) != Decimal::from_i32(222, 6, 2));+ assert!(Decimal::from_i32(222, 5, 2) != Decimal::from_i32(222, 5, 3));++ assert!(Decimal::from_i64(222, 5, 2) != Decimal::from_i32(222, 5, 2));+ }+}diff --git a/rust/src/parquet/encodings/decoding.rs b/rust/src/parquet/encodings/decoding.rsnew file mode 100644index 0000000000..c6a6fd49ee--- /dev/null+++ b/rust/src/parquet/encodings/decoding.rs@@ -0,0 +1,1403 @@+// 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.++//! Contains all supported decoders for Parquet.++use std::{cmp, marker::PhantomData, mem, slice::from_raw_parts_mut};++use super::rle::RleDecoder;++use byteorder::{ByteOrder, LittleEndian};++use crate::parquet::basic::*;+use crate::parquet::data_type::*;+use crate::parquet::errors::{ParquetError, Result};+use crate::parquet::schema::types::ColumnDescPtr;+use crate::parquet::util::{+ bit_util::BitReader,+ memory::{ByteBuffer, ByteBufferPtr},+};++// ----------------------------------------------------------------------+// Decoders++/// A Parquet decoder for the data type `T`.+pub trait Decoder<T: DataType> {+ /// Sets the data to decode to be `data`, which should contain `num_values` of values+ /// to decode.+ fn set_data(&mut self, data: ByteBufferPtr, num_values: usize) -> Result<()>;++ /// Consumes values from this decoder and write the results to `buffer`. This will try+ /// to fill up `buffer`.+ ///+ /// Returns the actual number of values decoded, which should be equal to `buffer.len()`+ /// unless the remaining number of values is less than `buffer.len()`.+ fn get(&mut self, buffer: &mut [T::T]) -> Result<usize>;++ /// Returns the number of values left in this decoder stream.+ fn values_left(&self) -> usize;++ /// Returns the encoding for this decoder.+ fn encoding(&self) -> Encoding;+}++/// Gets a decoder for the column descriptor `descr` and encoding type `encoding`.+///+/// NOTE: the primitive type in `descr` MUST match the data type `T`, otherwise+/// disastrous consequence could occur.+pub fn get_decoder<T: DataType>(+ descr: ColumnDescPtr,+ encoding: Encoding,+) -> Result<Box<Decoder<T>>> {+ let decoder: Box<Decoder<T>> = match encoding {+ Encoding::PLAIN => Box::new(PlainDecoder::new(descr.type_length())),+ Encoding::RLE_DICTIONARY | Encoding::PLAIN_DICTIONARY => {+ return Err(general_err!(+ "Cannot initialize this encoding through this function"+ ));+ }+ Encoding::RLE => Box::new(RleValueDecoder::new()),+ Encoding::DELTA_BINARY_PACKED => Box::new(DeltaBitPackDecoder::new()),+ Encoding::DELTA_LENGTH_BYTE_ARRAY => Box::new(DeltaLengthByteArrayDecoder::new()),+ Encoding::DELTA_BYTE_ARRAY => Box::new(DeltaByteArrayDecoder::new()),+ e => return Err(nyi_err!("Encoding {} is not supported", e)),+ };+ Ok(decoder)+}++// ----------------------------------------------------------------------+// PLAIN Decoding++/// Plain decoding that supports all types.+/// Values are encoded back to back. For native types, data is encoded as little endian.+/// Floating point types are encoded in IEEE.+/// See [`PlainDecoder`](`::encoding::PlainEncoder`) for more information.+pub struct PlainDecoder<T: DataType> {+ // The remaining number of values in the byte array+ num_values: usize,++ // The current starting index in the byte array.+ start: usize,++ // The length for the type `T`. Only used when `T` is `FixedLenByteArrayType`+ type_length: i32,++ // The byte array to decode from. Not set if `T` is bool.+ data: Option<ByteBufferPtr>,++ // Read `data` bit by bit. Only set if `T` is bool.+ bit_reader: Option<BitReader>,++ // To allow `T` in the generic parameter for this struct. This doesn't take any space.+ _phantom: PhantomData<T>,+}++impl<T: DataType> PlainDecoder<T> {+ /// Creates new plain decoder.+ pub fn new(type_length: i32) -> Self {+ PlainDecoder {+ data: None,+ bit_reader: None,+ type_length,+ num_values: 0,+ start: 0,+ _phantom: PhantomData,+ }+ }+}++impl<T: DataType> Decoder<T> for PlainDecoder<T> {+ #[inline]+ default fn set_data(&mut self, data: ByteBufferPtr, num_values: usize) -> Result<()> {+ self.num_values = num_values;+ self.start = 0;+ self.data = Some(data);+ Ok(())+ }++ #[inline]+ fn values_left(&self) -> usize {+ self.num_values+ }++ #[inline]+ fn encoding(&self) -> Encoding {+ Encoding::PLAIN+ }++ #[inline]+ default fn get(&mut self, buffer: &mut [T::T]) -> Result<usize> {+ assert!(self.data.is_some());++ let data = self.data.as_mut().unwrap();+ let num_values = cmp::min(buffer.len(), self.num_values);+ let bytes_left = data.len() - self.start;+ let bytes_to_decode = mem::size_of::<T::T>() * num_values;+ if bytes_left < bytes_to_decode {+ return Err(eof_err!("Not enough bytes to decode"));+ }+ let raw_buffer: &mut [u8] =+ unsafe { from_raw_parts_mut(buffer.as_ptr() as *mut u8, bytes_to_decode) };+ raw_buffer.copy_from_slice(data.range(self.start, bytes_to_decode).as_ref());+ self.start += bytes_to_decode;+ self.num_values -= num_values;++ Ok(num_values)+ }+}++impl Decoder<Int96Type> for PlainDecoder<Int96Type> {+ fn get(&mut self, buffer: &mut [Int96]) -> Result<usize> {+ assert!(self.data.is_some());++ let data = self.data.as_ref().unwrap();+ let num_values = cmp::min(buffer.len(), self.num_values);+ let bytes_left = data.len() - self.start;+ let bytes_to_decode = 12 * num_values;+ if bytes_left < bytes_to_decode {+ return Err(eof_err!("Not enough bytes to decode"));+ }++ let data_range = data.range(self.start, bytes_to_decode);+ let bytes: &[u8] = data_range.data();+ self.start += bytes_to_decode;++ let mut pos = 0; // position in byte array+ for i in 0..num_values {+ let elem0 = LittleEndian::read_u32(&bytes[pos..pos + 4]);+ let elem1 = LittleEndian::read_u32(&bytes[pos + 4..pos + 8]);+ let elem2 = LittleEndian::read_u32(&bytes[pos + 8..pos + 12]);+ buffer[i].set_data(elem0, elem1, elem2);+ pos += 12;+ }+ self.num_values -= num_values;++ Ok(num_values)+ }+}++impl Decoder<BoolType> for PlainDecoder<BoolType> {+ fn set_data(&mut self, data: ByteBufferPtr, num_values: usize) -> Result<()> {+ self.num_values = num_values;+ self.bit_reader = Some(BitReader::new(data));+ Ok(())+ }++ fn get(&mut self, buffer: &mut [bool]) -> Result<usize> {+ assert!(self.bit_reader.is_some());++ let bit_reader = self.bit_reader.as_mut().unwrap();+ let values_read = bit_reader.get_batch::<bool>(buffer, 1);+ self.num_values -= values_read;++ Ok(values_read)+ }+}++impl Decoder<ByteArrayType> for PlainDecoder<ByteArrayType> {+ fn get(&mut self, buffer: &mut [ByteArray]) -> Result<usize> {+ assert!(self.data.is_some());++ let data = self.data.as_mut().unwrap();+ let num_values = cmp::min(buffer.len(), self.num_values);+ for i in 0..num_values {+ let len: usize = read_num_bytes!(u32, 4, data.start_from(self.start).as_ref()) as usize;+ self.start += mem::size_of::<u32>();+ if data.len() < self.start + len {+ return Err(eof_err!("Not enough bytes to decode"));+ }+ buffer[i].set_data(data.range(self.start, len));+ self.start += len;+ }+ self.num_values -= num_values;++ Ok(num_values)+ }+}++impl Decoder<FixedLenByteArrayType> for PlainDecoder<FixedLenByteArrayType> {+ fn get(&mut self, buffer: &mut [ByteArray]) -> Result<usize> {+ assert!(self.data.is_some());+ assert!(self.type_length > 0);++ let data = self.data.as_mut().unwrap();+ let type_length = self.type_length as usize;+ let num_values = cmp::min(buffer.len(), self.num_values);+ for i in 0..num_values {+ if data.len() < self.start + type_length {+ return Err(eof_err!("Not enough bytes to decode"));+ }+ buffer[i].set_data(data.range(self.start, type_length));+ self.start += type_length;+ }+ self.num_values -= num_values;++ Ok(num_values)+ }+}++// ----------------------------------------------------------------------+// RLE_DICTIONARY/PLAIN_DICTIONARY Decoding++/// Dictionary decoder.+/// The dictionary encoding builds a dictionary of values encountered in a given column.+/// The dictionary is be stored in a dictionary page per column chunk.+/// See [`DictEncoder`](`::encoding::DictEncoder`) for more information.+pub struct DictDecoder<T: DataType> {+ // The dictionary, which maps ids to the values+ dictionary: Vec<T::T>,++ // Whether `dictionary` has been initialized+ has_dictionary: bool,++ // The decoder for the value ids+ rle_decoder: Option<RleDecoder>,++ // Number of values left in the data stream+ num_values: usize,+}++impl<T: DataType> DictDecoder<T> {+ /// Creates new dictionary decoder.+ pub fn new() -> Self {+ Self {+ dictionary: vec![],+ has_dictionary: false,+ rle_decoder: None,+ num_values: 0,+ }+ }++ /// Decodes and sets values for dictionary using `decoder` decoder.+ pub fn set_dict(&mut self, mut decoder: Box<Decoder<T>>) -> Result<()> {+ let num_values = decoder.values_left();+ self.dictionary.resize(num_values, T::T::default());+ let _ = decoder.get(&mut self.dictionary)?;+ self.has_dictionary = true;+ Ok(())+ }+}++impl<T: DataType> Decoder<T> for DictDecoder<T> {+ fn set_data(&mut self, data: ByteBufferPtr, num_values: usize) -> Result<()> {+ // First byte in `data` is bit width+ let bit_width = data.as_ref()[0];+ let mut rle_decoder = RleDecoder::new(bit_width);+ rle_decoder.set_data(data.start_from(1));+ self.num_values = num_values;+ self.rle_decoder = Some(rle_decoder);+ Ok(())+ }++ fn get(&mut self, buffer: &mut [T::T]) -> Result<usize> {+ assert!(self.rle_decoder.is_some());+ assert!(self.has_dictionary, "Must call set_dict() first!");++ let rle = self.rle_decoder.as_mut().unwrap();+ let num_values = cmp::min(buffer.len(), self.num_values);+ rle.get_batch_with_dict(&self.dictionary[..], buffer, num_values)+ }++ /// Number of values left in this decoder stream+ fn values_left(&self) -> usize {+ self.num_values+ }++ fn encoding(&self) -> Encoding {+ Encoding::RLE_DICTIONARY+ }+}++// ----------------------------------------------------------------------+// RLE Decoding++/// RLE/Bit-Packing hybrid decoding for values.+/// Currently is used only for data pages v2 and supports boolean types.+/// See [`RleValueEncoder`](`::encoding::RleValueEncoder`) for more information.+pub struct RleValueDecoder<T: DataType> {+ values_left: usize,+ decoder: Option<RleDecoder>,+ _phantom: PhantomData<T>,+}++impl<T: DataType> RleValueDecoder<T> {+ pub fn new() -> Self {+ Self {+ values_left: 0,+ decoder: None,+ _phantom: PhantomData,+ }+ }++ #[inline]+ fn set_data_internal(&mut self, data: ByteBufferPtr, num_values: usize) -> Result<()> {+ // We still need to remove prefix of i32 from the stream.+ let i32_size = mem::size_of::<i32>();+ let data_size = read_num_bytes!(i32, i32_size, data.as_ref()) as usize;+ let rle_decoder = self+ .decoder+ .as_mut()+ .expect("RLE decoder is not initialized");+ rle_decoder.set_data(data.range(i32_size, data_size));+ self.values_left = num_values;+ Ok(())+ }+}++impl<T: DataType> Decoder<T> for RleValueDecoder<T> {+ #[inline]+ default fn set_data(&mut self, _data: ByteBufferPtr, _num_values: usize) -> Result<()> {+ panic!("RleValueDecoder only supports BoolType");+ }++ #[inline]+ fn values_left(&self) -> usize {+ self.values_left+ }++ #[inline]+ fn encoding(&self) -> Encoding {+ Encoding::RLE+ }++ #[inline]+ fn get(&mut self, buffer: &mut [T::T]) -> Result<usize> {+ let rle_decoder = self+ .decoder+ .as_mut()+ .expect("RLE decoder is not initialized");+ let values_read = rle_decoder.get_batch(buffer)?;+ self.values_left -= values_read;+ Ok(values_read)+ }+}++impl Decoder<BoolType> for RleValueDecoder<BoolType> {+ #[inline]+ fn set_data(&mut self, data: ByteBufferPtr, num_values: usize) -> Result<()> {+ // Only support RLE value reader for boolean values with bit width of 1.+ self.decoder = Some(RleDecoder::new(1));+ self.set_data_internal(data, num_values)+ }+}++// ----------------------------------------------------------------------+// DELTA_BINARY_PACKED Decoding++/// Delta binary packed decoder.+/// Supports INT32 and INT64 types.+/// See [`DeltaBitPackEncoder`](`::encoding::DeltaBitPackEncoder`) for more information.+pub struct DeltaBitPackDecoder<T: DataType> {+ bit_reader: BitReader,+ initialized: bool,++ // Header info+ num_values: usize,+ num_mini_blocks: i64,+ values_per_mini_block: usize,+ values_current_mini_block: usize,+ first_value: i64,+ first_value_read: bool,++ // Per block info+ min_delta: i64,+ mini_block_idx: usize,+ delta_bit_width: u8,+ delta_bit_widths: ByteBuffer,+ deltas_in_mini_block: Vec<T::T>, // eagerly loaded deltas for a mini block+ use_batch: bool,++ current_value: i64,++ _phantom: PhantomData<T>,+}++impl<T: DataType> DeltaBitPackDecoder<T> {+ /// Creates new delta bit packed decoder.+ pub fn new() -> Self {+ Self {+ bit_reader: BitReader::from(vec![]),+ initialized: false,+ num_values: 0,+ num_mini_blocks: 0,+ values_per_mini_block: 0,+ values_current_mini_block: 0,+ first_value: 0,+ first_value_read: false,+ min_delta: 0,+ mini_block_idx: 0,+ delta_bit_width: 0,+ delta_bit_widths: ByteBuffer::new(),+ deltas_in_mini_block: vec![],+ use_batch: mem::size_of::<T::T>() == 4,+ current_value: 0,+ _phantom: PhantomData,+ }+ }++ /// Returns underlying bit reader offset.+ pub fn get_offset(&self) -> usize {+ assert!(self.initialized, "Bit reader is not initialized");+ self.bit_reader.get_byte_offset()+ }++ /// Initializes new mini block.+ #[inline]+ fn init_block(&mut self) -> Result<()> {+ self.min_delta = self+ .bit_reader+ .get_zigzag_vlq_int()+ .ok_or(eof_err!("Not enough data to decode 'min_delta'"))?;++ let mut widths = vec![];+ for _ in 0..self.num_mini_blocks {+ let w = self+ .bit_reader+ .get_aligned::<u8>(1)+ .ok_or(eof_err!("Not enough data to decode 'width'"))?;+ widths.push(w);+ }++ self.delta_bit_widths.set_data(widths);+ self.mini_block_idx = 0;+ self.delta_bit_width = self.delta_bit_widths.data()[0];+ self.values_current_mini_block = self.values_per_mini_block;+ Ok(())+ }++ /// Loads delta into mini block.+ #[inline]+ fn load_deltas_in_mini_block(&mut self) -> Result<()> {+ self.deltas_in_mini_block.clear();+ if self.use_batch {+ self.deltas_in_mini_block+ .resize(self.values_current_mini_block, T::T::default());+ let loaded = self.bit_reader.get_batch::<T::T>(+ &mut self.deltas_in_mini_block[..],+ self.delta_bit_width as usize,+ );+ assert!(loaded == self.values_current_mini_block);+ } else {+ for _ in 0..self.values_current_mini_block {+ // TODO: load one batch at a time similar to int32+ let delta = self+ .bit_reader+ .get_value::<T::T>(self.delta_bit_width as usize)+ .ok_or(eof_err!("Not enough data to decode 'delta'"))?;+ self.deltas_in_mini_block.push(delta);+ }+ }++ Ok(())+ }+}++impl<T: DataType> Decoder<T> for DeltaBitPackDecoder<T> {+ // # of total values is derived from encoding+ #[inline]+ default fn set_data(&mut self, data: ByteBufferPtr, _: usize) -> Result<()> {+ self.bit_reader = BitReader::new(data);+ self.initialized = true;++ let block_size = self+ .bit_reader+ .get_vlq_int()+ .ok_or(eof_err!("Not enough data to decode 'block_size'"))?;+ self.num_mini_blocks = self+ .bit_reader+ .get_vlq_int()+ .ok_or(eof_err!("Not enough data to decode 'num_mini_blocks'"))?;+ self.num_values =+ self.bit_reader+ .get_vlq_int()+ .ok_or(eof_err!("Not enough data to decode 'num_values'"))? as usize;+ self.first_value = self+ .bit_reader+ .get_zigzag_vlq_int()+ .ok_or(eof_err!("Not enough data to decode 'first_value'"))?;++ // Reset decoding state+ self.first_value_read = false;+ self.mini_block_idx = 0;+ self.delta_bit_widths.clear();+ self.values_current_mini_block = 0;++ self.values_per_mini_block = (block_size / self.num_mini_blocks) as usize;+ assert!(self.values_per_mini_block % 8 == 0);++ Ok(())+ }++ default fn get(&mut self, buffer: &mut [T::T]) -> Result<usize> {+ assert!(self.initialized, "Bit reader is not initialized");++ let num_values = cmp::min(buffer.len(), self.num_values);+ for i in 0..num_values {+ if !self.first_value_read {+ self.set_decoded_value(buffer, i, self.first_value);+ self.current_value = self.first_value;+ self.first_value_read = true;+ continue;+ }++ if self.values_current_mini_block == 0 {+ self.mini_block_idx += 1;+ if self.mini_block_idx < self.delta_bit_widths.size() {+ self.delta_bit_width = self.delta_bit_widths.data()[self.mini_block_idx];+ self.values_current_mini_block = self.values_per_mini_block;+ } else {+ self.init_block()?;+ }+ self.load_deltas_in_mini_block()?;+ }++ // we decrement values in current mini block, so we need to invert index for delta+ let delta =+ self.get_delta(self.deltas_in_mini_block.len() - self.values_current_mini_block);+ // It is OK for deltas to contain "overflowed" values after encoding,+ // e.g. i64::MAX - i64::MIN, so we use `wrapping_add` to "overflow" again and+ // restore original value.+ self.current_value = self.current_value.wrapping_add(self.min_delta);+ self.current_value = self.current_value.wrapping_add(delta as i64);+ self.set_decoded_value(buffer, i, self.current_value);+ self.values_current_mini_block -= 1;+ }++ self.num_values -= num_values;+ Ok(num_values)+ }++ fn values_left(&self) -> usize {+ self.num_values+ }++ fn encoding(&self) -> Encoding {+ Encoding::DELTA_BINARY_PACKED+ }+}++/// Helper trait to define specific conversions when decoding values+trait DeltaBitPackDecoderConversion<T: DataType> {+ /// Sets decoded value based on type `T`.+ #[inline]+ fn get_delta(&self, index: usize) -> i64;++ #[inline]+ fn set_decoded_value(&self, buffer: &mut [T::T], index: usize, value: i64);+}++impl<T: DataType> DeltaBitPackDecoderConversion<T> for DeltaBitPackDecoder<T> {+ #[inline]+ default fn get_delta(&self, _: usize) -> i64 {+ panic!("DeltaBitPackDecoder only supports Int32Type and Int64Type")+ }++ #[inline]+ default fn set_decoded_value(&self, _: &mut [T::T], _: usize, _: i64) {+ panic!("DeltaBitPackDecoder only supports Int32Type and Int64Type")+ }+}++impl DeltaBitPackDecoderConversion<Int32Type> for DeltaBitPackDecoder<Int32Type> {+ #[inline]+ fn get_delta(&self, index: usize) -> i64 {+ self.deltas_in_mini_block[index] as i64+ }++ #[inline]+ fn set_decoded_value(&self, buffer: &mut [i32], index: usize, value: i64) {+ buffer[index] = value as i32;+ }+}++impl DeltaBitPackDecoderConversion<Int64Type> for DeltaBitPackDecoder<Int64Type> {+ #[inline]+ fn get_delta(&self, index: usize) -> i64 {+ self.deltas_in_mini_block[index]+ }++ #[inline]+ fn set_decoded_value(&self, buffer: &mut [i64], index: usize, value: i64) {+ buffer[index] = value;+ }+}++// ----------------------------------------------------------------------+// DELTA_LENGTH_BYTE_ARRAY Decoding++/// Delta length byte array decoder.+/// Only applied to byte arrays to separate the length values and the data, the lengths+/// are encoded using DELTA_BINARY_PACKED encoding.+/// See [`DeltaLengthByteArrayEncoder`](`::encoding::DeltaLengthByteArrayEncoder`)+/// for more information.+pub struct DeltaLengthByteArrayDecoder<T: DataType> {+ // Lengths for each byte array in `data`+ // TODO: add memory tracker to this+ lengths: Vec<i32>,++ // Current index into `lengths`+ current_idx: usize,++ // Concatenated byte array data+ data: Option<ByteBufferPtr>,++ // Offset into `data`, always point to the beginning of next byte array.+ offset: usize,++ // Number of values left in this decoder stream+ num_values: usize,++ // Placeholder to allow `T` as generic parameter+ _phantom: PhantomData<T>,+}++impl<T: DataType> DeltaLengthByteArrayDecoder<T> {+ /// Creates new delta length byte array decoder.+ pub fn new() -> Self {+ Self {+ lengths: vec![],+ current_idx: 0,+ data: None,+ offset: 0,+ num_values: 0,+ _phantom: PhantomData,+ }+ }+}++impl<T: DataType> Decoder<T> for DeltaLengthByteArrayDecoder<T> {+ default fn set_data(&mut self, _: ByteBufferPtr, _: usize) -> Result<()> {+ Err(general_err!(+ "DeltaLengthByteArrayDecoder only support ByteArrayType"+ ))+ }++ default fn get(&mut self, _: &mut [T::T]) -> Result<usize> {+ Err(general_err!(+ "DeltaLengthByteArrayDecoder only support ByteArrayType"+ ))+ }++ fn values_left(&self) -> usize {+ self.num_values+ }++ fn encoding(&self) -> Encoding {+ Encoding::DELTA_LENGTH_BYTE_ARRAY+ }+}++impl Decoder<ByteArrayType> for DeltaLengthByteArrayDecoder<ByteArrayType> {+ fn set_data(&mut self, data: ByteBufferPtr, num_values: usize) -> Result<()> {+ let mut len_decoder = DeltaBitPackDecoder::<Int32Type>::new();+ len_decoder.set_data(data.all(), num_values)?;+ let num_lengths = len_decoder.values_left();+ self.lengths.resize(num_lengths, 0);+ len_decoder.get(&mut self.lengths[..])?;++ self.data = Some(data.start_from(len_decoder.get_offset()));+ self.offset = 0;+ self.current_idx = 0;+ self.num_values = num_lengths;+ Ok(())+ }++ fn get(&mut self, buffer: &mut [ByteArray]) -> Result<usize> {+ assert!(self.data.is_some());++ let data = self.data.as_ref().unwrap();+ let num_values = cmp::min(buffer.len(), self.num_values);+ for i in 0..num_values {+ let len = self.lengths[self.current_idx] as usize;+ buffer[i].set_data(data.range(self.offset, len));+ self.offset += len;+ self.current_idx += 1;+ }++ self.num_values -= num_values;+ Ok(num_values)+ }+}++// ----------------------------------------------------------------------+// DELTA_BYTE_ARRAY Decoding++/// Delta byte array decoder.+/// Prefix lengths are encoded using `DELTA_BINARY_PACKED` encoding, Suffixes are stored+/// using `DELTA_LENGTH_BYTE_ARRAY` encoding.+/// See [`DeltaByteArrayEncoder`](`::encoding::DeltaByteArrayEncoder`) for more+/// information.+pub struct DeltaByteArrayDecoder<T: DataType> {+ // Prefix lengths for each byte array+ // TODO: add memory tracker to this+ prefix_lengths: Vec<i32>,++ // The current index into `prefix_lengths`,+ current_idx: usize,++ // Decoder for all suffixes, the # of which should be the same as+ // `prefix_lengths.len()`+ suffix_decoder: Option<DeltaLengthByteArrayDecoder<ByteArrayType>>,++ // The last byte array, used to derive the current prefix+ previous_value: Vec<u8>,++ // Number of values left+ num_values: usize,++ // Placeholder to allow `T` as generic parameter+ _phantom: PhantomData<T>,+}++impl<T: DataType> DeltaByteArrayDecoder<T> {+ /// Creates new delta byte array decoder.+ pub fn new() -> Self {+ Self {+ prefix_lengths: vec![],+ current_idx: 0,+ suffix_decoder: None,+ previous_value: vec![],+ num_values: 0,+ _phantom: PhantomData,+ }+ }+}++impl<'m, T: DataType> Decoder<T> for DeltaByteArrayDecoder<T> {+ default fn set_data(&mut self, _: ByteBufferPtr, _: usize) -> Result<()> {+ Err(general_err!(+ "DeltaByteArrayDecoder only supports ByteArrayType and FixedLenByteArrayType"+ ))+ }++ default fn get(&mut self, _: &mut [T::T]) -> Result<usize> {+ Err(general_err!(+ "DeltaByteArrayDecoder only supports ByteArrayType and FixedLenByteArrayType"+ ))+ }++ fn values_left(&self) -> usize {+ self.num_values+ }++ fn encoding(&self) -> Encoding {+ Encoding::DELTA_BYTE_ARRAY+ }+}++impl Decoder<ByteArrayType> for DeltaByteArrayDecoder<ByteArrayType> {+ fn set_data(&mut self, data: ByteBufferPtr, num_values: usize) -> Result<()> {+ let mut prefix_len_decoder = DeltaBitPackDecoder::<Int32Type>::new();+ prefix_len_decoder.set_data(data.all(), num_values)?;+ let num_prefixes = prefix_len_decoder.values_left();+ self.prefix_lengths.resize(num_prefixes, 0);+ prefix_len_decoder.get(&mut self.prefix_lengths[..])?;++ let mut suffix_decoder = DeltaLengthByteArrayDecoder::new();+ suffix_decoder.set_data(data.start_from(prefix_len_decoder.get_offset()), num_values)?;+ self.suffix_decoder = Some(suffix_decoder);+ self.num_values = num_prefixes;+ self.current_idx = 0;+ self.previous_value.clear();+ Ok(())+ }++ fn get(&mut self, buffer: &mut [ByteArray]) -> Result<usize> {+ assert!(self.suffix_decoder.is_some());++ let num_values = cmp::min(buffer.len(), self.num_values);+ let mut v: [ByteArray; 1] = [ByteArray::new(); 1];+ for i in 0..num_values {+ // Process suffix+ // TODO: this is awkward - maybe we should add a non-vectorized API?+ let suffix_decoder = self.suffix_decoder.as_mut().unwrap();+ suffix_decoder.get(&mut v[..])?;+ let suffix = v[0].data();++ // Extract current prefix length, can be 0+ let prefix_len = self.prefix_lengths[self.current_idx] as usize;++ // Concatenate prefix with suffix+ let mut result = Vec::new();+ result.extend_from_slice(&self.previous_value[0..prefix_len]);+ result.extend_from_slice(suffix);++ let data = ByteBufferPtr::new(result.clone());+ buffer[i].set_data(data);+ self.previous_value = result;+ self.current_idx += 1;+ }++ self.num_values -= num_values;+ Ok(num_values)+ }+}++impl Decoder<FixedLenByteArrayType> for DeltaByteArrayDecoder<FixedLenByteArrayType> {+ fn set_data(&mut self, data: ByteBufferPtr, num_values: usize) -> Result<()> {+ let s: &mut DeltaByteArrayDecoder<ByteArrayType> = unsafe { mem::transmute(self) };+ s.set_data(data, num_values)+ }++ fn get(&mut self, buffer: &mut [ByteArray]) -> Result<usize> {+ let s: &mut DeltaByteArrayDecoder<ByteArrayType> = unsafe { mem::transmute(self) };+ s.get(buffer)+ }+}++#[cfg(test)]+mod tests {+ use super::{super::encoding::*, *};++ use std::{mem, rc::Rc};++ use crate::parquet::schema::types::{+ ColumnDescPtr, ColumnDescriptor, ColumnPath, Type as SchemaType,+ };+ use crate::parquet::util::{bit_util::set_array_bit, memory::MemTracker, test_common::RandGen};++ #[test]+ fn test_get_decoders() {+ // supported encodings+ create_and_check_decoder::<Int32Type>(Encoding::PLAIN, None);+ create_and_check_decoder::<Int32Type>(Encoding::DELTA_BINARY_PACKED, None);+ create_and_check_decoder::<Int32Type>(Encoding::DELTA_LENGTH_BYTE_ARRAY, None);+ create_and_check_decoder::<Int32Type>(Encoding::DELTA_BYTE_ARRAY, None);+ create_and_check_decoder::<BoolType>(Encoding::RLE, None);++ // error when initializing+ create_and_check_decoder::<Int32Type>(+ Encoding::RLE_DICTIONARY,+ Some(general_err!(+ "Cannot initialize this encoding through this function"+ )),+ );+ create_and_check_decoder::<Int32Type>(+ Encoding::PLAIN_DICTIONARY,+ Some(general_err!(+ "Cannot initialize this encoding through this function"+ )),+ );++ // unsupported+ create_and_check_decoder::<Int32Type>(+ Encoding::BIT_PACKED,+ Some(nyi_err!("Encoding BIT_PACKED is not supported")),+ );+ }++ #[test]+ fn test_plain_decode_int32() {+ let data = vec![42, 18, 52];+ let data_bytes = Int32Type::to_byte_array(&data[..]);+ let mut buffer = vec![0; 3];+ test_plain_decode::<Int32Type>(+ ByteBufferPtr::new(data_bytes),+ 3,+ -1,+ &mut buffer[..],+ &data[..],+ );+ }++ #[test]+ fn test_plain_decode_int64() {+ let data = vec![42, 18, 52];+ let data_bytes = Int64Type::to_byte_array(&data[..]);+ let mut buffer = vec![0; 3];+ test_plain_decode::<Int64Type>(+ ByteBufferPtr::new(data_bytes),+ 3,+ -1,+ &mut buffer[..],+ &data[..],+ );+ }++ #[test]+ fn test_plain_decode_float() {+ let data = vec![3.14, 2.414, 12.51];+ let data_bytes = FloatType::to_byte_array(&data[..]);+ let mut buffer = vec![0.0; 3];+ test_plain_decode::<FloatType>(+ ByteBufferPtr::new(data_bytes),+ 3,+ -1,+ &mut buffer[..],+ &data[..],+ );+ }++ #[test]+ fn test_plain_decode_double() {+ let data = vec![3.14f64, 2.414f64, 12.51f64];+ let data_bytes = DoubleType::to_byte_array(&data[..]);+ let mut buffer = vec![0.0f64; 3];+ test_plain_decode::<DoubleType>(+ ByteBufferPtr::new(data_bytes),+ 3,+ -1,+ &mut buffer[..],+ &data[..],+ );+ }++ #[test]+ fn test_plain_decode_int96() {+ let mut data = vec![Int96::new(); 4];+ data[0].set_data(11, 22, 33);+ data[1].set_data(44, 55, 66);+ data[2].set_data(10, 20, 30);+ data[3].set_data(40, 50, 60);+ let data_bytes = Int96Type::to_byte_array(&data[..]);+ let mut buffer = vec![Int96::new(); 4];+ test_plain_decode::<Int96Type>(+ ByteBufferPtr::new(data_bytes),+ 4,+ -1,+ &mut buffer[..],+ &data[..],+ );+ }++ #[test]+ fn test_plain_decode_bool() {+ let data = vec![+ false, true, false, false, true, false, true, true, false, true,+ ];+ let data_bytes = BoolType::to_byte_array(&data[..]);+ let mut buffer = vec![false; 10];+ test_plain_decode::<BoolType>(+ ByteBufferPtr::new(data_bytes),+ 10,+ -1,+ &mut buffer[..],+ &data[..],+ );+ }++ #[test]+ fn test_plain_decode_byte_array() {+ let mut data = vec![ByteArray::new(); 2];+ data[0].set_data(ByteBufferPtr::new(String::from("hello").into_bytes()));+ data[1].set_data(ByteBufferPtr::new(String::from("parquet").into_bytes()));+ let data_bytes = ByteArrayType::to_byte_array(&data[..]);+ let mut buffer = vec![ByteArray::new(); 2];+ test_plain_decode::<ByteArrayType>(+ ByteBufferPtr::new(data_bytes),+ 2,+ -1,+ &mut buffer[..],+ &data[..],+ );+ }++ #[test]+ fn test_plain_decode_fixed_len_byte_array() {+ let mut data = vec![ByteArray::default(); 3];+ data[0].set_data(ByteBufferPtr::new(String::from("bird").into_bytes()));+ data[1].set_data(ByteBufferPtr::new(String::from("come").into_bytes()));+ data[2].set_data(ByteBufferPtr::new(String::from("flow").into_bytes()));+ let data_bytes = FixedLenByteArrayType::to_byte_array(&data[..]);+ let mut buffer = vec![ByteArray::default(); 3];+ test_plain_decode::<FixedLenByteArrayType>(+ ByteBufferPtr::new(data_bytes),+ 3,+ 4,+ &mut buffer[..],+ &data[..],+ );+ }++ #[test]+ #[should_panic(expected = "RleValueEncoder only supports BoolType")]+ fn test_rle_value_encode_int32_not_supported() {+ let mut encoder = RleValueEncoder::<Int32Type>::new();+ encoder.put(&vec![1, 2, 3, 4]).unwrap();+ }++ #[test]+ #[should_panic(expected = "RleValueDecoder only supports BoolType")]+ fn test_rle_value_decode_int32_not_supported() {+ let mut decoder = RleValueDecoder::<Int32Type>::new();+ decoder+ .set_data(ByteBufferPtr::new(vec![5, 0, 0, 0]), 1)+ .unwrap();+ }++ #[test]+ fn test_rle_value_decode_bool_decode() {+ // Test multiple 'put' calls on the same encoder+ let data = vec![+ BoolType::gen_vec(-1, 256),+ BoolType::gen_vec(-1, 257),+ BoolType::gen_vec(-1, 126),+ ];+ test_rle_value_decode::<BoolType>(data);+ }++ #[test]+ #[should_panic(expected = "Bit reader is not initialized")]+ fn test_delta_bit_packed_not_initialized_offset() {+ // Fail if set_data() is not called before get_offset()+ let decoder = DeltaBitPackDecoder::<Int32Type>::new();+ decoder.get_offset();+ }++ #[test]+ #[should_panic(expected = "Bit reader is not initialized")]+ fn test_delta_bit_packed_not_initialized_get() {+ // Fail if set_data() is not called before get()+ let mut decoder = DeltaBitPackDecoder::<Int32Type>::new();+ let mut buffer = vec![];+ decoder.get(&mut buffer).unwrap();+ }++ #[test]+ fn test_delta_bit_packed_int32_empty() {+ let data = vec![vec![0; 0]];+ test_delta_bit_packed_decode::<Int32Type>(data);+ }++ #[test]+ fn test_delta_bit_packed_int32_repeat() {+ let block_data = vec![+ 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5,+ 6, 7, 8,+ ];+ test_delta_bit_packed_decode::<Int32Type>(vec![block_data]);+ }++ #[test]+ fn test_delta_bit_packed_int32_uneven() {+ let block_data = vec![1, -2, 3, -4, 5, 6, 7, 8, 9, 10, 11];+ test_delta_bit_packed_decode::<Int32Type>(vec![block_data]);+ }++ #[test]+ fn test_delta_bit_packed_int32_same_values() {+ let block_data = vec![+ 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,+ ];+ test_delta_bit_packed_decode::<Int32Type>(vec![block_data]);++ let block_data = vec![+ -127, -127, -127, -127, -127, -127, -127, -127, -127, -127, -127, -127, -127, -127,+ -127, -127,+ ];+ test_delta_bit_packed_decode::<Int32Type>(vec![block_data]);+ }++ #[test]+ fn test_delta_bit_packed_int32_min_max() {+ let block_data = vec![+ i32::min_value(),+ i32::max_value(),+ i32::min_value(),+ i32::max_value(),+ i32::min_value(),+ i32::max_value(),+ i32::min_value(),+ i32::max_value(),+ ];+ test_delta_bit_packed_decode::<Int32Type>(vec![block_data]);+ }++ #[test]+ fn test_delta_bit_packed_int32_multiple_blocks() {+ // Test multiple 'put' calls on the same encoder+ let data = vec![+ Int32Type::gen_vec(-1, 64),+ Int32Type::gen_vec(-1, 128),+ Int32Type::gen_vec(-1, 64),+ ];+ test_delta_bit_packed_decode::<Int32Type>(data);+ }++ #[test]+ fn test_delta_bit_packed_int32_data_across_blocks() {+ // Test multiple 'put' calls on the same encoder+ let data = vec![Int32Type::gen_vec(-1, 256), Int32Type::gen_vec(-1, 257)];+ test_delta_bit_packed_decode::<Int32Type>(data);+ }++ #[test]+ fn test_delta_bit_packed_int32_with_empty_blocks() {+ let data = vec![+ Int32Type::gen_vec(-1, 128),+ vec![0; 0],+ Int32Type::gen_vec(-1, 64),+ ];+ test_delta_bit_packed_decode::<Int32Type>(data);+ }++ #[test]+ fn test_delta_bit_packed_int64_empty() {+ let data = vec![vec![0; 0]];+ test_delta_bit_packed_decode::<Int64Type>(data);+ }++ #[test]+ fn test_delta_bit_packed_int64_min_max() {+ let block_data = vec![+ i64::min_value(),+ i64::max_value(),+ i64::min_value(),+ i64::max_value(),+ i64::min_value(),+ i64::max_value(),+ i64::min_value(),+ i64::max_value(),+ ];+ test_delta_bit_packed_decode::<Int64Type>(vec![block_data]);+ }++ #[test]+ fn test_delta_bit_packed_int64_multiple_blocks() {+ // Test multiple 'put' calls on the same encoder+ let data = vec![+ Int64Type::gen_vec(-1, 64),+ Int64Type::gen_vec(-1, 128),+ Int64Type::gen_vec(-1, 64),+ ];+ test_delta_bit_packed_decode::<Int64Type>(data);+ }++ #[test]+ fn test_delta_bit_packed_decoder_sample() {+ let data_bytes = vec![+ 128, 1, 4, 3, 58, 28, 6, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,+ 0, 0, 0, 0, 0, 0,+ ];+ let buffer = ByteBufferPtr::new(data_bytes);+ let mut decoder: DeltaBitPackDecoder<Int32Type> = DeltaBitPackDecoder::new();+ decoder.set_data(buffer, 3).unwrap();+ // check exact offsets, because when reading partial values we end up with+ // some data not being read from bit reader+ assert_eq!(decoder.get_offset(), 5);+ let mut result = vec![0, 0, 0];+ decoder.get(&mut result).unwrap();+ assert_eq!(decoder.get_offset(), 34);+ assert_eq!(result, vec![29, 43, 89]);+ }++ #[test]+ fn test_delta_byte_array_same_arrays() {+ let data = vec![+ vec![ByteArray::from(vec![1, 2, 3, 4, 5, 6])],+ vec![+ ByteArray::from(vec![1, 2, 3, 4, 5, 6]),+ ByteArray::from(vec![1, 2, 3, 4, 5, 6]),+ ],+ vec![+ ByteArray::from(vec![1, 2, 3, 4, 5, 6]),+ ByteArray::from(vec![1, 2, 3, 4, 5, 6]),+ ],+ ];+ test_delta_byte_array_decode(data);+ }++ #[test]+ fn test_delta_byte_array_unique_arrays() {+ let data = vec![+ vec![ByteArray::from(vec![1])],+ vec![ByteArray::from(vec![2, 3]), ByteArray::from(vec![4, 5, 6])],+ vec![+ ByteArray::from(vec![7, 8]),+ ByteArray::from(vec![9, 0, 1, 2]),+ ],+ ];+ test_delta_byte_array_decode(data);+ }++ #[test]+ fn test_delta_byte_array_single_array() {+ let data = vec![vec![ByteArray::from(vec![1, 2, 3, 4, 5, 6])]];+ test_delta_byte_array_decode(data);+ }++ fn test_plain_decode<T: DataType>(+ data: ByteBufferPtr,+ num_values: usize,+ type_length: i32,+ buffer: &mut [T::T],+ expected: &[T::T],+ ) {+ let mut decoder: PlainDecoder<T> = PlainDecoder::new(type_length);+ let result = decoder.set_data(data, num_values);+ assert!(result.is_ok());+ let result = decoder.get(&mut buffer[..]);+ assert!(result.is_ok());+ assert_eq!(decoder.values_left(), 0);+ assert_eq!(buffer, expected);+ }++ fn test_rle_value_decode<T: DataType>(data: Vec<Vec<T::T>>) {+ test_encode_decode::<T>(data, Encoding::RLE);+ }++ fn test_delta_bit_packed_decode<T: DataType>(data: Vec<Vec<T::T>>) {+ test_encode_decode::<T>(data, Encoding::DELTA_BINARY_PACKED);+ }++ fn test_delta_byte_array_decode(data: Vec<Vec<ByteArray>>) {+ test_encode_decode::<ByteArrayType>(data, Encoding::DELTA_BYTE_ARRAY);+ }++ // Input data represents vector of data slices to write (test multiple `put()` calls)+ // For example,+ // vec![vec![1, 2, 3]] invokes `put()` once and writes {1, 2, 3}+ // vec![vec![1, 2], vec![3]] invokes `put()` twice and writes {1, 2, 3}+ fn test_encode_decode<T: DataType>(data: Vec<Vec<T::T>>, encoding: Encoding) {+ // Type length should not really matter for encode/decode test,+ // otherwise change it based on type+ let col_descr = create_test_col_desc_ptr(-1, T::get_physical_type());++ // Encode data+ let mut encoder = get_encoder::<T>(col_descr.clone(), encoding, Rc::new(MemTracker::new()))+ .expect("get encoder");++ for v in &data[..] {+ encoder.put(&v[..]).expect("ok to encode");+ }+ let bytes = encoder.flush_buffer().expect("ok to flush buffer");++ // Flatten expected data as contiguous array of values+ let expected: Vec<T::T> = data.iter().flat_map(|s| s.clone()).collect();++ // Decode data and compare with original+ let mut decoder = get_decoder::<T>(col_descr.clone(), encoding).expect("get decoder");++ let mut result = vec![T::T::default(); expected.len()];+ decoder+ .set_data(bytes, expected.len())+ .expect("ok to set data");+ let mut result_num_values = 0;+ while decoder.values_left() > 0 {+ result_num_values += decoder+ .get(&mut result[result_num_values..])+ .expect("ok to decode");+ }+ assert_eq!(result_num_values, expected.len());+ assert_eq!(result, expected);+ }++ fn create_and_check_decoder<T: DataType>(encoding: Encoding, err: Option<ParquetError>) {+ let descr = create_test_col_desc_ptr(-1, T::get_physical_type());+ let decoder = get_decoder::<T>(descr, encoding);+ match err {+ Some(parquet_error) => {+ assert!(decoder.is_err());+ assert_eq!(decoder.err().unwrap(), parquet_error);+ }+ None => {+ assert!(decoder.is_ok());+ assert_eq!(decoder.unwrap().encoding(), encoding);+ }+ }+ }++ // Creates test column descriptor.+ fn create_test_col_desc_ptr(type_len: i32, t: Type) -> ColumnDescPtr {+ let ty = SchemaType::primitive_type_builder("t", t)+ .with_length(type_len)+ .build()+ .unwrap();+ Rc::new(ColumnDescriptor::new(+ Rc::new(ty),+ None,+ 0,+ 0,+ ColumnPath::new(vec![]),+ ))+ }++ fn usize_to_bytes(v: usize) -> [u8; 4] {+ unsafe { mem::transmute::<u32, [u8; 4]>(v as u32) }+ }++ /// A util trait to convert slices of different types to byte arrays+ trait ToByteArray<T: DataType> {+ fn to_byte_array(data: &[T::T]) -> Vec<u8>;+ }++ impl<T> ToByteArray<T> for T+ where+ T: DataType,+ {+ default fn to_byte_array(data: &[T::T]) -> Vec<u8> {+ let mut v = vec![];+ let type_len = ::std::mem::size_of::<T::T>();+ v.extend_from_slice(unsafe {+ ::std::slice::from_raw_parts(data.as_ptr() as *const u8, data.len() * type_len)+ });+ v+ }+ }++ impl ToByteArray<BoolType> for BoolType {+ fn to_byte_array(data: &[bool]) -> Vec<u8> {+ let mut v = vec![];+ for i in 0..data.len() {+ if i % 8 == 0 {+ v.push(0);+ }+ if data[i] {+ set_array_bit(&mut v[..], i);+ }+ }+ v+ }+ }++ impl ToByteArray<Int96Type> for Int96Type {+ fn to_byte_array(data: &[Int96]) -> Vec<u8> {+ let mut v = vec![];+ for d in data {+ unsafe {+ let copy = ::std::slice::from_raw_parts(d.data().as_ptr() as *const u8, 12);+ v.extend_from_slice(copy);+ };+ }+ v+ }+ }++ impl ToByteArray<ByteArrayType> for ByteArrayType {+ fn to_byte_array(data: &[ByteArray]) -> Vec<u8> {+ let mut v = vec![];+ for d in data {+ let buf = d.data();+ let len = &usize_to_bytes(buf.len());+ v.extend_from_slice(len);+ v.extend(buf);+ }+ v+ }+ }++ impl ToByteArray<FixedLenByteArrayType> for FixedLenByteArrayType {+ fn to_byte_array(data: &[ByteArray]) -> Vec<u8> {+ let mut v = vec![];+ for d in data {+ let buf = d.data();+ v.extend(buf);+ }+ v+ }+ }+}diff --git a/rust/src/parquet/encodings/encoding.rs b/rust/src/parquet/encodings/encoding.rsnew file mode 100644index 0000000000..cecb03cb54--- /dev/null+++ b/rust/src/parquet/encodings/encoding.rs@@ -0,0 +1,1360 @@+// 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.++//! Contains all supported encoders for Parquet.++use std::{cmp, io::Write, marker::PhantomData, mem, slice};++use crate::parquet::basic::*;+use crate::parquet::data_type::*;+use crate::parquet::encodings::rle::RleEncoder;+use crate::parquet::errors::{ParquetError, Result};+use crate::parquet::schema::types::ColumnDescPtr;+use crate::parquet::util::{+ bit_util::{log2, num_required_bits, BitWriter},+ hash_util,+ memory::{Buffer, ByteBuffer, ByteBufferPtr, MemTrackerPtr},+};++// ----------------------------------------------------------------------+// Encoders++/// An Parquet encoder for the data type `T`.+///+/// Currently this allocates internal buffers for the encoded values. After done putting+/// values, caller should call `flush_buffer()` to get an immutable buffer pointer.+pub trait Encoder<T: DataType> {+ /// Encodes data from `values`.+ fn put(&mut self, values: &[T::T]) -> Result<()>;++ /// Returns the encoding type of this encoder.+ fn encoding(&self) -> Encoding;++ /// Returns an estimate of the encoded data, in bytes.+ /// Method call must be O(1).+ fn estimated_data_encoded_size(&self) -> usize;++ /// Flushes the underlying byte buffer that's being processed by this encoder, and+ /// return the immutable copy of it. This will also reset the internal state.+ fn flush_buffer(&mut self) -> Result<ByteBufferPtr>;+}++/// Gets a encoder for the particular data type `T` and encoding `encoding`. Memory usage+/// for the encoder instance is tracked by `mem_tracker`.+pub fn get_encoder<T: DataType>(+ desc: ColumnDescPtr,+ encoding: Encoding,+ mem_tracker: MemTrackerPtr,+) -> Result<Box<Encoder<T>>> {+ let encoder: Box<Encoder<T>> = match encoding {+ Encoding::PLAIN => Box::new(PlainEncoder::new(desc, mem_tracker, vec![])),+ Encoding::RLE_DICTIONARY | Encoding::PLAIN_DICTIONARY => {+ return Err(general_err!(+ "Cannot initialize this encoding through this function"+ ));+ }+ Encoding::RLE => Box::new(RleValueEncoder::new()),+ Encoding::DELTA_BINARY_PACKED => Box::new(DeltaBitPackEncoder::new()),+ Encoding::DELTA_LENGTH_BYTE_ARRAY => Box::new(DeltaLengthByteArrayEncoder::new()),+ Encoding::DELTA_BYTE_ARRAY => Box::new(DeltaByteArrayEncoder::new()),+ e => return Err(nyi_err!("Encoding {} is not supported", e)),+ };+ Ok(encoder)+}++// ----------------------------------------------------------------------+// Plain encoding++/// Plain encoding that supports all types.+/// Values are encoded back to back.+/// The plain encoding is used whenever a more efficient encoding can not be used.+/// It stores the data in the following format:+/// - BOOLEAN - 1 bit per value, 0 is false; 1 is true.+/// - INT32 - 4 bytes per value, stored as little-endian.+/// - INT64 - 8 bytes per value, stored as little-endian.+/// - FLOAT - 4 bytes per value, stored as IEEE little-endian.+/// - DOUBLE - 8 bytes per value, stored as IEEE little-endian.+/// - BYTE_ARRAY - 4 byte length stored as little endian, followed by bytes.+/// - FIXED_LEN_BYTE_ARRAY - just the bytes are stored.+pub struct PlainEncoder<T: DataType> {+ buffer: ByteBuffer,+ bit_writer: BitWriter,+ desc: ColumnDescPtr,+ _phantom: PhantomData<T>,+}++impl<T: DataType> PlainEncoder<T> {+ /// Creates new plain encoder.+ pub fn new(desc: ColumnDescPtr, mem_tracker: MemTrackerPtr, vec: Vec<u8>) -> Self {+ let mut byte_buffer = ByteBuffer::new().with_mem_tracker(mem_tracker);+ byte_buffer.set_data(vec);+ Self {+ buffer: byte_buffer,+ bit_writer: BitWriter::new(256),+ desc,+ _phantom: PhantomData,+ }+ }+}++impl<T: DataType> Encoder<T> for PlainEncoder<T> {+ default fn put(&mut self, values: &[T::T]) -> Result<()> {+ let bytes = unsafe {+ slice::from_raw_parts(+ values as *const [T::T] as *const u8,+ mem::size_of::<T::T>() * values.len(),+ )+ };+ self.buffer.write(bytes)?;+ Ok(())+ }++ fn encoding(&self) -> Encoding {+ Encoding::PLAIN+ }++ fn estimated_data_encoded_size(&self) -> usize {+ self.buffer.size() + self.bit_writer.bytes_written()+ }++ #[inline]+ default fn flush_buffer(&mut self) -> Result<ByteBufferPtr> {+ self.buffer.write(self.bit_writer.flush_buffer())?;+ self.buffer.flush()?;+ self.bit_writer.clear();++ Ok(self.buffer.consume())+ }+}++impl Encoder<BoolType> for PlainEncoder<BoolType> {+ fn put(&mut self, values: &[bool]) -> Result<()> {+ for v in values {+ self.bit_writer.put_value(*v as u64, 1);+ }+ Ok(())+ }+}++impl Encoder<Int96Type> for PlainEncoder<Int96Type> {+ fn put(&mut self, values: &[Int96]) -> Result<()> {+ for v in values {+ self.buffer.write(v.as_bytes())?;+ }+ self.buffer.flush()?;+ Ok(())+ }+}++impl Encoder<ByteArrayType> for PlainEncoder<ByteArrayType> {+ fn put(&mut self, values: &[ByteArray]) -> Result<()> {+ for v in values {+ self.buffer.write(&(v.len().to_le() as u32).as_bytes())?;+ self.buffer.write(v.data())?;+ }+ self.buffer.flush()?;+ Ok(())+ }+}++impl Encoder<FixedLenByteArrayType> for PlainEncoder<FixedLenByteArrayType> {+ fn put(&mut self, values: &[ByteArray]) -> Result<()> {+ for v in values {+ self.buffer.write(v.data())?;+ }+ self.buffer.flush()?;+ Ok(())+ }+}++// ----------------------------------------------------------------------+// Dictionary encoding++const INITIAL_HASH_TABLE_SIZE: usize = 1024;+const MAX_HASH_LOAD: f32 = 0.7;+const HASH_SLOT_EMPTY: i32 = -1;++/// Dictionary encoder.+/// The dictionary encoding builds a dictionary of values encountered in a given column.+/// The dictionary page is written first, before the data pages of the column chunk.+///+/// Dictionary page format: the entries in the dictionary - in dictionary order -+/// using the plain encoding.+///+/// Data page format: the bit width used to encode the entry ids stored as 1 byte+/// (max bit width = 32), followed by the values encoded using RLE/Bit packed described+/// above (with the given bit width).+pub struct DictEncoder<T: DataType> {+ // Descriptor for the column to be encoded.+ desc: ColumnDescPtr,++ // Size of the table. **Must be** a power of 2.+ hash_table_size: usize,++ // Store `hash_table_size` - 1, so that `j & mod_bitmask` is equivalent to+ // `j % hash_table_size`, but uses far fewer CPU cycles.+ mod_bitmask: u32,++ // Stores indices which map (many-to-one) to the values in the `uniques` array.+ // Here we are using fix-sized array with linear probing.+ // A slot with `HASH_SLOT_EMPTY` indicates the slot is not currently occupied.+ hash_slots: Buffer<i32>,++ // Indices that have not yet be written out by `write_indices()`.+ buffered_indices: Buffer<i32>,++ // The unique observed values.+ uniques: Buffer<T::T>,++ // Size in bytes needed to encode this dictionary.+ uniques_size_in_bytes: usize,++ // Tracking memory usage for the various data structures in this struct.+ mem_tracker: MemTrackerPtr,+}++impl<T: DataType> DictEncoder<T> {+ /// Creates new dictionary encoder.+ pub fn new(desc: ColumnDescPtr, mem_tracker: MemTrackerPtr) -> Self {+ let mut slots = Buffer::new().with_mem_tracker(mem_tracker.clone());+ slots.resize(INITIAL_HASH_TABLE_SIZE, -1);+ Self {+ desc,+ hash_table_size: INITIAL_HASH_TABLE_SIZE,+ mod_bitmask: (INITIAL_HASH_TABLE_SIZE - 1) as u32,+ hash_slots: slots,+ buffered_indices: Buffer::new().with_mem_tracker(mem_tracker.clone()),+ uniques: Buffer::new().with_mem_tracker(mem_tracker.clone()),+ uniques_size_in_bytes: 0,+ mem_tracker,+ }+ }++ /// Returns true if dictionary entries are sorted, false otherwise.+ #[inline]+ pub fn is_sorted(&self) -> bool {+ // Sorting is not supported currently.+ false+ }++ /// Returns number of unique values (keys) in the dictionary.+ pub fn num_entries(&self) -> usize {+ self.uniques.size()+ }++ /// Returns size of unique values (keys) in the dictionary, in bytes.+ pub fn dict_encoded_size(&self) -> usize {+ self.uniques_size_in_bytes+ }++ /// Writes out the dictionary values with PLAIN encoding in a byte buffer, and return+ /// the result.+ #[inline]+ pub fn write_dict(&self) -> Result<ByteBufferPtr> {+ let mut plain_encoder =+ PlainEncoder::<T>::new(self.desc.clone(), self.mem_tracker.clone(), vec![]);+ plain_encoder.put(self.uniques.data())?;+ plain_encoder.flush_buffer()+ }++ /// Writes out the dictionary values with RLE encoding in a byte buffer, and return the+ /// result.+ #[inline]+ pub fn write_indices(&mut self) -> Result<ByteBufferPtr> {+ // TODO: the caller should allocate the buffer+ let buffer_len = self.estimated_data_encoded_size();+ let mut buffer: Vec<u8> = vec![0; buffer_len as usize];+ buffer[0] = self.bit_width() as u8;+ self.mem_tracker.alloc(buffer.capacity() as i64);++ // Write bit width in the first byte+ buffer.write((self.bit_width() as u8).as_bytes())?;+ let mut encoder = RleEncoder::new_from_buf(self.bit_width(), buffer, 1);+ for index in self.buffered_indices.data() {+ if !encoder.put(*index as u64)? {+ return Err(general_err!("Encoder doesn't have enough space"));+ }+ }+ self.buffered_indices.clear();+ Ok(ByteBufferPtr::new(encoder.consume()?))+ }++ #[inline]+ fn put_one(&mut self, value: &T::T) -> Result<()> {+ let mut j = (hash_util::hash(value, 0) & self.mod_bitmask) as usize;+ let mut index = self.hash_slots[j];++ while index != HASH_SLOT_EMPTY && self.uniques[index as usize] != *value {+ j += 1;+ if j == self.hash_table_size {+ j = 0;+ }+ index = self.hash_slots[j];+ }++ if index == HASH_SLOT_EMPTY {+ index = self.uniques.size() as i32;+ self.hash_slots[j] = index;+ self.add_dict_key(value.clone());++ if self.uniques.size() > (self.hash_table_size as f32 * MAX_HASH_LOAD) as usize {+ self.double_table_size();+ }+ }++ self.buffered_indices.push(index);+ Ok(())+ }++ #[inline]+ fn add_dict_key(&mut self, value: T::T) {+ self.uniques_size_in_bytes += self.get_encoded_size(&value);+ self.uniques.push(value);+ }++ #[inline]+ fn bit_width(&self) -> u8 {+ let num_entries = self.uniques.size();+ if num_entries == 0 {+ 0+ } else if num_entries == 1 {+ 1+ } else {+ log2(num_entries as u64) as u8+ }+ }++ #[inline]+ fn double_table_size(&mut self) {+ let new_size = self.hash_table_size * 2;+ let mut new_hash_slots = Buffer::new().with_mem_tracker(self.mem_tracker.clone());+ new_hash_slots.resize(new_size, HASH_SLOT_EMPTY);+ for i in 0..self.hash_table_size {+ let index = self.hash_slots[i];+ if index == HASH_SLOT_EMPTY {+ continue;+ }+ let value = &self.uniques[index as usize];+ let mut j = (hash_util::hash(value, 0) & ((new_size - 1) as u32)) as usize;+ let mut slot = new_hash_slots[j];+ while slot != HASH_SLOT_EMPTY && self.uniques[slot as usize] != *value {+ j += 1;+ if j == new_size {+ j = 0;+ }+ slot = new_hash_slots[j];+ }++ new_hash_slots[j] = index;+ }++ self.hash_table_size = new_size;+ self.mod_bitmask = (new_size - 1) as u32;+ mem::replace(&mut self.hash_slots, new_hash_slots);+ }+}++impl<T: DataType> Encoder<T> for DictEncoder<T> {+ #[inline]+ fn put(&mut self, values: &[T::T]) -> Result<()> {+ for i in values {+ self.put_one(&i)?+ }+ Ok(())+ }++ #[inline]+ fn encoding(&self) -> Encoding {+ Encoding::PLAIN_DICTIONARY+ }++ #[inline]+ fn estimated_data_encoded_size(&self) -> usize {+ let bit_width = self.bit_width();+ 1 + RleEncoder::min_buffer_size(bit_width)+ + RleEncoder::max_buffer_size(bit_width, self.buffered_indices.size())+ }++ #[inline]+ fn flush_buffer(&mut self) -> Result<ByteBufferPtr> {+ self.write_indices()+ }+}++/// Provides encoded size for a data type.+/// This is a workaround to calculate dictionary size in bytes.+trait DictEncodedSize<T: DataType> {+ #[inline]+ fn get_encoded_size(&self, value: &T::T) -> usize;+}++impl<T: DataType> DictEncodedSize<T> for DictEncoder<T> {+ #[inline]+ default fn get_encoded_size(&self, _: &T::T) -> usize {+ mem::size_of::<T::T>()+ }+}++impl DictEncodedSize<ByteArrayType> for DictEncoder<ByteArrayType> {+ #[inline]+ fn get_encoded_size(&self, value: &ByteArray) -> usize {+ mem::size_of::<u32>() + value.len()+ }+}++impl DictEncodedSize<FixedLenByteArrayType> for DictEncoder<FixedLenByteArrayType> {+ #[inline]+ fn get_encoded_size(&self, _value: &ByteArray) -> usize {+ self.desc.type_length() as usize+ }+}++// ----------------------------------------------------------------------+// RLE encoding++const DEFAULT_RLE_BUFFER_LEN: usize = 1024;++/// RLE/Bit-Packing hybrid encoding for values.+/// Currently is used only for data pages v2 and supports boolean types.+pub struct RleValueEncoder<T: DataType> {+ // Buffer with raw values that we collect,+ // when flushing buffer they are encoded using RLE encoder+ encoder: Option<RleEncoder>,+ _phantom: PhantomData<T>,+}++impl<T: DataType> RleValueEncoder<T> {+ /// Creates new rle value encoder.+ pub fn new() -> Self {+ Self {+ encoder: None,+ _phantom: PhantomData,+ }+ }+}++impl<T: DataType> Encoder<T> for RleValueEncoder<T> {+ #[inline]+ default fn put(&mut self, _values: &[T::T]) -> Result<()> {+ panic!("RleValueEncoder only supports BoolType");+ }++ fn encoding(&self) -> Encoding {+ Encoding::RLE+ }++ #[inline]+ default fn estimated_data_encoded_size(&self) -> usize {+ match self.encoder {+ Some(ref enc) => enc.len(),+ None => 0,+ }+ }++ #[inline]+ default fn flush_buffer(&mut self) -> Result<ByteBufferPtr> {+ panic!("RleValueEncoder only supports BoolType");+ }+}++impl Encoder<BoolType> for RleValueEncoder<BoolType> {+ #[inline]+ default fn put(&mut self, values: &[bool]) -> Result<()> {+ if self.encoder.is_none() {+ self.encoder = Some(RleEncoder::new(1, DEFAULT_RLE_BUFFER_LEN));+ }+ let rle_encoder = self.encoder.as_mut().unwrap();+ for value in values {+ if !rle_encoder.put(*value as u64)? {+ return Err(general_err!("RLE buffer is full"));+ }+ }+ Ok(())+ }++ #[inline]+ fn flush_buffer(&mut self) -> Result<ByteBufferPtr> {+ assert!(+ self.encoder.is_some(),+ "RLE value encoder is not initialized"+ );+ let rle_encoder = self.encoder.as_mut().unwrap();++ // Flush all encoder buffers and raw values+ let encoded_data = {+ let buf = rle_encoder.flush_buffer()?;++ // Note that buf does not have any offset, all data is encoded bytes+ let len = (buf.len() as i32).to_le();+ let len_bytes = len.as_bytes();+ let mut encoded_data = Vec::new();+ encoded_data.extend_from_slice(len_bytes);+ encoded_data.extend_from_slice(buf);+ encoded_data+ };+ // Reset rle encoder for the next batch+ rle_encoder.clear();++ Ok(ByteBufferPtr::new(encoded_data))+ }+}++// ----------------------------------------------------------------------+// DELTA_BINARY_PACKED encoding++const MAX_PAGE_HEADER_WRITER_SIZE: usize = 32;+const MAX_BIT_WRITER_SIZE: usize = 10 * 1024 * 1024;+const DEFAULT_BLOCK_SIZE: usize = 128;+const DEFAULT_NUM_MINI_BLOCKS: usize = 4;++/// Delta bit packed encoder.+/// Consists of a header followed by blocks of delta encoded values binary packed.+///+/// Delta-binary-packing:+/// ```shell+/// [page-header] [block 1], [block 2], ... [block N]+/// ```+///+/// Each page header consists of:+/// ```shell+/// [block size] [number of miniblocks in a block] [total value count] [first value]+/// ```+///+/// Each block consists of:+/// ```shell+/// [min delta] [list of bitwidths of miniblocks] [miniblocks]+/// ```+///+/// Current implementation writes values in `put` method, multiple calls to `put` to+/// existing block or start new block if block size is exceeded. Calling `flush_buffer`+/// writes out all data and resets internal state, including page header.+///+/// Supports only INT32 and INT64.+pub struct DeltaBitPackEncoder<T: DataType> {+ page_header_writer: BitWriter,+ bit_writer: BitWriter,+ total_values: usize,+ first_value: i64,+ current_value: i64,+ block_size: usize,+ mini_block_size: usize,+ num_mini_blocks: usize,+ values_in_block: usize,+ deltas: Vec<i64>,+ _phantom: PhantomData<T>,+}++impl<T: DataType> DeltaBitPackEncoder<T> {+ /// Creates new delta bit packed encoder.+ pub fn new() -> Self {+ let block_size = DEFAULT_BLOCK_SIZE;+ let num_mini_blocks = DEFAULT_NUM_MINI_BLOCKS;+ let mini_block_size = block_size / num_mini_blocks;+ assert!(mini_block_size % 8 == 0);+ Self::assert_supported_type();++ DeltaBitPackEncoder {+ page_header_writer: BitWriter::new(MAX_PAGE_HEADER_WRITER_SIZE),+ bit_writer: BitWriter::new(MAX_BIT_WRITER_SIZE),+ total_values: 0,+ first_value: 0,+ current_value: 0, // current value to keep adding deltas+ block_size, // can write fewer values than block size for last block+ mini_block_size,+ num_mini_blocks,+ values_in_block: 0, // will be at most block_size+ deltas: vec![0; block_size],+ _phantom: PhantomData,+ }+ }++ /// Writes page header for blocks, this method is invoked when we are done encoding+ /// values. It is also okay to encode when no values have been provided+ fn write_page_header(&mut self) {+ // We ignore the result of each 'put' operation, because MAX_PAGE_HEADER_WRITER_SIZE+ // is chosen to fit all header values and guarantees that writes will not fail.++ // Write the size of each block+ self.page_header_writer.put_vlq_int(self.block_size as u64);+ // Write the number of mini blocks+ self.page_header_writer+ .put_vlq_int(self.num_mini_blocks as u64);+ // Write the number of all values (including non-encoded first value)+ self.page_header_writer+ .put_vlq_int(self.total_values as u64);+ // Write first value+ self.page_header_writer.put_zigzag_vlq_int(self.first_value);+ }++ // Write current delta buffer (<= 'block size' values) into bit writer+ fn flush_block_values(&mut self) -> Result<()> {+ if self.values_in_block == 0 {+ return Ok(());+ }++ let mut min_delta = i64::max_value();+ for i in 0..self.values_in_block {+ min_delta = cmp::min(min_delta, self.deltas[i]);+ }++ // Write min delta+ self.bit_writer.put_zigzag_vlq_int(min_delta);++ // Slice to store bit width for each mini block+ // apply unsafe allocation to avoid double mutable borrow+ let mini_block_widths: &mut [u8] = unsafe {+ let tmp_slice = self.bit_writer.get_next_byte_ptr(self.num_mini_blocks)?;+ slice::from_raw_parts_mut(tmp_slice.as_ptr() as *mut u8, self.num_mini_blocks)+ };++ for i in 0..self.num_mini_blocks {+ // Find how many values we need to encode - either block size or whatever values+ // left+ let n = cmp::min(self.mini_block_size, self.values_in_block);+ if n == 0 {+ break;+ }++ // Compute the max delta in current mini block+ let mut max_delta = i64::min_value();+ for j in 0..n {+ max_delta = cmp::max(max_delta, self.deltas[i * self.mini_block_size + j]);+ }++ // Compute bit width to store (max_delta - min_delta)+ let bit_width = num_required_bits(self.subtract_u64(max_delta, min_delta));+ mini_block_widths[i] = bit_width as u8;++ // Encode values in current mini block using min_delta and bit_width+ for j in 0..n {+ let packed_value =+ self.subtract_u64(self.deltas[i * self.mini_block_size + j], min_delta);+ self.bit_writer.put_value(packed_value, bit_width);+ }++ // Pad the last block (n < mini_block_size)+ for _ in n..self.mini_block_size {+ self.bit_writer.put_value(0, bit_width);+ }++ self.values_in_block -= n;+ }++ assert!(+ self.values_in_block == 0,+ "Expected 0 values in block, found {}",+ self.values_in_block+ );+ Ok(())+ }+}++// Implementation is shared between Int32Type and Int64Type,+// see `DeltaBitPackEncoderConversion` below for specifics.+impl<T: DataType> Encoder<T> for DeltaBitPackEncoder<T> {+ fn put(&mut self, values: &[T::T]) -> Result<()> {+ if values.is_empty() {+ return Ok(());+ }++ let mut idx;+ // Define values to encode, initialize state+ if self.total_values == 0 {+ self.first_value = self.as_i64(values, 0);+ self.current_value = self.first_value;+ idx = 1;+ } else {+ idx = 0;+ }+ // Add all values (including first value)+ self.total_values += values.len();++ // Write block+ while idx < values.len() {+ let value = self.as_i64(values, idx);+ self.deltas[self.values_in_block] = self.subtract(value, self.current_value);+ self.current_value = value;+ idx += 1;+ self.values_in_block += 1;+ if self.values_in_block == self.block_size {+ self.flush_block_values()?;+ }+ }+ Ok(())+ }++ fn encoding(&self) -> Encoding {+ Encoding::DELTA_BINARY_PACKED+ }++ fn estimated_data_encoded_size(&self) -> usize {+ self.bit_writer.bytes_written()+ }++ fn flush_buffer(&mut self) -> Result<ByteBufferPtr> {+ // Write remaining values+ self.flush_block_values()?;+ // Write page header with total values+ self.write_page_header();++ let mut buffer = ByteBuffer::new();+ buffer.write(self.page_header_writer.flush_buffer())?;+ buffer.write(self.bit_writer.flush_buffer())?;+ buffer.flush()?;++ // Reset state+ self.page_header_writer.clear();+ self.bit_writer.clear();+ self.total_values = 0;+ self.first_value = 0;+ self.current_value = 0;+ self.values_in_block = 0;++ Ok(buffer.consume())+ }+}++/// Helper trait to define specific conversions and subtractions when computing deltas+trait DeltaBitPackEncoderConversion<T: DataType> {+ // Method should panic if type is not supported, otherwise no-op+ #[inline]+ fn assert_supported_type();++ #[inline]+ fn as_i64(&self, values: &[T::T], index: usize) -> i64;++ #[inline]+ fn subtract(&self, left: i64, right: i64) -> i64;++ #[inline]+ fn subtract_u64(&self, left: i64, right: i64) -> u64;+}++impl<T: DataType> DeltaBitPackEncoderConversion<T> for DeltaBitPackEncoder<T> {+ #[inline]+ default fn assert_supported_type() {+ panic!("DeltaBitPackDecoder only supports Int32Type and Int64Type");+ }++ #[inline]+ default fn as_i64(&self, _values: &[T::T], _index: usize) -> i64 {+ 0+ }++ #[inline]+ default fn subtract(&self, _left: i64, _right: i64) -> i64 {+ 0+ }++ #[inline]+ default fn subtract_u64(&self, _left: i64, _right: i64) -> u64 {+ 0+ }+}++impl DeltaBitPackEncoderConversion<Int32Type> for DeltaBitPackEncoder<Int32Type> {+ #[inline]+ fn assert_supported_type() {+ // no-op: supported type+ }++ #[inline]+ fn as_i64(&self, values: &[i32], index: usize) -> i64 {+ values[index] as i64+ }++ #[inline]+ fn subtract(&self, left: i64, right: i64) -> i64 {+ // It is okay for values to overflow, wrapping_sub wrapping around at the boundary+ (left as i32).wrapping_sub(right as i32) as i64+ }++ #[inline]+ fn subtract_u64(&self, left: i64, right: i64) -> u64 {+ // Conversion of i32 -> u32 -> u64 is to avoid non-zero left most bytes in int+ // representation+ (left as i32).wrapping_sub(right as i32) as u32 as u64+ }+}++impl DeltaBitPackEncoderConversion<Int64Type> for DeltaBitPackEncoder<Int64Type> {+ #[inline]+ fn assert_supported_type() {+ // no-op: supported type+ }++ #[inline]+ fn as_i64(&self, values: &[i64], index: usize) -> i64 {+ values[index]+ }++ #[inline]+ fn subtract(&self, left: i64, right: i64) -> i64 {+ // It is okay for values to overflow, wrapping_sub wrapping around at the boundary+ left.wrapping_sub(right)+ }++ #[inline]+ fn subtract_u64(&self, left: i64, right: i64) -> u64 {+ left.wrapping_sub(right) as u64+ }+}++// ----------------------------------------------------------------------+// DELTA_LENGTH_BYTE_ARRAY encoding++/// Encoding for byte arrays to separate the length values and the data.+/// The lengths are encoded using DELTA_BINARY_PACKED encoding, data is+/// stored as raw bytes.+pub struct DeltaLengthByteArrayEncoder<T: DataType> {+ // length encoder+ len_encoder: DeltaBitPackEncoder<Int32Type>,+ // byte array data+ data: Vec<ByteArray>,+ // data size in bytes of encoded values+ encoded_size: usize,+ _phantom: PhantomData<T>,+}++impl<T: DataType> DeltaLengthByteArrayEncoder<T> {+ /// Creates new delta length byte array encoder.+ pub fn new() -> Self {+ Self {+ len_encoder: DeltaBitPackEncoder::new(),+ data: vec![],+ encoded_size: 0,+ _phantom: PhantomData,+ }+ }+}++impl<T: DataType> Encoder<T> for DeltaLengthByteArrayEncoder<T> {+ default fn put(&mut self, _values: &[T::T]) -> Result<()> {+ panic!("DeltaLengthByteArrayEncoder only supports ByteArrayType");+ }++ fn encoding(&self) -> Encoding {+ Encoding::DELTA_LENGTH_BYTE_ARRAY+ }++ fn estimated_data_encoded_size(&self) -> usize {+ self.len_encoder.estimated_data_encoded_size() + self.encoded_size+ }++ default fn flush_buffer(&mut self) -> Result<ByteBufferPtr> {+ panic!("DeltaLengthByteArrayEncoder only supports ByteArrayType");+ }+}++impl Encoder<ByteArrayType> for DeltaLengthByteArrayEncoder<ByteArrayType> {+ fn put(&mut self, values: &[ByteArray]) -> Result<()> {+ let lengths: Vec<i32> = values+ .iter()+ .map(|byte_array| byte_array.len() as i32)+ .collect();+ self.len_encoder.put(&lengths)?;+ for byte_array in values {+ self.encoded_size += byte_array.len();+ self.data.push(byte_array.clone());+ }+ Ok(())+ }++ fn flush_buffer(&mut self) -> Result<ByteBufferPtr> {+ let mut total_bytes = vec![];+ let lengths = self.len_encoder.flush_buffer()?;+ total_bytes.extend_from_slice(lengths.data());+ self.data.iter().for_each(|byte_array| {+ total_bytes.extend_from_slice(byte_array.data());+ });+ self.data.clear();+ self.encoded_size = 0;+ Ok(ByteBufferPtr::new(total_bytes))+ }+}++// ----------------------------------------------------------------------+// DELTA_BYTE_ARRAY encoding++/// Encoding for byte arrays, prefix lengths are encoded using DELTA_BINARY_PACKED+/// encoding, followed by suffixes with DELTA_LENGTH_BYTE_ARRAY encoding.+pub struct DeltaByteArrayEncoder<T: DataType> {+ prefix_len_encoder: DeltaBitPackEncoder<Int32Type>,+ suffix_writer: DeltaLengthByteArrayEncoder<T>,+ previous: Vec<u8>,+ _phantom: PhantomData<T>,+}++impl<T: DataType> DeltaByteArrayEncoder<T> {+ /// Creates new delta byte array encoder.+ pub fn new() -> Self {+ Self {+ prefix_len_encoder: DeltaBitPackEncoder::<Int32Type>::new(),+ suffix_writer: DeltaLengthByteArrayEncoder::<T>::new(),+ previous: vec![],+ _phantom: PhantomData,+ }+ }+}++impl<T: DataType> Encoder<T> for DeltaByteArrayEncoder<T> {+ default fn put(&mut self, _values: &[T::T]) -> Result<()> {+ panic!("DeltaByteArrayEncoder only supports ByteArrayType and FixedLenByteArrayType");+ }++ fn encoding(&self) -> Encoding {+ Encoding::DELTA_BYTE_ARRAY+ }++ fn estimated_data_encoded_size(&self) -> usize {+ self.prefix_len_encoder.estimated_data_encoded_size()+ + self.suffix_writer.estimated_data_encoded_size()+ }++ default fn flush_buffer(&mut self) -> Result<ByteBufferPtr> {+ panic!("DeltaByteArrayEncoder only supports ByteArrayType and FixedLenByteArrayType");+ }+}++impl Encoder<ByteArrayType> for DeltaByteArrayEncoder<ByteArrayType> {+ fn put(&mut self, values: &[ByteArray]) -> Result<()> {+ let mut prefix_lengths: Vec<i32> = vec![];+ let mut suffixes: Vec<ByteArray> = vec![];++ for byte_array in values {+ let current = byte_array.data();+ // Maximum prefix length that is shared between previous value and current value+ let prefix_len = cmp::min(self.previous.len(), current.len());+ let mut match_len = 0;+ while match_len < prefix_len && self.previous[match_len] == current[match_len] {+ match_len += 1;+ }+ prefix_lengths.push(match_len as i32);+ suffixes.push(byte_array.slice(match_len, byte_array.len() - match_len));+ // Update previous for the next prefix+ self.previous.clear();+ self.previous.extend_from_slice(current);+ }+ self.prefix_len_encoder.put(&prefix_lengths)?;+ self.suffix_writer.put(&suffixes)?;+ Ok(())+ }++ fn flush_buffer(&mut self) -> Result<ByteBufferPtr> {+ // TODO: investigate if we can merge lengths and suffixes+ // without copying data into new vector.+ let mut total_bytes = vec![];+ // Insert lengths ...+ let lengths = self.prefix_len_encoder.flush_buffer()?;+ total_bytes.extend_from_slice(lengths.data());+ // ... followed by suffixes+ let suffixes = self.suffix_writer.flush_buffer()?;+ total_bytes.extend_from_slice(suffixes.data());++ self.previous.clear();+ Ok(ByteBufferPtr::new(total_bytes))+ }+}++impl Encoder<FixedLenByteArrayType> for DeltaByteArrayEncoder<FixedLenByteArrayType> {+ fn put(&mut self, values: &[ByteArray]) -> Result<()> {+ let s: &mut DeltaByteArrayEncoder<ByteArrayType> = unsafe { mem::transmute(self) };+ s.put(values)+ }++ fn flush_buffer(&mut self) -> Result<ByteBufferPtr> {+ let s: &mut DeltaByteArrayEncoder<ByteArrayType> = unsafe { mem::transmute(self) };+ s.flush_buffer()+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ use std::rc::Rc;++ use crate::parquet::decoding::{get_decoder, Decoder, DictDecoder, PlainDecoder};+ use crate::parquet::schema::types::{+ ColumnDescPtr, ColumnDescriptor, ColumnPath, Type as SchemaType,+ };+ use crate::parquet::util::{memory::MemTracker, test_common::RandGen};++ const TEST_SET_SIZE: usize = 1024;++ #[test]+ fn test_get_encoders() {+ // supported encodings+ create_and_check_encoder::<Int32Type>(Encoding::PLAIN, None);+ create_and_check_encoder::<Int32Type>(Encoding::DELTA_BINARY_PACKED, None);+ create_and_check_encoder::<Int32Type>(Encoding::DELTA_LENGTH_BYTE_ARRAY, None);+ create_and_check_encoder::<Int32Type>(Encoding::DELTA_BYTE_ARRAY, None);+ create_and_check_encoder::<BoolType>(Encoding::RLE, None);++ // error when initializing+ create_and_check_encoder::<Int32Type>(+ Encoding::RLE_DICTIONARY,+ Some(general_err!(+ "Cannot initialize this encoding through this function"+ )),+ );+ create_and_check_encoder::<Int32Type>(+ Encoding::PLAIN_DICTIONARY,+ Some(general_err!(+ "Cannot initialize this encoding through this function"+ )),+ );++ // unsupported+ create_and_check_encoder::<Int32Type>(+ Encoding::BIT_PACKED,+ Some(nyi_err!("Encoding BIT_PACKED is not supported")),+ );+ }++ #[test]+ fn test_bool() {+ BoolType::test(Encoding::PLAIN, TEST_SET_SIZE, -1);+ BoolType::test(Encoding::PLAIN_DICTIONARY, TEST_SET_SIZE, -1);+ BoolType::test(Encoding::RLE, TEST_SET_SIZE, -1);+ }++ #[test]+ fn test_i32() {+ Int32Type::test(Encoding::PLAIN, TEST_SET_SIZE, -1);+ Int32Type::test(Encoding::PLAIN_DICTIONARY, TEST_SET_SIZE, -1);+ Int32Type::test(Encoding::DELTA_BINARY_PACKED, TEST_SET_SIZE, -1);+ }++ #[test]+ fn test_i64() {+ Int64Type::test(Encoding::PLAIN, TEST_SET_SIZE, -1);+ Int64Type::test(Encoding::PLAIN_DICTIONARY, TEST_SET_SIZE, -1);+ Int64Type::test(Encoding::DELTA_BINARY_PACKED, TEST_SET_SIZE, -1);+ }++ #[test]+ fn test_i96() {+ Int96Type::test(Encoding::PLAIN, TEST_SET_SIZE, -1);+ Int96Type::test(Encoding::PLAIN_DICTIONARY, TEST_SET_SIZE, -1);+ }++ #[test]+ fn test_float() {+ FloatType::test(Encoding::PLAIN, TEST_SET_SIZE, -1);+ FloatType::test(Encoding::PLAIN_DICTIONARY, TEST_SET_SIZE, -1);+ }++ #[test]+ fn test_double() {+ DoubleType::test(Encoding::PLAIN, TEST_SET_SIZE, -1);+ DoubleType::test(Encoding::PLAIN_DICTIONARY, TEST_SET_SIZE, -1);+ }++ #[test]+ fn test_byte_array() {+ ByteArrayType::test(Encoding::PLAIN, TEST_SET_SIZE, -1);+ ByteArrayType::test(Encoding::PLAIN_DICTIONARY, TEST_SET_SIZE, -1);+ ByteArrayType::test(Encoding::DELTA_LENGTH_BYTE_ARRAY, TEST_SET_SIZE, -1);+ ByteArrayType::test(Encoding::DELTA_BYTE_ARRAY, TEST_SET_SIZE, -1);+ }++ #[test]+ fn test_fixed_lenbyte_array() {+ FixedLenByteArrayType::test(Encoding::PLAIN, TEST_SET_SIZE, 100);+ FixedLenByteArrayType::test(Encoding::PLAIN_DICTIONARY, TEST_SET_SIZE, 100);+ FixedLenByteArrayType::test(Encoding::DELTA_BYTE_ARRAY, TEST_SET_SIZE, 100);+ }++ #[test]+ fn test_dict_encoded_size() {+ fn run_test<T: DataType>(type_length: i32, values: &[T::T], expected_size: usize) {+ let mut encoder = create_test_dict_encoder::<T>(type_length);+ assert_eq!(encoder.dict_encoded_size(), 0);+ encoder.put(values).unwrap();+ assert_eq!(encoder.dict_encoded_size(), expected_size);+ // We do not reset encoded size of the dictionary keys after flush_buffer+ encoder.flush_buffer().unwrap();+ assert_eq!(encoder.dict_encoded_size(), expected_size);+ }++ // Only 2 variations of values 1 byte each+ run_test::<BoolType>(-1, &[true, false, true, false, true], 2);+ run_test::<Int32Type>(-1, &[1i32, 2i32, 3i32, 4i32, 5i32], 20);+ run_test::<Int64Type>(-1, &[1i64, 2i64, 3i64, 4i64, 5i64], 40);+ run_test::<FloatType>(-1, &[1f32, 2f32, 3f32, 4f32, 5f32], 20);+ run_test::<DoubleType>(-1, &[1f64, 2f64, 3f64, 4f64, 5f64], 40);+ // Int96: len + reference+ run_test::<Int96Type>(+ -1,+ &[Int96::from(vec![1, 2, 3]), Int96::from(vec![2, 3, 4])],+ 32,+ );+ run_test::<ByteArrayType>(-1, &[ByteArray::from("abcd"), ByteArray::from("efj")], 15);+ run_test::<FixedLenByteArrayType>(2, &[ByteArray::from("ab"), ByteArray::from("bc")], 4);+ }++ #[test]+ fn test_estimated_data_encoded_size() {+ fn run_test<T: DataType>(+ encoding: Encoding,+ type_length: i32,+ values: &[T::T],+ initial_size: usize,+ max_size: usize,+ flush_size: usize,+ ) {+ let mut encoder = match encoding {+ Encoding::PLAIN_DICTIONARY | Encoding::RLE_DICTIONARY => {+ Box::new(create_test_dict_encoder::<T>(type_length))+ }+ _ => create_test_encoder::<T>(type_length, encoding),+ };+ assert_eq!(encoder.estimated_data_encoded_size(), initial_size);++ encoder.put(values).unwrap();+ assert_eq!(encoder.estimated_data_encoded_size(), max_size);++ encoder.flush_buffer().unwrap();+ assert_eq!(encoder.estimated_data_encoded_size(), flush_size);+ }++ // PLAIN+ run_test::<Int32Type>(Encoding::PLAIN, -1, &vec![123; 1024], 0, 4096, 0);++ // DICTIONARY+ // NOTE: The final size is almost the same because the dictionary entries are+ // preserved after encoded values have been written.+ run_test::<Int32Type>(Encoding::RLE_DICTIONARY, -1, &vec![123, 1024], 11, 68, 66);++ // DELTA_BINARY_PACKED+ run_test::<Int32Type>(+ Encoding::DELTA_BINARY_PACKED,+ -1,+ &vec![123; 1024],+ 0,+ 35,+ 0,+ );++ // RLE+ let mut values = vec![];+ values.extend_from_slice(&vec![true; 16]);+ values.extend_from_slice(&vec![false; 16]);+ run_test::<BoolType>(Encoding::RLE, -1, &values, 0, 2, 0);++ // DELTA_LENGTH_BYTE_ARRAY+ run_test::<ByteArrayType>(+ Encoding::DELTA_LENGTH_BYTE_ARRAY,+ -1,+ &[ByteArray::from("ab"), ByteArray::from("abc")],+ 0,+ 5, // only value bytes, length encoder is not flushed yet+ 0,+ );++ // DELTA_BYTE_ARRAY+ run_test::<ByteArrayType>(+ Encoding::DELTA_BYTE_ARRAY,+ -1,+ &[ByteArray::from("ab"), ByteArray::from("abc")],+ 0,+ 3, // only suffix bytes, length encoder is not flushed yet+ 0,+ );+ }++ // See: https://github.com/sunchao/parquet-rs/issues/47+ #[test]+ fn test_issue_47() {+ let mut encoder = create_test_encoder::<ByteArrayType>(0, Encoding::DELTA_BYTE_ARRAY);+ let mut decoder = create_test_decoder::<ByteArrayType>(0, Encoding::DELTA_BYTE_ARRAY);++ let mut input = vec![];+ input.push(ByteArray::from("aa"));+ input.push(ByteArray::from("aaa"));+ input.push(ByteArray::from("aa"));+ input.push(ByteArray::from("aaa"));+ let mut output = vec![ByteArray::default(); input.len()];++ let mut result = put_and_get(&mut encoder, &mut decoder, &input[..2], &mut output[..2]);+ assert!(+ result.is_ok(),+ "first put_and_get() failed with: {}",+ result.unwrap_err()+ );+ result = put_and_get(&mut encoder, &mut decoder, &input[2..], &mut output[2..]);+ assert!(+ result.is_ok(),+ "second put_and_get() failed with: {}",+ result.unwrap_err()+ );+ assert_eq!(output, input);+ }++ trait EncodingTester<T: DataType> {+ fn test(enc: Encoding, total: usize, type_length: i32) {+ let result = match enc {+ Encoding::PLAIN_DICTIONARY | Encoding::RLE_DICTIONARY => {+ Self::test_dict_internal(total, type_length)+ }+ enc @ _ => Self::test_internal(enc, total, type_length),+ };++ assert!(+ result.is_ok(),+ "Expected result to be OK but got err:\n {}",+ result.unwrap_err()+ );+ }++ fn test_internal(enc: Encoding, total: usize, type_length: i32) -> Result<()>;++ fn test_dict_internal(total: usize, type_length: i32) -> Result<()>;+ }++ impl<T: DataType> EncodingTester<T> for T {+ fn test_internal(enc: Encoding, total: usize, type_length: i32) -> Result<()> {+ let mut encoder = create_test_encoder::<T>(type_length, enc);+ let mut decoder = create_test_decoder::<T>(type_length, enc);+ let mut values = <T as RandGen<T>>::gen_vec(type_length, total);+ let mut result_data = vec![T::T::default(); total];++ let mut actual_total = put_and_get(+ &mut encoder,+ &mut decoder,+ &values[..],+ &mut result_data[..],+ )?;+ assert_eq!(actual_total, total);+ assert_eq!(result_data, values);++ // Encode more data after flush and test with decoder++ values = <T as RandGen<T>>::gen_vec(type_length, total);+ actual_total = put_and_get(+ &mut encoder,+ &mut decoder,+ &values[..],+ &mut result_data[..],+ )?;+ assert_eq!(actual_total, total);+ assert_eq!(result_data, values);++ Ok(())+ }++ fn test_dict_internal(total: usize, type_length: i32) -> Result<()> {+ let mut encoder = create_test_dict_encoder::<T>(type_length);+ let mut values = <T as RandGen<T>>::gen_vec(type_length, total);+ encoder.put(&values[..])?;++ let mut data = encoder.flush_buffer()?;+ let mut decoder = create_test_dict_decoder::<T>();+ let mut dict_decoder = PlainDecoder::<T>::new(type_length);+ dict_decoder.set_data(encoder.write_dict()?, encoder.num_entries())?;+ decoder.set_dict(Box::new(dict_decoder))?;+ let mut result_data = vec![T::T::default(); total];+ decoder.set_data(data, total)?;+ let mut actual_total = decoder.get(&mut result_data)?;++ assert_eq!(actual_total, total);+ assert_eq!(result_data, values);++ // Encode more data after flush and test with decoder++ values = <T as RandGen<T>>::gen_vec(type_length, total);+ encoder.put(&values[..])?;+ data = encoder.flush_buffer()?;++ let mut dict_decoder = PlainDecoder::<T>::new(type_length);+ dict_decoder.set_data(encoder.write_dict()?, encoder.num_entries())?;+ decoder.set_dict(Box::new(dict_decoder))?;+ decoder.set_data(data, total)?;+ actual_total = decoder.get(&mut result_data)?;++ assert_eq!(actual_total, total);+ assert_eq!(result_data, values);++ Ok(())+ }+ }++ fn put_and_get<T: DataType>(+ encoder: &mut Box<Encoder<T>>,+ decoder: &mut Box<Decoder<T>>,+ input: &[T::T],+ output: &mut [T::T],+ ) -> Result<usize> {+ encoder.put(input)?;+ let data = encoder.flush_buffer()?;+ decoder.set_data(data, input.len())?;+ decoder.get(output)+ }++ fn create_and_check_encoder<T: DataType>(encoding: Encoding, err: Option<ParquetError>) {+ let descr = create_test_col_desc_ptr(-1, T::get_physical_type());+ let mem_tracker = Rc::new(MemTracker::new());+ let encoder = get_encoder::<T>(descr, encoding, mem_tracker);+ match err {+ Some(parquet_error) => {+ assert!(encoder.is_err());+ assert_eq!(encoder.err().unwrap(), parquet_error);+ }+ None => {+ assert!(encoder.is_ok());+ assert_eq!(encoder.unwrap().encoding(), encoding);+ }+ }+ }++ // Creates test column descriptor.+ fn create_test_col_desc_ptr(type_len: i32, t: Type) -> ColumnDescPtr {+ let ty = SchemaType::primitive_type_builder("t", t)+ .with_length(type_len)+ .build()+ .unwrap();+ Rc::new(ColumnDescriptor::new(+ Rc::new(ty),+ None,+ 0,+ 0,+ ColumnPath::new(vec![]),+ ))+ }++ fn create_test_encoder<T: DataType>(type_len: i32, enc: Encoding) -> Box<Encoder<T>> {+ let desc = create_test_col_desc_ptr(type_len, T::get_physical_type());+ let mem_tracker = Rc::new(MemTracker::new());+ get_encoder(desc, enc, mem_tracker).unwrap()+ }++ fn create_test_decoder<T: DataType>(type_len: i32, enc: Encoding) -> Box<Decoder<T>> {+ let desc = create_test_col_desc_ptr(type_len, T::get_physical_type());+ get_decoder(desc, enc).unwrap()+ }++ fn create_test_dict_encoder<T: DataType>(type_len: i32) -> DictEncoder<T> {+ let desc = create_test_col_desc_ptr(type_len, T::get_physical_type());+ let mem_tracker = Rc::new(MemTracker::new());+ DictEncoder::<T>::new(desc, mem_tracker)+ }++ fn create_test_dict_decoder<T: DataType>() -> DictDecoder<T> {+ DictDecoder::<T>::new()+ }+}diff --git a/rust/src/parquet/encodings/levels.rs b/rust/src/parquet/encodings/levels.rsnew file mode 100644index 0000000000..ec65198ce5--- /dev/null+++ b/rust/src/parquet/encodings/levels.rs@@ -0,0 +1,529 @@+// 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, mem};++use super::rle::{RleDecoder, RleEncoder};++use crate::parquet::basic::Encoding;+use crate::parquet::data_type::AsBytes;+use crate::parquet::errors::{ParquetError, Result};+use crate::parquet::util::{+ bit_util::{ceil, log2, BitReader, BitWriter},+ memory::ByteBufferPtr,+};++/// Computes max buffer size for level encoder/decoder based on encoding, max+/// repetition/definition level and number of total buffered values (includes null+/// values).+#[inline]+pub fn max_buffer_size(encoding: Encoding, max_level: i16, num_buffered_values: usize) -> usize {+ let bit_width = log2(max_level as u64 + 1) as u8;+ match encoding {+ Encoding::RLE => {+ RleEncoder::max_buffer_size(bit_width, num_buffered_values)+ + RleEncoder::min_buffer_size(bit_width)+ }+ Encoding::BIT_PACKED => ceil((num_buffered_values * bit_width as usize) as i64, 8) as usize,+ _ => panic!("Unsupported encoding type {}", encoding),+ }+}++/// Encoder for definition/repetition levels.+/// Currently only supports RLE and BIT_PACKED (dev/null) encoding, including v2.+pub enum LevelEncoder {+ RLE(RleEncoder),+ RLE_V2(RleEncoder),+ BIT_PACKED(u8, BitWriter),+}++impl LevelEncoder {+ /// Creates new level encoder based on encoding, max level and underlying byte buffer.+ /// For bit packed encoding it is assumed that buffer is already allocated with+ /// `levels::max_buffer_size` method.+ ///+ /// Used to encode levels for Data Page v1.+ ///+ /// Panics, if encoding is not supported.+ pub fn v1(encoding: Encoding, max_level: i16, byte_buffer: Vec<u8>) -> Self {+ let bit_width = log2(max_level as u64 + 1) as u8;+ match encoding {+ Encoding::RLE => LevelEncoder::RLE(RleEncoder::new_from_buf(+ bit_width,+ byte_buffer,+ mem::size_of::<i32>(),+ )),+ Encoding::BIT_PACKED => {+ // Here we set full byte buffer without adjusting for num_buffered_values,+ // because byte buffer will already be allocated with size from+ // `max_buffer_size()` method.+ LevelEncoder::BIT_PACKED(bit_width, BitWriter::new_from_buf(byte_buffer, 0))+ }+ _ => panic!("Unsupported encoding type {}", encoding),+ }+ }++ /// Creates new level encoder based on RLE encoding. Used to encode Data Page v2+ /// repetition and definition levels.+ pub fn v2(max_level: i16, byte_buffer: Vec<u8>) -> Self {+ let bit_width = log2(max_level as u64 + 1) as u8;+ LevelEncoder::RLE_V2(RleEncoder::new_from_buf(bit_width, byte_buffer, 0))+ }++ /// Put/encode levels vector into this level encoder.+ /// Returns number of encoded values that are less than or equal to length of the input+ /// buffer.+ ///+ /// RLE and BIT_PACKED level encoders return Err() when internal buffer overflows or+ /// flush fails.+ #[inline]+ pub fn put(&mut self, buffer: &[i16]) -> Result<usize> {+ let mut num_encoded = 0;+ match *self {+ LevelEncoder::RLE(ref mut encoder) | LevelEncoder::RLE_V2(ref mut encoder) => {+ for value in buffer {+ if !encoder.put(*value as u64)? {+ return Err(general_err!("RLE buffer is full"));+ }+ num_encoded += 1;+ }+ encoder.flush()?;+ }+ LevelEncoder::BIT_PACKED(bit_width, ref mut encoder) => {+ for value in buffer {+ if !encoder.put_value(*value as u64, bit_width as usize) {+ return Err(general_err!("Not enough bytes left"));+ }+ num_encoded += 1;+ }+ encoder.flush();+ }+ }+ Ok(num_encoded)+ }++ /// Finalizes level encoder, flush all intermediate buffers and return resulting+ /// encoded buffer. Returned buffer is already truncated to encoded bytes only.+ #[inline]+ pub fn consume(self) -> Result<Vec<u8>> {+ match self {+ LevelEncoder::RLE(encoder) => {+ let mut encoded_data = encoder.consume()?;+ // Account for the buffer offset+ let encoded_len = encoded_data.len() - mem::size_of::<i32>();+ let len = (encoded_len as i32).to_le();+ let len_bytes = len.as_bytes();+ encoded_data[0..len_bytes.len()].copy_from_slice(len_bytes);+ Ok(encoded_data)+ }+ LevelEncoder::RLE_V2(encoder) => encoder.consume(),+ LevelEncoder::BIT_PACKED(_, encoder) => Ok(encoder.consume()),+ }+ }+}++/// Decoder for definition/repetition levels.+/// Currently only supports RLE and BIT_PACKED encoding for Data Page v1 and+/// RLE for Data Page v2.+pub enum LevelDecoder {+ RLE(Option<usize>, RleDecoder),+ RLE_V2(Option<usize>, RleDecoder),+ BIT_PACKED(Option<usize>, u8, BitReader),+}++impl LevelDecoder {+ /// Creates new level decoder based on encoding and max definition/repetition level.+ /// This method only initializes level decoder, `set_data` method must be called+ /// before reading any value.+ ///+ /// Used to encode levels for Data Page v1.+ ///+ /// Panics if encoding is not supported+ pub fn v1(encoding: Encoding, max_level: i16) -> Self {+ let bit_width = log2(max_level as u64 + 1) as u8;+ match encoding {+ Encoding::RLE => LevelDecoder::RLE(None, RleDecoder::new(bit_width)),+ Encoding::BIT_PACKED => {+ LevelDecoder::BIT_PACKED(None, bit_width, BitReader::from(Vec::new()))+ }+ _ => panic!("Unsupported encoding type {}", encoding),+ }+ }++ /// Creates new level decoder based on RLE encoding.+ /// Used to decode Data Page v2 repetition and definition levels.+ ///+ /// To set data for this decoder, use `set_data_range` method.+ pub fn v2(max_level: i16) -> Self {+ let bit_width = log2(max_level as u64 + 1) as u8;+ LevelDecoder::RLE_V2(None, RleDecoder::new(bit_width))+ }++ /// Sets data for this level decoder, and returns total number of bytes set.+ /// This is used for Data Page v1 levels.+ ///+ /// `data` is encoded data as byte buffer, `num_buffered_values` represents total+ /// number of values that is expected.+ ///+ /// Both RLE and BIT_PACKED level decoders set `num_buffered_values` as total number of+ /// values that they can return and track num values.+ #[inline]+ pub fn set_data(&mut self, num_buffered_values: usize, data: ByteBufferPtr) -> usize {+ match *self {+ LevelDecoder::RLE(ref mut num_values, ref mut decoder) => {+ *num_values = Some(num_buffered_values);+ let i32_size = mem::size_of::<i32>();+ let data_size = read_num_bytes!(i32, i32_size, data.as_ref()) as usize;+ decoder.set_data(data.range(i32_size, data_size));+ i32_size + data_size+ }+ LevelDecoder::BIT_PACKED(ref mut num_values, bit_width, ref mut decoder) => {+ *num_values = Some(num_buffered_values);+ // Set appropriate number of bytes: if max size is larger than buffer - set full+ // buffer+ let num_bytes = ceil((num_buffered_values * bit_width as usize) as i64, 8);+ let data_size = cmp::min(num_bytes as usize, data.len());+ decoder.reset(data.range(data.start(), data_size));+ data_size+ }+ _ => panic!(),+ }+ }++ /// Sets byte array explicitly when start position `start` and length `len` are known+ /// in advance. Only supported by RLE level decoder and used for Data Page v2 levels.+ /// Returns number of total bytes set for this decoder (len).+ #[inline]+ pub fn set_data_range(+ &mut self,+ num_buffered_values: usize,+ data: &ByteBufferPtr,+ start: usize,+ len: usize,+ ) -> usize {+ match *self {+ LevelDecoder::RLE_V2(ref mut num_values, ref mut decoder) => {+ decoder.set_data(data.range(start, len));+ *num_values = Some(num_buffered_values);+ len+ }+ _ => panic!("set_data_range() method is only supported by RLE v2 encoding type"),+ }+ }++ /// Returns true if data is set for decoder, false otherwise.+ #[inline]+ pub fn is_data_set(&self) -> bool {+ match self {+ LevelDecoder::RLE(ref num_values, _) => num_values.is_some(),+ LevelDecoder::RLE_V2(ref num_values, _) => num_values.is_some(),+ LevelDecoder::BIT_PACKED(ref num_values, ..) => num_values.is_some(),+ }+ }++ /// Decodes values and puts them into `buffer`.+ /// Returns number of values that were successfully decoded (less than or equal to+ /// buffer length).+ #[inline]+ pub fn get(&mut self, buffer: &mut [i16]) -> Result<usize> {+ assert!(self.is_data_set(), "No data set for decoding");+ match *self {+ LevelDecoder::RLE(ref mut num_values, ref mut decoder)+ | LevelDecoder::RLE_V2(ref mut num_values, ref mut decoder) => {+ // Max length we can read+ let len = cmp::min(num_values.unwrap(), buffer.len());+ let values_read = decoder.get_batch::<i16>(&mut buffer[0..len])?;+ *num_values = num_values.map(|len| len - values_read);+ Ok(values_read)+ }+ LevelDecoder::BIT_PACKED(ref mut num_values, bit_width, ref mut decoder) => {+ // When extracting values from bit reader, it might return more values than left+ // because of padding to a full byte, we use num_values to track precise number+ // of values.+ let len = cmp::min(num_values.unwrap(), buffer.len());+ let values_read = decoder.get_batch::<i16>(&mut buffer[..len], bit_width as usize);+ *num_values = num_values.map(|len| len - values_read);+ Ok(values_read)+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ use crate::parquet::util::test_common::random_numbers_range;++ fn test_internal_roundtrip(enc: Encoding, levels: &[i16], max_level: i16, v2: bool) {+ let size = max_buffer_size(enc, max_level, levels.len());+ let mut encoder = if v2 {+ LevelEncoder::v2(max_level, vec![0; size])+ } else {+ LevelEncoder::v1(enc, max_level, vec![0; size])+ };+ encoder.put(&levels).expect("put() should be OK");+ let encoded_levels = encoder.consume().expect("consume() should be OK");++ let byte_buf = ByteBufferPtr::new(encoded_levels);+ let mut decoder;+ if v2 {+ decoder = LevelDecoder::v2(max_level);+ decoder.set_data_range(levels.len(), &byte_buf, 0, byte_buf.len());+ } else {+ decoder = LevelDecoder::v1(enc, max_level);+ decoder.set_data(levels.len(), byte_buf);+ };++ let mut buffer = vec![0; levels.len()];+ let num_decoded = decoder.get(&mut buffer).expect("get() should be OK");+ assert_eq!(num_decoded, levels.len());+ assert_eq!(buffer, levels);+ }++ // Performs incremental read until all bytes are read+ fn test_internal_roundtrip_incremental(+ enc: Encoding,+ levels: &[i16],+ max_level: i16,+ v2: bool,+ ) {+ let size = max_buffer_size(enc, max_level, levels.len());+ let mut encoder = if v2 {+ LevelEncoder::v2(max_level, vec![0; size])+ } else {+ LevelEncoder::v1(enc, max_level, vec![0; size])+ };+ encoder.put(&levels).expect("put() should be OK");+ let encoded_levels = encoder.consume().expect("consume() should be OK");++ let byte_buf = ByteBufferPtr::new(encoded_levels);+ let mut decoder;+ if v2 {+ decoder = LevelDecoder::v2(max_level);+ decoder.set_data_range(levels.len(), &byte_buf, 0, byte_buf.len());+ } else {+ decoder = LevelDecoder::v1(enc, max_level);+ decoder.set_data(levels.len(), byte_buf);+ }++ let mut buffer = vec![0; levels.len() * 2];+ let mut total_decoded = 0;+ let mut safe_stop = levels.len() * 2; // still terminate in case of issues in the code+ while safe_stop > 0 {+ safe_stop -= 1;+ let num_decoded = decoder+ .get(&mut buffer[total_decoded..total_decoded + 1])+ .expect("get() should be OK");+ if num_decoded == 0 {+ break;+ }+ total_decoded += num_decoded;+ }+ assert!(+ safe_stop > 0,+ "Failed to read values incrementally, reached safe stop"+ );+ assert_eq!(total_decoded, levels.len());+ assert_eq!(&buffer[0..levels.len()], levels);+ }++ // Tests encoding/decoding of values when output buffer is larger than number of+ // encoded values+ fn test_internal_roundtrip_underflow(enc: Encoding, levels: &[i16], max_level: i16, v2: bool) {+ let size = max_buffer_size(enc, max_level, levels.len());+ let mut encoder = if v2 {+ LevelEncoder::v2(max_level, vec![0; size])+ } else {+ LevelEncoder::v1(enc, max_level, vec![0; size])+ };+ // Encode only one value+ let num_encoded = encoder.put(&levels[0..1]).expect("put() should be OK");+ let encoded_levels = encoder.consume().expect("consume() should be OK");+ assert_eq!(num_encoded, 1);++ let byte_buf = ByteBufferPtr::new(encoded_levels);+ let mut decoder;+ // Set one encoded value as `num_buffered_values`+ if v2 {+ decoder = LevelDecoder::v2(max_level);+ decoder.set_data_range(1, &byte_buf, 0, byte_buf.len());+ } else {+ decoder = LevelDecoder::v1(enc, max_level);+ decoder.set_data(1, byte_buf);+ }++ let mut buffer = vec![0; levels.len()];+ let num_decoded = decoder.get(&mut buffer).expect("get() should be OK");+ assert_eq!(num_decoded, num_encoded);+ assert_eq!(buffer[0..num_decoded], levels[0..num_decoded]);+ }++ // Tests when encoded values are larger than encoder's buffer+ fn test_internal_roundtrip_overflow(enc: Encoding, levels: &[i16], max_level: i16, v2: bool) {+ let size = max_buffer_size(enc, max_level, levels.len());+ let mut encoder = if v2 {+ LevelEncoder::v2(max_level, vec![0; size])+ } else {+ LevelEncoder::v1(enc, max_level, vec![0; size])+ };+ let mut found_err = false;+ // Insert a large number of values, so we run out of space+ for _ in 0..100 {+ match encoder.put(&levels) {+ Err(err) => {+ assert!(format!("{}", err).contains("Not enough bytes left"));+ found_err = true;+ break;+ }+ Ok(_) => {}+ }+ }+ if !found_err {+ panic!("Failed test: no buffer overflow");+ }+ }++ #[test]+ fn test_roundtrip_one() {+ let levels = vec![0, 1, 1, 1, 1, 0, 0, 0, 0, 1];+ let max_level = 1;+ test_internal_roundtrip(Encoding::RLE, &levels, max_level, false);+ test_internal_roundtrip(Encoding::BIT_PACKED, &levels, max_level, false);+ test_internal_roundtrip(Encoding::RLE, &levels, max_level, true);+ }++ #[test]+ fn test_roundtrip() {+ let levels = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];+ let max_level = 10;+ test_internal_roundtrip(Encoding::RLE, &levels, max_level, false);+ test_internal_roundtrip(Encoding::BIT_PACKED, &levels, max_level, false);+ test_internal_roundtrip(Encoding::RLE, &levels, max_level, true);+ }++ #[test]+ fn test_roundtrip_incremental() {+ let levels = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];+ let max_level = 10;+ test_internal_roundtrip_incremental(Encoding::RLE, &levels, max_level, false);+ test_internal_roundtrip_incremental(Encoding::BIT_PACKED, &levels, max_level, false);+ test_internal_roundtrip_incremental(Encoding::RLE, &levels, max_level, true);+ }++ #[test]+ fn test_roundtrip_all_zeros() {+ let levels = vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0];+ let max_level = 1;+ test_internal_roundtrip(Encoding::RLE, &levels, max_level, false);+ test_internal_roundtrip(Encoding::BIT_PACKED, &levels, max_level, false);+ test_internal_roundtrip(Encoding::RLE, &levels, max_level, true);+ }++ #[test]+ fn test_roundtrip_random() {+ // This test is mainly for bit packed level encoder/decoder+ let mut levels = Vec::new();+ let max_level = 5;+ random_numbers_range::<i16>(120, 0, max_level, &mut levels);+ test_internal_roundtrip(Encoding::RLE, &levels, max_level, false);+ test_internal_roundtrip(Encoding::BIT_PACKED, &levels, max_level, false);+ test_internal_roundtrip(Encoding::RLE, &levels, max_level, true);+ }++ #[test]+ fn test_roundtrip_underflow() {+ let levels = vec![1, 1, 2, 3, 2, 1, 1, 2, 3, 1];+ let max_level = 3;+ test_internal_roundtrip_underflow(Encoding::RLE, &levels, max_level, false);+ test_internal_roundtrip_underflow(Encoding::BIT_PACKED, &levels, max_level, false);+ test_internal_roundtrip_underflow(Encoding::RLE, &levels, max_level, true);+ }++ #[test]+ fn test_roundtrip_overflow() {+ let levels = vec![1, 1, 2, 3, 2, 1, 1, 2, 3, 1];+ let max_level = 3;+ test_internal_roundtrip_overflow(Encoding::RLE, &levels, max_level, false);+ test_internal_roundtrip_overflow(Encoding::BIT_PACKED, &levels, max_level, false);+ test_internal_roundtrip_overflow(Encoding::RLE, &levels, max_level, true);+ }++ #[test]+ fn test_rle_decoder_set_data_range() {+ // Buffer containing both repetition and definition levels+ let buffer = ByteBufferPtr::new(vec![5, 198, 2, 5, 42, 168, 10, 0, 2, 3, 36, 73]);++ let max_rep_level = 1;+ let mut decoder = LevelDecoder::v2(max_rep_level);+ assert_eq!(decoder.set_data_range(10, &buffer, 0, 3), 3);+ let mut result = vec![0; 10];+ let num_decoded = decoder.get(&mut result).expect("get() should be OK");+ assert_eq!(num_decoded, 10);+ assert_eq!(result, vec![0, 1, 1, 0, 0, 0, 1, 1, 0, 1]);++ let max_def_level = 2;+ let mut decoder = LevelDecoder::v2(max_def_level);+ assert_eq!(decoder.set_data_range(10, &buffer, 3, 5), 5);+ let mut result = vec![0; 10];+ let num_decoded = decoder.get(&mut result).expect("get() should be OK");+ assert_eq!(num_decoded, 10);+ assert_eq!(result, vec![2, 2, 2, 0, 0, 2, 2, 2, 2, 2]);+ }++ #[test]+ #[should_panic(expected = "set_data_range() method is only supported by RLE v2 encoding type")]+ fn test_bit_packed_decoder_set_data_range() {+ // Buffer containing both repetition and definition levels+ let buffer = ByteBufferPtr::new(vec![1, 2, 3, 4, 5]);+ let max_level = 1;+ let mut decoder = LevelDecoder::v1(Encoding::BIT_PACKED, max_level);+ decoder.set_data_range(10, &buffer, 0, 3);+ }++ #[test]+ fn test_bit_packed_decoder_set_data() {+ // Test the maximum size that is assigned based on number of values and buffer length+ let buffer = ByteBufferPtr::new(vec![1, 2, 3, 4, 5]);+ let max_level = 1;+ let mut decoder = LevelDecoder::v1(Encoding::BIT_PACKED, max_level);+ // This should reset to entire buffer+ assert_eq!(decoder.set_data(1024, buffer.all()), buffer.len());+ // This should set smallest num bytes+ assert_eq!(decoder.set_data(3, buffer.all()), 1);+ }++ #[test]+ #[should_panic(expected = "No data set for decoding")]+ fn test_rle_level_decoder_get_no_set_data() {+ // `get()` normally panics because bit_reader is not set for RLE decoding+ // we have explicit check now in set_data+ let max_rep_level = 2;+ let mut decoder = LevelDecoder::v1(Encoding::RLE, max_rep_level);+ let mut buffer = vec![0; 16];+ decoder.get(&mut buffer).unwrap();+ }++ #[test]+ #[should_panic(expected = "No data set for decoding")]+ fn test_bit_packed_level_decoder_get_no_set_data() {+ let max_rep_level = 2;+ let mut decoder = LevelDecoder::v1(Encoding::BIT_PACKED, max_rep_level);+ let mut buffer = vec![0; 16];+ decoder.get(&mut buffer).unwrap();+ }+}diff --git a/rust/src/parquet/encodings/mod.rs b/rust/src/parquet/encodings/mod.rsnew file mode 100644index 0000000000..33b1e233d8--- /dev/null+++ b/rust/src/parquet/encodings/mod.rs@@ -0,0 +1,21 @@+// 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 decoding;+pub mod encoding;+pub mod levels;+mod rle;diff --git a/rust/src/parquet/encodings/rle.rs b/rust/src/parquet/encodings/rle.rsnew file mode 100644index 0000000000..5b56c2a250--- /dev/null+++ b/rust/src/parquet/encodings/rle.rs@@ -0,0 +1,839 @@+// 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,+ mem::{size_of, transmute_copy},+};++use crate::parquet::errors::{ParquetError, Result};+use crate::parquet::util::{+ bit_util::{self, BitReader, BitWriter},+ memory::ByteBufferPtr,+};++/// Rle/Bit-Packing Hybrid Encoding+/// The grammar for this encoding looks like the following (copied verbatim+/// from https://github.com/Parquet/parquet-format/blob/master/Encodings.md):+///+/// rle-bit-packed-hybrid: <length> <encoded-data>+/// length := length of the <encoded-data> in bytes stored as 4 bytes little endian+/// encoded-data := <run>*+/// run := <bit-packed-run> | <rle-run>+/// bit-packed-run := <bit-packed-header> <bit-packed-values>+/// bit-packed-header := varint-encode(<bit-pack-count> << 1 | 1)+/// we always bit-pack a multiple of 8 values at a time, so we only store the number of+/// values / 8+/// bit-pack-count := (number of values in this run) / 8+/// bit-packed-values := *see 1 below*+/// rle-run := <rle-header> <repeated-value>+/// rle-header := varint-encode( (number of times repeated) << 1)+/// repeated-value := value that is repeated, using a fixed-width of+/// round-up-to-next-byte(bit-width)++/// Maximum groups per bit-packed run. Current value is 64.+const MAX_GROUPS_PER_BIT_PACKED_RUN: usize = 1 << 6;+const MAX_VALUES_PER_BIT_PACKED_RUN: usize = MAX_GROUPS_PER_BIT_PACKED_RUN * 8;+const MAX_WRITER_BUF_SIZE: usize = 1 << 10;++/// A RLE/Bit-Packing hybrid encoder.+// TODO: tracking memory usage+pub struct RleEncoder {+ // Number of bits needed to encode the value. Must be in the range of [0, 64].+ bit_width: u8,++ // Underlying writer which holds an internal buffer.+ bit_writer: BitWriter,++ // If this is true, the buffer is full and subsequent `put()` calls will fail.+ buffer_full: bool,++ // The maximum byte size a single run can take.+ max_run_byte_size: usize,++ // Buffered values for bit-packed runs.+ buffered_values: [u64; 8],++ // Number of current buffered values. Must be less than 8.+ num_buffered_values: usize,++ // The current (also last) value that was written and the count of how many+ // times in a row that value has been seen.+ current_value: u64,++ // The number of repetitions for `current_value`. If this gets too high we'd+ // switch to use RLE encoding.+ repeat_count: usize,++ // Number of bit-packed values in the current run. This doesn't include values+ // in `buffered_values`.+ bit_packed_count: usize,++ // The position of the indicator byte in the `bit_writer`.+ indicator_byte_pos: i64,+}++impl RleEncoder {+ pub fn new(bit_width: u8, buffer_len: usize) -> Self {+ let buffer = vec![0; buffer_len];+ RleEncoder::new_from_buf(bit_width, buffer, 0)+ }++ /// Initialize the encoder from existing `buffer` and the starting offset `start`.+ pub fn new_from_buf(bit_width: u8, buffer: Vec<u8>, start: usize) -> Self {+ assert!(bit_width <= 64, "bit_width ({}) out of range.", bit_width);+ let max_run_byte_size = RleEncoder::min_buffer_size(bit_width);+ assert!(+ buffer.len() >= max_run_byte_size,+ "buffer length {} must be greater than {}",+ buffer.len(),+ max_run_byte_size+ );+ let bit_writer = BitWriter::new_from_buf(buffer, start);+ RleEncoder {+ bit_width,+ bit_writer,+ buffer_full: false,+ max_run_byte_size,+ buffered_values: [0; 8],+ num_buffered_values: 0,+ current_value: 0,+ repeat_count: 0,+ bit_packed_count: 0,+ indicator_byte_pos: -1,+ }+ }++ /// Returns the minimum buffer size needed to use the encoder for `bit_width`.+ /// This is the maximum length of a single run for `bit_width`.+ pub fn min_buffer_size(bit_width: u8) -> usize {+ let max_bit_packed_run_size = 1 + bit_util::ceil(+ (MAX_VALUES_PER_BIT_PACKED_RUN * bit_width as usize) as i64,+ 8,+ );+ let max_rle_run_size =+ bit_util::MAX_VLQ_BYTE_LEN + bit_util::ceil(bit_width as i64, 8) as usize;+ ::std::cmp::max(max_bit_packed_run_size as usize, max_rle_run_size)+ }++ /// Returns the maximum buffer size takes to encode `num_values` values with+ /// `bit_width`.+ pub fn max_buffer_size(bit_width: u8, num_values: usize) -> usize {+ // First the maximum size for bit-packed run+ let bytes_per_run = bit_width;+ let num_runs = bit_util::ceil(num_values as i64, 8) as usize;+ let bit_packed_max_size = num_runs + num_runs * bytes_per_run as usize;++ // Second the maximum size for RLE run+ let min_rle_run_size = 1 + bit_util::ceil(bit_width as i64, 8) as usize;+ let rle_max_size = bit_util::ceil(num_values as i64, 8) as usize * min_rle_run_size;+ ::std::cmp::max(bit_packed_max_size, rle_max_size) as usize+ }++ /// Encodes `value`, which must be representable with `bit_width` bits.+ /// Returns true if the value fits in buffer, false if it doesn't, or+ /// error if something is wrong.+ #[inline]+ pub fn put(&mut self, value: u64) -> Result<bool> {+ // This function buffers 8 values at a time. After seeing 8 values, it+ // decides whether the current run should be encoded in bit-packed or RLE.+ if self.buffer_full {+ // The value cannot fit in the current buffer.+ return Ok(false);+ }+ if self.current_value == value {+ self.repeat_count += 1;+ if self.repeat_count > 8 {+ // A continuation of last value. No need to buffer.+ return Ok(true);+ }+ } else {+ if self.repeat_count >= 8 {+ // The current RLE run has ended and we've gathered enough. Flush first.+ assert_eq!(self.bit_packed_count, 0);+ self.flush_rle_run()?;+ }+ self.repeat_count = 1;+ self.current_value = value;+ }++ self.buffered_values[self.num_buffered_values] = value;+ self.num_buffered_values += 1;+ if self.num_buffered_values == 8 {+ // Buffered values are full. Flush them.+ assert_eq!(self.bit_packed_count % 8, 0);+ self.flush_buffered_values()?;+ }++ Ok(true)+ }++ #[inline]+ pub fn buffer(&self) -> &[u8] {+ self.bit_writer.buffer()+ }++ #[inline]+ pub fn len(&self) -> usize {+ self.bit_writer.bytes_written()+ }++ #[inline]+ pub fn consume(mut self) -> Result<Vec<u8>> {+ self.flush()?;+ Ok(self.bit_writer.consume())+ }++ /// Borrow equivalent of the `consume` method.+ /// Call `clear()` after invoking this method.+ #[inline]+ pub fn flush_buffer(&mut self) -> Result<&[u8]> {+ self.flush()?;+ Ok(self.bit_writer.flush_buffer())+ }++ /// Clears the internal state so this encoder can be reused (e.g., after becoming full).+ #[inline]+ pub fn clear(&mut self) {+ self.bit_writer.clear();+ self.buffer_full = false;+ self.num_buffered_values = 0;+ self.current_value = 0;+ self.repeat_count = 0;+ self.bit_packed_count = 0;+ self.indicator_byte_pos = -1;+ }++ /// Flushes all remaining values and return the final byte buffer maintained by the+ /// internal writer.+ #[inline]+ pub fn flush(&mut self) -> Result<()> {+ if self.bit_packed_count > 0 || self.repeat_count > 0 || self.num_buffered_values > 0 {+ let all_repeat = self.bit_packed_count == 0+ && (self.repeat_count == self.num_buffered_values || self.num_buffered_values == 0);+ if self.repeat_count > 0 && all_repeat {+ self.flush_rle_run()?;+ } else {+ // Buffer the last group of bit-packed values to 8 by padding with 0s.+ if self.num_buffered_values > 0 {+ while self.num_buffered_values < 8 {+ self.buffered_values[self.num_buffered_values] = 0;+ self.num_buffered_values += 1;+ }+ }+ self.bit_packed_count += self.num_buffered_values;+ self.flush_bit_packed_run(true)?;+ self.repeat_count = 0;+ }+ }+ Ok(())+ }++ #[inline]+ fn flush_rle_run(&mut self) -> Result<()> {+ assert!(self.repeat_count > 0);+ let indicator_value = self.repeat_count << 1 | 0;+ let mut result = self.bit_writer.put_vlq_int(indicator_value as u64);+ result &= self.bit_writer.put_aligned(+ self.current_value,+ bit_util::ceil(self.bit_width as i64, 8) as usize,+ );+ if !result {+ return Err(general_err!("Failed to write RLE run"));+ }+ self.num_buffered_values = 0;+ self.repeat_count = 0;+ Ok(())+ }++ #[inline]+ fn flush_bit_packed_run(&mut self, update_indicator_byte: bool) -> Result<()> {+ if self.indicator_byte_pos < 0 {+ self.indicator_byte_pos = self.bit_writer.skip(1)? as i64;+ }++ // Write all buffered values as bit-packed literals+ for i in 0..self.num_buffered_values {+ let _ = self+ .bit_writer+ .put_value(self.buffered_values[i], self.bit_width as usize);+ }+ self.num_buffered_values = 0;+ if update_indicator_byte {+ // Write the indicator byte to the reserved position in `bit_writer`+ let num_groups = self.bit_packed_count / 8;+ let indicator_byte = ((num_groups << 1) | 1) as u8;+ if !self.bit_writer.put_aligned_offset(+ indicator_byte,+ 1,+ self.indicator_byte_pos as usize,+ ) {+ return Err(general_err!("Not enough space to write indicator byte"));+ }+ self.indicator_byte_pos = -1;+ self.bit_packed_count = 0;+ }+ Ok(())+ }++ #[inline]+ fn flush_buffered_values(&mut self) -> Result<()> {+ if self.repeat_count >= 8 {+ self.num_buffered_values = 0;+ if self.bit_packed_count > 0 {+ // In this case we choose RLE encoding. Flush the current buffered values+ // as bit-packed encoding.+ assert_eq!(self.bit_packed_count % 8, 0);+ self.flush_bit_packed_run(true)?+ }+ return Ok(());+ }++ self.bit_packed_count += self.num_buffered_values;+ let num_groups = self.bit_packed_count / 8;+ if num_groups + 1 >= MAX_GROUPS_PER_BIT_PACKED_RUN {+ // We've reached the maximum value that can be hold in a single bit-packed run.+ assert!(self.indicator_byte_pos >= 0);+ self.flush_bit_packed_run(true)?;+ } else {+ self.flush_bit_packed_run(false)?;+ }+ self.repeat_count = 0;+ Ok(())+ }+}++/// A RLE/Bit-Packing hybrid decoder.+pub struct RleDecoder {+ // Number of bits used to encode the value. Must be between [0, 64].+ bit_width: u8,++ // Bit reader loaded with input buffer.+ bit_reader: Option<BitReader>,++ // Buffer used when `bit_reader` is not `None`, for batch reading.+ index_buf: Option<[i32; 1024]>,++ // The remaining number of values in RLE for this run+ rle_left: u32,++ // The remaining number of values in Bit-Packing for this run+ bit_packed_left: u32,++ // The current value for the case of RLE mode+ current_value: Option<u64>,+}++impl RleDecoder {+ pub fn new(bit_width: u8) -> Self {+ RleDecoder {+ bit_width,+ rle_left: 0,+ bit_packed_left: 0,+ bit_reader: None,+ index_buf: None,+ current_value: None,+ }+ }++ pub fn set_data(&mut self, data: ByteBufferPtr) {+ if let Some(ref mut bit_reader) = self.bit_reader {+ bit_reader.reset(data);+ } else {+ self.bit_reader = Some(BitReader::new(data));+ self.index_buf = Some([0; 1024]);+ }++ let _ = self.reload();+ }++ #[inline]+ pub fn get<T: Default>(&mut self) -> Result<Option<T>> {+ assert!(size_of::<T>() <= 8);++ while self.rle_left <= 0 && self.bit_packed_left <= 0 {+ if !self.reload() {+ return Ok(None);+ }+ }++ let value = if self.rle_left > 0 {+ let rle_value = unsafe {+ transmute_copy::<u64, T>(+ self.current_value+ .as_mut()+ .expect("current_value should be Some"),+ )+ };+ self.rle_left -= 1;+ rle_value+ } else {+ // self.bit_packed_left > 0+ let bit_reader = self.bit_reader.as_mut().expect("bit_reader should be Some");+ let bit_packed_value = bit_reader+ .get_value(self.bit_width as usize)+ .ok_or(eof_err!("Not enough data for 'bit_packed_value'"))?;+ self.bit_packed_left -= 1;+ bit_packed_value+ };++ Ok(Some(value))+ }++ #[inline]+ pub fn get_batch<T: Default>(&mut self, buffer: &mut [T]) -> Result<usize> {+ assert!(self.bit_reader.is_some());+ assert!(size_of::<T>() <= 8);++ let mut values_read = 0;+ while values_read < buffer.len() {+ if self.rle_left > 0 {+ assert!(self.current_value.is_some());+ let num_values = cmp::min(buffer.len() - values_read, self.rle_left as usize);+ for i in 0..num_values {+ let repeated_value =+ unsafe { transmute_copy::<u64, T>(self.current_value.as_mut().unwrap()) };+ buffer[values_read + i] = repeated_value;+ }+ self.rle_left -= num_values as u32;+ values_read += num_values;+ } else if self.bit_packed_left > 0 {+ assert!(self.bit_reader.is_some());+ let mut num_values =+ cmp::min(buffer.len() - values_read, self.bit_packed_left as usize);+ if let Some(ref mut bit_reader) = self.bit_reader {+ num_values = bit_reader.get_batch::<T>(+ &mut buffer[values_read..values_read + num_values],+ self.bit_width as usize,+ );+ self.bit_packed_left -= num_values as u32;+ values_read += num_values;+ }+ } else {+ if !self.reload() {+ break;+ }+ }+ }++ Ok(values_read)+ }++ #[inline]+ pub fn get_batch_with_dict<T>(+ &mut self,+ dict: &[T],+ buffer: &mut [T],+ max_values: usize,+ ) -> Result<usize>+ where+ T: Default + Clone,+ {+ assert!(buffer.len() >= max_values);++ let mut values_read = 0;+ while values_read < max_values {+ if self.rle_left > 0 {+ assert!(self.current_value.is_some());+ let num_values = cmp::min(max_values - values_read, self.rle_left as usize);+ let dict_idx = self.current_value.unwrap() as usize;+ for i in 0..num_values {+ buffer[values_read + i] = dict[dict_idx].clone();+ }+ self.rle_left -= num_values as u32;+ values_read += num_values;+ } else if self.bit_packed_left > 0 {+ assert!(self.bit_reader.is_some());+ let mut num_values =+ cmp::min(max_values - values_read, self.bit_packed_left as usize);+ if let Some(ref mut bit_reader) = self.bit_reader {+ let mut index_buf = self.index_buf.unwrap();+ num_values = cmp::min(num_values, index_buf.len());+ loop {+ num_values = bit_reader.get_batch::<i32>(+ &mut index_buf[..num_values],+ self.bit_width as usize,+ );+ for i in 0..num_values {+ buffer[values_read + i] = dict[index_buf[i] as usize].clone();+ }+ self.bit_packed_left -= num_values as u32;+ values_read += num_values;+ if num_values < index_buf.len() {+ break;+ }+ }+ }+ } else {+ if !self.reload() {+ break;+ }+ }+ }++ Ok(values_read)+ }++ #[inline]+ fn reload(&mut self) -> bool {+ assert!(self.bit_reader.is_some());+ if let Some(ref mut bit_reader) = self.bit_reader {+ if let Some(indicator_value) = bit_reader.get_vlq_int() {+ if indicator_value & 1 == 1 {+ self.bit_packed_left = ((indicator_value >> 1) * 8) as u32;+ } else {+ self.rle_left = (indicator_value >> 1) as u32;+ let value_width = bit_util::ceil(self.bit_width as i64, 8);+ self.current_value = bit_reader.get_aligned::<u64>(value_width as usize);+ assert!(self.current_value.is_some());+ }+ return true;+ } else {+ return false;+ }+ }+ return false;+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ use rand::{+ self,+ distributions::{Distribution, Standard},+ thread_rng, Rng, SeedableRng,+ };++ use crate::parquet::util::memory::ByteBufferPtr;++ const MAX_WIDTH: usize = 32;++ #[test]+ fn test_rle_decode_int32() {+ // Test data: 0-7 with bit width 3+ // 00000011 10001000 11000110 11111010+ let data = ByteBufferPtr::new(vec![0x03, 0x88, 0xC6, 0xFA]);+ let mut decoder: RleDecoder = RleDecoder::new(3);+ decoder.set_data(data);+ let mut buffer = vec![0; 8];+ let expected = vec![0, 1, 2, 3, 4, 5, 6, 7];+ let result = decoder.get_batch::<i32>(&mut buffer);+ assert!(result.is_ok());+ assert_eq!(buffer, expected);+ }++ #[test]+ fn test_rle_consume_flush_buffer() {+ let data = vec![1, 1, 1, 2, 2, 3, 3, 3];+ let mut encoder1 = RleEncoder::new(3, 256);+ let mut encoder2 = RleEncoder::new(3, 256);+ for value in data {+ encoder1.put(value as u64).unwrap();+ encoder2.put(value as u64).unwrap();+ }+ let res1 = encoder1.flush_buffer().unwrap();+ let res2 = encoder2.consume().unwrap();+ assert_eq!(res1, &res2[..]);+ }++ #[test]+ fn test_rle_decode_bool() {+ // RLE test data: 50 1s followed by 50 0s+ // 01100100 00000001 01100100 00000000+ let data1 = ByteBufferPtr::new(vec![0x64, 0x01, 0x64, 0x00]);++ // Bit-packing test data: alternating 1s and 0s, 100 total+ // 100 / 8 = 13 groups+ // 00011011 10101010 ... 00001010+ let data2 = ByteBufferPtr::new(vec![+ 0x1B, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x0A,+ ]);++ let mut decoder: RleDecoder = RleDecoder::new(1);+ decoder.set_data(data1);+ let mut buffer = vec![false; 100];+ let mut expected = vec![];+ for i in 0..100 {+ if i < 50 {+ expected.push(true);+ } else {+ expected.push(false);+ }+ }+ let result = decoder.get_batch::<bool>(&mut buffer);+ assert!(result.is_ok());+ assert_eq!(buffer, expected);++ decoder.set_data(data2);+ let mut buffer = vec![false; 100];+ let mut expected = vec![];+ for i in 0..100 {+ if i % 2 == 0 {+ expected.push(false);+ } else {+ expected.push(true);+ }+ }+ let result = decoder.get_batch::<bool>(&mut buffer);+ assert!(result.is_ok());+ assert_eq!(buffer, expected);+ }++ #[test]+ fn test_rle_decode_with_dict_int32() {+ // Test RLE encoding: 3 0s followed by 4 1s followed by 5 2s+ // 00000110 00000000 00001000 00000001 00001010 00000010+ let dict = vec![10, 20, 30];+ let data = ByteBufferPtr::new(vec![0x06, 0x00, 0x08, 0x01, 0x0A, 0x02]);+ let mut decoder: RleDecoder = RleDecoder::new(3);+ decoder.set_data(data);+ let mut buffer = vec![0; 12];+ let expected = vec![10, 10, 10, 20, 20, 20, 20, 30, 30, 30, 30, 30];+ let result = decoder.get_batch_with_dict::<i32>(&dict, &mut buffer, 12);+ assert!(result.is_ok());+ assert_eq!(buffer, expected);++ // Test bit-pack encoding: 345345345455 (2 groups: 8 and 4)+ // 011 100 101 011 100 101 011 100 101 100 101 101+ // 00000011 01100011 11000111 10001110 00000011 01100101 00001011+ let dict = vec!["aaa", "bbb", "ccc", "ddd", "eee", "fff"];+ let data = ByteBufferPtr::new(vec![0x03, 0x63, 0xC7, 0x8E, 0x03, 0x65, 0x0B]);+ let mut decoder: RleDecoder = RleDecoder::new(3);+ decoder.set_data(data);+ let mut buffer = vec![""; 12];+ let expected = vec![+ "ddd", "eee", "fff", "ddd", "eee", "fff", "ddd", "eee", "fff", "eee", "fff", "fff",+ ];+ let result =+ decoder.get_batch_with_dict::<&str>(dict.as_slice(), buffer.as_mut_slice(), 12);+ assert!(result.is_ok());+ assert_eq!(buffer, expected);+ }++ fn validate_rle(+ values: &[i64],+ bit_width: u8,+ expected_encoding: Option<&[u8]>,+ expected_len: i32,+ ) {+ let buffer_len = 64 * 1024;+ let mut encoder = RleEncoder::new(bit_width, buffer_len);+ for v in values {+ let result = encoder.put(*v as u64);+ assert!(result.is_ok());+ }+ let buffer = ByteBufferPtr::new(encoder.consume().expect("Expect consume() OK"));+ if expected_len != -1 {+ assert_eq!(buffer.len(), expected_len as usize);+ }+ match expected_encoding {+ Some(b) => assert_eq!(buffer.as_ref(), b),+ _ => (),+ }++ // Verify read+ let mut decoder = RleDecoder::new(bit_width);+ decoder.set_data(buffer.all());+ for v in values {+ let val: i64 = decoder+ .get()+ .expect("get() should be OK")+ .expect("get() should return more value");+ assert_eq!(val, *v);+ }++ // Verify batch read+ decoder.set_data(buffer);+ let mut values_read: Vec<i64> = vec![0; values.len()];+ decoder+ .get_batch(&mut values_read[..])+ .expect("get_batch() should be OK");+ assert_eq!(&values_read[..], values);+ }++ #[test]+ fn test_rle_specific_sequences() {+ let mut expected_buffer = Vec::new();+ let mut values = Vec::new();+ for _ in 0..50 {+ values.push(0);+ }+ for _ in 0..50 {+ values.push(1);+ }+ expected_buffer.push(50 << 1);+ expected_buffer.push(0);+ expected_buffer.push(50 << 1);+ expected_buffer.push(1);++ for width in 1..9 {+ validate_rle(&values[..], width, Some(&expected_buffer[..]), 4);+ }+ for width in 9..MAX_WIDTH + 1 {+ validate_rle(+ &values[..],+ width as u8,+ None,+ 2 * (1 + bit_util::ceil(width as i64, 8) as i32),+ );+ }++ // Test 100 0's and 1's alternating+ values.clear();+ expected_buffer.clear();+ for i in 0..101 {+ values.push(i % 2);+ }+ let num_groups = bit_util::ceil(100, 8) as u8;+ expected_buffer.push(((num_groups << 1) as u8) | 1);+ for _ in 1..(100 / 8) + 1 {+ expected_buffer.push(0b10101010);+ }+ // For the last 4 0 and 1's, padded with 0.+ expected_buffer.push(0b00001010);+ validate_rle(+ &values,+ 1,+ Some(&expected_buffer[..]),+ 1 + num_groups as i32,+ );+ for width in 2..MAX_WIDTH + 1 {+ let num_values = bit_util::ceil(100, 8) * 8;+ validate_rle(+ &values,+ width as u8,+ None,+ 1 + bit_util::ceil(width as i64 * num_values, 8) as i32,+ );+ }+ }++ // `validate_rle` on `num_vals` with width `bit_width`. If `value` is -1, that value+ // is used, otherwise alternating values are used.+ fn test_rle_values(bit_width: usize, num_vals: usize, value: i32) {+ let mod_val = if bit_width == 64 {+ 1+ } else {+ 1u64 << bit_width+ };+ let mut values: Vec<i64> = vec![];+ for v in 0..num_vals {+ let val = if value == -1 {+ v as i64 % mod_val as i64+ } else {+ value as i64+ };+ values.push(val);+ }+ validate_rle(&values, bit_width as u8, None, -1);+ }++ #[test]+ fn test_values() {+ for width in 1..MAX_WIDTH + 1 {+ test_rle_values(width, 1, -1);+ test_rle_values(width, 1024, -1);+ test_rle_values(width, 1024, 0);+ test_rle_values(width, 1024, 1);+ }+ }++ #[test]+ fn test_rle_specific_roundtrip() {+ let bit_width = 1;+ let buffer_len = RleEncoder::min_buffer_size(bit_width);+ let values: Vec<i16> = vec![0, 1, 1, 1, 1, 0, 0, 0, 0, 1];+ let mut encoder = RleEncoder::new(bit_width, buffer_len);+ for v in &values {+ assert!(encoder.put(*v as u64).expect("put() should be OK"));+ }+ let buffer = encoder.consume().expect("consume() should be OK");+ let mut decoder = RleDecoder::new(bit_width);+ decoder.set_data(ByteBufferPtr::new(buffer));+ let mut actual_values: Vec<i16> = vec![0; values.len()];+ decoder+ .get_batch(&mut actual_values)+ .expect("get_batch() should be OK");+ assert_eq!(actual_values, values);+ }++ fn test_round_trip(values: &[i32], bit_width: u8) {+ let buffer_len = 64 * 1024;+ let mut encoder = RleEncoder::new(bit_width, buffer_len);+ for v in values {+ let result = encoder.put(*v as u64).expect("put() should be OK");+ assert!(result, "put() should not return false");+ }++ let buffer = ByteBufferPtr::new(encoder.consume().expect("consume() should be OK"));++ // Verify read+ let mut decoder = RleDecoder::new(bit_width);+ decoder.set_data(buffer.all());+ for v in values {+ let val = decoder+ .get::<i32>()+ .expect("get() should be OK")+ .expect("get() should return value");+ assert_eq!(val, *v);+ }++ // Verify batch read+ let mut decoder = RleDecoder::new(bit_width);+ decoder.set_data(buffer);+ let mut values_read: Vec<i32> = vec![0; values.len()];+ decoder+ .get_batch(&mut values_read[..])+ .expect("get_batch() should be OK");+ assert_eq!(&values_read[..], values);+ }++ #[test]+ fn test_random() {+ let seed_len = 32;+ let niters = 50;+ let ngroups = 1000;+ let max_group_size = 15;+ let mut values = vec![];++ for _ in 0..niters {+ values.clear();+ let mut rng = thread_rng();+ let seed_vec: Vec<u8> = Standard.sample_iter(&mut rng).take(seed_len).collect();+ let mut seed = [0u8; 32];+ seed.copy_from_slice(&seed_vec[0..seed_len]);+ let mut gen = rand::StdRng::from_seed(seed);++ let mut parity = false;+ for _ in 0..ngroups {+ let mut group_size = gen.gen_range::<u32>(1, 20);+ if group_size > max_group_size {+ group_size = 1;+ }+ for _ in 0..group_size {+ values.push(parity as i32);+ }+ parity = !parity;+ }+ let bit_width = bit_util::num_required_bits(values.len() as u64);+ assert!(bit_width < 64);+ test_round_trip(&values[..], bit_width as u8);+ }+ }+}diff --git a/rust/src/parquet/errors.rs b/rust/src/parquet/errors.rsnew file mode 100644index 0000000000..a5532c1eb6--- /dev/null+++ b/rust/src/parquet/errors.rs@@ -0,0 +1,87 @@+// 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.++//! Common Parquet errors and macros.++use std::{cell, convert, io, result};++use quick_error::quick_error;+use snap;+use thrift;++quick_error! {+ /// Set of errors that can be produced during different operations in Parquet.+ #[derive(Debug, PartialEq)]+ pub enum ParquetError {+ /// General Parquet error.+ /// Returned when code violates normal workflow of working with Parquet files.+ General(message: String) {+ display("Parquet error: {}", message)+ description(message)+ from(e: io::Error) -> (format!("underlying IO error: {}", e))+ from(e: snap::Error) -> (format!("underlying snap error: {}", e))+ from(e: thrift::Error) -> (format!("underlying Thrift error: {}", e))+ from(e: cell::BorrowMutError) -> (format!("underlying borrow error: {}", e))+ }+ /// "Not yet implemented" Parquet error.+ /// Returned when functionality is not yet available.+ NYI(message: String) {+ display("NYI: {}", message)+ description(message)+ }+ /// "End of file" Parquet error.+ /// Returned when IO related failures occur, e.g. when there are not enough bytes to+ /// decode.+ EOF(message: String) {+ display("EOF: {}", message)+ description(message)+ }+ }+}++/// A specialized `Result` for Parquet errors.+pub type Result<T> = result::Result<T, ParquetError>;++// ----------------------------------------------------------------------+// Conversion from `ParquetError` to other types of `Error`s++impl convert::From<ParquetError> for io::Error {+ fn from(e: ParquetError) -> Self {+ io::Error::new(io::ErrorKind::Other, e)+ }+}++// ----------------------------------------------------------------------+// Convenient macros for different errors++macro_rules! general_err {+ ($fmt:expr) => (ParquetError::General($fmt.to_owned()));+ ($fmt:expr, $($args:expr),*) => (ParquetError::General(format!($fmt, $($args),*)));+ ($e:expr, $fmt:expr) => (ParquetError::General($fmt.to_owned(), $e));+ ($e:ident, $fmt:expr, $($args:tt),*) => (+ ParquetError::General(&format!($fmt, $($args),*), $e));+}++macro_rules! nyi_err {+ ($fmt:expr) => (ParquetError::NYI($fmt.to_owned()));+ ($fmt:expr, $($args:expr),*) => (ParquetError::NYI(format!($fmt, $($args),*)));+}++macro_rules! eof_err {+ ($fmt:expr) => (ParquetError::EOF($fmt.to_owned()));+ ($fmt:expr, $($args:expr),*) => (ParquetError::EOF(format!($fmt, $($args),*)));+}diff --git a/rust/src/parquet/file/metadata.rs b/rust/src/parquet/file/metadata.rsnew file mode 100644index 0000000000..7f2442506f--- /dev/null+++ b/rust/src/parquet/file/metadata.rs@@ -0,0 +1,736 @@+// 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.++//! Contains information about available Parquet metadata.+//!+//! The hierarchy of metadata is as follows:+//!+//! [`ParquetMetaData`](struct.ParquetMetaData.html) contains+//! [`FileMetaData`](struct.FileMetaData.html) and zero or more+//! [`RowGroupMetaData`](struct.RowGroupMetaData.html) for each row group.+//!+//! [`FileMetaData`](struct.FileMetaData.html) includes file version, application specific+//! metadata.+//!+//! Each [`RowGroupMetaData`](struct.RowGroupMetaData.html) contains information about row+//! group and one or more [`ColumnChunkMetaData`](struct.ColumnChunkMetaData.html) for+//! each column chunk.+//!+//! [`ColumnChunkMetaData`](struct.ColumnChunkMetaData.html) has information about column+//! chunk (primitive leaf column), including encoding/compression, number of values, etc.++use std::rc::Rc;++use parquet_format::{ColumnChunk, ColumnMetaData, RowGroup};++use crate::parquet::basic::{ColumnOrder, Compression, Encoding, Type};+use crate::parquet::errors::{ParquetError, Result};+use crate::parquet::file::statistics::{self, Statistics};+use crate::parquet::schema::types::{+ ColumnDescPtr, ColumnDescriptor, ColumnPath, SchemaDescPtr, SchemaDescriptor,+ Type as SchemaType, TypePtr,+};++/// Reference counted pointer for [`ParquetMetaData`].+pub type ParquetMetaDataPtr = Rc<ParquetMetaData>;++/// Global Parquet metadata.+pub struct ParquetMetaData {+ file_metadata: FileMetaDataPtr,+ row_groups: Vec<RowGroupMetaDataPtr>,+}++impl ParquetMetaData {+ /// Creates Parquet metadata from file metadata and a list of row group metadata `Rc`s+ /// for each available row group.+ pub fn new(file_metadata: FileMetaData, row_group_ptrs: Vec<RowGroupMetaDataPtr>) -> Self {+ ParquetMetaData {+ file_metadata: Rc::new(file_metadata),+ row_groups: row_group_ptrs,+ }+ }++ /// Returns file metadata as reference counted clone.+ pub fn file_metadata(&self) -> FileMetaDataPtr {+ self.file_metadata.clone()+ }++ /// Returns number of row groups in this file.+ pub fn num_row_groups(&self) -> usize {+ self.row_groups.len()+ }++ /// Returns row group metadata for `i`th position.+ /// Position should be less than number of row groups `num_row_groups`.+ pub fn row_group(&self, i: usize) -> RowGroupMetaDataPtr {+ self.row_groups[i].clone()+ }++ /// Returns slice of row group reference counted pointers in this file.+ pub fn row_groups(&self) -> &[RowGroupMetaDataPtr] {+ &self.row_groups.as_slice()+ }+}++/// Reference counted pointer for [`FileMetaData`].+pub type FileMetaDataPtr = Rc<FileMetaData>;++/// Metadata for a Parquet file.+pub struct FileMetaData {+ version: i32,+ num_rows: i64,+ created_by: Option<String>,+ schema: TypePtr,+ schema_descr: SchemaDescPtr,+ column_orders: Option<Vec<ColumnOrder>>,+}++impl FileMetaData {+ /// Creates new file metadata.+ pub fn new(+ version: i32,+ num_rows: i64,+ created_by: Option<String>,+ schema: TypePtr,+ schema_descr: SchemaDescPtr,+ column_orders: Option<Vec<ColumnOrder>>,+ ) -> Self {+ FileMetaData {+ version,+ num_rows,+ created_by,+ schema,+ schema_descr,+ column_orders,+ }+ }++ /// Returns version of this file.+ pub fn version(&self) -> i32 {+ self.version+ }++ /// Returns number of rows in the file.+ pub fn num_rows(&self) -> i64 {+ self.num_rows+ }++ /// String message for application that wrote this file.+ ///+ /// This should have the following format:+ /// `<application> version <application version> (build <application build hash>)`.+ ///+ /// ```shell+ /// parquet-mr version 1.8.0 (build 0fda28af84b9746396014ad6a415b90592a98b3b)+ /// ```+ pub fn created_by(&self) -> &Option<String> {+ &self.created_by+ }++ /// Returns Parquet ['Type`] that describes schema in this file.+ pub fn schema(&self) -> &SchemaType {+ self.schema.as_ref()+ }++ /// Returns a reference to schema descriptor.+ pub fn schema_descr(&self) -> &SchemaDescriptor {+ &self.schema_descr+ }++ /// Returns reference counted clone for schema descriptor.+ pub fn schema_descr_ptr(&self) -> SchemaDescPtr {+ self.schema_descr.clone()+ }++ /// Column (sort) order used for `min` and `max` values of each column in this file.+ ///+ /// Each column order corresponds to one column, determined by its position in the list,+ /// matching the position of the column in the schema.+ ///+ /// When `None` is returned, there are no column orders available, and each column+ /// should be assumed to have undefined (legacy) column order.+ pub fn column_orders(&self) -> Option<&Vec<ColumnOrder>> {+ self.column_orders.as_ref()+ }++ /// Returns column order for `i`th column in this file.+ /// If column orders are not available, returns undefined (legacy) column order.+ pub fn column_order(&self, i: usize) -> ColumnOrder {+ self.column_orders+ .as_ref()+ .map(|data| data[i])+ .unwrap_or(ColumnOrder::UNDEFINED)+ }+}++/// Reference counted pointer for [`RowGroupMetaData`].+pub type RowGroupMetaDataPtr = Rc<RowGroupMetaData>;++/// Metadata for a row group.+pub struct RowGroupMetaData {+ columns: Vec<ColumnChunkMetaDataPtr>,+ num_rows: i64,+ total_byte_size: i64,+ schema_descr: SchemaDescPtr,+}++impl RowGroupMetaData {+ /// Returns builer for row group metadata.+ pub fn builder(schema_descr: SchemaDescPtr) -> RowGroupMetaDataBuilder {+ RowGroupMetaDataBuilder::new(schema_descr)+ }++ /// Number of columns in this row group.+ pub fn num_columns(&self) -> usize {+ self.columns.len()+ }++ /// Returns column chunk metadata for `i`th column.+ pub fn column(&self, i: usize) -> &ColumnChunkMetaData {+ &self.columns[i]+ }++ /// Returns slice of column chunk metadata [`Rc`] pointers.+ pub fn columns(&self) -> &[ColumnChunkMetaDataPtr] {+ &self.columns+ }++ /// Number of rows in this row group.+ pub fn num_rows(&self) -> i64 {+ self.num_rows+ }++ /// Total byte size of all uncompressed column data in this row group.+ pub fn total_byte_size(&self) -> i64 {+ self.total_byte_size+ }++ /// Returns reference to a schema descriptor.+ pub fn schema_descr(&self) -> &SchemaDescriptor {+ self.schema_descr.as_ref()+ }++ /// Returns reference counted clone of schema descriptor.+ pub fn schema_descr_ptr(&self) -> SchemaDescPtr {+ self.schema_descr.clone()+ }++ /// Method to convert from Thrift.+ pub fn from_thrift(schema_descr: SchemaDescPtr, mut rg: RowGroup) -> Result<RowGroupMetaData> {+ assert_eq!(schema_descr.num_columns(), rg.columns.len());+ let total_byte_size = rg.total_byte_size;+ let num_rows = rg.num_rows;+ let mut columns = vec![];+ for (c, d) in rg.columns.drain(0..).zip(schema_descr.columns()) {+ let cc = ColumnChunkMetaData::from_thrift(d.clone(), c)?;+ columns.push(Rc::new(cc));+ }+ Ok(RowGroupMetaData {+ columns,+ num_rows,+ total_byte_size,+ schema_descr,+ })+ }++ /// Method to convert to Thrift.+ pub fn to_thrift(&self) -> RowGroup {+ RowGroup {+ columns: self.columns().into_iter().map(|v| v.to_thrift()).collect(),+ total_byte_size: self.total_byte_size,+ num_rows: self.num_rows,+ sorting_columns: None,+ }+ }+}++/// Builder for row group metadata.+pub struct RowGroupMetaDataBuilder {+ columns: Vec<ColumnChunkMetaDataPtr>,+ schema_descr: SchemaDescPtr,+ num_rows: i64,+ total_byte_size: i64,+}++impl RowGroupMetaDataBuilder {+ /// Creates new builder from schema descriptor.+ fn new(schema_descr: SchemaDescPtr) -> Self {+ Self {+ columns: Vec::with_capacity(schema_descr.num_columns()),+ schema_descr,+ num_rows: 0,+ total_byte_size: 0,+ }+ }++ /// Sets number of rows in this row group.+ pub fn set_num_rows(mut self, value: i64) -> Self {+ self.num_rows = value;+ self+ }++ /// Sets total size in bytes for this row group.+ pub fn set_total_byte_size(mut self, value: i64) -> Self {+ self.total_byte_size = value;+ self+ }++ /// Sets column metadata for this row group.+ pub fn set_column_metadata(mut self, value: Vec<ColumnChunkMetaDataPtr>) -> Self {+ self.columns = value;+ self+ }++ /// Builds row group metadata.+ pub fn build(self) -> Result<RowGroupMetaData> {+ if self.schema_descr.num_columns() != self.columns.len() {+ return Err(general_err!(+ "Column length mismatch: {} != {}",+ self.schema_descr.num_columns(),+ self.columns.len()+ ));+ }++ Ok(RowGroupMetaData {+ columns: self.columns,+ num_rows: self.num_rows,+ total_byte_size: self.total_byte_size,+ schema_descr: self.schema_descr,+ })+ }+}++/// Reference counted pointer for [`ColumnChunkMetaData`].+pub type ColumnChunkMetaDataPtr = Rc<ColumnChunkMetaData>;++/// Metadata for a column chunk.+pub struct ColumnChunkMetaData {+ column_type: Type,+ column_path: ColumnPath,+ column_descr: ColumnDescPtr,+ encodings: Vec<Encoding>,+ file_path: Option<String>,+ file_offset: i64,+ num_values: i64,+ compression: Compression,+ total_compressed_size: i64,+ total_uncompressed_size: i64,+ data_page_offset: i64,+ index_page_offset: Option<i64>,+ dictionary_page_offset: Option<i64>,+ statistics: Option<Statistics>,+}++/// Represents common operations for a column chunk.+impl ColumnChunkMetaData {+ /// Returns builder for column chunk metadata.+ pub fn builder(column_descr: ColumnDescPtr) -> ColumnChunkMetaDataBuilder {+ ColumnChunkMetaDataBuilder::new(column_descr)+ }++ /// File where the column chunk is stored.+ ///+ /// If not set, assumed to belong to the same file as the metadata.+ /// This path is relative to the current file.+ pub fn file_path(&self) -> Option<&String> {+ self.file_path.as_ref()+ }++ /// Byte offset in `file_path()`.+ pub fn file_offset(&self) -> i64 {+ self.file_offset+ }++ /// Type of this column. Must be primitive.+ pub fn column_type(&self) -> Type {+ self.column_type+ }++ /// Path (or identifier) of this column.+ pub fn column_path(&self) -> &ColumnPath {+ &self.column_path+ }++ /// Descriptor for this column.+ pub fn column_descr(&self) -> &ColumnDescriptor {+ self.column_descr.as_ref()+ }++ /// Reference counted clone of descriptor for this column.+ pub fn column_descr_ptr(&self) -> ColumnDescPtr {+ self.column_descr.clone()+ }++ /// All encodings used for this column.+ pub fn encodings(&self) -> &Vec<Encoding> {+ &self.encodings+ }++ /// Total number of values in this column chunk.+ pub fn num_values(&self) -> i64 {+ self.num_values+ }++ /// Compression for this column.+ pub fn compression(&self) -> Compression {+ self.compression+ }++ /// Returns the total compressed data size of this column chunk.+ pub fn compressed_size(&self) -> i64 {+ self.total_compressed_size+ }++ /// Returns the total uncompressed data size of this column chunk.+ pub fn uncompressed_size(&self) -> i64 {+ self.total_uncompressed_size+ }++ /// Returns the offset for the column data.+ pub fn data_page_offset(&self) -> i64 {+ self.data_page_offset+ }++ /// Returns `true` if this column chunk contains a index page, `false` otherwise.+ pub fn has_index_page(&self) -> bool {+ self.index_page_offset.is_some()+ }++ /// Returns the offset for the index page.+ pub fn index_page_offset(&self) -> Option<i64> {+ self.index_page_offset+ }++ /// Returns `true` if this column chunk contains a dictionary page, `false` otherwise.+ pub fn has_dictionary_page(&self) -> bool {+ self.dictionary_page_offset.is_some()+ }++ /// Returns the offset for the dictionary page, if any.+ pub fn dictionary_page_offset(&self) -> Option<i64> {+ self.dictionary_page_offset+ }++ /// Returns statistics that are set for this column chunk,+ /// or `None` if no statistics are available.+ pub fn statistics(&self) -> Option<&Statistics> {+ self.statistics.as_ref()+ }++ /// Method to convert from Thrift.+ pub fn from_thrift(column_descr: ColumnDescPtr, cc: ColumnChunk) -> Result<Self> {+ if cc.meta_data.is_none() {+ return Err(general_err!("Expected to have column metadata"));+ }+ let mut col_metadata: ColumnMetaData = cc.meta_data.unwrap();+ let column_type = Type::from(col_metadata.type_);+ let column_path = ColumnPath::new(col_metadata.path_in_schema);+ let encodings = col_metadata+ .encodings+ .drain(0..)+ .map(Encoding::from)+ .collect();+ let compression = Compression::from(col_metadata.codec);+ let file_path = cc.file_path;+ let file_offset = cc.file_offset;+ let num_values = col_metadata.num_values;+ let total_compressed_size = col_metadata.total_compressed_size;+ let total_uncompressed_size = col_metadata.total_uncompressed_size;+ let data_page_offset = col_metadata.data_page_offset;+ let index_page_offset = col_metadata.index_page_offset;+ let dictionary_page_offset = col_metadata.dictionary_page_offset;+ let statistics = statistics::from_thrift(column_type, col_metadata.statistics);+ let result = ColumnChunkMetaData {+ column_type,+ column_path,+ column_descr,+ encodings,+ file_path,+ file_offset,+ num_values,+ compression,+ total_compressed_size,+ total_uncompressed_size,+ data_page_offset,+ index_page_offset,+ dictionary_page_offset,+ statistics,+ };+ Ok(result)+ }++ /// Method to convert to Thrift.+ pub fn to_thrift(&self) -> ColumnChunk {+ let column_metadata = ColumnMetaData {+ type_: self.column_type.into(),+ encodings: self.encodings().into_iter().map(|&v| v.into()).collect(),+ path_in_schema: Vec::from(self.column_path.as_ref()),+ codec: self.compression.into(),+ num_values: self.num_values,+ total_uncompressed_size: self.total_uncompressed_size,+ total_compressed_size: self.total_compressed_size,+ key_value_metadata: None,+ data_page_offset: self.data_page_offset,+ index_page_offset: self.index_page_offset,+ dictionary_page_offset: self.dictionary_page_offset,+ statistics: statistics::to_thrift(self.statistics.as_ref()),+ encoding_stats: None,+ };++ ColumnChunk {+ file_path: self.file_path().map(|v| v.clone()),+ file_offset: self.file_offset,+ meta_data: Some(column_metadata),+ offset_index_offset: None,+ offset_index_length: None,+ column_index_offset: None,+ column_index_length: None,+ }+ }+}++/// Builder for column chunk metadata.+pub struct ColumnChunkMetaDataBuilder {+ column_descr: ColumnDescPtr,+ encodings: Vec<Encoding>,+ file_path: Option<String>,+ file_offset: i64,+ num_values: i64,+ compression: Compression,+ total_compressed_size: i64,+ total_uncompressed_size: i64,+ data_page_offset: i64,+ index_page_offset: Option<i64>,+ dictionary_page_offset: Option<i64>,+ statistics: Option<Statistics>,+}++impl ColumnChunkMetaDataBuilder {+ /// Creates new column chunk metadata builder.+ fn new(column_descr: ColumnDescPtr) -> Self {+ Self {+ column_descr,+ encodings: Vec::new(),+ file_path: None,+ file_offset: 0,+ num_values: 0,+ compression: Compression::UNCOMPRESSED,+ total_compressed_size: 0,+ total_uncompressed_size: 0,+ data_page_offset: 0,+ index_page_offset: None,+ dictionary_page_offset: None,+ statistics: None,+ }+ }++ /// Sets list of encodings for this column chunk.+ pub fn set_encodings(mut self, encodings: Vec<Encoding>) -> Self {+ self.encodings = encodings;+ self+ }++ /// Sets optional file path for this column chunk.+ pub fn set_file_path(mut self, value: String) -> Self {+ self.file_path = Some(value);+ self+ }++ /// Sets file offset in bytes.+ pub fn set_file_offset(mut self, value: i64) -> Self {+ self.file_offset = value;+ self+ }++ /// Sets number of values.+ pub fn set_num_values(mut self, value: i64) -> Self {+ self.num_values = value;+ self+ }++ /// Sets compression.+ pub fn set_compression(mut self, value: Compression) -> Self {+ self.compression = value;+ self+ }++ /// Sets total compressed size in bytes.+ pub fn set_total_compressed_size(mut self, value: i64) -> Self {+ self.total_compressed_size = value;+ self+ }++ /// Sets total uncompressed size in bytes.+ pub fn set_total_uncompressed_size(mut self, value: i64) -> Self {+ self.total_uncompressed_size = value;+ self+ }++ /// Sets data page offset in bytes.+ pub fn set_data_page_offset(mut self, value: i64) -> Self {+ self.data_page_offset = value;+ self+ }++ /// Sets optional dictionary page ofset in bytes.+ pub fn set_dictionary_page_offset(mut self, value: Option<i64>) -> Self {+ self.dictionary_page_offset = value;+ self+ }++ /// Sets optional index page offset in bytes.+ pub fn set_index_page_offset(mut self, value: Option<i64>) -> Self {+ self.index_page_offset = value;+ self+ }++ /// Sets statistics for this column chunk.+ pub fn set_statistics(mut self, value: Statistics) -> Self {+ self.statistics = Some(value);+ self+ }++ /// Builds column chunk metadata.+ pub fn build(self) -> Result<ColumnChunkMetaData> {+ Ok(ColumnChunkMetaData {+ column_type: self.column_descr.physical_type(),+ column_path: self.column_descr.path().clone(),+ column_descr: self.column_descr,+ encodings: self.encodings,+ file_path: self.file_path,+ file_offset: self.file_offset,+ num_values: self.num_values,+ compression: self.compression,+ total_compressed_size: self.total_compressed_size,+ total_uncompressed_size: self.total_uncompressed_size,+ data_page_offset: self.data_page_offset,+ index_page_offset: self.index_page_offset,+ dictionary_page_offset: self.dictionary_page_offset,+ statistics: self.statistics,+ })+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_row_group_metadata_thrift_conversion() {+ let schema_descr = get_test_schema_descr();++ let mut columns = vec![];+ for ptr in schema_descr.columns() {+ let column = ColumnChunkMetaData::builder(ptr.clone()).build().unwrap();+ columns.push(Rc::new(column));+ }+ let row_group_meta = RowGroupMetaData::builder(schema_descr.clone())+ .set_num_rows(1000)+ .set_total_byte_size(2000)+ .set_column_metadata(columns)+ .build()+ .unwrap();++ let row_group_exp = row_group_meta.to_thrift();+ let row_group_res =+ RowGroupMetaData::from_thrift(schema_descr.clone(), row_group_exp.clone())+ .unwrap()+ .to_thrift();++ assert_eq!(row_group_res, row_group_exp);+ }++ #[test]+ fn test_row_group_metadata_thrift_conversion_empty() {+ let schema_descr = get_test_schema_descr();++ let row_group_meta = RowGroupMetaData::builder(schema_descr.clone()).build();++ assert!(row_group_meta.is_err());+ if let Err(e) = row_group_meta {+ assert_eq!(+ e.to_string(),+ "Parquet error: Column length mismatch: 2 != 0"+ );+ }+ }++ #[test]+ fn test_column_chunk_metadata_thrift_conversion() {+ let column_descr = get_test_schema_descr().column(0);++ let col_metadata = ColumnChunkMetaData::builder(column_descr.clone())+ .set_encodings(vec![Encoding::PLAIN, Encoding::RLE])+ .set_file_path("file_path".to_owned())+ .set_file_offset(100)+ .set_num_values(1000)+ .set_compression(Compression::SNAPPY)+ .set_total_compressed_size(2000)+ .set_total_uncompressed_size(3000)+ .set_data_page_offset(4000)+ .set_dictionary_page_offset(Some(5000))+ .build()+ .unwrap();++ let col_chunk_exp = col_metadata.to_thrift();++ let col_chunk_res =+ ColumnChunkMetaData::from_thrift(column_descr.clone(), col_chunk_exp.clone())+ .unwrap()+ .to_thrift();++ assert_eq!(col_chunk_res, col_chunk_exp);+ }++ #[test]+ fn test_column_chunk_metadata_thrift_conversion_empty() {+ let column_descr = get_test_schema_descr().column(0);++ let col_metadata = ColumnChunkMetaData::builder(column_descr.clone())+ .build()+ .unwrap();++ let col_chunk_exp = col_metadata.to_thrift();+ let col_chunk_res =+ ColumnChunkMetaData::from_thrift(column_descr.clone(), col_chunk_exp.clone())+ .unwrap()+ .to_thrift();++ assert_eq!(col_chunk_res, col_chunk_exp);+ }++ /// Returns sample schema descriptor so we can create column metadata.+ fn get_test_schema_descr() -> SchemaDescPtr {+ let schema = SchemaType::group_type_builder("schema")+ .with_fields(&mut vec![+ Rc::new(+ SchemaType::primitive_type_builder("a", Type::INT32)+ .build()+ .unwrap(),+ ),+ Rc::new(+ SchemaType::primitive_type_builder("b", Type::INT32)+ .build()+ .unwrap(),+ ),+ ])+ .build()+ .unwrap();++ Rc::new(SchemaDescriptor::new(Rc::new(schema)))+ }+}diff --git a/rust/src/parquet/file/mod.rs b/rust/src/parquet/file/mod.rsnew file mode 100644index 0000000000..ebaebbad0b--- /dev/null+++ b/rust/src/parquet/file/mod.rs@@ -0,0 +1,88 @@+// 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.++//! Main entrypoint for working with Parquet API.+//!+//! Provides access to file and row group readers and writers, record API, metadata, etc.+//!+//! See [`reader::SerializedFileReader`](reader/struct.SerializedFileReader.html) or+//! [`writer::SerializedFileWriter`](writer/struct.SerializedFileWriter.html) for a+//! starting reference, [`metadata::ParquetMetaData`](metadata/index.html) for file+//! metadata, and [`statistics`](statistics/index.html) for working with statistics.+//!+//! # Example of writing a new file+//!+//! ```rust+//! use std::{fs, path::Path, rc::Rc};+//!+//! use arrow::parquet::{+//! file::{+//! properties::WriterProperties,+//! writer::{FileWriter, SerializedFileWriter},+//! },+//! schema::parser::parse_message_type,+//! };+//!+//! let path = Path::new("target/debug/examples/sample.parquet");+//!+//! let message_type = "+//! message schema {+//! REQUIRED INT32 b;+//! }+//! ";+//! let schema = Rc::new(parse_message_type(message_type).unwrap());+//! let props = Rc::new(WriterProperties::builder().build());+//! let file = fs::File::create(&path).unwrap();+//! let mut writer = SerializedFileWriter::new(file, schema, props).unwrap();+//! let mut row_group_writer = writer.next_row_group().unwrap();+//! while let Some(mut col_writer) = row_group_writer.next_column().unwrap() {+//! // ... write values to a column writer+//! row_group_writer.close_column(col_writer).unwrap();+//! }+//! writer.close_row_group(row_group_writer).unwrap();+//! writer.close().unwrap();+//!+//! let bytes = fs::read(&path).unwrap();+//! assert_eq!(&bytes[0..4], &[b'P', b'A', b'R', b'1']);+//! ```+//! # Example of reading an existing file+//!+//! ```rust+//! use arrow::parquet::file::reader::{FileReader, SerializedFileReader};+//! use std::{fs::File, path::Path};+//!+//! let path = Path::new("target/debug/examples/sample.parquet");+//! if let Ok(file) = File::open(&path) {+//! let file = File::open(&path).unwrap();+//! let reader = SerializedFileReader::new(file).unwrap();+//!+//! let parquet_metadata = reader.metadata();+//! assert_eq!(parquet_metadata.num_row_groups(), 1);+//!+//! let row_group_reader = reader.get_row_group(0).unwrap();+//! assert_eq!(row_group_reader.num_columns(), 1);+//! }+//! ```++pub mod metadata;+pub mod properties;+pub mod reader;+pub mod statistics;+pub mod writer;++const FOOTER_SIZE: usize = 8;+const PARQUET_MAGIC: [u8; 4] = [b'P', b'A', b'R', b'1'];diff --git a/rust/src/parquet/file/properties.rs b/rust/src/parquet/file/properties.rsnew file mode 100644index 0000000000..911ec55733--- /dev/null+++ b/rust/src/parquet/file/properties.rs@@ -0,0 +1,648 @@+// 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.++//! Writer properties.+//!+//! # Usage+//!+//! ```rust+//! use arrow::parquet::{+//! basic::{Compression, Encoding},+//! file::properties::*,+//! schema::types::ColumnPath,+//! };+//!+//! // Create properties with default configuration.+//! let props = WriterProperties::builder().build();+//!+//! // Use properties builder to set certain options and assemble the configuration.+//! let props = WriterProperties::builder()+//! .set_writer_version(WriterVersion::PARQUET_1_0)+//! .set_encoding(Encoding::PLAIN)+//! .set_column_encoding(ColumnPath::from("col1"), Encoding::DELTA_BINARY_PACKED)+//! .set_compression(Compression::SNAPPY)+//! .build();+//!+//! assert_eq!(props.writer_version(), WriterVersion::PARQUET_1_0);+//! assert_eq!(+//! props.encoding(&ColumnPath::from("col1")),+//! Some(Encoding::DELTA_BINARY_PACKED)+//! );+//! assert_eq!(+//! props.encoding(&ColumnPath::from("col2")),+//! Some(Encoding::PLAIN)+//! );+//! ```++use std::{collections::HashMap, rc::Rc};++use crate::parquet::basic::{Compression, Encoding};+use crate::parquet::schema::types::ColumnPath;++const DEFAULT_PAGE_SIZE: usize = 1024 * 1024;+const DEFAULT_WRITE_BATCH_SIZE: usize = 1024;+const DEFAULT_WRITER_VERSION: WriterVersion = WriterVersion::PARQUET_1_0;+const DEFAULT_COMPRESSION: Compression = Compression::UNCOMPRESSED;+const DEFAULT_DICTIONARY_ENABLED: bool = true;+const DEFAULT_DICTIONARY_PAGE_SIZE_LIMIT: usize = DEFAULT_PAGE_SIZE;+const DEFAULT_STATISTICS_ENABLED: bool = true;+const DEFAULT_MAX_STATISTICS_SIZE: usize = 4096;+const DEFAULT_MAX_ROW_GROUP_SIZE: usize = 128 * 1024 * 1024;+const DEFAULT_CREATED_BY: &str = env!("PARQUET_CREATED_BY");++/// Parquet writer version.+///+/// Basic constant, which is not part of the Thrift definition.+#[derive(Debug, Clone, Copy, PartialEq)]+pub enum WriterVersion {+ PARQUET_1_0,+ PARQUET_2_0,+}++impl WriterVersion {+ /// Returns writer version as `i32`.+ pub fn as_num(&self) -> i32 {+ match self {+ WriterVersion::PARQUET_1_0 => 1,+ WriterVersion::PARQUET_2_0 => 2,+ }+ }+}++/// Reference counted writer properties.+pub type WriterPropertiesPtr = Rc<WriterProperties>;++/// Writer properties.+///+/// It is created as an immutable data structure, use [`WriterPropertiesBuilder`] to+/// assemble the properties.+#[derive(Debug, Clone)]+pub struct WriterProperties {+ data_pagesize_limit: usize,+ dictionary_pagesize_limit: usize,+ write_batch_size: usize,+ max_row_group_size: usize,+ writer_version: WriterVersion,+ created_by: String,+ default_column_properties: ColumnProperties,+ column_properties: HashMap<ColumnPath, ColumnProperties>,+}++impl WriterProperties {+ /// Returns builder for writer properties with default values.+ pub fn builder() -> WriterPropertiesBuilder {+ WriterPropertiesBuilder::with_defaults()+ }++ /// Returns data page size limit.+ pub fn data_pagesize_limit(&self) -> usize {+ self.data_pagesize_limit+ }++ /// Returns dictionary page size limit.+ pub fn dictionary_pagesize_limit(&self) -> usize {+ self.dictionary_pagesize_limit+ }++ /// Returns configured batch size for writes.+ ///+ /// When writing a batch of data, this setting allows to split it internally into+ /// smaller batches so we can better estimate the size of a page currently being+ /// written.+ pub fn write_batch_size(&self) -> usize {+ self.write_batch_size+ }++ /// Returns max size for a row group.+ pub fn max_row_group_size(&self) -> usize {+ self.max_row_group_size+ }++ /// Returns configured writer version.+ pub fn writer_version(&self) -> WriterVersion {+ self.writer_version+ }++ /// Returns `created_by` string.+ pub fn created_by(&self) -> &str {+ &self.created_by+ }++ /// Returns encoding for a data page, when dictionary encoding is enabled.+ /// This is not configurable.+ #[inline]+ pub fn dictionary_data_page_encoding(&self) -> Encoding {+ // PLAIN_DICTIONARY encoding is deprecated in writer version 1.+ // Dictionary values are encoded using RLE_DICTIONARY encoding.+ Encoding::RLE_DICTIONARY+ }++ /// Returns encoding for dictionary page, when dictionary encoding is enabled.+ /// This is not configurable.+ #[inline]+ pub fn dictionary_page_encoding(&self) -> Encoding {+ // PLAIN_DICTIONARY is deprecated in writer version 1.+ // Dictionary is encoded using plain encoding.+ Encoding::PLAIN+ }++ /// Returns encoding for a column, if set.+ /// In case when dictionary is enabled, returns fallback encoding.+ ///+ /// If encoding is not set, then column writer will choose the best encoding+ /// based on the column type.+ pub fn encoding(&self, col: &ColumnPath) -> Option<Encoding> {+ self.column_properties+ .get(col)+ .and_then(|c| c.encoding())+ .or_else(|| self.default_column_properties.encoding())+ }++ /// Returns compression codec for a column.+ pub fn compression(&self, col: &ColumnPath) -> Compression {+ self.column_properties+ .get(col)+ .and_then(|c| c.compression())+ .or_else(|| self.default_column_properties.compression())+ .unwrap_or(DEFAULT_COMPRESSION)+ }++ /// Returns `true` if dictionary encoding is enabled for a column.+ pub fn dictionary_enabled(&self, col: &ColumnPath) -> bool {+ self.column_properties+ .get(col)+ .and_then(|c| c.dictionary_enabled())+ .or_else(|| self.default_column_properties.dictionary_enabled())+ .unwrap_or(DEFAULT_DICTIONARY_ENABLED)+ }++ /// Returns `true` if statistics are enabled for a column.+ pub fn statistics_enabled(&self, col: &ColumnPath) -> bool {+ self.column_properties+ .get(col)+ .and_then(|c| c.statistics_enabled())+ .or_else(|| self.default_column_properties.statistics_enabled())+ .unwrap_or(DEFAULT_STATISTICS_ENABLED)+ }++ /// Returns max size for statistics.+ /// Only applicable if statistics are enabled.+ pub fn max_statistics_size(&self, col: &ColumnPath) -> usize {+ self.column_properties+ .get(col)+ .and_then(|c| c.max_statistics_size())+ .or_else(|| self.default_column_properties.max_statistics_size())+ .unwrap_or(DEFAULT_MAX_STATISTICS_SIZE)+ }+}++/// Writer properties builder.+pub struct WriterPropertiesBuilder {+ data_pagesize_limit: usize,+ dictionary_pagesize_limit: usize,+ write_batch_size: usize,+ max_row_group_size: usize,+ writer_version: WriterVersion,+ created_by: String,+ default_column_properties: ColumnProperties,+ column_properties: HashMap<ColumnPath, ColumnProperties>,+}++impl WriterPropertiesBuilder {+ /// Returns default state of the builder.+ fn with_defaults() -> Self {+ Self {+ data_pagesize_limit: DEFAULT_PAGE_SIZE,+ dictionary_pagesize_limit: DEFAULT_DICTIONARY_PAGE_SIZE_LIMIT,+ write_batch_size: DEFAULT_WRITE_BATCH_SIZE,+ max_row_group_size: DEFAULT_MAX_ROW_GROUP_SIZE,+ writer_version: DEFAULT_WRITER_VERSION,+ created_by: DEFAULT_CREATED_BY.to_string(),+ default_column_properties: ColumnProperties::new(),+ column_properties: HashMap::new(),+ }+ }++ /// Finalizes the configuration and returns immutable writer properties struct.+ pub fn build(self) -> WriterProperties {+ WriterProperties {+ data_pagesize_limit: self.data_pagesize_limit,+ dictionary_pagesize_limit: self.dictionary_pagesize_limit,+ write_batch_size: self.write_batch_size,+ max_row_group_size: self.max_row_group_size,+ writer_version: self.writer_version,+ created_by: self.created_by,+ default_column_properties: self.default_column_properties,+ column_properties: self.column_properties,+ }+ }++ // ----------------------------------------------------------------------+ // Writer properies related to a file++ /// Sets writer version.+ pub fn set_writer_version(mut self, value: WriterVersion) -> Self {+ self.writer_version = value;+ self+ }++ /// Sets data page size limit.+ pub fn set_data_pagesize_limit(mut self, value: usize) -> Self {+ self.data_pagesize_limit = value;+ self+ }++ /// Sets dictionary page size limit.+ pub fn set_dictionary_pagesize_limit(mut self, value: usize) -> Self {+ self.dictionary_pagesize_limit = value;+ self+ }++ /// Sets write batch size.+ pub fn set_write_batch_size(mut self, value: usize) -> Self {+ self.write_batch_size = value;+ self+ }++ /// Sets max size for a row group.+ pub fn set_max_row_group_size(mut self, value: usize) -> Self {+ self.max_row_group_size = value;+ self+ }++ /// Sets "created by" property.+ pub fn set_created_by(mut self, value: String) -> Self {+ self.created_by = value;+ self+ }++ // ----------------------------------------------------------------------+ // Setters for any column (global)++ /// Sets encoding for any column.+ ///+ /// If dictionary is not enabled, this is treated as a primary encoding for all columns.+ /// In case when dictionary is enabled for any column, this value is considered to+ /// be a fallback encoding for that column.+ ///+ /// Panics if user tries to set dictionary encoding here, regardless of dictinoary+ /// encoding flag being set.+ pub fn set_encoding(mut self, value: Encoding) -> Self {+ self.default_column_properties.set_encoding(value);+ self+ }++ /// Sets compression codec for any column.+ pub fn set_compression(mut self, value: Compression) -> Self {+ self.default_column_properties.set_compression(value);+ self+ }++ /// Sets flag to enable/disable dictionary encoding for any column.+ ///+ /// Use this method to set dictionary encoding, instead of explicitly specifying+ /// encoding in `set_encoding` method.+ pub fn set_dictionary_enabled(mut self, value: bool) -> Self {+ self.default_column_properties.set_dictionary_enabled(value);+ self+ }++ /// Sets flag to enable/disable statistics for any column.+ pub fn set_statistics_enabled(mut self, value: bool) -> Self {+ self.default_column_properties.set_statistics_enabled(value);+ self+ }++ /// Sets max statistics size for any column.+ /// Applicable only if statistics are enabled.+ pub fn set_max_statistics_size(mut self, value: usize) -> Self {+ self.default_column_properties+ .set_max_statistics_size(value);+ self+ }++ // ----------------------------------------------------------------------+ // Setters for a specific column++ /// Helper method to get existing or new mutable reference of column properties.+ #[inline]+ fn get_mut_props(&mut self, col: ColumnPath) -> &mut ColumnProperties {+ self.column_properties+ .entry(col)+ .or_insert(ColumnProperties::new())+ }++ /// Sets encoding for a column.+ /// Takes precedence over globally defined settings.+ ///+ /// If dictionary is not enabled, this is treated as a primary encoding for this column.+ /// In case when dictionary is enabled for this column, either through global defaults+ /// or explicitly, this value is considered to be a fallback encoding for this column.+ ///+ /// Panics if user tries to set dictionary encoding here, regardless of dictinoary+ /// encoding flag being set.+ pub fn set_column_encoding(mut self, col: ColumnPath, value: Encoding) -> Self {+ self.get_mut_props(col).set_encoding(value);+ self+ }++ /// Sets compression codec for a column.+ /// Takes precedence over globally defined settings.+ pub fn set_column_compression(mut self, col: ColumnPath, value: Compression) -> Self {+ self.get_mut_props(col).set_compression(value);+ self+ }++ /// Sets flag to enable/disable dictionary encoding for a column.+ /// Takes precedence over globally defined settings.+ pub fn set_column_dictionary_enabled(mut self, col: ColumnPath, value: bool) -> Self {+ self.get_mut_props(col).set_dictionary_enabled(value);+ self+ }++ /// Sets flag to enable/disable statistics for a column.+ /// Takes precedence over globally defined settings.+ pub fn set_column_statistics_enabled(mut self, col: ColumnPath, value: bool) -> Self {+ self.get_mut_props(col).set_statistics_enabled(value);+ self+ }++ /// Sets max size for statistics for a column.+ /// Takes precedence over globally defined settings.+ pub fn set_column_max_statistics_size(mut self, col: ColumnPath, value: usize) -> Self {+ self.get_mut_props(col).set_max_statistics_size(value);+ self+ }+}++/// Container for column properties that can be changed as part of writer.+///+/// If a field is `None`, it means that no specific value has been set for this column,+/// so some subsequent or default value must be used.+#[derive(Debug, Clone, PartialEq)]+struct ColumnProperties {+ encoding: Option<Encoding>,+ codec: Option<Compression>,+ dictionary_enabled: Option<bool>,+ statistics_enabled: Option<bool>,+ max_statistics_size: Option<usize>,+}++impl ColumnProperties {+ /// Initialise column properties with default values.+ fn new() -> Self {+ Self {+ encoding: None,+ codec: None,+ dictionary_enabled: None,+ statistics_enabled: None,+ max_statistics_size: None,+ }+ }++ /// Sets encoding for this column.+ ///+ /// If dictionary is not enabled, this is treated as a primary encoding for a column.+ /// In case when dictionary is enabled for a column, this value is considered to+ /// be a fallback encoding.+ ///+ /// Panics if user tries to set dictionary encoding here, regardless of dictinoary+ /// encoding flag being set. Use `set_dictionary_enabled` method to enable dictionary+ /// for a column.+ fn set_encoding(&mut self, value: Encoding) {+ if value == Encoding::PLAIN_DICTIONARY || value == Encoding::RLE_DICTIONARY {+ panic!("Dictionary encoding can not be used as fallback encoding");+ }+ self.encoding = Some(value);+ }++ /// Sets compression codec for this column.+ fn set_compression(&mut self, value: Compression) {+ self.codec = Some(value);+ }++ /// Sets whether or not dictionary encoding is enabled for this column.+ fn set_dictionary_enabled(&mut self, enabled: bool) {+ self.dictionary_enabled = Some(enabled);+ }++ /// Sets whether or not statistics are enabled for this column.+ fn set_statistics_enabled(&mut self, enabled: bool) {+ self.statistics_enabled = Some(enabled);+ }++ /// Sets max size for statistics for this column.+ fn set_max_statistics_size(&mut self, value: usize) {+ self.max_statistics_size = Some(value);+ }++ /// Returns optional encoding for this column.+ fn encoding(&self) -> Option<Encoding> {+ self.encoding+ }++ /// Returns optional compression codec for this column.+ fn compression(&self) -> Option<Compression> {+ self.codec+ }++ /// Returns `Some(true)` if dictionary encoding is enabled for this column, if disabled+ /// then returns `Some(false)`. If result is `None`, then no setting has been provided.+ fn dictionary_enabled(&self) -> Option<bool> {+ self.dictionary_enabled+ }++ /// Returns `Some(true)` if statistics are enabled for this column, if disabled then+ /// returns `Some(false)`. If result is `None`, then no setting has been provided.+ fn statistics_enabled(&self) -> Option<bool> {+ self.statistics_enabled+ }++ /// Returns optional max size in bytes for statistics.+ fn max_statistics_size(&self) -> Option<usize> {+ self.max_statistics_size+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_writer_version() {+ assert_eq!(WriterVersion::PARQUET_1_0.as_num(), 1);+ assert_eq!(WriterVersion::PARQUET_2_0.as_num(), 2);+ }++ #[test]+ fn test_writer_properties_default_settings() {+ let props = WriterProperties::builder().build();+ assert_eq!(props.data_pagesize_limit(), DEFAULT_PAGE_SIZE);+ assert_eq!(+ props.dictionary_pagesize_limit(),+ DEFAULT_DICTIONARY_PAGE_SIZE_LIMIT+ );+ assert_eq!(props.write_batch_size(), DEFAULT_WRITE_BATCH_SIZE);+ assert_eq!(props.max_row_group_size(), DEFAULT_MAX_ROW_GROUP_SIZE);+ assert_eq!(props.writer_version(), DEFAULT_WRITER_VERSION);+ assert_eq!(props.created_by(), DEFAULT_CREATED_BY);+ assert_eq!(props.encoding(&ColumnPath::from("col")), None);+ assert_eq!(+ props.compression(&ColumnPath::from("col")),+ DEFAULT_COMPRESSION+ );+ assert_eq!(+ props.dictionary_enabled(&ColumnPath::from("col")),+ DEFAULT_DICTIONARY_ENABLED+ );+ assert_eq!(+ props.statistics_enabled(&ColumnPath::from("col")),+ DEFAULT_STATISTICS_ENABLED+ );+ assert_eq!(+ props.max_statistics_size(&ColumnPath::from("col")),+ DEFAULT_MAX_STATISTICS_SIZE+ );+ }++ #[test]+ fn test_writer_properties_dictionary_encoding() {+ // dictionary encoding is not configurable, and it should be the same for both+ // writer version 1 and 2.+ for version in vec![WriterVersion::PARQUET_1_0, WriterVersion::PARQUET_2_0] {+ let props = WriterProperties::builder()+ .set_writer_version(version)+ .build();+ assert_eq!(props.dictionary_page_encoding(), Encoding::PLAIN);+ assert_eq!(+ props.dictionary_data_page_encoding(),+ Encoding::RLE_DICTIONARY+ );+ }+ }++ #[test]+ #[should_panic(expected = "Dictionary encoding can not be used as fallback encoding")]+ fn test_writer_properties_panic_when_plain_dictionary_is_fallback() {+ // Should panic when user specifies dictionary encoding as fallback encoding.+ WriterProperties::builder()+ .set_encoding(Encoding::PLAIN_DICTIONARY)+ .build();+ }++ #[test]+ #[should_panic(expected = "Dictionary encoding can not be used as fallback encoding")]+ fn test_writer_properties_panic_when_rle_dictionary_is_fallback() {+ // Should panic when user specifies dictionary encoding as fallback encoding.+ WriterProperties::builder()+ .set_encoding(Encoding::RLE_DICTIONARY)+ .build();+ }++ #[test]+ #[should_panic(expected = "Dictionary encoding can not be used as fallback encoding")]+ fn test_writer_properties_panic_when_dictionary_is_enabled() {+ WriterProperties::builder()+ .set_dictionary_enabled(true)+ .set_column_encoding(ColumnPath::from("col"), Encoding::RLE_DICTIONARY)+ .build();+ }++ #[test]+ #[should_panic(expected = "Dictionary encoding can not be used as fallback encoding")]+ fn test_writer_properties_panic_when_dictionary_is_disabled() {+ WriterProperties::builder()+ .set_dictionary_enabled(false)+ .set_column_encoding(ColumnPath::from("col"), Encoding::RLE_DICTIONARY)+ .build();+ }++ #[test]+ fn test_writer_properties_builder() {+ let props = WriterProperties::builder()+ // file settings+ .set_writer_version(WriterVersion::PARQUET_2_0)+ .set_data_pagesize_limit(10)+ .set_dictionary_pagesize_limit(20)+ .set_write_batch_size(30)+ .set_max_row_group_size(40)+ .set_created_by("default".to_owned())+ // global column settings+ .set_encoding(Encoding::DELTA_BINARY_PACKED)+ .set_compression(Compression::GZIP)+ .set_dictionary_enabled(false)+ .set_statistics_enabled(false)+ .set_max_statistics_size(50)+ // specific column settings+ .set_column_encoding(ColumnPath::from("col"), Encoding::RLE)+ .set_column_compression(ColumnPath::from("col"), Compression::SNAPPY)+ .set_column_dictionary_enabled(ColumnPath::from("col"), true)+ .set_column_statistics_enabled(ColumnPath::from("col"), true)+ .set_column_max_statistics_size(ColumnPath::from("col"), 123)+ .build();++ assert_eq!(props.writer_version(), WriterVersion::PARQUET_2_0);+ assert_eq!(props.data_pagesize_limit(), 10);+ assert_eq!(props.dictionary_pagesize_limit(), 20);+ assert_eq!(props.write_batch_size(), 30);+ assert_eq!(props.max_row_group_size(), 40);+ assert_eq!(props.created_by(), "default");++ assert_eq!(+ props.encoding(&ColumnPath::from("a")),+ Some(Encoding::DELTA_BINARY_PACKED)+ );+ assert_eq!(props.compression(&ColumnPath::from("a")), Compression::GZIP);+ assert_eq!(props.dictionary_enabled(&ColumnPath::from("a")), false);+ assert_eq!(props.statistics_enabled(&ColumnPath::from("a")), false);+ assert_eq!(props.max_statistics_size(&ColumnPath::from("a")), 50);++ assert_eq!(+ props.encoding(&ColumnPath::from("col")),+ Some(Encoding::RLE)+ );+ assert_eq!(+ props.compression(&ColumnPath::from("col")),+ Compression::SNAPPY+ );+ assert_eq!(props.dictionary_enabled(&ColumnPath::from("col")), true);+ assert_eq!(props.statistics_enabled(&ColumnPath::from("col")), true);+ assert_eq!(props.max_statistics_size(&ColumnPath::from("col")), 123);+ }++ #[test]+ fn test_writer_properties_builder_partial_defaults() {+ let props = WriterProperties::builder()+ .set_encoding(Encoding::DELTA_BINARY_PACKED)+ .set_compression(Compression::GZIP)+ .set_column_encoding(ColumnPath::from("col"), Encoding::RLE)+ .build();++ assert_eq!(+ props.encoding(&ColumnPath::from("col")),+ Some(Encoding::RLE)+ );+ assert_eq!(+ props.compression(&ColumnPath::from("col")),+ Compression::GZIP+ );+ assert_eq!(+ props.dictionary_enabled(&ColumnPath::from("col")),+ DEFAULT_DICTIONARY_ENABLED+ );+ }+}diff --git a/rust/src/parquet/file/reader.rs b/rust/src/parquet/file/reader.rsnew file mode 100644index 0000000000..c2e5dd176d--- /dev/null+++ b/rust/src/parquet/file/reader.rs@@ -0,0 +1,899 @@+// 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.++//! Contains file reader API and provides methods to access file metadata, row group+//! readers to read individual column chunks, or access record iterator.++use std::{+ convert::TryFrom,+ fs::File,+ io::{BufReader, Cursor, Read, Seek, SeekFrom},+ path::Path,+ rc::Rc,+};++use byteorder::{ByteOrder, LittleEndian};+use parquet_format::{+ ColumnOrder as TColumnOrder, FileMetaData as TFileMetaData, PageHeader, PageType,+};+use thrift::protocol::TCompactInputProtocol;++use crate::parquet::basic::{ColumnOrder, Compression, Encoding, Type};+use crate::parquet::column::{+ page::{Page, PageReader},+ reader::{ColumnReader, ColumnReaderImpl},+};+use crate::parquet::compression::{create_codec, Codec};+use crate::parquet::errors::{ParquetError, Result};+use crate::parquet::file::{metadata::*, statistics, FOOTER_SIZE, PARQUET_MAGIC};+use crate::parquet::record::reader::RowIter;+use crate::parquet::schema::types::{self, SchemaDescriptor, Type as SchemaType};+use crate::parquet::util::{io::FileSource, memory::ByteBufferPtr};++// ----------------------------------------------------------------------+// APIs for file & row group readers++/// Parquet file reader API. With this, user can get metadata information about the+/// Parquet file, can get reader for each row group, and access record iterator.+pub trait FileReader {+ /// Get metadata information about this file.+ fn metadata(&self) -> ParquetMetaDataPtr;++ /// Get the total number of row groups for this file.+ fn num_row_groups(&self) -> usize;++ /// Get the `i`th row group reader. Note this doesn't do bound check.+ fn get_row_group(&self, i: usize) -> Result<Box<RowGroupReader>>;++ /// Get full iterator of `Row`s from a file (over all row groups).+ ///+ /// Iterator will automatically load the next row group to advance.+ ///+ /// Projected schema can be a subset of or equal to the file schema, when it is None,+ /// full file schema is assumed.+ fn get_row_iter(&self, projection: Option<SchemaType>) -> Result<RowIter>;+}++/// Parquet row group reader API. With this, user can get metadata information about the+/// row group, as well as readers for each individual column chunk.+pub trait RowGroupReader {+ /// Get metadata information about this row group.+ fn metadata(&self) -> RowGroupMetaDataPtr;++ /// Get the total number of column chunks in this row group.+ fn num_columns(&self) -> usize;++ /// Get page reader for the `i`th column chunk.+ fn get_column_page_reader(&self, i: usize) -> Result<Box<PageReader>>;++ /// Get value reader for the `i`th column chunk.+ fn get_column_reader(&self, i: usize) -> Result<ColumnReader>;++ /// Get iterator of `Row`s from this row group.+ ///+ /// Projected schema can be a subset of or equal to the file schema, when it is None,+ /// full file schema is assumed.+ fn get_row_iter(&self, projection: Option<SchemaType>) -> Result<RowIter>;+}++// ----------------------------------------------------------------------+// Serialized impl for file & row group readers++/// Length should return the amount of bytes that implementor contains.+/// It's mainly used to read the metadata, which is at the end of the source.+pub trait Length {+ /// Returns the amount of bytes of the inner source.+ fn len(&self) -> u64;+}++/// TryClone tries to clone the type and should maintain the `Seek` position of the given+/// instance.+pub trait TryClone: Sized {+ /// Clones the type returning a new instance or an error if it's not possible+ /// to clone it.+ fn try_clone(&self) -> Result<Self>;+}++impl Length for File {+ fn len(&self) -> u64 {+ self.metadata().map(|m| m.len()).unwrap_or(0u64)+ }+}++impl TryClone for File {+ fn try_clone(&self) -> Result<Self> {+ self.try_clone().map_err(|e| e.into())+ }+}++impl<'a> Length for Cursor<&'a [u8]> {+ fn len(&self) -> u64 {+ self.get_ref().len() as u64+ }+}++impl<'a> TryClone for Cursor<&'a [u8]> {+ fn try_clone(&self) -> Result<Self> {+ Ok(self.clone())+ }+}++/// ParquetReader is the interface which needs to be fulfilled to be able to parse a+/// parquet source.+pub trait ParquetReader: Read + Seek + Length + TryClone {}+impl<T: Read + Seek + Length + TryClone> ParquetReader for T {}++/// A serialized implementation for Parquet [`FileReader`].+pub struct SerializedFileReader<R: ParquetReader> {+ buf: BufReader<R>,+ metadata: ParquetMetaDataPtr,+}++impl<R: ParquetReader> SerializedFileReader<R> {+ /// Creates file reader from a Parquet file.+ /// Returns error if Parquet file does not exist or is corrupt.+ pub fn new(reader: R) -> Result<Self> {+ let mut buf = BufReader::new(reader);+ let metadata = Self::parse_metadata(&mut buf)?;+ Ok(Self {+ buf,+ metadata: Rc::new(metadata),+ })+ }++ // Layout of Parquet file+ // +---------------------------+---+-----++ // | Rest of file | B | A |+ // +---------------------------+---+-----++ // where A: parquet footer, B: parquet metadata.+ //+ fn parse_metadata(buf: &mut BufReader<R>) -> Result<ParquetMetaData> {+ let file_size = buf.get_ref().len();+ if file_size < (FOOTER_SIZE as u64) {+ return Err(general_err!(+ "Invalid Parquet file. Size is smaller than footer"+ ));+ }+ let mut footer_buffer: [u8; FOOTER_SIZE] = [0; FOOTER_SIZE];+ buf.seek(SeekFrom::End(-(FOOTER_SIZE as i64)))?;+ buf.read_exact(&mut footer_buffer)?;+ if footer_buffer[4..] != PARQUET_MAGIC {+ return Err(general_err!("Invalid Parquet file. Corrupt footer"));+ }+ let metadata_len = LittleEndian::read_i32(&footer_buffer[0..4]) as i64;+ if metadata_len < 0 {+ return Err(general_err!(+ "Invalid Parquet file. Metadata length is less than zero ({})",+ metadata_len+ ));+ }+ let metadata_start: i64 = file_size as i64 - FOOTER_SIZE as i64 - metadata_len;+ if metadata_start < 0 {+ return Err(general_err!(+ "Invalid Parquet file. Metadata start is less than zero ({})",+ metadata_start+ ));+ }+ buf.seek(SeekFrom::Start(metadata_start as u64))?;+ let metadata_buf = buf.take(metadata_len as u64).into_inner();++ // TODO: row group filtering+ let mut prot = TCompactInputProtocol::new(metadata_buf);+ let mut t_file_metadata: TFileMetaData = TFileMetaData::read_from_in_protocol(&mut prot)+ .map_err(|e| ParquetError::General(format!("Could not parse metadata: {}", e)))?;+ let schema = types::from_thrift(&mut t_file_metadata.schema)?;+ let schema_descr = Rc::new(SchemaDescriptor::new(schema.clone()));+ let mut row_groups = Vec::new();+ for rg in t_file_metadata.row_groups {+ row_groups.push(Rc::new(RowGroupMetaData::from_thrift(+ schema_descr.clone(),+ rg,+ )?));+ }+ let column_orders = Self::parse_column_orders(t_file_metadata.column_orders, &schema_descr);++ let file_metadata = FileMetaData::new(+ t_file_metadata.version,+ t_file_metadata.num_rows,+ t_file_metadata.created_by,+ schema,+ schema_descr,+ column_orders,+ );+ Ok(ParquetMetaData::new(file_metadata, row_groups))+ }++ /// Parses column orders from Thrift definition.+ /// If no column orders are defined, returns `None`.+ fn parse_column_orders(+ t_column_orders: Option<Vec<TColumnOrder>>,+ schema_descr: &SchemaDescriptor,+ ) -> Option<Vec<ColumnOrder>> {+ match t_column_orders {+ Some(orders) => {+ // Should always be the case+ assert_eq!(+ orders.len(),+ schema_descr.num_columns(),+ "Column order length mismatch"+ );+ let mut res = Vec::new();+ for (i, column) in schema_descr.columns().iter().enumerate() {+ match orders[i] {+ TColumnOrder::TYPEORDER(_) => {+ let sort_order = ColumnOrder::get_sort_order(+ column.logical_type(),+ column.physical_type(),+ );+ res.push(ColumnOrder::TYPE_DEFINED_ORDER(sort_order));+ }+ }+ }+ Some(res)+ }+ None => None,+ }+ }+}++impl<R: 'static + ParquetReader> FileReader for SerializedFileReader<R> {+ fn metadata(&self) -> ParquetMetaDataPtr {+ self.metadata.clone()+ }++ fn num_row_groups(&self) -> usize {+ self.metadata.num_row_groups()+ }++ fn get_row_group(&self, i: usize) -> Result<Box<RowGroupReader>> {+ let row_group_metadata = self.metadata.row_group(i);+ // Row groups should be processed sequentially.+ let f = self.buf.get_ref().try_clone()?;+ Ok(Box::new(SerializedRowGroupReader::new(+ f,+ row_group_metadata,+ )))+ }++ fn get_row_iter(&self, projection: Option<SchemaType>) -> Result<RowIter> {+ RowIter::from_file(projection, self)+ }+}++impl TryFrom<File> for SerializedFileReader<File> {+ type Error = ParquetError;++ fn try_from(file: File) -> Result<Self> {+ Self::new(file)+ }+}++impl<'a> TryFrom<&'a Path> for SerializedFileReader<File> {+ type Error = ParquetError;++ fn try_from(path: &Path) -> Result<Self> {+ let file = File::open(path)?;+ Self::try_from(file)+ }+}++impl TryFrom<String> for SerializedFileReader<File> {+ type Error = ParquetError;++ fn try_from(path: String) -> Result<Self> {+ Self::try_from(Path::new(&path))+ }+}++impl<'a> TryFrom<&'a str> for SerializedFileReader<File> {+ type Error = ParquetError;++ fn try_from(path: &str) -> Result<Self> {+ Self::try_from(Path::new(&path))+ }+}++/// A serialized implementation for Parquet [`RowGroupReader`].+pub struct SerializedRowGroupReader<R: ParquetReader> {+ buf: BufReader<R>,+ metadata: RowGroupMetaDataPtr,+}++impl<R: 'static + ParquetReader> SerializedRowGroupReader<R> {+ /// Creates new row group reader from a file and row group metadata.+ fn new(file: R, metadata: RowGroupMetaDataPtr) -> Self {+ let buf = BufReader::new(file);+ Self { buf, metadata }+ }+}++impl<R: 'static + ParquetReader> RowGroupReader for SerializedRowGroupReader<R> {+ fn metadata(&self) -> RowGroupMetaDataPtr {+ self.metadata.clone()+ }++ fn num_columns(&self) -> usize {+ self.metadata.num_columns()+ }++ // TODO: fix PARQUET-816+ fn get_column_page_reader(&self, i: usize) -> Result<Box<PageReader>> {+ let col = self.metadata.column(i);+ let mut col_start = col.data_page_offset();+ if col.has_dictionary_page() {+ col_start = col.dictionary_page_offset().unwrap();+ }+ let col_length = col.compressed_size();+ let file_chunk = FileSource::new(self.buf.get_ref(), col_start as u64, col_length as usize);+ let page_reader = SerializedPageReader::new(+ file_chunk,+ col.num_values(),+ col.compression(),+ col.column_descr().physical_type(),+ )?;+ Ok(Box::new(page_reader))+ }++ fn get_column_reader(&self, i: usize) -> Result<ColumnReader> {+ let schema_descr = self.metadata.schema_descr();+ let col_descr = schema_descr.column(i);+ let col_page_reader = self.get_column_page_reader(i)?;+ let col_reader = match col_descr.physical_type() {+ Type::BOOLEAN => {+ ColumnReader::BoolColumnReader(ColumnReaderImpl::new(col_descr, col_page_reader))+ }+ Type::INT32 => {+ ColumnReader::Int32ColumnReader(ColumnReaderImpl::new(col_descr, col_page_reader))+ }+ Type::INT64 => {+ ColumnReader::Int64ColumnReader(ColumnReaderImpl::new(col_descr, col_page_reader))+ }+ Type::INT96 => {+ ColumnReader::Int96ColumnReader(ColumnReaderImpl::new(col_descr, col_page_reader))+ }+ Type::FLOAT => {+ ColumnReader::FloatColumnReader(ColumnReaderImpl::new(col_descr, col_page_reader))+ }+ Type::DOUBLE => {+ ColumnReader::DoubleColumnReader(ColumnReaderImpl::new(col_descr, col_page_reader))+ }+ Type::BYTE_ARRAY => ColumnReader::ByteArrayColumnReader(ColumnReaderImpl::new(+ col_descr,+ col_page_reader,+ )),+ Type::FIXED_LEN_BYTE_ARRAY => ColumnReader::FixedLenByteArrayColumnReader(+ ColumnReaderImpl::new(col_descr, col_page_reader),+ ),+ };+ Ok(col_reader)+ }++ fn get_row_iter(&self, projection: Option<SchemaType>) -> Result<RowIter> {+ RowIter::from_row_group(projection, self)+ }+}++/// A serialized implementation for Parquet [`PageReader`].+pub struct SerializedPageReader<T: Read> {+ // The file source buffer which references exactly the bytes for the column trunk+ // to be read by this page reader.+ buf: T,++ // The compression codec for this column chunk. Only set for non-PLAIN codec.+ decompressor: Option<Box<Codec>>,++ // The number of values we have seen so far.+ seen_num_values: i64,++ // The number of total values in this column chunk.+ total_num_values: i64,++ // Column chunk type.+ physical_type: Type,+}++impl<T: Read> SerializedPageReader<T> {+ /// Creates a new serialized page reader from file source.+ pub fn new(+ buf: T,+ total_num_values: i64,+ compression: Compression,+ physical_type: Type,+ ) -> Result<Self> {+ let decompressor = create_codec(compression)?;+ let result = Self {+ buf,+ total_num_values,+ seen_num_values: 0,+ decompressor,+ physical_type,+ };+ Ok(result)+ }++ /// Reads Page header from Thrift.+ fn read_page_header(&mut self) -> Result<PageHeader> {+ let mut prot = TCompactInputProtocol::new(&mut self.buf);+ let page_header = PageHeader::read_from_in_protocol(&mut prot)?;+ Ok(page_header)+ }+}++impl<T: Read> PageReader for SerializedPageReader<T> {+ fn get_next_page(&mut self) -> Result<Option<Page>> {+ while self.seen_num_values < self.total_num_values {+ let page_header = self.read_page_header()?;++ // When processing data page v2, depending on enabled compression for the page, we+ // should account for uncompressed data ('offset') of repetition and definition+ // levels.+ //+ // We always use 0 offset for other pages other than v2, `true` flag means that+ // compression will be applied if decompressor is defined+ let mut offset: usize = 0;+ let mut can_decompress = true;++ if let Some(ref header_v2) = page_header.data_page_header_v2 {+ offset = (header_v2.definition_levels_byte_length+ + header_v2.repetition_levels_byte_length) as usize;+ // When is_compressed flag is missing the page is considered compressed+ can_decompress = header_v2.is_compressed.unwrap_or(true);+ }++ let compressed_len = page_header.compressed_page_size as usize - offset;+ let uncompressed_len = page_header.uncompressed_page_size as usize - offset;+ // We still need to read all bytes from buffered stream+ let mut buffer = vec![0; offset + compressed_len];+ self.buf.read_exact(&mut buffer)?;++ // TODO: page header could be huge because of statistics. We should set a maximum+ // page header size and abort if that is exceeded.+ if let Some(decompressor) = self.decompressor.as_mut() {+ if can_decompress {+ let mut decompressed_buffer = Vec::with_capacity(uncompressed_len);+ let decompressed_size =+ decompressor.decompress(&buffer[offset..], &mut decompressed_buffer)?;+ if decompressed_size != uncompressed_len {+ return Err(general_err!(+ "Actual decompressed size doesn't match the expected one ({} vs {})",+ decompressed_size,+ uncompressed_len+ ));+ }+ if offset == 0 {+ buffer = decompressed_buffer;+ } else {+ // Prepend saved offsets to the buffer+ buffer.truncate(offset);+ buffer.append(&mut decompressed_buffer);+ }+ }+ }++ let result = match page_header.type_ {+ PageType::DICTIONARY_PAGE => {+ assert!(page_header.dictionary_page_header.is_some());+ let dict_header = page_header.dictionary_page_header.as_ref().unwrap();+ let is_sorted = dict_header.is_sorted.unwrap_or(false);+ Page::DictionaryPage {+ buf: ByteBufferPtr::new(buffer),+ num_values: dict_header.num_values as u32,+ encoding: Encoding::from(dict_header.encoding),+ is_sorted,+ }+ }+ PageType::DATA_PAGE => {+ assert!(page_header.data_page_header.is_some());+ let header = page_header.data_page_header.unwrap();+ self.seen_num_values += header.num_values as i64;+ Page::DataPage {+ buf: ByteBufferPtr::new(buffer),+ num_values: header.num_values as u32,+ encoding: Encoding::from(header.encoding),+ def_level_encoding: Encoding::from(header.definition_level_encoding),+ rep_level_encoding: Encoding::from(header.repetition_level_encoding),+ statistics: statistics::from_thrift(self.physical_type, header.statistics),+ }+ }+ PageType::DATA_PAGE_V2 => {+ assert!(page_header.data_page_header_v2.is_some());+ let header = page_header.data_page_header_v2.unwrap();+ let is_compressed = header.is_compressed.unwrap_or(true);+ self.seen_num_values += header.num_values as i64;+ Page::DataPageV2 {+ buf: ByteBufferPtr::new(buffer),+ num_values: header.num_values as u32,+ encoding: Encoding::from(header.encoding),+ num_nulls: header.num_nulls as u32,+ num_rows: header.num_rows as u32,+ def_levels_byte_len: header.definition_levels_byte_length as u32,+ rep_levels_byte_len: header.repetition_levels_byte_length as u32,+ is_compressed,+ statistics: statistics::from_thrift(self.physical_type, header.statistics),+ }+ }+ _ => {+ // For unknown page type (e.g., INDEX_PAGE), skip and read next.+ continue;+ }+ };+ return Ok(Some(result));+ }++ // We are at the end of this column chunk and no more page left. Return None.+ Ok(None)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ use parquet_format::TypeDefinedOrder;++ use crate::parquet::basic::SortOrder;+ use crate::parquet::util::test_common::{get_temp_file, get_test_file, get_test_path};++ #[test]+ fn test_file_reader_metadata_size_smaller_than_footer() {+ let test_file = get_temp_file("corrupt-1.parquet", &[]);+ let reader_result = SerializedFileReader::new(test_file);+ assert!(reader_result.is_err());+ assert_eq!(+ reader_result.err().unwrap(),+ general_err!("Invalid Parquet file. Size is smaller than footer")+ );+ }++ // #[test]+ // fn test_cursor_and_file_has_the_same_behaviour() {+ // let path = get_test_path("alltypes_plain.parquet");+ // let buffer = include_bytes!(path);+ // let cursor = Cursor::new(buffer.as_ref());++ // let read_from_file =+ // SerializedFileReader::new(File::open("testdata/alltypes_plain.parquet").unwrap())+ // .unwrap();+ // let read_from_cursor = SerializedFileReader::new(cursor).unwrap();++ // let file_iter = read_from_file.get_row_iter(None).unwrap();+ // let cursor_iter = read_from_cursor.get_row_iter(None).unwrap();++ // assert!(file_iter.eq(cursor_iter));+ // }++ #[test]+ fn test_file_reader_metadata_corrupt_footer() {+ let test_file = get_temp_file("corrupt-2.parquet", &[1, 2, 3, 4, 5, 6, 7, 8]);+ let reader_result = SerializedFileReader::new(test_file);+ assert!(reader_result.is_err());+ assert_eq!(+ reader_result.err().unwrap(),+ general_err!("Invalid Parquet file. Corrupt footer")+ );+ }++ #[test]+ fn test_file_reader_metadata_invalid_length() {+ let test_file = get_temp_file("corrupt-3.parquet", &[0, 0, 0, 255, b'P', b'A', b'R', b'1']);+ let reader_result = SerializedFileReader::new(test_file);+ assert!(reader_result.is_err());+ assert_eq!(+ reader_result.err().unwrap(),+ general_err!("Invalid Parquet file. Metadata length is less than zero (-16777216)")+ );+ }++ #[test]+ fn test_file_reader_metadata_invalid_start() {+ let test_file = get_temp_file("corrupt-4.parquet", &[255, 0, 0, 0, b'P', b'A', b'R', b'1']);+ let reader_result = SerializedFileReader::new(test_file);+ assert!(reader_result.is_err());+ assert_eq!(+ reader_result.err().unwrap(),+ general_err!("Invalid Parquet file. Metadata start is less than zero (-255)")+ );+ }++ #[test]+ fn test_file_reader_column_orders_parse() {+ // Define simple schema, we do not need to provide logical types.+ let mut fields = vec![+ Rc::new(+ SchemaType::primitive_type_builder("col1", Type::INT32)+ .build()+ .unwrap(),+ ),+ Rc::new(+ SchemaType::primitive_type_builder("col2", Type::FLOAT)+ .build()+ .unwrap(),+ ),+ ];+ let schema = SchemaType::group_type_builder("schema")+ .with_fields(&mut fields)+ .build()+ .unwrap();+ let schema_descr = SchemaDescriptor::new(Rc::new(schema));++ let t_column_orders = Some(vec![+ TColumnOrder::TYPEORDER(TypeDefinedOrder::new()),+ TColumnOrder::TYPEORDER(TypeDefinedOrder::new()),+ ]);++ assert_eq!(+ SerializedFileReader::<File>::parse_column_orders(t_column_orders, &schema_descr),+ Some(vec![+ ColumnOrder::TYPE_DEFINED_ORDER(SortOrder::SIGNED),+ ColumnOrder::TYPE_DEFINED_ORDER(SortOrder::SIGNED)+ ])+ );++ // Test when no column orders are defined.+ assert_eq!(+ SerializedFileReader::<File>::parse_column_orders(None, &schema_descr),+ None+ );+ }++ #[test]+ #[should_panic(expected = "Column order length mismatch")]+ fn test_file_reader_column_orders_len_mismatch() {+ let schema = SchemaType::group_type_builder("schema").build().unwrap();+ let schema_descr = SchemaDescriptor::new(Rc::new(schema));++ let t_column_orders = Some(vec![TColumnOrder::TYPEORDER(TypeDefinedOrder::new())]);++ SerializedFileReader::<File>::parse_column_orders(t_column_orders, &schema_descr);+ }++ #[test]+ fn test_file_reader_try_from() {+ // Valid file path+ let test_file = get_test_file("alltypes_plain.parquet");+ let test_path_buf = get_test_path("alltypes_plain.parquet");+ let test_path = test_path_buf.as_path();+ let test_path_str = test_path.to_str().unwrap();++ let reader = SerializedFileReader::try_from(test_file);+ assert!(reader.is_ok());++ let reader = SerializedFileReader::try_from(test_path);+ assert!(reader.is_ok());++ let reader = SerializedFileReader::try_from(test_path_str);+ assert!(reader.is_ok());++ let reader = SerializedFileReader::try_from(test_path_str.to_string());+ assert!(reader.is_ok());++ // Invalid file path+ let test_path = Path::new("invalid.parquet");+ let test_path_str = test_path.to_str().unwrap();++ let reader = SerializedFileReader::try_from(test_path);+ assert!(reader.is_err());++ let reader = SerializedFileReader::try_from(test_path_str);+ assert!(reader.is_err());++ let reader = SerializedFileReader::try_from(test_path_str.to_string());+ assert!(reader.is_err());+ }++ #[test]+ fn test_reuse_file_chunk() {+ // This test covers the case of maintaining the correct start position in a file+ // stream for each column reader after initializing and moving to the next one+ // (without necessarily reading the entire column).+ let test_file = get_test_file("alltypes_plain.parquet");+ let reader = SerializedFileReader::new(test_file).unwrap();+ let row_group = reader.get_row_group(0).unwrap();++ let mut page_readers = Vec::new();+ for i in 0..row_group.num_columns() {+ page_readers.push(row_group.get_column_page_reader(i).unwrap());+ }++ // Now buffer each col reader, we do not expect any failures like:+ // General("underlying Thrift error: end of file")+ for mut page_reader in page_readers {+ assert!(page_reader.get_next_page().is_ok());+ }+ }++ #[test]+ fn test_file_reader() {+ let test_file = get_test_file("alltypes_plain.parquet");+ let reader_result = SerializedFileReader::new(test_file);+ assert!(reader_result.is_ok());+ let reader = reader_result.unwrap();++ // Test contents in Parquet metadata+ let metadata = reader.metadata();+ assert_eq!(metadata.num_row_groups(), 1);++ // Test contents in file metadata+ let file_metadata = metadata.file_metadata();+ assert!(file_metadata.created_by().is_some());+ assert_eq!(+ file_metadata.created_by().as_ref().unwrap(),+ "impala version 1.3.0-INTERNAL (build 8a48ddb1eff84592b3fc06bc6f51ec120e1fffc9)"+ );+ assert_eq!(file_metadata.num_rows(), 8);+ assert_eq!(file_metadata.version(), 1);+ assert_eq!(file_metadata.column_orders(), None);++ // Test contents in row group metadata+ let row_group_metadata = metadata.row_group(0);+ assert_eq!(row_group_metadata.num_columns(), 11);+ assert_eq!(row_group_metadata.num_rows(), 8);+ assert_eq!(row_group_metadata.total_byte_size(), 671);+ // Check each column order+ for i in 0..row_group_metadata.num_columns() {+ assert_eq!(file_metadata.column_order(i), ColumnOrder::UNDEFINED);+ }++ // Test row group reader+ let row_group_reader_result = reader.get_row_group(0);+ assert!(row_group_reader_result.is_ok());+ let row_group_reader: Box<RowGroupReader> = row_group_reader_result.unwrap();+ assert_eq!(+ row_group_reader.num_columns(),+ row_group_metadata.num_columns()+ );+ assert_eq!(+ row_group_reader.metadata().total_byte_size(),+ row_group_metadata.total_byte_size()+ );++ // Test page readers+ // TODO: test for every column+ let page_reader_0_result = row_group_reader.get_column_page_reader(0);+ assert!(page_reader_0_result.is_ok());+ let mut page_reader_0: Box<PageReader> = page_reader_0_result.unwrap();+ let mut page_count = 0;+ while let Ok(Some(page)) = page_reader_0.get_next_page() {+ let is_expected_page = match page {+ Page::DictionaryPage {+ buf,+ num_values,+ encoding,+ is_sorted,+ } => {+ assert_eq!(buf.len(), 32);+ assert_eq!(num_values, 8);+ assert_eq!(encoding, Encoding::PLAIN_DICTIONARY);+ assert_eq!(is_sorted, false);+ true+ }+ Page::DataPage {+ buf,+ num_values,+ encoding,+ def_level_encoding,+ rep_level_encoding,+ statistics,+ } => {+ assert_eq!(buf.len(), 11);+ assert_eq!(num_values, 8);+ assert_eq!(encoding, Encoding::PLAIN_DICTIONARY);+ assert_eq!(def_level_encoding, Encoding::RLE);+ assert_eq!(rep_level_encoding, Encoding::BIT_PACKED);+ assert!(statistics.is_none());+ true+ }+ _ => false,+ };+ assert!(is_expected_page);+ page_count += 1;+ }+ assert_eq!(page_count, 2);+ }++ #[test]+ fn test_file_reader_datapage_v2() {+ let test_file = get_test_file("datapage_v2.snappy.parquet");+ let reader_result = SerializedFileReader::new(test_file);+ assert!(reader_result.is_ok());+ let reader = reader_result.unwrap();++ // Test contents in Parquet metadata+ let metadata = reader.metadata();+ assert_eq!(metadata.num_row_groups(), 1);++ // Test contents in file metadata+ let file_metadata = metadata.file_metadata();+ assert!(file_metadata.created_by().is_some());+ assert_eq!(+ file_metadata.created_by().as_ref().unwrap(),+ "parquet-mr version 1.8.1 (build 4aba4dae7bb0d4edbcf7923ae1339f28fd3f7fcf)"+ );+ assert_eq!(file_metadata.num_rows(), 5);+ assert_eq!(file_metadata.version(), 1);+ assert_eq!(file_metadata.column_orders(), None);++ let row_group_metadata = metadata.row_group(0);++ // Check each column order+ for i in 0..row_group_metadata.num_columns() {+ assert_eq!(file_metadata.column_order(i), ColumnOrder::UNDEFINED);+ }++ // Test row group reader+ let row_group_reader_result = reader.get_row_group(0);+ assert!(row_group_reader_result.is_ok());+ let row_group_reader: Box<RowGroupReader> = row_group_reader_result.unwrap();+ assert_eq!(+ row_group_reader.num_columns(),+ row_group_metadata.num_columns()+ );+ assert_eq!(+ row_group_reader.metadata().total_byte_size(),+ row_group_metadata.total_byte_size()+ );++ // Test page readers+ // TODO: test for every column+ let page_reader_0_result = row_group_reader.get_column_page_reader(0);+ assert!(page_reader_0_result.is_ok());+ let mut page_reader_0: Box<PageReader> = page_reader_0_result.unwrap();+ let mut page_count = 0;+ while let Ok(Some(page)) = page_reader_0.get_next_page() {+ let is_expected_page = match page {+ Page::DictionaryPage {+ buf,+ num_values,+ encoding,+ is_sorted,+ } => {+ assert_eq!(buf.len(), 7);+ assert_eq!(num_values, 1);+ assert_eq!(encoding, Encoding::PLAIN);+ assert_eq!(is_sorted, false);+ true+ }+ Page::DataPageV2 {+ buf,+ num_values,+ encoding,+ num_nulls,+ num_rows,+ def_levels_byte_len,+ rep_levels_byte_len,+ is_compressed,+ statistics,+ } => {+ assert_eq!(buf.len(), 4);+ assert_eq!(num_values, 5);+ assert_eq!(encoding, Encoding::RLE_DICTIONARY);+ assert_eq!(num_nulls, 1);+ assert_eq!(num_rows, 5);+ assert_eq!(def_levels_byte_len, 2);+ assert_eq!(rep_levels_byte_len, 0);+ assert_eq!(is_compressed, true);+ assert!(statistics.is_some());+ true+ }+ _ => false,+ };+ assert!(is_expected_page);+ page_count += 1;+ }+ assert_eq!(page_count, 2);+ }+}diff --git a/rust/src/parquet/file/statistics.rs b/rust/src/parquet/file/statistics.rsnew file mode 100644index 0000000000..ff4d731857--- /dev/null+++ b/rust/src/parquet/file/statistics.rs@@ -0,0 +1,692 @@+// 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.++//! Contains definitions for working with Parquet statistics.+//!+//! Though some common methods are available on enum, use pattern match to extract+//! actual min and max values from statistics, see below:+//!+//! ```rust+//! use arrow::parquet::file::statistics::Statistics;+//!+//! let stats = Statistics::int32(Some(1), Some(10), None, 3, true);+//! assert_eq!(stats.null_count(), 3);+//! assert!(stats.has_min_max_set());+//! assert!(stats.is_min_max_deprecated());+//!+//! match stats {+//! Statistics::Int32(ref typed) => {+//! assert_eq!(*typed.min(), 1);+//! assert_eq!(*typed.max(), 10);+//! }+//! _ => {}+//! }+//! ```++use std::{cmp, fmt};++use byteorder::{ByteOrder, LittleEndian};+use parquet_format::Statistics as TStatistics;++use crate::parquet::basic::Type;+use crate::parquet::data_type::*;++// Macro to generate methods create Statistics.+macro_rules! statistics_new_func {+ ($func:ident, $vtype:ty, $stat:ident) => {+ pub fn $func(+ min: $vtype,+ max: $vtype,+ distinct: Option<u64>,+ nulls: u64,+ is_deprecated: bool,+ ) -> Self {+ Statistics::$stat(TypedStatistics::new(+ min,+ max,+ distinct,+ nulls,+ is_deprecated,+ ))+ }+ };+}++// Macro to generate getter functions for Statistics.+macro_rules! statistics_enum_func {+ ($self:ident, $func:ident) => {{+ match *$self {+ Statistics::Boolean(ref typed) => typed.$func(),+ Statistics::Int32(ref typed) => typed.$func(),+ Statistics::Int64(ref typed) => typed.$func(),+ Statistics::Int96(ref typed) => typed.$func(),+ Statistics::Float(ref typed) => typed.$func(),+ Statistics::Double(ref typed) => typed.$func(),+ Statistics::ByteArray(ref typed) => typed.$func(),+ Statistics::FixedLenByteArray(ref typed) => typed.$func(),+ }+ }};+}++/// Converts Thrift definition into `Statistics`.+pub fn from_thrift(physical_type: Type, thrift_stats: Option<TStatistics>) -> Option<Statistics> {+ match thrift_stats {+ Some(stats) => {+ // Number of nulls recorded, when it is not available, we just mark it as 0.+ let null_count = stats.null_count.unwrap_or(0);+ assert!(+ null_count >= 0,+ "Statistics null count is negative ({})",+ null_count+ );++ // Generic null count.+ let null_count = null_count as u64;+ // Generic distinct count (count of distinct values occurring)+ let distinct_count = stats.distinct_count.map(|value| value as u64);+ // Whether or not statistics use deprecated min/max fields.+ let old_format = stats.min_value.is_none() && stats.max_value.is_none();+ // Generic min value as bytes.+ let min = if old_format {+ stats.min+ } else {+ stats.min_value+ };+ // Generic max value as bytes.+ let max = if old_format {+ stats.max+ } else {+ stats.max_value+ };++ // Values are encoded using PLAIN encoding definition, except that+ // variable-length byte arrays do not include a length prefix.+ //+ // Instead of using actual decoder, we manually convert values.+ let res = match physical_type {+ Type::BOOLEAN => Statistics::boolean(+ min.map(|data| data[0] != 0),+ max.map(|data| data[0] != 0),+ distinct_count,+ null_count,+ old_format,+ ),+ Type::INT32 => Statistics::int32(+ min.map(|data| LittleEndian::read_i32(&data)),+ max.map(|data| LittleEndian::read_i32(&data)),+ distinct_count,+ null_count,+ old_format,+ ),+ Type::INT64 => Statistics::int64(+ min.map(|data| LittleEndian::read_i64(&data)),+ max.map(|data| LittleEndian::read_i64(&data)),+ distinct_count,+ null_count,+ old_format,+ ),+ Type::INT96 => {+ // INT96 statistics may not be correct, because comparison is signed+ // byte-wise, not actual timestamps. It is recommended to ignore min/max+ // statistics for INT96 columns.+ let min = min.map(|data| {+ assert_eq!(data.len(), 12);+ unsafe {+ let raw = ::std::slice::from_raw_parts(data.as_ptr() as *mut u32, 3);+ Int96::from(Vec::from(raw))+ }+ });+ let max = max.map(|data| {+ assert_eq!(data.len(), 12);+ unsafe {+ let raw = ::std::slice::from_raw_parts(data.as_ptr() as *mut u32, 3);+ Int96::from(Vec::from(raw))+ }+ });+ Statistics::int96(min, max, distinct_count, null_count, old_format)+ }+ Type::FLOAT => Statistics::float(+ min.map(|data| LittleEndian::read_f32(&data)),+ max.map(|data| LittleEndian::read_f32(&data)),+ distinct_count,+ null_count,+ old_format,+ ),+ Type::DOUBLE => Statistics::double(+ min.map(|data| LittleEndian::read_f64(&data)),+ max.map(|data| LittleEndian::read_f64(&data)),+ distinct_count,+ null_count,+ old_format,+ ),+ Type::BYTE_ARRAY => Statistics::byte_array(+ min.map(|data| ByteArray::from(data)),+ max.map(|data| ByteArray::from(data)),+ distinct_count,+ null_count,+ old_format,+ ),+ Type::FIXED_LEN_BYTE_ARRAY => Statistics::fixed_len_byte_array(+ min.map(|data| ByteArray::from(data)),+ max.map(|data| ByteArray::from(data)),+ distinct_count,+ null_count,+ old_format,+ ),+ };++ Some(res)+ }+ None => None,+ }+}++// Convert Statistics into Thrift definition.+pub fn to_thrift(stats: Option<&Statistics>) -> Option<TStatistics> {+ if stats.is_none() {+ return None;+ }++ let stats = stats.unwrap();++ let mut thrift_stats = TStatistics {+ max: None,+ min: None,+ null_count: if stats.has_nulls() {+ Some(stats.null_count() as i64)+ } else {+ None+ },+ distinct_count: stats.distinct_count().map(|value| value as i64),+ max_value: None,+ min_value: None,+ };++ // Get min/max if set.+ let (min, max) = if stats.has_min_max_set() {+ (+ Some(stats.min_bytes().to_vec()),+ Some(stats.max_bytes().to_vec()),+ )+ } else {+ (None, None)+ };++ if stats.is_min_max_deprecated() {+ thrift_stats.min = min;+ thrift_stats.max = max;+ } else {+ thrift_stats.min_value = min;+ thrift_stats.max_value = max;+ }++ Some(thrift_stats)+}++/// Statistics for a column chunk and data page.+#[derive(Debug, PartialEq)]+pub enum Statistics {+ Boolean(TypedStatistics<BoolType>),+ Int32(TypedStatistics<Int32Type>),+ Int64(TypedStatistics<Int64Type>),+ Int96(TypedStatistics<Int96Type>),+ Float(TypedStatistics<FloatType>),+ Double(TypedStatistics<DoubleType>),+ ByteArray(TypedStatistics<ByteArrayType>),+ FixedLenByteArray(TypedStatistics<FixedLenByteArrayType>),+}++impl Statistics {+ statistics_new_func![boolean, Option<bool>, Boolean];++ statistics_new_func![int32, Option<i32>, Int32];++ statistics_new_func![int64, Option<i64>, Int64];++ statistics_new_func![int96, Option<Int96>, Int96];++ statistics_new_func![float, Option<f32>, Float];++ statistics_new_func![double, Option<f64>, Double];++ statistics_new_func![byte_array, Option<ByteArray>, ByteArray];++ statistics_new_func![fixed_len_byte_array, Option<ByteArray>, FixedLenByteArray];++ /// Returns `true` if statistics have old `min` and `max` fields set.+ /// This means that the column order is likely to be undefined, which, for old files+ /// could mean a signed sort order of values.+ ///+ /// Refer to [`ColumnOrder`](`::basic::ColumnOrder`) and+ /// [`SortOrder`](`::basic::SortOrder`) for more information.+ pub fn is_min_max_deprecated(&self) -> bool {+ statistics_enum_func![self, is_min_max_deprecated]+ }++ /// Returns optional value of number of distinct values occurring.+ /// When it is `None`, the value should be ignored.+ pub fn distinct_count(&self) -> Option<u64> {+ statistics_enum_func![self, distinct_count]+ }++ /// Returns number of null values for the column.+ /// Note that this includes all nulls when column is part of the complex type.+ pub fn null_count(&self) -> u64 {+ statistics_enum_func![self, null_count]+ }++ /// Returns `true` if statistics collected any null values, `false` otherwise.+ pub fn has_nulls(&self) -> bool {+ self.null_count() > 0+ }++ /// Returns `true` if min value and max value are set.+ /// Normally both min/max values will be set to `Some(value)` or `None`.+ pub fn has_min_max_set(&self) -> bool {+ statistics_enum_func![self, has_min_max_set]+ }++ /// Returns slice of bytes that represent min value.+ /// Panics if min value is not set.+ pub fn min_bytes(&self) -> &[u8] {+ statistics_enum_func![self, min_bytes]+ }++ /// Returns slice of bytes that represent max value.+ /// Panics if max value is not set.+ pub fn max_bytes(&self) -> &[u8] {+ statistics_enum_func![self, max_bytes]+ }++ /// Returns physical type associated with statistics.+ pub fn physical_type(&self) -> Type {+ match self {+ Statistics::Boolean(_) => Type::BOOLEAN,+ Statistics::Int32(_) => Type::INT32,+ Statistics::Int64(_) => Type::INT64,+ Statistics::Int96(_) => Type::INT96,+ Statistics::Float(_) => Type::FLOAT,+ Statistics::Double(_) => Type::DOUBLE,+ Statistics::ByteArray(_) => Type::BYTE_ARRAY,+ Statistics::FixedLenByteArray(_) => Type::FIXED_LEN_BYTE_ARRAY,+ }+ }+}++impl fmt::Display for Statistics {+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {+ match self {+ Statistics::Boolean(typed) => write!(f, "{}", typed),+ Statistics::Int32(typed) => write!(f, "{}", typed),+ Statistics::Int64(typed) => write!(f, "{}", typed),+ Statistics::Int96(typed) => write!(f, "{}", typed),+ Statistics::Float(typed) => write!(f, "{}", typed),+ Statistics::Double(typed) => write!(f, "{}", typed),+ Statistics::ByteArray(typed) => write!(f, "{}", typed),+ Statistics::FixedLenByteArray(typed) => write!(f, "{}", typed),+ }+ }+}++/// Typed implementation for [`Statistics`].+pub struct TypedStatistics<T: DataType> {+ min: Option<T::T>,+ max: Option<T::T>,+ // Distinct count could be omitted in some cases+ distinct_count: Option<u64>,+ null_count: u64,+ is_min_max_deprecated: bool,+}++impl<T: DataType> TypedStatistics<T> {+ /// Creates new typed statistics.+ pub fn new(+ min: Option<T::T>,+ max: Option<T::T>,+ distinct_count: Option<u64>,+ null_count: u64,+ is_min_max_deprecated: bool,+ ) -> Self {+ Self {+ min,+ max,+ distinct_count,+ null_count,+ is_min_max_deprecated,+ }+ }++ /// Returns min value of the statistics.+ ///+ /// Panics if min value is not set, e.g. all values are `null`.+ /// Use `has_min_max_set` method to check that.+ pub fn min(&self) -> &T::T {+ self.min.as_ref().unwrap()+ }++ /// Returns max value of the statistics.+ ///+ /// Panics if max value is not set, e.g. all values are `null`.+ /// Use `has_min_max_set` method to check that.+ pub fn max(&self) -> &T::T {+ self.max.as_ref().unwrap()+ }++ /// Returns min value as bytes of the statistics.+ ///+ /// Panics if min value is not set, use `has_min_max_set` method to check+ /// if values are set.+ pub fn min_bytes(&self) -> &[u8] {+ self.min().as_bytes()+ }++ /// Returns max value as bytes of the statistics.+ ///+ /// Panics if max value is not set, use `has_min_max_set` method to check+ /// if values are set.+ pub fn max_bytes(&self) -> &[u8] {+ self.max().as_bytes()+ }++ /// Whether or not min and max values are set.+ /// Normally both min/max values will be set to `Some(value)` or `None`.+ fn has_min_max_set(&self) -> bool {+ self.min.is_some() && self.max.is_some()+ }++ /// Returns optional value of number of distinct values occurring.+ fn distinct_count(&self) -> Option<u64> {+ self.distinct_count+ }++ /// Returns null count.+ fn null_count(&self) -> u64 {+ self.null_count+ }++ /// Returns `true` if statistics were created using old min/max fields.+ fn is_min_max_deprecated(&self) -> bool {+ self.is_min_max_deprecated+ }+}++impl<T: DataType> fmt::Display for TypedStatistics<T> {+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {+ write!(f, "{{")?;+ write!(f, "min: ")?;+ match self.min {+ Some(ref value) => self.value_fmt(f, value)?,+ None => write!(f, "N/A")?,+ }+ write!(f, ", max: ")?;+ match self.max {+ Some(ref value) => self.value_fmt(f, value)?,+ None => write!(f, "N/A")?,+ }+ write!(f, ", distinct_count: ")?;+ match self.distinct_count {+ Some(value) => write!(f, "{}", value)?,+ None => write!(f, "N/A")?,+ }+ write!(f, ", null_count: {}", self.null_count)?;+ write!(f, ", min_max_deprecated: {}", self.is_min_max_deprecated)?;+ write!(f, "}}")+ }+}++impl<T: DataType> fmt::Debug for TypedStatistics<T> {+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {+ write!(+ f,+ "{{min: {:?}, max: {:?}, distinct_count: {:?}, null_count: {}, \+ min_max_deprecated: {}}}",+ self.min, self.max, self.distinct_count, self.null_count, self.is_min_max_deprecated+ )+ }+}++impl<T: DataType> cmp::PartialEq for TypedStatistics<T> {+ fn eq(&self, other: &TypedStatistics<T>) -> bool {+ self.min == other.min+ && self.max == other.max+ && self.distinct_count == other.distinct_count+ && self.null_count == other.null_count+ && self.is_min_max_deprecated == other.is_min_max_deprecated+ }+}++/// Trait to provide a specific write format for values.+/// For example, we should display vector slices for byte array types, and original+/// values for other types.+trait ValueDisplay<T: DataType> {+ fn value_fmt(&self, f: &mut fmt::Formatter, value: &T::T) -> fmt::Result;+}++impl<T: DataType> ValueDisplay<T> for TypedStatistics<T> {+ default fn value_fmt(&self, f: &mut fmt::Formatter, value: &T::T) -> fmt::Result {+ write!(f, "{:?}", value)+ }+}++impl ValueDisplay<Int96Type> for TypedStatistics<Int96Type> {+ fn value_fmt(&self, f: &mut fmt::Formatter, value: &Int96) -> fmt::Result {+ write!(f, "{:?}", value.data())+ }+}++impl ValueDisplay<ByteArrayType> for TypedStatistics<ByteArrayType> {+ fn value_fmt(&self, f: &mut fmt::Formatter, value: &ByteArray) -> fmt::Result {+ write!(f, "{:?}", value.data())+ }+}++impl ValueDisplay<FixedLenByteArrayType> for TypedStatistics<FixedLenByteArrayType> {+ fn value_fmt(&self, f: &mut fmt::Formatter, value: &ByteArray) -> fmt::Result {+ write!(f, "{:?}", value.data())+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_statistics_min_max_bytes() {+ let stats = Statistics::int32(Some(-123), Some(234), None, 1, false);+ assert!(stats.has_min_max_set());+ assert_eq!(stats.min_bytes(), (-123).as_bytes());+ assert_eq!(stats.max_bytes(), 234.as_bytes());++ let stats = Statistics::byte_array(+ Some(ByteArray::from(vec![1, 2, 3])),+ Some(ByteArray::from(vec![3, 4, 5])),+ None,+ 1,+ true,+ );+ assert!(stats.has_min_max_set());+ assert_eq!(stats.min_bytes(), &[1, 2, 3]);+ assert_eq!(stats.max_bytes(), &[3, 4, 5]);+ }++ #[test]+ #[should_panic(expected = "Statistics null count is negative (-10)")]+ fn test_statistics_negative_null_count() {+ let thrift_stats = TStatistics {+ max: None,+ min: None,+ null_count: Some(-10),+ distinct_count: None,+ max_value: None,+ min_value: None,+ };++ from_thrift(Type::INT32, Some(thrift_stats));+ }++ #[test]+ fn test_statistics_thrift_none() {+ assert_eq!(from_thrift(Type::INT32, None), None);+ assert_eq!(from_thrift(Type::BYTE_ARRAY, None), None);+ }++ #[test]+ fn test_statistics_debug() {+ let stats = Statistics::int32(Some(1), Some(12), None, 12, true);+ assert_eq!(+ format!("{:?}", stats),+ "Int32({min: Some(1), max: Some(12), distinct_count: None, null_count: 12, \+ min_max_deprecated: true})"+ );++ let stats = Statistics::int32(None, None, None, 7, false);+ assert_eq!(+ format!("{:?}", stats),+ "Int32({min: None, max: None, distinct_count: None, null_count: 7, \+ min_max_deprecated: false})"+ )+ }++ #[test]+ fn test_statistics_display() {+ let stats = Statistics::int32(Some(1), Some(12), None, 12, true);+ assert_eq!(+ format!("{}", stats),+ "{min: 1, max: 12, distinct_count: N/A, null_count: 12, min_max_deprecated: true}"+ );++ let stats = Statistics::int64(None, None, None, 7, false);+ assert_eq!(+ format!("{}", stats),+ "{min: N/A, max: N/A, distinct_count: N/A, null_count: 7, min_max_deprecated: \+ false}"+ );++ let stats = Statistics::int96(+ Some(Int96::from(vec![1, 0, 0])),+ Some(Int96::from(vec![2, 3, 4])),+ None,+ 3,+ true,+ );+ assert_eq!(+ format!("{}", stats),+ "{min: [1, 0, 0], max: [2, 3, 4], distinct_count: N/A, null_count: 3, \+ min_max_deprecated: true}"+ );++ let stats = Statistics::byte_array(+ Some(ByteArray::from(vec![1u8])),+ Some(ByteArray::from(vec![2u8])),+ Some(5),+ 7,+ false,+ );+ assert_eq!(+ format!("{}", stats),+ "{min: [1], max: [2], distinct_count: 5, null_count: 7, min_max_deprecated: false}"+ );+ }++ #[test]+ fn test_statistics_partial_eq() {+ let expected = Statistics::int32(Some(12), Some(45), None, 11, true);++ assert!(Statistics::int32(Some(12), Some(45), None, 11, true) == expected);+ assert!(Statistics::int32(Some(11), Some(45), None, 11, true) != expected);+ assert!(Statistics::int32(Some(12), Some(44), None, 11, true) != expected);+ assert!(Statistics::int32(Some(12), Some(45), None, 23, true) != expected);+ assert!(Statistics::int32(Some(12), Some(45), None, 11, false) != expected);++ assert!(+ Statistics::int32(Some(12), Some(45), None, 11, false)+ != Statistics::int64(Some(12), Some(45), None, 11, false)+ );++ assert!(+ Statistics::boolean(Some(false), Some(true), None, 0, true)+ != Statistics::double(Some(1.2), Some(4.5), None, 0, true)+ );++ assert!(+ Statistics::byte_array(+ Some(ByteArray::from(vec![1, 2, 3])),+ Some(ByteArray::from(vec![1, 2, 3])),+ None,+ 0,+ true+ ) != Statistics::fixed_len_byte_array(+ Some(ByteArray::from(vec![1, 2, 3])),+ Some(ByteArray::from(vec![1, 2, 3])),+ None,+ 0,+ true+ )+ );+ }++ #[test]+ fn test_statistics_from_thrift() {+ // Helper method to check statistics conversion.+ fn check_stats(stats: Statistics) {+ let tpe = stats.physical_type();+ let thrift_stats = to_thrift(Some(&stats));+ assert_eq!(from_thrift(tpe, thrift_stats), Some(stats));+ }++ check_stats(Statistics::boolean(Some(false), Some(true), None, 7, true));+ check_stats(Statistics::boolean(Some(false), Some(true), None, 7, true));+ check_stats(Statistics::boolean(Some(false), Some(true), None, 0, false));+ check_stats(Statistics::boolean(Some(true), Some(true), None, 7, true));+ check_stats(Statistics::boolean(Some(false), Some(false), None, 7, true));+ check_stats(Statistics::boolean(None, None, None, 7, true));++ check_stats(Statistics::int32(Some(-100), Some(500), None, 7, true));+ check_stats(Statistics::int32(Some(-100), Some(500), None, 0, false));+ check_stats(Statistics::int32(None, None, None, 7, true));++ check_stats(Statistics::int64(Some(-100), Some(200), None, 7, true));+ check_stats(Statistics::int64(Some(-100), Some(200), None, 0, false));+ check_stats(Statistics::int64(None, None, None, 7, true));++ check_stats(Statistics::float(Some(1.2), Some(3.4), None, 7, true));+ check_stats(Statistics::float(Some(1.2), Some(3.4), None, 0, false));+ check_stats(Statistics::float(None, None, None, 7, true));++ check_stats(Statistics::double(Some(1.2), Some(3.4), None, 7, true));+ check_stats(Statistics::double(Some(1.2), Some(3.4), None, 0, false));+ check_stats(Statistics::double(None, None, None, 7, true));++ check_stats(Statistics::byte_array(+ Some(ByteArray::from(vec![1, 2, 3])),+ Some(ByteArray::from(vec![3, 4, 5])),+ None,+ 7,+ true,+ ));+ check_stats(Statistics::byte_array(None, None, None, 7, true));++ check_stats(Statistics::fixed_len_byte_array(+ Some(ByteArray::from(vec![1, 2, 3])),+ Some(ByteArray::from(vec![3, 4, 5])),+ None,+ 7,+ true,+ ));+ check_stats(Statistics::fixed_len_byte_array(None, None, None, 7, true));+ }+}diff --git a/rust/src/parquet/file/writer.rs b/rust/src/parquet/file/writer.rsnew file mode 100644index 0000000000..1e0c11641f--- /dev/null+++ b/rust/src/parquet/file/writer.rs@@ -0,0 +1,936 @@+// 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.++//! Contains file writer API, and provides methods to write row groups and columns by+//! using row group writers and column writers respectively.++use std::{+ fs::File,+ io::{Seek, SeekFrom, Write},+ rc::Rc,+};++use byteorder::{ByteOrder, LittleEndian};+use parquet_format as parquet;+use thrift::protocol::{TCompactOutputProtocol, TOutputProtocol};++use crate::parquet::basic::PageType;+use crate::parquet::column::{+ page::{CompressedPage, Page, PageWriteSpec, PageWriter},+ writer::{get_column_writer, ColumnWriter},+};+use crate::parquet::errors::{ParquetError, Result};+use crate::parquet::file::{+ metadata::*, properties::WriterPropertiesPtr, statistics::to_thrift as statistics_to_thrift,+ FOOTER_SIZE, PARQUET_MAGIC,+};+use crate::parquet::schema::types::{self, SchemaDescPtr, SchemaDescriptor, TypePtr};+use crate::parquet::util::io::{FileSink, Position};++// ----------------------------------------------------------------------+// APIs for file & row group writers++/// Parquet file writer API.+/// Provides methods to write row groups sequentially.+///+/// The main workflow should be as following:+/// - Create file writer, this will open a new file and potentially write some metadata.+/// - Request a new row group writer by calling `next_row_group`.+/// - Once finished writing row group, close row group writer by passing it into+/// `close_row_group` method - this will finalise row group metadata and update metrics.+/// - Write subsequent row groups, if necessary.+/// - After all row groups have been written, close the file writer using `close` method.+pub trait FileWriter {+ /// Creates new row group from this file writer.+ /// In case of IO error or Thrift error, returns `Err`.+ ///+ /// There is no limit on a number of row groups in a file; however, row groups have+ /// to be written sequentially. Every time the next row group is requested, the+ /// previous row group must be finalised and closed using `close_row_group` method.+ fn next_row_group(&mut self) -> Result<Box<RowGroupWriter>>;++ /// Finalises and closes row group that was created using `next_row_group` method.+ /// After calling this method, the next row group is available for writes.+ fn close_row_group(&mut self, row_group_writer: Box<RowGroupWriter>) -> Result<()>;++ /// Closes and finalises file writer.+ ///+ /// All row groups must be appended before this method is called.+ /// No writes are allowed after this point.+ ///+ /// Can be called multiple times. It is up to implementation to either result in no-op,+ /// or return an `Err` for subsequent calls.+ fn close(&mut self) -> Result<()>;+}++/// Parquet row group writer API.+/// Provides methods to access column writers in an iterator-like fashion, order is+/// guaranteed to match the order of schema leaves (column descriptors).+///+/// All columns should be written sequentially; the main workflow is:+/// - Request the next column using `next_column` method - this will return `None` if no+/// more columns are available to write.+/// - Once done writing a column, close column writer with `close_column` method - this+/// will finalise column chunk metadata and update row group metrics.+/// - Once all columns have been written, close row group writer with `close` method -+/// it will return row group metadata and is no-op on already closed row group.+pub trait RowGroupWriter {+ /// Returns the next column writer, if available; otherwise returns `None`.+ /// In case of any IO error or Thrift error, or if row group writer has already been+ /// closed returns `Err`.+ ///+ /// To request the next column writer, the previous one must be finalised and closed+ /// using `close_column`.+ fn next_column(&mut self) -> Result<Option<ColumnWriter>>;++ /// Closes column writer that was created using `next_column` method.+ /// This should be called before requesting the next column writer.+ fn close_column(&mut self, column_writer: ColumnWriter) -> Result<()>;++ /// Closes this row group writer and returns row group metadata.+ /// After calling this method row group writer must not be used.+ ///+ /// It is recommended to call this method before requesting another row group, but it+ /// will be closed automatically before returning a new row group.+ ///+ /// Can be called multiple times. In subsequent calls will result in no-op and return+ /// already created row group metadata.+ fn close(&mut self) -> Result<RowGroupMetaDataPtr>;+}++// ----------------------------------------------------------------------+// Serialized impl for file & row group writers++/// A serialized implementation for Parquet [`FileWriter`].+/// See documentation on file writer for more information.+pub struct SerializedFileWriter {+ file: File,+ schema: TypePtr,+ descr: SchemaDescPtr,+ props: WriterPropertiesPtr,+ total_num_rows: u64,+ row_groups: Vec<RowGroupMetaDataPtr>,+ previous_writer_closed: bool,+ is_closed: bool,+}++impl SerializedFileWriter {+ /// Creates new file writer.+ pub fn new(mut file: File, schema: TypePtr, properties: WriterPropertiesPtr) -> Result<Self> {+ Self::start_file(&mut file)?;+ Ok(Self {+ file,+ schema: schema.clone(),+ descr: Rc::new(SchemaDescriptor::new(schema)),+ props: properties,+ total_num_rows: 0,+ row_groups: Vec::new(),+ previous_writer_closed: true,+ is_closed: false,+ })+ }++ /// Writes magic bytes at the beginning of the file.+ fn start_file(file: &mut File) -> Result<()> {+ file.write(&PARQUET_MAGIC)?;+ Ok(())+ }++ /// Finalises active row group writer, otherwise no-op.+ fn finalise_row_group_writer(+ &mut self,+ mut row_group_writer: Box<RowGroupWriter>,+ ) -> Result<()> {+ let row_group_metadata = row_group_writer.close()?;+ self.row_groups.push(row_group_metadata);+ Ok(())+ }++ /// Assembles and writes metadata at the end of the file.+ fn write_metadata(&mut self) -> Result<()> {+ let file_metadata = parquet::FileMetaData {+ version: self.props.writer_version().as_num(),+ schema: types::to_thrift(self.schema.as_ref())?,+ num_rows: self.total_num_rows as i64,+ row_groups: self+ .row_groups+ .as_slice()+ .into_iter()+ .map(|v| v.to_thrift())+ .collect(),+ key_value_metadata: None,+ created_by: Some(self.props.created_by().to_owned()),+ column_orders: None,+ };++ // Write file metadata+ let start_pos = self.file.seek(SeekFrom::Current(0))?;+ {+ let mut protocol = TCompactOutputProtocol::new(&mut self.file);+ file_metadata.write_to_out_protocol(&mut protocol)?;+ protocol.flush()?;+ }+ let end_pos = self.file.seek(SeekFrom::Current(0))?;++ // Write footer+ let mut footer_buffer: [u8; FOOTER_SIZE] = [0; FOOTER_SIZE];+ let metadata_len = (end_pos - start_pos) as i32;+ LittleEndian::write_i32(&mut footer_buffer, metadata_len);+ (&mut footer_buffer[4..]).write(&PARQUET_MAGIC)?;+ self.file.write(&footer_buffer)?;+ Ok(())+ }++ #[inline]+ fn assert_closed(&self) -> Result<()> {+ if self.is_closed {+ Err(general_err!("File writer is closed"))+ } else {+ Ok(())+ }+ }++ #[inline]+ fn assert_previous_writer_closed(&self) -> Result<()> {+ if !self.previous_writer_closed {+ Err(general_err!("Previous row group writer was not closed"))+ } else {+ Ok(())+ }+ }+}++impl FileWriter for SerializedFileWriter {+ #[inline]+ fn next_row_group(&mut self) -> Result<Box<RowGroupWriter>> {+ self.assert_closed()?;+ self.assert_previous_writer_closed()?;+ let row_group_writer =+ SerializedRowGroupWriter::new(self.descr.clone(), self.props.clone(), &self.file);+ self.previous_writer_closed = false;+ Ok(Box::new(row_group_writer))+ }++ #[inline]+ fn close_row_group(&mut self, row_group_writer: Box<RowGroupWriter>) -> Result<()> {+ self.assert_closed()?;+ let res = self.finalise_row_group_writer(row_group_writer);+ self.previous_writer_closed = res.is_ok();+ res+ }++ #[inline]+ fn close(&mut self) -> Result<()> {+ self.assert_closed()?;+ self.assert_previous_writer_closed()?;+ self.write_metadata()?;+ self.is_closed = true;+ Ok(())+ }+}++/// A serialized implementation for Parquet [`RowGroupWriter`].+/// Coordinates writing of a row group with column writers.+/// See documentation on row group writer for more information.+pub struct SerializedRowGroupWriter {+ descr: SchemaDescPtr,+ props: WriterPropertiesPtr,+ file: File,+ total_rows_written: Option<u64>,+ total_bytes_written: u64,+ column_index: usize,+ previous_writer_closed: bool,+ row_group_metadata: Option<RowGroupMetaDataPtr>,+ column_chunks: Vec<ColumnChunkMetaDataPtr>,+}++impl SerializedRowGroupWriter {+ pub fn new(schema_descr: SchemaDescPtr, properties: WriterPropertiesPtr, file: &File) -> Self {+ let num_columns = schema_descr.num_columns();+ Self {+ descr: schema_descr,+ props: properties,+ file: file.try_clone().unwrap(),+ total_rows_written: None,+ total_bytes_written: 0,+ column_index: 0,+ previous_writer_closed: true,+ row_group_metadata: None,+ column_chunks: Vec::with_capacity(num_columns),+ }+ }++ /// Checks and finalises current column writer.+ fn finalise_column_writer(&mut self, writer: ColumnWriter) -> Result<()> {+ let (bytes_written, rows_written, metadata) = match writer {+ ColumnWriter::BoolColumnWriter(typed) => typed.close()?,+ ColumnWriter::Int32ColumnWriter(typed) => typed.close()?,+ ColumnWriter::Int64ColumnWriter(typed) => typed.close()?,+ ColumnWriter::Int96ColumnWriter(typed) => typed.close()?,+ ColumnWriter::FloatColumnWriter(typed) => typed.close()?,+ ColumnWriter::DoubleColumnWriter(typed) => typed.close()?,+ ColumnWriter::ByteArrayColumnWriter(typed) => typed.close()?,+ ColumnWriter::FixedLenByteArrayColumnWriter(typed) => typed.close()?,+ };++ // Update row group writer metrics+ self.total_bytes_written += bytes_written;+ self.column_chunks.push(Rc::new(metadata));+ if let Some(rows) = self.total_rows_written {+ if rows != rows_written {+ return Err(general_err!(+ "Incorrect number of rows, expected {} != {} rows",+ rows,+ rows_written+ ));+ }+ } else {+ self.total_rows_written = Some(rows_written);+ }++ Ok(())+ }++ #[inline]+ fn assert_closed(&self) -> Result<()> {+ if self.row_group_metadata.is_some() {+ Err(general_err!("Row group writer is closed"))+ } else {+ Ok(())+ }+ }++ #[inline]+ fn assert_previous_writer_closed(&self) -> Result<()> {+ if !self.previous_writer_closed {+ Err(general_err!("Previous column writer was not closed"))+ } else {+ Ok(())+ }+ }+}++impl RowGroupWriter for SerializedRowGroupWriter {+ #[inline]+ fn next_column(&mut self) -> Result<Option<ColumnWriter>> {+ self.assert_closed()?;+ self.assert_previous_writer_closed()?;++ if self.column_index >= self.descr.num_columns() {+ return Ok(None);+ }+ let sink = FileSink::new(&self.file);+ let page_writer = Box::new(SerializedPageWriter::new(sink));+ let column_writer = get_column_writer(+ self.descr.column(self.column_index),+ self.props.clone(),+ page_writer,+ );+ self.column_index += 1;+ self.previous_writer_closed = false;++ Ok(Some(column_writer))+ }++ #[inline]+ fn close_column(&mut self, column_writer: ColumnWriter) -> Result<()> {+ let res = self.finalise_column_writer(column_writer);+ self.previous_writer_closed = res.is_ok();+ res+ }++ #[inline]+ fn close(&mut self) -> Result<RowGroupMetaDataPtr> {+ if self.row_group_metadata.is_none() {+ self.assert_previous_writer_closed()?;++ let row_group_metadata = RowGroupMetaData::builder(self.descr.clone())+ .set_column_metadata(self.column_chunks.clone())+ .set_total_byte_size(self.total_bytes_written as i64)+ .set_num_rows(self.total_rows_written.unwrap_or(0) as i64)+ .build()?;++ self.row_group_metadata = Some(Rc::new(row_group_metadata));+ }++ let metadata = self.row_group_metadata.as_ref().unwrap().clone();+ Ok(metadata)+ }+}++/// A serialized implementation for Parquet [`PageWriter`].+/// Writes and serializes pages and metadata into output stream.+///+/// `SerializedPageWriter` should not be used after calling `close()`.+pub struct SerializedPageWriter<T: Write + Position> {+ sink: T,+}++impl<T: Write + Position> SerializedPageWriter<T> {+ /// Creates new page writer.+ pub fn new(sink: T) -> Self {+ Self { sink }+ }++ /// Serializes page header into Thrift.+ /// Returns number of bytes that have been written into the sink.+ #[inline]+ fn serialize_page_header(&mut self, header: parquet::PageHeader) -> Result<usize> {+ let start_pos = self.sink.pos();+ {+ let mut protocol = TCompactOutputProtocol::new(&mut self.sink);+ header.write_to_out_protocol(&mut protocol)?;+ protocol.flush()?;+ }+ Ok((self.sink.pos() - start_pos) as usize)+ }++ /// Serializes column chunk into Thrift.+ /// Returns Ok() if there are not errors serializing and writing data into the sink.+ #[inline]+ fn serialize_column_chunk(&mut self, chunk: parquet::ColumnChunk) -> Result<()> {+ let mut protocol = TCompactOutputProtocol::new(&mut self.sink);+ chunk.write_to_out_protocol(&mut protocol)?;+ protocol.flush()?;+ Ok(())+ }+}++impl<T: Write + Position> PageWriter for SerializedPageWriter<T> {+ fn write_page(&mut self, page: CompressedPage) -> Result<PageWriteSpec> {+ let uncompressed_size = page.uncompressed_size();+ let compressed_size = page.compressed_size();+ let num_values = page.num_values();+ let encoding = page.encoding();+ let page_type = page.page_type();++ let mut page_header = parquet::PageHeader {+ type_: page_type.into(),+ uncompressed_page_size: uncompressed_size as i32,+ compressed_page_size: compressed_size as i32,+ // TODO: Add support for crc checksum+ crc: None,+ data_page_header: None,+ index_page_header: None,+ dictionary_page_header: None,+ data_page_header_v2: None,+ };++ match page.compressed_page() {+ &Page::DataPage {+ def_level_encoding,+ rep_level_encoding,+ ref statistics,+ ..+ } => {+ let data_page_header = parquet::DataPageHeader {+ num_values: num_values as i32,+ encoding: encoding.into(),+ definition_level_encoding: def_level_encoding.into(),+ repetition_level_encoding: rep_level_encoding.into(),+ statistics: statistics_to_thrift(statistics.as_ref()),+ };+ page_header.data_page_header = Some(data_page_header);+ }+ &Page::DataPageV2 {+ num_nulls,+ num_rows,+ def_levels_byte_len,+ rep_levels_byte_len,+ is_compressed,+ ref statistics,+ ..+ } => {+ let data_page_header_v2 = parquet::DataPageHeaderV2 {+ num_values: num_values as i32,+ num_nulls: num_nulls as i32,+ num_rows: num_rows as i32,+ encoding: encoding.into(),+ definition_levels_byte_length: def_levels_byte_len as i32,+ repetition_levels_byte_length: rep_levels_byte_len as i32,+ is_compressed: Some(is_compressed),+ statistics: statistics_to_thrift(statistics.as_ref()),+ };+ page_header.data_page_header_v2 = Some(data_page_header_v2);+ }+ &Page::DictionaryPage { is_sorted, .. } => {+ let dictionary_page_header = parquet::DictionaryPageHeader {+ num_values: num_values as i32,+ encoding: encoding.into(),+ is_sorted: Some(is_sorted),+ };+ page_header.dictionary_page_header = Some(dictionary_page_header);+ }+ }++ let start_pos = self.sink.pos();++ let header_size = self.serialize_page_header(page_header)?;+ self.sink.write_all(page.data())?;++ let mut spec = PageWriteSpec::new();+ spec.page_type = page_type;+ spec.uncompressed_size = uncompressed_size + header_size;+ spec.compressed_size = compressed_size + header_size;+ spec.offset = start_pos;+ spec.bytes_written = self.sink.pos() - start_pos;+ // Number of values is incremented for data pages only+ if page_type == PageType::DATA_PAGE || page_type == PageType::DATA_PAGE_V2 {+ spec.num_values = num_values;+ }++ Ok(spec)+ }++ fn write_metadata(&mut self, metadata: &ColumnChunkMetaData) -> Result<()> {+ self.serialize_column_chunk(metadata.to_thrift())+ }++ fn close(&mut self) -> Result<()> {+ self.sink.flush()?;+ Ok(())+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ use std::{error::Error, io::Cursor};++ use crate::parquet::basic::{Compression, Encoding, Repetition, Type};+ use crate::parquet::column::page::PageReader;+ use crate::parquet::compression::{create_codec, Codec};+ use crate::parquet::file::{+ properties::WriterProperties,+ reader::{FileReader, SerializedFileReader, SerializedPageReader},+ statistics::{from_thrift, to_thrift, Statistics},+ };+ use crate::parquet::record::RowAccessor;+ use crate::parquet::util::{memory::ByteBufferPtr, test_common::get_temp_file};++ #[test]+ fn test_file_writer_error_after_close() {+ let file = get_temp_file("test_file_writer_error_after_close", &[]);+ let schema = Rc::new(types::Type::group_type_builder("schema").build().unwrap());+ let props = Rc::new(WriterProperties::builder().build());+ let mut writer = SerializedFileWriter::new(file, schema, props).unwrap();+ writer.close().unwrap();+ {+ let res = writer.next_row_group();+ assert!(res.is_err());+ if let Err(err) = res {+ assert_eq!(err.description(), "File writer is closed");+ }+ }+ {+ let res = writer.close();+ assert!(res.is_err());+ if let Err(err) = res {+ assert_eq!(err.description(), "File writer is closed");+ }+ }+ }++ #[test]+ fn test_row_group_writer_error_after_close() {+ let file = get_temp_file("test_file_writer_row_group_error_after_close", &[]);+ let schema = Rc::new(types::Type::group_type_builder("schema").build().unwrap());+ let props = Rc::new(WriterProperties::builder().build());+ let mut writer = SerializedFileWriter::new(file, schema, props).unwrap();+ let mut row_group_writer = writer.next_row_group().unwrap();+ row_group_writer.close().unwrap();++ let res = row_group_writer.next_column();+ assert!(res.is_err());+ if let Err(err) = res {+ assert_eq!(err.description(), "Row group writer is closed");+ }+ }++ #[test]+ fn test_row_group_writer_error_not_all_columns_written() {+ let file = get_temp_file("test_row_group_writer_error_not_all_columns_written", &[]);+ let schema = Rc::new(+ types::Type::group_type_builder("schema")+ .with_fields(&mut vec![Rc::new(+ types::Type::primitive_type_builder("col1", Type::INT32)+ .build()+ .unwrap(),+ )])+ .build()+ .unwrap(),+ );+ let props = Rc::new(WriterProperties::builder().build());+ let mut writer = SerializedFileWriter::new(file, schema, props).unwrap();+ let mut row_group_writer = writer.next_row_group().unwrap();+ let res = row_group_writer.close();+ assert!(res.is_err());+ if let Err(err) = res {+ assert_eq!(err.description(), "Column length mismatch: 1 != 0");+ }+ }++ #[test]+ fn test_row_group_writer_num_records_mismatch() {+ let file = get_temp_file("test_row_group_writer_num_records_mismatch", &[]);+ let schema = Rc::new(+ types::Type::group_type_builder("schema")+ .with_fields(&mut vec![+ Rc::new(+ types::Type::primitive_type_builder("col1", Type::INT32)+ .with_repetition(Repetition::REQUIRED)+ .build()+ .unwrap(),+ ),+ Rc::new(+ types::Type::primitive_type_builder("col2", Type::INT32)+ .with_repetition(Repetition::REQUIRED)+ .build()+ .unwrap(),+ ),+ ])+ .build()+ .unwrap(),+ );+ let props = Rc::new(WriterProperties::builder().build());+ let mut writer = SerializedFileWriter::new(file, schema, props).unwrap();+ let mut row_group_writer = writer.next_row_group().unwrap();++ let mut col_writer = row_group_writer.next_column().unwrap().unwrap();+ if let ColumnWriter::Int32ColumnWriter(ref mut typed) = col_writer {+ typed.write_batch(&[1, 2, 3], None, None).unwrap();+ }+ row_group_writer.close_column(col_writer).unwrap();++ let mut col_writer = row_group_writer.next_column().unwrap().unwrap();+ if let ColumnWriter::Int32ColumnWriter(ref mut typed) = col_writer {+ typed.write_batch(&[1, 2], None, None).unwrap();+ }++ let res = row_group_writer.close_column(col_writer);+ assert!(res.is_err());+ if let Err(err) = res {+ assert_eq!(+ err.description(),+ "Incorrect number of rows, expected 3 != 2 rows"+ );+ }+ }++ #[test]+ fn test_file_writer_empty_file() {+ let file = get_temp_file("test_file_writer_write_empty_file", &[]);++ let schema = Rc::new(+ types::Type::group_type_builder("schema")+ .with_fields(&mut vec![Rc::new(+ types::Type::primitive_type_builder("col1", Type::INT32)+ .build()+ .unwrap(),+ )])+ .build()+ .unwrap(),+ );+ let props = Rc::new(WriterProperties::builder().build());+ let mut writer =+ SerializedFileWriter::new(file.try_clone().unwrap(), schema, props).unwrap();+ writer.close().unwrap();++ let reader = SerializedFileReader::new(file).unwrap();+ assert_eq!(reader.get_row_iter(None).unwrap().count(), 0);+ }++ #[test]+ fn test_file_writer_empty_row_groups() {+ let file = get_temp_file("test_file_writer_write_empty_row_groups", &[]);+ test_file_roundtrip(file, vec![]);+ }++ #[test]+ fn test_file_writer_single_row_group() {+ let file = get_temp_file("test_file_writer_write_single_row_group", &[]);+ test_file_roundtrip(file, vec![vec![1, 2, 3, 4, 5]]);+ }++ #[test]+ fn test_file_writer_multiple_row_groups() {+ let file = get_temp_file("test_file_writer_write_multiple_row_groups", &[]);+ test_file_roundtrip(+ file,+ vec![+ vec![1, 2, 3, 4, 5],+ vec![1, 2, 3],+ vec![1],+ vec![1, 2, 3, 4, 5, 6],+ ],+ );+ }++ #[test]+ fn test_file_writer_multiple_large_row_groups() {+ let file = get_temp_file("test_file_writer_multiple_large_row_groups", &[]);+ test_file_roundtrip(+ file,+ vec![vec![123; 1024], vec![124; 1000], vec![125; 15], vec![]],+ );+ }++ #[test]+ fn test_page_writer_data_pages() {+ let pages = vec![+ Page::DataPage {+ buf: ByteBufferPtr::new(vec![1, 2, 3, 4, 5, 6, 7, 8]),+ num_values: 10,+ encoding: Encoding::DELTA_BINARY_PACKED,+ def_level_encoding: Encoding::RLE,+ rep_level_encoding: Encoding::RLE,+ statistics: Some(Statistics::int32(Some(1), Some(3), None, 7, true)),+ },+ Page::DataPageV2 {+ buf: ByteBufferPtr::new(vec![4; 128]),+ num_values: 10,+ encoding: Encoding::DELTA_BINARY_PACKED,+ num_nulls: 2,+ num_rows: 12,+ def_levels_byte_len: 24,+ rep_levels_byte_len: 32,+ is_compressed: false,+ statistics: Some(Statistics::int32(Some(1), Some(3), None, 7, true)),+ },+ ];++ test_page_roundtrip(&pages[..], Compression::SNAPPY, Type::INT32);+ test_page_roundtrip(&pages[..], Compression::UNCOMPRESSED, Type::INT32);+ }++ #[test]+ fn test_page_writer_dict_pages() {+ let pages = vec![+ Page::DictionaryPage {+ buf: ByteBufferPtr::new(vec![1, 2, 3, 4, 5]),+ num_values: 5,+ encoding: Encoding::RLE_DICTIONARY,+ is_sorted: false,+ },+ Page::DataPage {+ buf: ByteBufferPtr::new(vec![1, 2, 3, 4, 5, 6, 7, 8]),+ num_values: 10,+ encoding: Encoding::DELTA_BINARY_PACKED,+ def_level_encoding: Encoding::RLE,+ rep_level_encoding: Encoding::RLE,+ statistics: Some(Statistics::int32(Some(1), Some(3), None, 7, true)),+ },+ Page::DataPageV2 {+ buf: ByteBufferPtr::new(vec![4; 128]),+ num_values: 10,+ encoding: Encoding::DELTA_BINARY_PACKED,+ num_nulls: 2,+ num_rows: 12,+ def_levels_byte_len: 24,+ rep_levels_byte_len: 32,+ is_compressed: false,+ statistics: None,+ },+ ];++ test_page_roundtrip(&pages[..], Compression::SNAPPY, Type::INT32);+ test_page_roundtrip(&pages[..], Compression::UNCOMPRESSED, Type::INT32);+ }++ /// Tests writing and reading pages.+ /// Physical type is for statistics only, should match any defined statistics type in+ /// pages.+ fn test_page_roundtrip(pages: &[Page], codec: Compression, physical_type: Type) {+ let mut compressed_pages = vec![];+ let mut total_num_values = 0i64;+ let mut compressor = create_codec(codec).unwrap();++ for page in pages {+ let uncompressed_len = page.buffer().len();++ let compressed_page = match page {+ &Page::DataPage {+ ref buf,+ num_values,+ encoding,+ def_level_encoding,+ rep_level_encoding,+ ref statistics,+ } => {+ total_num_values += num_values as i64;+ let output_buf = compress_helper(compressor.as_mut(), buf.data());++ Page::DataPage {+ buf: ByteBufferPtr::new(output_buf),+ num_values,+ encoding,+ def_level_encoding,+ rep_level_encoding,+ statistics: from_thrift(physical_type, to_thrift(statistics.as_ref())),+ }+ }+ &Page::DataPageV2 {+ ref buf,+ num_values,+ encoding,+ num_nulls,+ num_rows,+ def_levels_byte_len,+ rep_levels_byte_len,+ ref statistics,+ ..+ } => {+ total_num_values += num_values as i64;+ let offset = (def_levels_byte_len + rep_levels_byte_len) as usize;+ let cmp_buf = compress_helper(compressor.as_mut(), &buf.data()[offset..]);+ let mut output_buf = Vec::from(&buf.data()[..offset]);+ output_buf.extend_from_slice(&cmp_buf[..]);++ Page::DataPageV2 {+ buf: ByteBufferPtr::new(output_buf),+ num_values,+ encoding,+ num_nulls,+ num_rows,+ def_levels_byte_len,+ rep_levels_byte_len,+ is_compressed: compressor.is_some(),+ statistics: from_thrift(physical_type, to_thrift(statistics.as_ref())),+ }+ }+ &Page::DictionaryPage {+ ref buf,+ num_values,+ encoding,+ is_sorted,+ } => {+ let output_buf = compress_helper(compressor.as_mut(), buf.data());++ Page::DictionaryPage {+ buf: ByteBufferPtr::new(output_buf),+ num_values,+ encoding,+ is_sorted,+ }+ }+ };++ let compressed_page = CompressedPage::new(compressed_page, uncompressed_len);+ compressed_pages.push(compressed_page);+ }++ let mut buffer: Vec<u8> = vec![];+ let mut result_pages: Vec<Page> = vec![];+ {+ let cursor = Cursor::new(&mut buffer);+ let mut page_writer = SerializedPageWriter::new(cursor);++ for page in compressed_pages {+ page_writer.write_page(page).unwrap();+ }+ page_writer.close().unwrap();+ }+ {+ let mut page_reader = SerializedPageReader::new(+ Cursor::new(&buffer),+ total_num_values,+ codec,+ physical_type,+ )+ .unwrap();++ while let Some(page) = page_reader.get_next_page().unwrap() {+ result_pages.push(page);+ }+ }++ assert_eq!(result_pages.len(), pages.len());+ for i in 0..result_pages.len() {+ assert_page(&result_pages[i], &pages[i]);+ }+ }++ /// Helper function to compress a slice+ fn compress_helper(compressor: Option<&mut Box<Codec>>, data: &[u8]) -> Vec<u8> {+ let mut output_buf = vec![];+ if let Some(cmpr) = compressor {+ cmpr.compress(data, &mut output_buf).unwrap();+ } else {+ output_buf.extend_from_slice(data);+ }+ output_buf+ }++ /// Check if pages match.+ fn assert_page(left: &Page, right: &Page) {+ assert_eq!(left.page_type(), right.page_type());+ assert_eq!(left.buffer().data(), right.buffer().data());+ assert_eq!(left.num_values(), right.num_values());+ assert_eq!(left.encoding(), right.encoding());+ assert_eq!(to_thrift(left.statistics()), to_thrift(right.statistics()));+ }++ /// File write-read roundtrip.+ /// `data` consists of arrays of values for each row group.+ fn test_file_roundtrip(file: File, data: Vec<Vec<i32>>) {+ let schema = Rc::new(+ types::Type::group_type_builder("schema")+ .with_fields(&mut vec![Rc::new(+ types::Type::primitive_type_builder("col1", Type::INT32)+ .with_repetition(Repetition::REQUIRED)+ .build()+ .unwrap(),+ )])+ .build()+ .unwrap(),+ );+ let props = Rc::new(WriterProperties::builder().build());+ let mut file_writer =+ SerializedFileWriter::new(file.try_clone().unwrap(), schema, props).unwrap();++ for subset in &data {+ let mut row_group_writer = file_writer.next_row_group().unwrap();+ let col_writer = row_group_writer.next_column().unwrap();+ if let Some(mut writer) = col_writer {+ match writer {+ ColumnWriter::Int32ColumnWriter(ref mut typed) => {+ typed.write_batch(&subset[..], None, None).unwrap();+ }+ _ => {+ unimplemented!();+ }+ }+ row_group_writer.close_column(writer).unwrap();+ }+ file_writer.close_row_group(row_group_writer).unwrap();+ }++ file_writer.close().unwrap();++ let reader = SerializedFileReader::new(file).unwrap();+ assert_eq!(reader.num_row_groups(), data.len());+ for i in 0..reader.num_row_groups() {+ let row_group_reader = reader.get_row_group(i).unwrap();+ let iter = row_group_reader.get_row_iter(None).unwrap();+ let res = iter+ .map(|elem| elem.get_int(0).unwrap())+ .collect::<Vec<i32>>();+ assert_eq!(res, data[i]);+ }+ }+}diff --git a/rust/src/parquet/mod.rs b/rust/src/parquet/mod.rsnew file mode 100644index 0000000000..58cc7b13df--- /dev/null+++ b/rust/src/parquet/mod.rs@@ -0,0 +1,34 @@+// 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]+pub mod errors;+pub mod basic;+pub mod data_type;++// Exported for external use, such as benchmarks+pub use self::encodings::{decoding, encoding};+pub use self::util::memory;++#[macro_use]+mod util;+pub mod column;+pub mod compression;+mod encodings;+pub mod file;+pub mod record;+pub mod schema;diff --git a/rust/src/parquet/record/api.rs b/rust/src/parquet/record/api.rsnew file mode 100644index 0000000000..d6e3ec19b7--- /dev/null+++ b/rust/src/parquet/record/api.rs@@ -0,0 +1,1439 @@+// 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.++//! Contains Row enum that is used to represent record in Rust.++use std::fmt;++use chrono::{Local, TimeZone};+use num_bigint::{BigInt, Sign};++use crate::parquet::basic::{LogicalType, Type as PhysicalType};+use crate::parquet::data_type::{ByteArray, Decimal, Int96};+use crate::parquet::errors::{ParquetError, Result};+use crate::parquet::schema::types::ColumnDescPtr;++/// Macro as a shortcut to generate 'not yet implemented' panic error.+macro_rules! nyi {+ ($column_descr:ident, $value:ident) => {{+ unimplemented!(+ "Conversion for physical type {}, logical type {}, value {:?}",+ $column_descr.physical_type(),+ $column_descr.logical_type(),+ $value+ );+ }};+}++/// `Row` represents a nested Parquet record.+#[derive(Clone, Debug, PartialEq)]+pub struct Row {+ fields: Vec<(String, Field)>,+}++impl Row {+ /// Get the number of fields in this row.+ pub fn len(&self) -> usize {+ self.fields.len()+ }+}++/// Trait for type-safe convenient access to fields within a Row.+pub trait RowAccessor {+ fn get_bool(&self, i: usize) -> Result<bool>;+ fn get_byte(&self, i: usize) -> Result<i8>;+ fn get_short(&self, i: usize) -> Result<i16>;+ fn get_int(&self, i: usize) -> Result<i32>;+ fn get_long(&self, i: usize) -> Result<i64>;+ fn get_ubyte(&self, i: usize) -> Result<u8>;+ fn get_ushort(&self, i: usize) -> Result<u16>;+ fn get_uint(&self, i: usize) -> Result<u32>;+ fn get_ulong(&self, i: usize) -> Result<u64>;+ fn get_float(&self, i: usize) -> Result<f32>;+ fn get_double(&self, i: usize) -> Result<f64>;+ fn get_timestamp(&self, i: usize) -> Result<u64>;+ fn get_decimal(&self, i: usize) -> Result<&Decimal>;+ fn get_string(&self, i: usize) -> Result<&String>;+ fn get_bytes(&self, i: usize) -> Result<&ByteArray>;+ fn get_group(&self, i: usize) -> Result<&Row>;+ fn get_list(&self, i: usize) -> Result<&List>;+ fn get_map(&self, i: usize) -> Result<&Map>;+}++/// Macro to generate type-safe get_xxx methods for primitive types,+/// e.g. `get_bool`, `get_short`.+macro_rules! row_primitive_accessor {+ ($METHOD:ident, $VARIANT:ident, $TY:ty) => {+ fn $METHOD(&self, i: usize) -> Result<$TY> {+ match self.fields[i].1 {+ Field::$VARIANT(v) => Ok(v),+ _ => Err(general_err!("Cannot access {} as {}",+ self.fields[i].1.get_type_name(), stringify!($VARIANT)))+ }+ }+ }+}++/// Macro to generate type-safe get_xxx methods for reference types,+/// e.g. `get_list`, `get_map`.+macro_rules! row_complex_accessor {+ ($METHOD:ident, $VARIANT:ident, $TY:ty) => {+ fn $METHOD(&self, i: usize) -> Result<&$TY> {+ match self.fields[i].1 {+ Field::$VARIANT(ref v) => Ok(v),+ _ => Err(general_err!("Cannot access {} as {}",+ self.fields[i].1.get_type_name(), stringify!($VARIANT)))+ }+ }+ }+}++impl RowAccessor for Row {+ row_primitive_accessor!(get_bool, Bool, bool);++ row_primitive_accessor!(get_byte, Byte, i8);++ row_primitive_accessor!(get_short, Short, i16);++ row_primitive_accessor!(get_int, Int, i32);++ row_primitive_accessor!(get_long, Long, i64);++ row_primitive_accessor!(get_ubyte, UByte, u8);++ row_primitive_accessor!(get_ushort, UShort, u16);++ row_primitive_accessor!(get_uint, UInt, u32);++ row_primitive_accessor!(get_ulong, ULong, u64);++ row_primitive_accessor!(get_float, Float, f32);++ row_primitive_accessor!(get_double, Double, f64);++ row_primitive_accessor!(get_timestamp, Timestamp, u64);++ row_complex_accessor!(get_decimal, Decimal, Decimal);++ row_complex_accessor!(get_string, Str, String);++ row_complex_accessor!(get_bytes, Bytes, ByteArray);++ row_complex_accessor!(get_group, Group, Row);++ row_complex_accessor!(get_list, ListInternal, List);++ row_complex_accessor!(get_map, MapInternal, Map);+}++/// Constructs a `Row` from the list of `fields` and returns it.+#[inline]+pub fn make_row(fields: Vec<(String, Field)>) -> Row {+ Row { fields }+}++impl fmt::Display for Row {+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {+ write!(f, "{{")?;+ for (i, &(ref key, ref value)) in self.fields.iter().enumerate() {+ key.fmt(f)?;+ write!(f, ": ")?;+ value.fmt(f)?;+ if i < self.fields.len() - 1 {+ write!(f, ", ")?;+ }+ }+ write!(f, "}}")+ }+}++/// `List` represents a list which contains an array of elements.+#[derive(Clone, Debug, PartialEq)]+pub struct List {+ elements: Vec<Field>,+}++impl List {+ /// Get the number of fields in this row+ pub fn len(&self) -> usize {+ self.elements.len()+ }+}++/// Constructs a `List` from the list of `fields` and returns it.+#[inline]+pub fn make_list(elements: Vec<Field>) -> List {+ List { elements }+}++/// Trait for type-safe access of an index for a `List`.+/// Note that the get_XXX methods do not do bound checking.+pub trait ListAccessor {+ fn get_bool(&self, i: usize) -> Result<bool>;+ fn get_byte(&self, i: usize) -> Result<i8>;+ fn get_short(&self, i: usize) -> Result<i16>;+ fn get_int(&self, i: usize) -> Result<i32>;+ fn get_long(&self, i: usize) -> Result<i64>;+ fn get_ubyte(&self, i: usize) -> Result<u8>;+ fn get_ushort(&self, i: usize) -> Result<u16>;+ fn get_uint(&self, i: usize) -> Result<u32>;+ fn get_ulong(&self, i: usize) -> Result<u64>;+ fn get_float(&self, i: usize) -> Result<f32>;+ fn get_double(&self, i: usize) -> Result<f64>;+ fn get_timestamp(&self, i: usize) -> Result<u64>;+ fn get_decimal(&self, i: usize) -> Result<&Decimal>;+ fn get_string(&self, i: usize) -> Result<&String>;+ fn get_bytes(&self, i: usize) -> Result<&ByteArray>;+ fn get_group(&self, i: usize) -> Result<&Row>;+ fn get_list(&self, i: usize) -> Result<&List>;+ fn get_map(&self, i: usize) -> Result<&Map>;+}++/// Macro to generate type-safe get_xxx methods for primitive types,+/// e.g. get_bool, get_short+macro_rules! list_primitive_accessor {+ ($METHOD:ident, $VARIANT:ident, $TY:ty) => {+ fn $METHOD(&self, i: usize) -> Result<$TY> {+ match self.elements[i] {+ Field::$VARIANT(v) => Ok(v),+ _ => Err(general_err!(+ "Cannot access {} as {}",+ self.elements[i].get_type_name(), stringify!($VARIANT))+ )+ }+ }+ }+}++/// Macro to generate type-safe get_xxx methods for reference types+/// e.g. get_list, get_map+macro_rules! list_complex_accessor {+ ($METHOD:ident, $VARIANT:ident, $TY:ty) => {+ fn $METHOD(&self, i: usize) -> Result<&$TY> {+ match self.elements[i] {+ Field::$VARIANT(ref v) => Ok(v),+ _ => Err(general_err!(+ "Cannot access {} as {}",+ self.elements[i].get_type_name(), stringify!($VARIANT))+ )+ }+ }+ }+}++impl ListAccessor for List {+ list_primitive_accessor!(get_bool, Bool, bool);++ list_primitive_accessor!(get_byte, Byte, i8);++ list_primitive_accessor!(get_short, Short, i16);++ list_primitive_accessor!(get_int, Int, i32);++ list_primitive_accessor!(get_long, Long, i64);++ list_primitive_accessor!(get_ubyte, UByte, u8);++ list_primitive_accessor!(get_ushort, UShort, u16);++ list_primitive_accessor!(get_uint, UInt, u32);++ list_primitive_accessor!(get_ulong, ULong, u64);++ list_primitive_accessor!(get_float, Float, f32);++ list_primitive_accessor!(get_double, Double, f64);++ list_primitive_accessor!(get_timestamp, Timestamp, u64);++ list_complex_accessor!(get_decimal, Decimal, Decimal);++ list_complex_accessor!(get_string, Str, String);++ list_complex_accessor!(get_bytes, Bytes, ByteArray);++ list_complex_accessor!(get_group, Group, Row);++ list_complex_accessor!(get_list, ListInternal, List);++ list_complex_accessor!(get_map, MapInternal, Map);+}++/// `Map` represents a map which contains an list of key->value pairs.+#[derive(Clone, Debug, PartialEq)]+pub struct Map {+ entries: Vec<(Field, Field)>,+}++impl Map {+ /// Get the number of fields in this row+ pub fn len(&self) -> usize {+ self.entries.len()+ }+}++/// Constructs a `Map` from the list of `entries` and returns it.+#[inline]+pub fn make_map(entries: Vec<(Field, Field)>) -> Map {+ Map { entries }+}++/// Trait for type-safe access of an index for a `Map`+pub trait MapAccessor {+ fn get_keys<'a>(&'a self) -> Box<ListAccessor + 'a>;+ fn get_values<'a>(&'a self) -> Box<ListAccessor + 'a>;+}++struct MapList<'a> {+ elements: Vec<&'a Field>,+}++/// Macro to generate type-safe get_xxx methods for primitive types,+/// e.g. get_bool, get_short+macro_rules! map_list_primitive_accessor {+ ($METHOD:ident, $VARIANT:ident, $TY:ty) => {+ fn $METHOD(&self, i: usize) -> Result<$TY> {+ match self.elements[i] {+ Field::$VARIANT(v) => Ok(*v),+ _ => Err(general_err!(+ "Cannot access {} as {}",+ self.elements[i].get_type_name(), stringify!($VARIANT))+ )+ }+ }+ }+}++impl<'a> ListAccessor for MapList<'a> {+ map_list_primitive_accessor!(get_bool, Bool, bool);++ map_list_primitive_accessor!(get_byte, Byte, i8);++ map_list_primitive_accessor!(get_short, Short, i16);++ map_list_primitive_accessor!(get_int, Int, i32);++ map_list_primitive_accessor!(get_long, Long, i64);++ map_list_primitive_accessor!(get_ubyte, UByte, u8);++ map_list_primitive_accessor!(get_ushort, UShort, u16);++ map_list_primitive_accessor!(get_uint, UInt, u32);++ map_list_primitive_accessor!(get_ulong, ULong, u64);++ map_list_primitive_accessor!(get_float, Float, f32);++ map_list_primitive_accessor!(get_double, Double, f64);++ map_list_primitive_accessor!(get_timestamp, Timestamp, u64);++ list_complex_accessor!(get_decimal, Decimal, Decimal);++ list_complex_accessor!(get_string, Str, String);++ list_complex_accessor!(get_bytes, Bytes, ByteArray);++ list_complex_accessor!(get_group, Group, Row);++ list_complex_accessor!(get_list, ListInternal, List);++ list_complex_accessor!(get_map, MapInternal, Map);+}++impl MapAccessor for Map {+ fn get_keys<'a>(&'a self) -> Box<ListAccessor + 'a> {+ let map_list = MapList {+ elements: self.entries.iter().map(|v| &v.0).collect(),+ };+ Box::new(map_list)+ }++ fn get_values<'a>(&'a self) -> Box<ListAccessor + 'a> {+ let map_list = MapList {+ elements: self.entries.iter().map(|v| &v.1).collect(),+ };+ Box::new(map_list)+ }+}++/// API to represent a single field in a `Row`.+#[derive(Clone, Debug, PartialEq)]+pub enum Field {+ // Primitive types+ /// Null value.+ Null,+ /// Boolean value (`true`, `false`).+ Bool(bool),+ /// Signed integer INT_8.+ Byte(i8),+ /// Signed integer INT_16.+ Short(i16),+ /// Signed integer INT_32.+ Int(i32),+ /// Signed integer INT_64.+ Long(i64),+ // Unsigned integer UINT_8.+ UByte(u8),+ // Unsigned integer UINT_16.+ UShort(u16),+ // Unsigned integer UINT_32.+ UInt(u32),+ // Unsigned integer UINT_64.+ ULong(u64),+ /// IEEE 32-bit floating point value.+ Float(f32),+ /// IEEE 64-bit floating point value.+ Double(f64),+ /// Decimal value.+ Decimal(Decimal),+ /// UTF-8 encoded character string.+ Str(String),+ /// General binary value.+ Bytes(ByteArray),+ /// Date without a time of day, stores the number of days from the+ /// Unix epoch, 1 January 1970.+ Date(u32),+ /// Milliseconds from the Unix epoch, 1 January 1970.+ Timestamp(u64),++ // ----------------------------------------------------------------------+ // Complex types+ /// Struct, child elements are tuples of field-value pairs.+ Group(Row),+ /// List of elements.+ ListInternal(List),+ /// List of key-value pairs.+ MapInternal(Map),+}++impl Field {+ /// Get the type name.+ fn get_type_name(&self) -> &'static str {+ match *self {+ Field::Null => "Null",+ Field::Bool(_) => "Bool",+ Field::Byte(_) => "Byte",+ Field::Short(_) => "Short",+ Field::Int(_) => "Int",+ Field::Long(_) => "Long",+ Field::UByte(_) => "UByte",+ Field::UShort(_) => "UShort",+ Field::UInt(_) => "UInt",+ Field::ULong(_) => "ULong",+ Field::Float(_) => "Float",+ Field::Double(_) => "Double",+ Field::Decimal(_) => "Decimal",+ Field::Date(_) => "Date",+ Field::Str(_) => "Str",+ Field::Bytes(_) => "Bytes",+ Field::Timestamp(_) => "Timestamp",+ Field::Group(_) => "Group",+ Field::ListInternal(_) => "ListInternal",+ Field::MapInternal(_) => "MapInternal",+ }+ }++ /// Determines if this Row represents a primitive value.+ pub fn is_primitive(&self) -> bool {+ match *self {+ Field::Group(_) => false,+ Field::ListInternal(_) => false,+ Field::MapInternal(_) => false,+ _ => true,+ }+ }++ /// Converts Parquet BOOLEAN type with logical type into `bool` value.+ #[inline]+ pub fn convert_bool(_descr: &ColumnDescPtr, value: bool) -> Self {+ Field::Bool(value)+ }++ /// Converts Parquet INT32 type with logical type into `i32` value.+ #[inline]+ pub fn convert_int32(descr: &ColumnDescPtr, value: i32) -> Self {+ match descr.logical_type() {+ LogicalType::INT_8 => Field::Byte(value as i8),+ LogicalType::INT_16 => Field::Short(value as i16),+ LogicalType::INT_32 | LogicalType::NONE => Field::Int(value),+ LogicalType::UINT_8 => Field::UByte(value as u8),+ LogicalType::UINT_16 => Field::UShort(value as u16),+ LogicalType::UINT_32 => Field::UInt(value as u32),+ LogicalType::DATE => Field::Date(value as u32),+ LogicalType::DECIMAL => Field::Decimal(Decimal::from_i32(+ value,+ descr.type_precision(),+ descr.type_scale(),+ )),+ _ => nyi!(descr, value),+ }+ }++ /// Converts Parquet INT64 type with logical type into `i64` value.+ #[inline]+ pub fn convert_int64(descr: &ColumnDescPtr, value: i64) -> Self {+ match descr.logical_type() {+ LogicalType::INT_64 | LogicalType::NONE => Field::Long(value),+ LogicalType::UINT_64 => Field::ULong(value as u64),+ LogicalType::TIMESTAMP_MILLIS => Field::Timestamp(value as u64),+ LogicalType::DECIMAL => Field::Decimal(Decimal::from_i64(+ value,+ descr.type_precision(),+ descr.type_scale(),+ )),+ _ => nyi!(descr, value),+ }+ }++ /// Converts Parquet INT96 (nanosecond timestamps) type and logical type into+ /// `Timestamp` value.+ #[inline]+ pub fn convert_int96(_descr: &ColumnDescPtr, value: Int96) -> Self {+ const JULIAN_DAY_OF_EPOCH: i64 = 2_440_588;+ const SECONDS_PER_DAY: i64 = 86_400;+ const MILLIS_PER_SECOND: i64 = 1_000;++ let day = value.data()[2] as i64;+ let nanoseconds = ((value.data()[1] as i64) << 32) + value.data()[0] as i64;+ let seconds = (day - JULIAN_DAY_OF_EPOCH) * SECONDS_PER_DAY;+ let millis = seconds * MILLIS_PER_SECOND + nanoseconds / 1_000_000;++ // TODO: Add support for negative milliseconds.+ // Chrono library does not handle negative timestamps, but we could probably write+ // something similar to java.util.Date and java.util.Calendar.+ if millis < 0 {+ panic!(+ "Expected non-negative milliseconds when converting Int96, found {}",+ millis+ );+ }++ Field::Timestamp(millis as u64)+ }++ /// Converts Parquet FLOAT type with logical type into `f32` value.+ #[inline]+ pub fn convert_float(_descr: &ColumnDescPtr, value: f32) -> Self {+ Field::Float(value)+ }++ /// Converts Parquet DOUBLE type with logical type into `f64` value.+ #[inline]+ pub fn convert_double(_descr: &ColumnDescPtr, value: f64) -> Self {+ Field::Double(value)+ }++ /// Converts Parquet BYTE_ARRAY type with logical type into either UTF8 string or+ /// array of bytes.+ #[inline]+ pub fn convert_byte_array(descr: &ColumnDescPtr, value: ByteArray) -> Self {+ match descr.physical_type() {+ PhysicalType::BYTE_ARRAY => match descr.logical_type() {+ LogicalType::UTF8 | LogicalType::ENUM | LogicalType::JSON => {+ let value = unsafe { String::from_utf8_unchecked(value.data().to_vec()) };+ Field::Str(value)+ }+ LogicalType::BSON | LogicalType::NONE => Field::Bytes(value),+ LogicalType::DECIMAL => Field::Decimal(Decimal::from_bytes(+ value,+ descr.type_precision(),+ descr.type_scale(),+ )),+ _ => nyi!(descr, value),+ },+ PhysicalType::FIXED_LEN_BYTE_ARRAY => match descr.logical_type() {+ LogicalType::DECIMAL => Field::Decimal(Decimal::from_bytes(+ value,+ descr.type_precision(),+ descr.type_scale(),+ )),+ LogicalType::NONE => Field::Bytes(value),+ _ => nyi!(descr, value),+ },+ _ => nyi!(descr, value),+ }+ }+}++impl fmt::Display for Field {+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {+ match *self {+ Field::Null => write!(f, "null"),+ Field::Bool(value) => write!(f, "{}", value),+ Field::Byte(value) => write!(f, "{}", value),+ Field::Short(value) => write!(f, "{}", value),+ Field::Int(value) => write!(f, "{}", value),+ Field::Long(value) => write!(f, "{}", value),+ Field::UByte(value) => write!(f, "{}", value),+ Field::UShort(value) => write!(f, "{}", value),+ Field::UInt(value) => write!(f, "{}", value),+ Field::ULong(value) => write!(f, "{}", value),+ Field::Float(value) => {+ if value > 1e19 || value < 1e-15 {+ write!(f, "{:E}", value)+ } else {+ write!(f, "{:?}", value)+ }+ }+ Field::Double(value) => {+ if value > 1e19 || value < 1e-15 {+ write!(f, "{:E}", value)+ } else {+ write!(f, "{:?}", value)+ }+ }+ Field::Decimal(ref value) => write!(f, "{}", convert_decimal_to_string(value)),+ Field::Str(ref value) => write!(f, "\"{}\"", value),+ Field::Bytes(ref value) => write!(f, "{:?}", value.data()),+ Field::Date(value) => write!(f, "{}", convert_date_to_string(value)),+ Field::Timestamp(value) => write!(f, "{}", convert_timestamp_to_string(value)),+ Field::Group(ref fields) => write!(f, "{}", fields),+ Field::ListInternal(ref list) => {+ let elems = &list.elements;+ write!(f, "[")?;+ for (i, field) in elems.iter().enumerate() {+ field.fmt(f)?;+ if i < elems.len() - 1 {+ write!(f, ", ")?;+ }+ }+ write!(f, "]")+ }+ Field::MapInternal(ref map) => {+ let entries = &map.entries;+ write!(f, "{{")?;+ for (i, &(ref key, ref value)) in entries.iter().enumerate() {+ key.fmt(f)?;+ write!(f, " -> ")?;+ value.fmt(f)?;+ if i < entries.len() - 1 {+ write!(f, ", ")?;+ }+ }+ write!(f, "}}")+ }+ }+ }+}++/// Helper method to convert Parquet date into a string.+/// Input `value` is a number of days since the epoch in UTC.+/// Date is displayed in local timezone.+#[inline]+fn convert_date_to_string(value: u32) -> String {+ static NUM_SECONDS_IN_DAY: i64 = 60 * 60 * 24;+ let dt = Local.timestamp(value as i64 * NUM_SECONDS_IN_DAY, 0).date();+ format!("{}", dt.format("%Y-%m-%d %:z"))+}++/// Helper method to convert Parquet timestamp into a string.+/// Input `value` is a number of milliseconds since the epoch in UTC.+/// Datetime is displayed in local timezone.+#[inline]+fn convert_timestamp_to_string(value: u64) -> String {+ let dt = Local.timestamp((value / 1000) as i64, 0);+ format!("{}", dt.format("%Y-%m-%d %H:%M:%S %:z"))+}++/// Helper method to convert Parquet decimal into a string.+/// We assert that `scale >= 0` and `precision > scale`, but this will be enforced+/// when constructing Parquet schema.+#[inline]+fn convert_decimal_to_string(decimal: &Decimal) -> String {+ assert!(decimal.scale() >= 0 && decimal.precision() > decimal.scale());++ // Specify as signed bytes to resolve sign as part of conversion.+ let num = BigInt::from_signed_bytes_be(decimal.data());++ // Offset of the first digit in a string.+ let negative = if num.sign() == Sign::Minus { 1 } else { 0 };+ let mut num_str = num.to_string();+ let mut point = num_str.len() as i32 - decimal.scale() - negative;++ // Convert to string form without scientific notation.+ if point <= 0 {+ // Zeros need to be prepended to the unscaled value.+ while point < 0 {+ num_str.insert(negative as usize, '0');+ point += 1;+ }+ num_str.insert_str(negative as usize, "0.");+ } else {+ // No zeroes need to be prepended to the unscaled value, simply insert decimal point.+ num_str.insert((point + negative) as usize, '.');+ }++ num_str+}++#[cfg(test)]+mod tests {+ use super::*;++ use chrono;+ use std::rc::Rc;++ use crate::parquet::schema::types::{ColumnDescriptor, ColumnPath, PrimitiveTypeBuilder};++ /// Creates test column descriptor based on provided type parameters.+ macro_rules! make_column_descr {+ ($physical_type:expr, $logical_type:expr) => {{+ let tpe = PrimitiveTypeBuilder::new("col", $physical_type)+ .with_logical_type($logical_type)+ .build()+ .unwrap();+ Rc::new(ColumnDescriptor::new(+ Rc::new(tpe),+ None,+ 0,+ 0,+ ColumnPath::from("col"),+ ))+ }};+ ($physical_type:expr, $logical_type:expr, $len:expr, $prec:expr, $scale:expr) => {{+ let tpe = PrimitiveTypeBuilder::new("col", $physical_type)+ .with_logical_type($logical_type)+ .with_length($len)+ .with_precision($prec)+ .with_scale($scale)+ .build()+ .unwrap();+ Rc::new(ColumnDescriptor::new(+ Rc::new(tpe),+ None,+ 0,+ 0,+ ColumnPath::from("col"),+ ))+ }};+ }++ #[test]+ fn test_row_convert_bool() {+ // BOOLEAN value does not depend on logical type+ let descr = make_column_descr![PhysicalType::BOOLEAN, LogicalType::NONE];++ let row = Field::convert_bool(&descr, true);+ assert_eq!(row, Field::Bool(true));++ let row = Field::convert_bool(&descr, false);+ assert_eq!(row, Field::Bool(false));+ }++ #[test]+ fn test_row_convert_int32() {+ let descr = make_column_descr![PhysicalType::INT32, LogicalType::INT_8];+ let row = Field::convert_int32(&descr, 111);+ assert_eq!(row, Field::Byte(111));++ let descr = make_column_descr![PhysicalType::INT32, LogicalType::INT_16];+ let row = Field::convert_int32(&descr, 222);+ assert_eq!(row, Field::Short(222));++ let descr = make_column_descr![PhysicalType::INT32, LogicalType::INT_32];+ let row = Field::convert_int32(&descr, 333);+ assert_eq!(row, Field::Int(333));++ let descr = make_column_descr![PhysicalType::INT32, LogicalType::UINT_8];+ let row = Field::convert_int32(&descr, -1);+ assert_eq!(row, Field::UByte(255));++ let descr = make_column_descr![PhysicalType::INT32, LogicalType::UINT_16];+ let row = Field::convert_int32(&descr, 256);+ assert_eq!(row, Field::UShort(256));++ let descr = make_column_descr![PhysicalType::INT32, LogicalType::UINT_32];+ let row = Field::convert_int32(&descr, 1234);+ assert_eq!(row, Field::UInt(1234));++ let descr = make_column_descr![PhysicalType::INT32, LogicalType::NONE];+ let row = Field::convert_int32(&descr, 444);+ assert_eq!(row, Field::Int(444));++ let descr = make_column_descr![PhysicalType::INT32, LogicalType::DATE];+ let row = Field::convert_int32(&descr, 14611);+ assert_eq!(row, Field::Date(14611));++ let descr = make_column_descr![PhysicalType::INT32, LogicalType::DECIMAL, 0, 8, 2];+ let row = Field::convert_int32(&descr, 444);+ assert_eq!(row, Field::Decimal(Decimal::from_i32(444, 8, 2)));+ }++ #[test]+ fn test_row_convert_int64() {+ let descr = make_column_descr![PhysicalType::INT64, LogicalType::INT_64];+ let row = Field::convert_int64(&descr, 1111);+ assert_eq!(row, Field::Long(1111));++ let descr = make_column_descr![PhysicalType::INT64, LogicalType::UINT_64];+ let row = Field::convert_int64(&descr, 78239823);+ assert_eq!(row, Field::ULong(78239823));++ let descr = make_column_descr![PhysicalType::INT64, LogicalType::TIMESTAMP_MILLIS];+ let row = Field::convert_int64(&descr, 1541186529153);+ assert_eq!(row, Field::Timestamp(1541186529153));++ let descr = make_column_descr![PhysicalType::INT64, LogicalType::NONE];+ let row = Field::convert_int64(&descr, 2222);+ assert_eq!(row, Field::Long(2222));++ let descr = make_column_descr![PhysicalType::INT64, LogicalType::DECIMAL, 0, 8, 2];+ let row = Field::convert_int64(&descr, 3333);+ assert_eq!(row, Field::Decimal(Decimal::from_i64(3333, 8, 2)));+ }++ #[test]+ fn test_row_convert_int96() {+ // INT96 value does not depend on logical type+ let descr = make_column_descr![PhysicalType::INT96, LogicalType::NONE];++ let value = Int96::from(vec![0, 0, 2454923]);+ let row = Field::convert_int96(&descr, value);+ assert_eq!(row, Field::Timestamp(1238544000000));++ let value = Int96::from(vec![4165425152, 13, 2454923]);+ let row = Field::convert_int96(&descr, value);+ assert_eq!(row, Field::Timestamp(1238544060000));+ }++ #[test]+ #[should_panic(expected = "Expected non-negative milliseconds when converting Int96")]+ fn test_row_convert_int96_invalid() {+ // INT96 value does not depend on logical type+ let descr = make_column_descr![PhysicalType::INT96, LogicalType::NONE];++ let value = Int96::from(vec![0, 0, 0]);+ Field::convert_int96(&descr, value);+ }++ #[test]+ fn test_row_convert_float() {+ // FLOAT value does not depend on logical type+ let descr = make_column_descr![PhysicalType::FLOAT, LogicalType::NONE];+ let row = Field::convert_float(&descr, 2.31);+ assert_eq!(row, Field::Float(2.31));+ }++ #[test]+ fn test_row_convert_double() {+ // DOUBLE value does not depend on logical type+ let descr = make_column_descr![PhysicalType::DOUBLE, LogicalType::NONE];+ let row = Field::convert_double(&descr, 1.56);+ assert_eq!(row, Field::Double(1.56));+ }++ #[test]+ fn test_row_convert_byte_array() {+ // UTF8+ let descr = make_column_descr![PhysicalType::BYTE_ARRAY, LogicalType::UTF8];+ let value = ByteArray::from(vec![b'A', b'B', b'C', b'D']);+ let row = Field::convert_byte_array(&descr, value);+ assert_eq!(row, Field::Str("ABCD".to_string()));++ // ENUM+ let descr = make_column_descr![PhysicalType::BYTE_ARRAY, LogicalType::ENUM];+ let value = ByteArray::from(vec![b'1', b'2', b'3']);+ let row = Field::convert_byte_array(&descr, value);+ assert_eq!(row, Field::Str("123".to_string()));++ // JSON+ let descr = make_column_descr![PhysicalType::BYTE_ARRAY, LogicalType::JSON];+ let value = ByteArray::from(vec![b'{', b'"', b'a', b'"', b':', b'1', b'}']);+ let row = Field::convert_byte_array(&descr, value);+ assert_eq!(row, Field::Str("{\"a\":1}".to_string()));++ // NONE+ let descr = make_column_descr![PhysicalType::BYTE_ARRAY, LogicalType::NONE];+ let value = ByteArray::from(vec![1, 2, 3, 4, 5]);+ let row = Field::convert_byte_array(&descr, value.clone());+ assert_eq!(row, Field::Bytes(value));++ // BSON+ let descr = make_column_descr![PhysicalType::BYTE_ARRAY, LogicalType::BSON];+ let value = ByteArray::from(vec![1, 2, 3, 4, 5]);+ let row = Field::convert_byte_array(&descr, value.clone());+ assert_eq!(row, Field::Bytes(value));++ // DECIMAL+ let descr = make_column_descr![PhysicalType::BYTE_ARRAY, LogicalType::DECIMAL, 0, 8, 2];+ let value = ByteArray::from(vec![207, 200]);+ let row = Field::convert_byte_array(&descr, value.clone());+ assert_eq!(row, Field::Decimal(Decimal::from_bytes(value, 8, 2)));++ // DECIMAL (FIXED_LEN_BYTE_ARRAY)+ let descr = make_column_descr![+ PhysicalType::FIXED_LEN_BYTE_ARRAY,+ LogicalType::DECIMAL,+ 8,+ 17,+ 5+ ];+ let value = ByteArray::from(vec![0, 0, 0, 0, 0, 4, 147, 224]);+ let row = Field::convert_byte_array(&descr, value.clone());+ assert_eq!(row, Field::Decimal(Decimal::from_bytes(value, 17, 5)));++ // NONE (FIXED_LEN_BYTE_ARRAY)+ let descr = make_column_descr![+ PhysicalType::FIXED_LEN_BYTE_ARRAY,+ LogicalType::NONE,+ 6,+ 0,+ 0+ ];+ let value = ByteArray::from(vec![1, 2, 3, 4, 5, 6]);+ let row = Field::convert_byte_array(&descr, value.clone());+ assert_eq!(row, Field::Bytes(value));+ }++ #[test]+ fn test_convert_date_to_string() {+ fn check_date_conversion(y: u32, m: u32, d: u32) {+ let datetime = chrono::NaiveDate::from_ymd(y as i32, m, d).and_hms(0, 0, 0);+ let dt = Local.from_utc_datetime(&datetime);+ let res = convert_date_to_string((dt.timestamp() / 60 / 60 / 24) as u32);+ let exp = format!("{}", dt.format("%Y-%m-%d %:z"));+ assert_eq!(res, exp);+ }++ check_date_conversion(2010, 01, 02);+ check_date_conversion(2014, 05, 01);+ check_date_conversion(2016, 02, 29);+ check_date_conversion(2017, 09, 12);+ check_date_conversion(2018, 03, 31);+ }++ #[test]+ fn test_convert_timestamp_to_string() {+ fn check_datetime_conversion(y: u32, m: u32, d: u32, h: u32, mi: u32, s: u32) {+ let datetime = chrono::NaiveDate::from_ymd(y as i32, m, d).and_hms(h, mi, s);+ let dt = Local.from_utc_datetime(&datetime);+ let res = convert_timestamp_to_string(dt.timestamp_millis() as u64);+ let exp = format!("{}", dt.format("%Y-%m-%d %H:%M:%S %:z"));+ assert_eq!(res, exp);+ }++ check_datetime_conversion(2010, 01, 02, 13, 12, 54);+ check_datetime_conversion(2011, 01, 03, 08, 23, 01);+ check_datetime_conversion(2012, 04, 05, 11, 06, 32);+ check_datetime_conversion(2013, 05, 12, 16, 38, 00);+ check_datetime_conversion(2014, 11, 28, 21, 15, 12);+ }++ #[test]+ fn test_convert_float_to_string() {+ assert_eq!(format!("{}", Field::Float(1.0)), "1.0");+ assert_eq!(format!("{}", Field::Float(9.63)), "9.63");+ assert_eq!(format!("{}", Field::Float(1e-15)), "0.000000000000001");+ assert_eq!(format!("{}", Field::Float(1e-16)), "1E-16");+ assert_eq!(format!("{}", Field::Float(1e19)), "10000000000000000000.0");+ assert_eq!(format!("{}", Field::Float(1e20)), "1E20");+ assert_eq!(format!("{}", Field::Float(1.7976931E30)), "1.7976931E30");+ assert_eq!(format!("{}", Field::Float(-1.7976931E30)), "-1.7976931E30");+ }++ #[test]+ fn test_convert_double_to_string() {+ assert_eq!(format!("{}", Field::Double(1.0)), "1.0");+ assert_eq!(format!("{}", Field::Double(9.63)), "9.63");+ assert_eq!(format!("{}", Field::Double(1e-15)), "0.000000000000001");+ assert_eq!(format!("{}", Field::Double(1e-16)), "1E-16");+ assert_eq!(format!("{}", Field::Double(1e19)), "10000000000000000000.0");+ assert_eq!(format!("{}", Field::Double(1e20)), "1E20");+ assert_eq!(+ format!("{}", Field::Double(1.79769313486E308)),+ "1.79769313486E308"+ );+ assert_eq!(+ format!("{}", Field::Double(-1.79769313486E308)),+ "-1.79769313486E308"+ );+ }++ #[test]+ fn test_convert_decimal_to_string() {+ // Helper method to compare decimal+ fn check_decimal(bytes: Vec<u8>, precision: i32, scale: i32, res: &str) {+ let decimal = Decimal::from_bytes(ByteArray::from(bytes), precision, scale);+ assert_eq!(convert_decimal_to_string(&decimal), res);+ }++ // This example previously used to fail in some engines+ check_decimal(+ vec![0, 0, 0, 0, 0, 0, 0, 0, 13, 224, 182, 179, 167, 100, 0, 0],+ 38,+ 18,+ "1.000000000000000000",+ );+ check_decimal(+ vec![+ 249, 233, 247, 16, 185, 192, 202, 223, 215, 165, 192, 166, 67, 72,+ ],+ 36,+ 28,+ "-12344.0242342304923409234234293432",+ );+ check_decimal(vec![0, 0, 0, 0, 0, 4, 147, 224], 17, 5, "3.00000");+ check_decimal(vec![0, 0, 0, 0, 1, 201, 195, 140], 18, 2, "300000.12");+ check_decimal(vec![207, 200], 10, 2, "-123.44");+ check_decimal(vec![207, 200], 10, 8, "-0.00012344");+ }++ #[test]+ fn test_row_display() {+ // Primitive types+ assert_eq!(format!("{}", Field::Null), "null");+ assert_eq!(format!("{}", Field::Bool(true)), "true");+ assert_eq!(format!("{}", Field::Bool(false)), "false");+ assert_eq!(format!("{}", Field::Byte(1)), "1");+ assert_eq!(format!("{}", Field::Short(2)), "2");+ assert_eq!(format!("{}", Field::Int(3)), "3");+ assert_eq!(format!("{}", Field::Long(4)), "4");+ assert_eq!(format!("{}", Field::UByte(1)), "1");+ assert_eq!(format!("{}", Field::UShort(2)), "2");+ assert_eq!(format!("{}", Field::UInt(3)), "3");+ assert_eq!(format!("{}", Field::ULong(4)), "4");+ assert_eq!(format!("{}", Field::Float(5.0)), "5.0");+ assert_eq!(format!("{}", Field::Float(5.1234)), "5.1234");+ assert_eq!(format!("{}", Field::Double(6.0)), "6.0");+ assert_eq!(format!("{}", Field::Double(6.1234)), "6.1234");+ assert_eq!(format!("{}", Field::Str("abc".to_string())), "\"abc\"");+ assert_eq!(+ format!("{}", Field::Bytes(ByteArray::from(vec![1, 2, 3]))),+ "[1, 2, 3]"+ );+ assert_eq!(+ format!("{}", Field::Date(14611)),+ convert_date_to_string(14611)+ );+ assert_eq!(+ format!("{}", Field::Timestamp(1262391174000)),+ convert_timestamp_to_string(1262391174000)+ );+ assert_eq!(+ format!("{}", Field::Decimal(Decimal::from_i32(4, 8, 2))),+ convert_decimal_to_string(&Decimal::from_i32(4, 8, 2))+ );++ // Complex types+ let fields = vec![+ ("x".to_string(), Field::Null),+ ("Y".to_string(), Field::Int(2)),+ ("z".to_string(), Field::Float(3.1)),+ ("a".to_string(), Field::Str("abc".to_string())),+ ];+ let row = Field::Group(make_row(fields));+ assert_eq!(format!("{}", row), "{x: null, Y: 2, z: 3.1, a: \"abc\"}");++ let row = Field::ListInternal(make_list(vec![+ Field::Int(2),+ Field::Int(1),+ Field::Null,+ Field::Int(12),+ ]));+ assert_eq!(format!("{}", row), "[2, 1, null, 12]");++ let row = Field::MapInternal(make_map(vec![+ (Field::Int(1), Field::Float(1.2)),+ (Field::Int(2), Field::Float(4.5)),+ (Field::Int(3), Field::Float(2.3)),+ ]));+ assert_eq!(format!("{}", row), "{1 -> 1.2, 2 -> 4.5, 3 -> 2.3}");+ }++ #[test]+ fn test_is_primitive() {+ // primitives+ assert!(Field::Null.is_primitive());+ assert!(Field::Bool(true).is_primitive());+ assert!(Field::Bool(false).is_primitive());+ assert!(Field::Byte(1).is_primitive());+ assert!(Field::Short(2).is_primitive());+ assert!(Field::Int(3).is_primitive());+ assert!(Field::Long(4).is_primitive());+ assert!(Field::UByte(1).is_primitive());+ assert!(Field::UShort(2).is_primitive());+ assert!(Field::UInt(3).is_primitive());+ assert!(Field::ULong(4).is_primitive());+ assert!(Field::Float(5.0).is_primitive());+ assert!(Field::Float(5.1234).is_primitive());+ assert!(Field::Double(6.0).is_primitive());+ assert!(Field::Double(6.1234).is_primitive());+ assert!(Field::Str("abc".to_string()).is_primitive());+ assert!(Field::Bytes(ByteArray::from(vec![1, 2, 3])).is_primitive());+ assert!(Field::Timestamp(12345678).is_primitive());+ assert!(Field::Decimal(Decimal::from_i32(4, 8, 2)).is_primitive());++ // complex types+ assert_eq!(+ false,+ Field::Group(make_row(vec![+ ("x".to_string(), Field::Null),+ ("Y".to_string(), Field::Int(2)),+ ("z".to_string(), Field::Float(3.1)),+ ("a".to_string(), Field::Str("abc".to_string()))+ ]))+ .is_primitive()+ );++ assert_eq!(+ false,+ Field::ListInternal(make_list(vec![+ Field::Int(2),+ Field::Int(1),+ Field::Null,+ Field::Int(12)+ ]))+ .is_primitive()+ );++ assert_eq!(+ false,+ Field::MapInternal(make_map(vec![+ (Field::Int(1), Field::Float(1.2)),+ (Field::Int(2), Field::Float(4.5)),+ (Field::Int(3), Field::Float(2.3))+ ]))+ .is_primitive()+ );+ }++ #[test]+ fn test_row_primitive_accessors() {+ // primitives+ let row = make_row(vec![+ ("a".to_string(), Field::Null),+ ("b".to_string(), Field::Bool(false)),+ ("c".to_string(), Field::Byte(3)),+ ("d".to_string(), Field::Short(4)),+ ("e".to_string(), Field::Int(5)),+ ("f".to_string(), Field::Long(6)),+ ("g".to_string(), Field::UByte(3)),+ ("h".to_string(), Field::UShort(4)),+ ("i".to_string(), Field::UInt(5)),+ ("j".to_string(), Field::ULong(6)),+ ("k".to_string(), Field::Float(7.1)),+ ("l".to_string(), Field::Double(8.1)),+ ("m".to_string(), Field::Str("abc".to_string())),+ (+ "n".to_string(),+ Field::Bytes(ByteArray::from(vec![1, 2, 3, 4, 5])),+ ),+ ("o".to_string(), Field::Decimal(Decimal::from_i32(4, 7, 2))),+ ]);++ assert_eq!(false, row.get_bool(1).unwrap());+ assert_eq!(3, row.get_byte(2).unwrap());+ assert_eq!(4, row.get_short(3).unwrap());+ assert_eq!(5, row.get_int(4).unwrap());+ assert_eq!(6, row.get_long(5).unwrap());+ assert_eq!(3, row.get_ubyte(6).unwrap());+ assert_eq!(4, row.get_ushort(7).unwrap());+ assert_eq!(5, row.get_uint(8).unwrap());+ assert_eq!(6, row.get_ulong(9).unwrap());+ assert_eq!(7.1, row.get_float(10).unwrap());+ assert_eq!(8.1, row.get_double(11).unwrap());+ assert_eq!("abc", row.get_string(12).unwrap());+ assert_eq!(5, row.get_bytes(13).unwrap().len());+ assert_eq!(7, row.get_decimal(14).unwrap().precision());+ }++ #[test]+ fn test_row_primitive_invalid_accessors() {+ // primitives+ let row = make_row(vec![+ ("a".to_string(), Field::Null),+ ("b".to_string(), Field::Bool(false)),+ ("c".to_string(), Field::Byte(3)),+ ("d".to_string(), Field::Short(4)),+ ("e".to_string(), Field::Int(5)),+ ("f".to_string(), Field::Long(6)),+ ("g".to_string(), Field::UByte(3)),+ ("h".to_string(), Field::UShort(4)),+ ("i".to_string(), Field::UInt(5)),+ ("j".to_string(), Field::ULong(6)),+ ("k".to_string(), Field::Float(7.1)),+ ("l".to_string(), Field::Double(8.1)),+ ("m".to_string(), Field::Str("abc".to_string())),+ (+ "n".to_string(),+ Field::Bytes(ByteArray::from(vec![1, 2, 3, 4, 5])),+ ),+ ("o".to_string(), Field::Decimal(Decimal::from_i32(4, 7, 2))),+ ]);++ for i in 0..row.len() {+ assert!(row.get_group(i).is_err());+ }+ }++ #[test]+ fn test_row_complex_accessors() {+ let row = make_row(vec![+ (+ "a".to_string(),+ Field::Group(make_row(vec![+ ("x".to_string(), Field::Null),+ ("Y".to_string(), Field::Int(2)),+ ])),+ ),+ (+ "b".to_string(),+ Field::ListInternal(make_list(vec![+ Field::Int(2),+ Field::Int(1),+ Field::Null,+ Field::Int(12),+ ])),+ ),+ (+ "c".to_string(),+ Field::MapInternal(make_map(vec![+ (Field::Int(1), Field::Float(1.2)),+ (Field::Int(2), Field::Float(4.5)),+ (Field::Int(3), Field::Float(2.3)),+ ])),+ ),+ ]);++ assert_eq!(2, row.get_group(0).unwrap().len());+ assert_eq!(4, row.get_list(1).unwrap().len());+ assert_eq!(3, row.get_map(2).unwrap().len());+ }++ #[test]+ fn test_row_complex_invalid_accessors() {+ let row = make_row(vec![+ (+ "a".to_string(),+ Field::Group(make_row(vec![+ ("x".to_string(), Field::Null),+ ("Y".to_string(), Field::Int(2)),+ ])),+ ),+ (+ "b".to_string(),+ Field::ListInternal(make_list(vec![+ Field::Int(2),+ Field::Int(1),+ Field::Null,+ Field::Int(12),+ ])),+ ),+ (+ "c".to_string(),+ Field::MapInternal(make_map(vec![+ (Field::Int(1), Field::Float(1.2)),+ (Field::Int(2), Field::Float(4.5)),+ (Field::Int(3), Field::Float(2.3)),+ ])),+ ),+ ]);++ assert_eq!(+ ParquetError::General("Cannot access Group as Float".to_string()),+ row.get_float(0).unwrap_err()+ );+ assert_eq!(+ ParquetError::General("Cannot access ListInternal as Float".to_string()),+ row.get_float(1).unwrap_err()+ );+ assert_eq!(+ ParquetError::General("Cannot access MapInternal as Float".to_string()),+ row.get_float(2).unwrap_err()+ );+ }++ #[test]+ fn test_list_primitive_accessors() {+ // primitives+ let list = make_list(vec![Field::Bool(false)]);+ assert_eq!(false, list.get_bool(0).unwrap());++ let list = make_list(vec![Field::Byte(3), Field::Byte(4)]);+ assert_eq!(4, list.get_byte(1).unwrap());++ let list = make_list(vec![Field::Short(4), Field::Short(5), Field::Short(6)]);+ assert_eq!(6, list.get_short(2).unwrap());++ let list = make_list(vec![Field::Int(5)]);+ assert_eq!(5, list.get_int(0).unwrap());++ let list = make_list(vec![Field::Long(6), Field::Long(7)]);+ assert_eq!(7, list.get_long(1).unwrap());++ let list = make_list(vec![Field::UByte(3), Field::UByte(4)]);+ assert_eq!(4, list.get_ubyte(1).unwrap());++ let list = make_list(vec![Field::UShort(4), Field::UShort(5), Field::UShort(6)]);+ assert_eq!(6, list.get_ushort(2).unwrap());++ let list = make_list(vec![Field::UInt(5)]);+ assert_eq!(5, list.get_uint(0).unwrap());++ let list = make_list(vec![Field::ULong(6), Field::ULong(7)]);+ assert_eq!(7, list.get_ulong(1).unwrap());++ let list = make_list(vec![+ Field::Float(8.1),+ Field::Float(9.2),+ Field::Float(10.3),+ ]);+ assert_eq!(10.3, list.get_float(2).unwrap());++ let list = make_list(vec![Field::Double(3.1415)]);+ assert_eq!(3.1415, list.get_double(0).unwrap());++ let list = make_list(vec![Field::Str("abc".to_string())]);+ assert_eq!(&"abc".to_string(), list.get_string(0).unwrap());++ let list = make_list(vec![Field::Bytes(ByteArray::from(vec![1, 2, 3, 4, 5]))]);+ assert_eq!(&[1, 2, 3, 4, 5], list.get_bytes(0).unwrap().data());++ let list = make_list(vec![Field::Decimal(Decimal::from_i32(4, 5, 2))]);+ assert_eq!(&[0, 0, 0, 4], list.get_decimal(0).unwrap().data());+ }++ #[test]+ fn test_list_primitive_invalid_accessors() {+ // primitives+ let list = make_list(vec![Field::Bool(false)]);+ assert!(list.get_byte(0).is_err());++ let list = make_list(vec![Field::Byte(3), Field::Byte(4)]);+ assert!(list.get_short(1).is_err());++ let list = make_list(vec![Field::Short(4), Field::Short(5), Field::Short(6)]);+ assert!(list.get_int(2).is_err());++ let list = make_list(vec![Field::Int(5)]);+ assert!(list.get_long(0).is_err());++ let list = make_list(vec![Field::Long(6), Field::Long(7)]);+ assert!(list.get_float(1).is_err());++ let list = make_list(vec![Field::UByte(3), Field::UByte(4)]);+ assert!(list.get_short(1).is_err());++ let list = make_list(vec![Field::UShort(4), Field::UShort(5), Field::UShort(6)]);+ assert!(list.get_int(2).is_err());++ let list = make_list(vec![Field::UInt(5)]);+ assert!(list.get_long(0).is_err());++ let list = make_list(vec![Field::ULong(6), Field::ULong(7)]);+ assert!(list.get_float(1).is_err());++ let list = make_list(vec![+ Field::Float(8.1),+ Field::Float(9.2),+ Field::Float(10.3),+ ]);+ assert!(list.get_double(2).is_err());++ let list = make_list(vec![Field::Double(3.1415)]);+ assert!(list.get_string(0).is_err());++ let list = make_list(vec![Field::Str("abc".to_string())]);+ assert!(list.get_bytes(0).is_err());++ let list = make_list(vec![Field::Bytes(ByteArray::from(vec![1, 2, 3, 4, 5]))]);+ assert!(list.get_bool(0).is_err());++ let list = make_list(vec![Field::Decimal(Decimal::from_i32(4, 5, 2))]);+ assert!(list.get_bool(0).is_err());+ }++ #[test]+ fn test_list_complex_accessors() {+ let list = make_list(vec![Field::Group(make_row(vec![+ ("x".to_string(), Field::Null),+ ("Y".to_string(), Field::Int(2)),+ ]))]);+ assert_eq!(2, list.get_group(0).unwrap().len());++ let list = make_list(vec![Field::ListInternal(make_list(vec![+ Field::Int(2),+ Field::Int(1),+ Field::Null,+ Field::Int(12),+ ]))]);+ assert_eq!(4, list.get_list(0).unwrap().len());++ let list = make_list(vec![Field::MapInternal(make_map(vec![+ (Field::Int(1), Field::Float(1.2)),+ (Field::Int(2), Field::Float(4.5)),+ (Field::Int(3), Field::Float(2.3)),+ ]))]);+ assert_eq!(3, list.get_map(0).unwrap().len());+ }++ #[test]+ fn test_list_complex_invalid_accessors() {+ let list = make_list(vec![Field::Group(make_row(vec![+ ("x".to_string(), Field::Null),+ ("Y".to_string(), Field::Int(2)),+ ]))]);+ assert_eq!(+ general_err!("Cannot access Group as Float".to_string()),+ list.get_float(0).unwrap_err()+ );++ let list = make_list(vec![Field::ListInternal(make_list(vec![+ Field::Int(2),+ Field::Int(1),+ Field::Null,+ Field::Int(12),+ ]))]);+ assert_eq!(+ general_err!("Cannot access ListInternal as Float".to_string()),+ list.get_float(0).unwrap_err()+ );++ let list = make_list(vec![Field::MapInternal(make_map(vec![+ (Field::Int(1), Field::Float(1.2)),+ (Field::Int(2), Field::Float(4.5)),+ (Field::Int(3), Field::Float(2.3)),+ ]))]);+ assert_eq!(+ general_err!("Cannot access MapInternal as Float".to_string()),+ list.get_float(0).unwrap_err()+ );+ }++ #[test]+ fn test_map_accessors() {+ // a map from int to string+ let map = make_map(vec![+ (Field::Int(1), Field::Str("a".to_string())),+ (Field::Int(2), Field::Str("b".to_string())),+ (Field::Int(3), Field::Str("c".to_string())),+ (Field::Int(4), Field::Str("d".to_string())),+ (Field::Int(5), Field::Str("e".to_string())),+ ]);++ assert_eq!(5, map.len());+ for i in 0..5 {+ assert_eq!((i + 1) as i32, map.get_keys().get_int(i).unwrap());+ assert_eq!(+ &((i as u8 + 'a' as u8) as char).to_string(),+ map.get_values().get_string(i).unwrap()+ );+ }+ }+}diff --git a/rust/src/parquet/record/mod.rs b/rust/src/parquet/record/mod.rsnew file mode 100644index 0000000000..0dba8a78bd--- /dev/null+++ b/rust/src/parquet/record/mod.rs@@ -0,0 +1,24 @@+// 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.++//! Contains record-based API for reading Parquet files.++mod api;+pub mod reader;+mod triplet;++pub use self::api::{List, ListAccessor, Map, MapAccessor, Row, RowAccessor};diff --git a/rust/src/parquet/record/reader.rs b/rust/src/parquet/record/reader.rsnew file mode 100644index 0000000000..d9f3d6fea1--- /dev/null+++ b/rust/src/parquet/record/reader.rs@@ -0,0 +1,1464 @@+// 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.++//! Contains implementation of record assembly and converting Parquet types into+//! [`Row`](`::record::api::Row`)s.++use std::{collections::HashMap, fmt, rc::Rc};++use crate::parquet::basic::{LogicalType, Repetition};+use crate::parquet::errors::{ParquetError, Result};+use crate::parquet::file::reader::{FileReader, RowGroupReader};+use crate::parquet::record::{+ api::{make_list, make_map, make_row, Field, Row},+ triplet::TripletIter,+};+use crate::parquet::schema::types::{ColumnPath, SchemaDescPtr, SchemaDescriptor, Type, TypePtr};++/// Default batch size for a reader+const DEFAULT_BATCH_SIZE: usize = 1024;++/// Tree builder for `Reader` enum.+/// Serves as a container of options for building a reader tree and a builder, and+/// accessing a records iterator [`RowIter`].+pub struct TreeBuilder {+ // Batch size (>= 1) for triplet iterators+ batch_size: usize,+}++impl TreeBuilder {+ /// Creates new tree builder with default parameters.+ pub fn new() -> Self {+ Self {+ batch_size: DEFAULT_BATCH_SIZE,+ }+ }++ /// Sets batch size for this tree builder.+ pub fn with_batch_size(mut self, batch_size: usize) -> Self {+ self.batch_size = batch_size;+ self+ }++ /// Creates new root reader for provided schema and row group.+ pub fn build(&self, descr: SchemaDescPtr, row_group_reader: &RowGroupReader) -> Reader {+ // Prepare lookup table of column path -> original column index+ // This allows to prune columns and map schema leaf nodes to the column readers+ let mut paths: HashMap<ColumnPath, usize> = HashMap::new();+ let row_group_metadata = row_group_reader.metadata();++ for col_index in 0..row_group_reader.num_columns() {+ let col_meta = row_group_metadata.column(col_index);+ let col_path = col_meta.column_path().clone();+ paths.insert(col_path, col_index);+ }++ // Build child readers for the message type+ let mut readers = Vec::new();+ let mut path = Vec::new();++ for field in descr.root_schema().get_fields() {+ let reader = self.reader_tree(field.clone(), &mut path, 0, 0, &paths, row_group_reader);+ readers.push(reader);+ }++ // Return group reader for message type,+ // it is always required with definition level 0+ Reader::GroupReader(None, 0, readers)+ }++ /// Creates iterator of `Row`s directly from schema descriptor and row group.+ pub fn as_iter(&self, descr: SchemaDescPtr, row_group_reader: &RowGroupReader) -> ReaderIter {+ let num_records = row_group_reader.metadata().num_rows() as usize;+ ReaderIter::new(self.build(descr, row_group_reader), num_records)+ }++ /// Builds tree of readers for the current schema recursively.+ fn reader_tree(+ &self,+ field: TypePtr,+ mut path: &mut Vec<String>,+ mut curr_def_level: i16,+ mut curr_rep_level: i16,+ paths: &HashMap<ColumnPath, usize>,+ row_group_reader: &RowGroupReader,+ ) -> Reader {+ assert!(field.get_basic_info().has_repetition());+ // Update current definition and repetition levels for this type+ let repetition = field.get_basic_info().repetition();+ match repetition {+ Repetition::OPTIONAL => {+ curr_def_level += 1;+ }+ Repetition::REPEATED => {+ curr_def_level += 1;+ curr_rep_level += 1;+ }+ _ => {}+ }++ path.push(String::from(field.name()));+ let reader = if field.is_primitive() {+ let col_path = ColumnPath::new(path.to_vec());+ let orig_index = *paths.get(&col_path).unwrap();+ let col_descr = row_group_reader+ .metadata()+ .column(orig_index)+ .column_descr_ptr();+ let col_reader = row_group_reader.get_column_reader(orig_index).unwrap();+ let column = TripletIter::new(col_descr, col_reader, self.batch_size);+ Reader::PrimitiveReader(field, column)+ } else {+ match field.get_basic_info().logical_type() {+ // List types+ LogicalType::LIST => {+ assert_eq!(field.get_fields().len(), 1, "Invalid list type {:?}", field);++ let repeated_field = field.get_fields()[0].clone();+ assert_eq!(+ repeated_field.get_basic_info().repetition(),+ Repetition::REPEATED,+ "Invalid list type {:?}",+ field+ );++ if Reader::is_element_type(&repeated_field) {+ // Support for backward compatible lists+ let reader = self.reader_tree(+ repeated_field.clone(),+ &mut path,+ curr_def_level,+ curr_rep_level,+ paths,+ row_group_reader,+ );++ Reader::RepeatedReader(+ field,+ curr_def_level,+ curr_rep_level,+ Box::new(reader),+ )+ } else {+ let child_field = repeated_field.get_fields()[0].clone();++ path.push(String::from(repeated_field.name()));++ let reader = self.reader_tree(+ child_field,+ &mut path,+ curr_def_level + 1,+ curr_rep_level + 1,+ paths,+ row_group_reader,+ );++ path.pop();++ Reader::RepeatedReader(+ field,+ curr_def_level,+ curr_rep_level,+ Box::new(reader),+ )+ }+ }+ // Map types (key-value pairs)+ LogicalType::MAP | LogicalType::MAP_KEY_VALUE => {+ assert_eq!(field.get_fields().len(), 1, "Invalid map type: {:?}", field);+ assert!(+ !field.get_fields()[0].is_primitive(),+ "Invalid map type: {:?}",+ field+ );++ let key_value_type = field.get_fields()[0].clone();+ assert_eq!(+ key_value_type.get_basic_info().repetition(),+ Repetition::REPEATED,+ "Invalid map type: {:?}",+ field+ );+ assert_eq!(+ key_value_type.get_fields().len(),+ 2,+ "Invalid map type: {:?}",+ field+ );++ path.push(String::from(key_value_type.name()));++ let key_type = &key_value_type.get_fields()[0];+ assert!(+ key_type.is_primitive(),+ "Map key type is expected to be a primitive type, but found {:?}",+ key_type+ );+ let key_reader = self.reader_tree(+ key_type.clone(),+ &mut path,+ curr_def_level + 1,+ curr_rep_level + 1,+ paths,+ row_group_reader,+ );++ let value_type = &key_value_type.get_fields()[1];+ let value_reader = self.reader_tree(+ value_type.clone(),+ &mut path,+ curr_def_level + 1,+ curr_rep_level + 1,+ paths,+ row_group_reader,+ );++ path.pop();++ Reader::KeyValueReader(+ field,+ curr_def_level,+ curr_rep_level,+ Box::new(key_reader),+ Box::new(value_reader),+ )+ }+ // A repeated field that is neither contained by a `LIST`- or `MAP`-annotated+ // group nor annotated by `LIST` or `MAP` should be interpreted as a required+ // list of required elements where the element type is the type of the field.+ _ if repetition == Repetition::REPEATED => {+ let required_field = Type::group_type_builder(field.name())+ .with_repetition(Repetition::REQUIRED)+ .with_logical_type(field.get_basic_info().logical_type())+ .with_fields(&mut Vec::from(field.get_fields()))+ .build()+ .unwrap();++ path.pop();++ let reader = self.reader_tree(+ Rc::new(required_field),+ &mut path,+ curr_def_level,+ curr_rep_level,+ paths,+ row_group_reader,+ );++ Reader::RepeatedReader(+ field,+ curr_def_level - 1,+ curr_rep_level - 1,+ Box::new(reader),+ )+ }+ // Group types (structs)+ _ => {+ let mut readers = Vec::new();+ for child in field.get_fields() {+ let reader = self.reader_tree(+ child.clone(),+ &mut path,+ curr_def_level,+ curr_rep_level,+ paths,+ row_group_reader,+ );+ readers.push(reader);+ }+ Reader::GroupReader(Some(field), curr_def_level, readers)+ }+ }+ };+ path.pop();++ Reader::option(repetition, curr_def_level, reader)+ }+}++/// Reader tree for record assembly+pub enum Reader {+ // Primitive reader with type information and triplet iterator+ PrimitiveReader(TypePtr, TripletIter),+ // Optional reader with definition level of a parent and a reader+ OptionReader(i16, Box<Reader>),+ // Group (struct) reader with type information, definition level and list of child+ // readers. When it represents message type, type information is None+ GroupReader(Option<TypePtr>, i16, Vec<Reader>),+ // Reader for repeated values, e.g. lists, contains type information, definition+ // level, repetition level and a child reader+ RepeatedReader(TypePtr, i16, i16, Box<Reader>),+ // Reader of key-value pairs, e.g. maps, contains type information, definition level,+ // repetition level, child reader for keys and child reader for values+ KeyValueReader(TypePtr, i16, i16, Box<Reader>, Box<Reader>),+}++impl Reader {+ /// Wraps reader in option reader based on repetition.+ fn option(repetition: Repetition, def_level: i16, reader: Reader) -> Self {+ if repetition == Repetition::OPTIONAL {+ Reader::OptionReader(def_level - 1, Box::new(reader))+ } else {+ reader+ }+ }++ /// Returns true if repeated type is an element type for the list.+ /// Used to determine legacy list types.+ /// This method is copied from Spark Parquet reader and is based on the reference:+ /// https://github.com/apache/parquet-format/blob/master/LogicalTypes.md+ /// #backward-compatibility-rules+ fn is_element_type(repeated_type: &Type) -> bool {+ // For legacy 2-level list types with primitive element type, e.g.:+ //+ // // ARRAY<INT> (nullable list, non-null elements)+ // optional group my_list (LIST) {+ // repeated int32 element;+ // }+ //+ repeated_type.is_primitive() ||+ // For legacy 2-level list types whose element type is a group type with 2 or more+ // fields, e.g.:+ //+ // // ARRAY<STRUCT<str: STRING, num: INT>> (nullable list, non-null elements)+ // optional group my_list (LIST) {+ // repeated group element {+ // required binary str (UTF8);+ // required int32 num;+ // };+ // }+ //+ repeated_type.is_group() && repeated_type.get_fields().len() > 1 ||+ // For legacy 2-level list types generated by parquet-avro (Parquet version < 1.6.0),+ // e.g.:+ //+ // // ARRAY<STRUCT<str: STRING>> (nullable list, non-null elements)+ // optional group my_list (LIST) {+ // repeated group array {+ // required binary str (UTF8);+ // };+ // }+ //+ repeated_type.name() == "array" ||+ // For Parquet data generated by parquet-thrift, e.g.:+ //+ // // ARRAY<STRUCT<str: STRING>> (nullable list, non-null elements)+ // optional group my_list (LIST) {+ // repeated group my_list_tuple {+ // required binary str (UTF8);+ // };+ // }+ //+ repeated_type.name().ends_with("_tuple")+ }++ /// Reads current record as `Row` from the reader tree.+ /// Automatically advances all necessary readers.+ /// This must be called on the root level reader (i.e., for Message type).+ /// Otherwise, it will panic.+ fn read(&mut self) -> Row {+ match *self {+ Reader::GroupReader(_, _, ref mut readers) => {+ let mut fields = Vec::new();+ for reader in readers {+ fields.push((String::from(reader.field_name()), reader.read_field()));+ }+ make_row(fields)+ }+ _ => panic!("Cannot call read() on {}", self),+ }+ }++ /// Reads current record as `Field` from the reader tree.+ /// Automatically advances all necessary readers.+ fn read_field(&mut self) -> Field {+ match *self {+ Reader::PrimitiveReader(_, ref mut column) => {+ let value = column.current_value();+ column.read_next().unwrap();+ value+ }+ Reader::OptionReader(def_level, ref mut reader) => {+ if reader.current_def_level() > def_level {+ reader.read_field()+ } else {+ reader.advance_columns();+ Field::Null+ }+ }+ Reader::GroupReader(_, def_level, ref mut readers) => {+ let mut fields = Vec::new();+ for reader in readers {+ if reader.repetition() != Repetition::OPTIONAL+ || reader.current_def_level() > def_level+ {+ fields.push((String::from(reader.field_name()), reader.read_field()));+ } else {+ reader.advance_columns();+ fields.push((String::from(reader.field_name()), Field::Null));+ }+ }+ let row = make_row(fields);+ Field::Group(row)+ }+ Reader::RepeatedReader(_, def_level, rep_level, ref mut reader) => {+ let mut elements = Vec::new();+ loop {+ if reader.current_def_level() > def_level {+ elements.push(reader.read_field());+ } else {+ reader.advance_columns();+ // If the current definition level is equal to the definition level of this+ // repeated type, then the result is an empty list and the repetition level+ // will always be <= rl.+ break;+ }++ // This covers case when we are out of repetition levels and should close the+ // group, or there are no values left to buffer.+ if !reader.has_next() || reader.current_rep_level() <= rep_level {+ break;+ }+ }+ Field::ListInternal(make_list(elements))+ }+ Reader::KeyValueReader(_, def_level, rep_level, ref mut keys, ref mut values) => {+ let mut pairs = Vec::new();+ loop {+ if keys.current_def_level() > def_level {+ pairs.push((keys.read_field(), values.read_field()));+ } else {+ keys.advance_columns();+ values.advance_columns();+ // If the current definition level is equal to the definition level of this+ // repeated type, then the result is an empty list and the repetition level+ // will always be <= rl.+ break;+ }++ // This covers case when we are out of repetition levels and should close the+ // group, or there are no values left to buffer.+ if !keys.has_next() || keys.current_rep_level() <= rep_level {+ break;+ }+ }++ Field::MapInternal(make_map(pairs))+ }+ }+ }++ /// Returns field name for the current reader.+ fn field_name(&self) -> &str {+ match *self {+ Reader::PrimitiveReader(ref field, _) => field.name(),+ Reader::OptionReader(_, ref reader) => reader.field_name(),+ Reader::GroupReader(ref opt, ..) => match opt {+ &Some(ref field) => field.name(),+ &None => panic!("Field is None for group reader"),+ },+ Reader::RepeatedReader(ref field, ..) => field.name(),+ Reader::KeyValueReader(ref field, ..) => field.name(),+ }+ }++ /// Returns repetition for the current reader.+ fn repetition(&self) -> Repetition {+ match *self {+ Reader::PrimitiveReader(ref field, _) => field.get_basic_info().repetition(),+ Reader::OptionReader(_, ref reader) => reader.repetition(),+ Reader::GroupReader(ref opt, ..) => match opt {+ &Some(ref field) => field.get_basic_info().repetition(),+ &None => panic!("Field is None for group reader"),+ },+ Reader::RepeatedReader(ref field, ..) => field.get_basic_info().repetition(),+ Reader::KeyValueReader(ref field, ..) => field.get_basic_info().repetition(),+ }+ }++ /// Returns true, if current reader has more values, false otherwise.+ /// Method does not advance internal iterator.+ fn has_next(&self) -> bool {+ match *self {+ Reader::PrimitiveReader(_, ref column) => column.has_next(),+ Reader::OptionReader(_, ref reader) => reader.has_next(),+ Reader::GroupReader(_, _, ref readers) => readers.first().unwrap().has_next(),+ Reader::RepeatedReader(_, _, _, ref reader) => reader.has_next(),+ Reader::KeyValueReader(_, _, _, ref keys, _) => keys.has_next(),+ }+ }++ /// Returns current definition level,+ /// Method does not advance internal iterator.+ fn current_def_level(&self) -> i16 {+ match *self {+ Reader::PrimitiveReader(_, ref column) => column.current_def_level(),+ Reader::OptionReader(_, ref reader) => reader.current_def_level(),+ Reader::GroupReader(_, _, ref readers) => match readers.first() {+ Some(reader) => reader.current_def_level(),+ None => panic!("Current definition level: empty group reader"),+ },+ Reader::RepeatedReader(_, _, _, ref reader) => reader.current_def_level(),+ Reader::KeyValueReader(_, _, _, ref keys, _) => keys.current_def_level(),+ }+ }++ /// Returns current repetition level.+ /// Method does not advance internal iterator.+ fn current_rep_level(&self) -> i16 {+ match *self {+ Reader::PrimitiveReader(_, ref column) => column.current_rep_level(),+ Reader::OptionReader(_, ref reader) => reader.current_rep_level(),+ Reader::GroupReader(_, _, ref readers) => match readers.first() {+ Some(reader) => reader.current_rep_level(),+ None => panic!("Current repetition level: empty group reader"),+ },+ Reader::RepeatedReader(_, _, _, ref reader) => reader.current_rep_level(),+ Reader::KeyValueReader(_, _, _, ref keys, _) => keys.current_rep_level(),+ }+ }++ /// Advances leaf columns for the current reader.+ fn advance_columns(&mut self) {+ match *self {+ Reader::PrimitiveReader(_, ref mut column) => {+ column.read_next().unwrap();+ }+ Reader::OptionReader(_, ref mut reader) => {+ reader.advance_columns();+ }+ Reader::GroupReader(_, _, ref mut readers) => {+ for reader in readers {+ reader.advance_columns();+ }+ }+ Reader::RepeatedReader(_, _, _, ref mut reader) => {+ reader.advance_columns();+ }+ Reader::KeyValueReader(_, _, _, ref mut keys, ref mut values) => {+ keys.advance_columns();+ values.advance_columns();+ }+ }+ }+}++impl fmt::Display for Reader {+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {+ let s = match self {+ Reader::PrimitiveReader(..) => "PrimitiveReader",+ Reader::OptionReader(..) => "OptionReader",+ Reader::GroupReader(..) => "GroupReader",+ Reader::RepeatedReader(..) => "RepeatedReader",+ Reader::KeyValueReader(..) => "KeyValueReader",+ };+ write!(f, "{}", s)+ }+}++// ----------------------------------------------------------------------+// Row iterators++/// Iterator of [`Row`](`::record::api::Row`)s.+/// It is used either for a single row group to iterate over data in that row group, or+/// an entire file with auto buffering of all row groups.+pub struct RowIter<'a> {+ descr: SchemaDescPtr,+ tree_builder: TreeBuilder,+ file_reader: Option<&'a FileReader>,+ current_row_group: usize,+ num_row_groups: usize,+ row_iter: Option<ReaderIter>,+}++impl<'a> RowIter<'a> {+ /// Creates iterator of [`Row`](`::record::api::Row`)s for all row groups in a file.+ pub fn from_file(proj: Option<Type>, reader: &'a FileReader) -> Result<Self> {+ let descr =+ Self::get_proj_descr(proj, reader.metadata().file_metadata().schema_descr_ptr())?;+ let num_row_groups = reader.num_row_groups();++ Ok(Self {+ descr,+ tree_builder: Self::tree_builder(),+ file_reader: Some(reader),+ current_row_group: 0,+ num_row_groups,+ row_iter: None,+ })+ }++ /// Creates iterator of [`Row`](`::record::api::Row`)s for a specific row group.+ pub fn from_row_group(proj: Option<Type>, reader: &'a RowGroupReader) -> Result<Self> {+ let descr = Self::get_proj_descr(proj, reader.metadata().schema_descr_ptr())?;+ let tree_builder = Self::tree_builder();+ let row_iter = tree_builder.as_iter(descr.clone(), reader);++ // For row group we need to set `current_row_group` >= `num_row_groups`, because we+ // only have one row group and can't buffer more.+ Ok(Self {+ descr,+ tree_builder,+ file_reader: None,+ current_row_group: 0,+ num_row_groups: 0,+ row_iter: Some(row_iter),+ })+ }++ /// Returns common tree builder, so the same settings are applied to both iterators+ /// from file reader and row group.+ #[inline]+ fn tree_builder() -> TreeBuilder {+ TreeBuilder::new()+ }++ /// Helper method to get schema descriptor for projected schema.+ /// If projection is None, then full schema is returned.+ #[inline]+ fn get_proj_descr(proj: Option<Type>, root_descr: SchemaDescPtr) -> Result<SchemaDescPtr> {+ match proj {+ Some(projection) => {+ // check if projection is part of file schema+ let root_schema = root_descr.root_schema();+ if !root_schema.check_contains(&projection) {+ return Err(general_err!("Root schema does not contain projection"));+ }+ Ok(Rc::new(SchemaDescriptor::new(Rc::new(projection))))+ }+ None => Ok(root_descr),+ }+ }+}++impl<'a> Iterator for RowIter<'a> {+ type Item = Row;++ fn next(&mut self) -> Option<Row> {+ let mut row = None;+ if let Some(ref mut iter) = self.row_iter {+ row = iter.next();+ }++ while row.is_none() && self.current_row_group < self.num_row_groups {+ // We do not expect any failures when accessing a row group, and file reader+ // must be set for selecting next row group.+ let row_group_reader = &*self+ .file_reader+ .as_ref()+ .expect("File reader is required to advance row group")+ .get_row_group(self.current_row_group)+ .unwrap();+ self.current_row_group += 1;+ let mut iter = self+ .tree_builder+ .as_iter(self.descr.clone(), row_group_reader);+ row = iter.next();+ self.row_iter = Some(iter);+ }++ row+ }+}++/// Internal iterator of [`Row`](`::record::api::Row`)s for a reader.+pub struct ReaderIter {+ root_reader: Reader,+ records_left: usize,+}++impl ReaderIter {+ fn new(mut root_reader: Reader, num_records: usize) -> Self {+ // Prepare root reader by advancing all column vectors+ root_reader.advance_columns();+ Self {+ root_reader,+ records_left: num_records,+ }+ }+}++impl Iterator for ReaderIter {+ type Item = Row;++ fn next(&mut self) -> Option<Row> {+ if self.records_left > 0 {+ self.records_left -= 1;+ Some(self.root_reader.read())+ } else {+ None+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ use crate::parquet::errors::{ParquetError, Result};+ use crate::parquet::file::reader::{FileReader, SerializedFileReader};+ use crate::parquet::record::api::{Field, Row};+ use crate::parquet::schema::parser::parse_message_type;+ use crate::parquet::util::test_common::get_test_file;++ // Convenient macros to assemble row, list, map, and group.++ macro_rules! row {+ () => {+ {+ let result = Vec::new();+ make_row(result)+ }+ };+ ( $( $e:expr ), + ) => {+ {+ let mut result = Vec::new();+ $(+ result.push($e);+ )*+ make_row(result)+ }+ }+ }++ macro_rules! list {+ () => {+ {+ let result = Vec::new();+ Field::ListInternal(make_list(result))+ }+ };+ ( $( $e:expr ), + ) => {+ {+ let mut result = Vec::new();+ $(+ result.push($e);+ )*+ Field::ListInternal(make_list(result))+ }+ }+ }++ macro_rules! map {+ () => {+ {+ let result = Vec::new();+ Field::MapInternal(make_map(result))+ }+ };+ ( $( $e:expr ), + ) => {+ {+ let mut result = Vec::new();+ $(+ result.push($e);+ )*+ Field::MapInternal(make_map(result))+ }+ }+ }++ macro_rules! group {+ ( $( $e:expr ), * ) => {+ {+ Field::Group(row!($( $e ), *))+ }+ }+ }++ #[test]+ fn test_file_reader_rows_nulls() {+ let rows = test_file_reader_rows("nulls.snappy.parquet", None).unwrap();+ let expected_rows = vec![+ row![(+ "b_struct".to_string(),+ group![("b_c_int".to_string(), Field::Null)]+ )],+ row![(+ "b_struct".to_string(),+ group![("b_c_int".to_string(), Field::Null)]+ )],+ row![(+ "b_struct".to_string(),+ group![("b_c_int".to_string(), Field::Null)]+ )],+ row![(+ "b_struct".to_string(),+ group![("b_c_int".to_string(), Field::Null)]+ )],+ row![(+ "b_struct".to_string(),+ group![("b_c_int".to_string(), Field::Null)]+ )],+ row![(+ "b_struct".to_string(),+ group![("b_c_int".to_string(), Field::Null)]+ )],+ row![(+ "b_struct".to_string(),+ group![("b_c_int".to_string(), Field::Null)]+ )],+ row![(+ "b_struct".to_string(),+ group![("b_c_int".to_string(), Field::Null)]+ )],+ ];+ assert_eq!(rows, expected_rows);+ }++ #[test]+ fn test_file_reader_rows_nonnullable() {+ let rows = test_file_reader_rows("nonnullable.impala.parquet", None).unwrap();+ let expected_rows = vec![row![+ ("ID".to_string(), Field::Long(8)),+ ("Int_Array".to_string(), list![Field::Int(-1)]),+ (+ "int_array_array".to_string(),+ list![list![Field::Int(-1), Field::Int(-2)], list![]]+ ),+ (+ "Int_Map".to_string(),+ map![(Field::Str("k1".to_string()), Field::Int(-1))]+ ),+ (+ "int_map_array".to_string(),+ list![+ map![],+ map![(Field::Str("k1".to_string()), Field::Int(1))],+ map![],+ map![]+ ]+ ),+ (+ "nested_Struct".to_string(),+ group![+ ("a".to_string(), Field::Int(-1)),+ ("B".to_string(), list![Field::Int(-1)]),+ (+ "c".to_string(),+ group![(+ "D".to_string(),+ list![list![group![+ ("e".to_string(), Field::Int(-1)),+ ("f".to_string(), Field::Str("nonnullable".to_string()))+ ]]]+ )]+ ),+ ("G".to_string(), map![])+ ]+ )+ ]];+ assert_eq!(rows, expected_rows);+ }++ #[test]+ fn test_file_reader_rows_nullable() {+ let rows = test_file_reader_rows("nullable.impala.parquet", None).unwrap();+ let expected_rows = vec![+ row![+ ("id".to_string(), Field::Long(1)),+ (+ "int_array".to_string(),+ list![Field::Int(1), Field::Int(2), Field::Int(3)]+ ),+ (+ "int_array_Array".to_string(),+ list![+ list![Field::Int(1), Field::Int(2)],+ list![Field::Int(3), Field::Int(4)]+ ]+ ),+ (+ "int_map".to_string(),+ map![+ (Field::Str("k1".to_string()), Field::Int(1)),+ (Field::Str("k2".to_string()), Field::Int(100))+ ]+ ),+ (+ "int_Map_Array".to_string(),+ list![map![(Field::Str("k1".to_string()), Field::Int(1))]]+ ),+ (+ "nested_struct".to_string(),+ group![+ ("A".to_string(), Field::Int(1)),+ ("b".to_string(), list![Field::Int(1)]),+ (+ "C".to_string(),+ group![(+ "d".to_string(),+ list![+ list![+ group![+ ("E".to_string(), Field::Int(10)),+ ("F".to_string(), Field::Str("aaa".to_string()))+ ],+ group![+ ("E".to_string(), Field::Int(-10)),+ ("F".to_string(), Field::Str("bbb".to_string()))+ ]+ ],+ list![group![+ ("E".to_string(), Field::Int(11)),+ ("F".to_string(), Field::Str("c".to_string()))+ ]]+ ]+ )]+ ),+ (+ "g".to_string(),+ map![(+ Field::Str("foo".to_string()),+ group![(+ "H".to_string(),+ group![("i".to_string(), list![Field::Double(1.1)])]+ )]+ )]+ )+ ]+ )+ ],+ row![+ ("id".to_string(), Field::Long(2)),+ (+ "int_array".to_string(),+ list![+ Field::Null,+ Field::Int(1),+ Field::Int(2),+ Field::Null,+ Field::Int(3),+ Field::Null+ ]+ ),+ (+ "int_array_Array".to_string(),+ list![+ list![Field::Null, Field::Int(1), Field::Int(2), Field::Null],+ list![Field::Int(3), Field::Null, Field::Int(4)],+ list![],+ Field::Null+ ]+ ),+ (+ "int_map".to_string(),+ map![+ (Field::Str("k1".to_string()), Field::Int(2)),+ (Field::Str("k2".to_string()), Field::Null)+ ]+ ),+ (+ "int_Map_Array".to_string(),+ list![+ map![+ (Field::Str("k3".to_string()), Field::Null),+ (Field::Str("k1".to_string()), Field::Int(1))+ ],+ Field::Null,+ map![]+ ]+ ),+ (+ "nested_struct".to_string(),+ group![+ ("A".to_string(), Field::Null),+ ("b".to_string(), list![Field::Null]),+ (+ "C".to_string(),+ group![(+ "d".to_string(),+ list![+ list![+ group![+ ("E".to_string(), Field::Null),+ ("F".to_string(), Field::Null)+ ],+ group![+ ("E".to_string(), Field::Int(10)),+ ("F".to_string(), Field::Str("aaa".to_string()))+ ],+ group![+ ("E".to_string(), Field::Null),+ ("F".to_string(), Field::Null)+ ],+ group![+ ("E".to_string(), Field::Int(-10)),+ ("F".to_string(), Field::Str("bbb".to_string()))+ ],+ group![+ ("E".to_string(), Field::Null),+ ("F".to_string(), Field::Null)+ ]+ ],+ list![+ group![+ ("E".to_string(), Field::Int(11)),+ ("F".to_string(), Field::Str("c".to_string()))+ ],+ Field::Null+ ],+ list![],+ Field::Null+ ]+ )]+ ),+ (+ "g".to_string(),+ map![+ (+ Field::Str("g1".to_string()),+ group![(+ "H".to_string(),+ group![(+ "i".to_string(),+ list![Field::Double(2.2), Field::Null]+ )]+ )]+ ),+ (+ Field::Str("g2".to_string()),+ group![("H".to_string(), group![("i".to_string(), list![])])]+ ),+ (Field::Str("g3".to_string()), Field::Null),+ (+ Field::Str("g4".to_string()),+ group![(+ "H".to_string(),+ group![("i".to_string(), Field::Null)]+ )]+ ),+ (+ Field::Str("g5".to_string()),+ group![("H".to_string(), Field::Null)]+ )+ ]+ )+ ]+ )+ ],+ row![+ ("id".to_string(), Field::Long(3)),+ ("int_array".to_string(), list![]),+ ("int_array_Array".to_string(), list![Field::Null]),+ ("int_map".to_string(), map![]),+ ("int_Map_Array".to_string(), list![Field::Null, Field::Null]),+ (+ "nested_struct".to_string(),+ group![+ ("A".to_string(), Field::Null),+ ("b".to_string(), Field::Null),+ ("C".to_string(), group![("d".to_string(), list![])]),+ ("g".to_string(), map![])+ ]+ )+ ],+ row![+ ("id".to_string(), Field::Long(4)),+ ("int_array".to_string(), Field::Null),+ ("int_array_Array".to_string(), list![]),+ ("int_map".to_string(), map![]),+ ("int_Map_Array".to_string(), list![]),+ (+ "nested_struct".to_string(),+ group![+ ("A".to_string(), Field::Null),+ ("b".to_string(), Field::Null),+ ("C".to_string(), group![("d".to_string(), Field::Null)]),+ ("g".to_string(), Field::Null)+ ]+ )+ ],+ row![+ ("id".to_string(), Field::Long(5)),+ ("int_array".to_string(), Field::Null),+ ("int_array_Array".to_string(), Field::Null),+ ("int_map".to_string(), map![]),+ ("int_Map_Array".to_string(), Field::Null),+ (+ "nested_struct".to_string(),+ group![+ ("A".to_string(), Field::Null),+ ("b".to_string(), Field::Null),+ ("C".to_string(), Field::Null),+ (+ "g".to_string(),+ map![(+ Field::Str("foo".to_string()),+ group![(+ "H".to_string(),+ group![(+ "i".to_string(),+ list![Field::Double(2.2), Field::Double(3.3)]+ )]+ )]+ )]+ )+ ]+ )+ ],+ row![+ ("id".to_string(), Field::Long(6)),+ ("int_array".to_string(), Field::Null),+ ("int_array_Array".to_string(), Field::Null),+ ("int_map".to_string(), Field::Null),+ ("int_Map_Array".to_string(), Field::Null),+ ("nested_struct".to_string(), Field::Null)+ ],+ row![+ ("id".to_string(), Field::Long(7)),+ ("int_array".to_string(), Field::Null),+ (+ "int_array_Array".to_string(),+ list![Field::Null, list![Field::Int(5), Field::Int(6)]]+ ),+ (+ "int_map".to_string(),+ map![+ (Field::Str("k1".to_string()), Field::Null),+ (Field::Str("k3".to_string()), Field::Null)+ ]+ ),+ ("int_Map_Array".to_string(), Field::Null),+ (+ "nested_struct".to_string(),+ group![+ ("A".to_string(), Field::Int(7)),+ (+ "b".to_string(),+ list![Field::Int(2), Field::Int(3), Field::Null]+ ),+ (+ "C".to_string(),+ group![(+ "d".to_string(),+ list![list![], list![Field::Null], Field::Null]+ )]+ ),+ ("g".to_string(), Field::Null)+ ]+ )+ ],+ ];+ assert_eq!(rows, expected_rows);+ }++ #[test]+ fn test_file_reader_rows_projection() {+ let schema = "+ message spark_schema {+ REQUIRED DOUBLE c;+ REQUIRED INT32 b;+ }+ ";+ let schema = parse_message_type(&schema).unwrap();+ let rows = test_file_reader_rows("nested_maps.snappy.parquet", Some(schema)).unwrap();+ let expected_rows = vec![+ row![+ ("c".to_string(), Field::Double(1.0)),+ ("b".to_string(), Field::Int(1))+ ],+ row![+ ("c".to_string(), Field::Double(1.0)),+ ("b".to_string(), Field::Int(1))+ ],+ row![+ ("c".to_string(), Field::Double(1.0)),+ ("b".to_string(), Field::Int(1))+ ],+ row![+ ("c".to_string(), Field::Double(1.0)),+ ("b".to_string(), Field::Int(1))+ ],+ row![+ ("c".to_string(), Field::Double(1.0)),+ ("b".to_string(), Field::Int(1))+ ],+ row![+ ("c".to_string(), Field::Double(1.0)),+ ("b".to_string(), Field::Int(1))+ ],+ ];+ assert_eq!(rows, expected_rows);+ }++ #[test]+ fn test_file_reader_rows_projection_map() {+ let schema = "+ message spark_schema {+ OPTIONAL group a (MAP) {+ REPEATED group key_value {+ REQUIRED BYTE_ARRAY key (UTF8);+ OPTIONAL group value (MAP) {+ REPEATED group key_value {+ REQUIRED INT32 key;+ REQUIRED BOOLEAN value;+ }+ }+ }+ }+ }+ ";+ let schema = parse_message_type(&schema).unwrap();+ let rows = test_file_reader_rows("nested_maps.snappy.parquet", Some(schema)).unwrap();+ let expected_rows = vec![+ row![(+ "a".to_string(),+ map![(+ Field::Str("a".to_string()),+ map![+ (Field::Int(1), Field::Bool(true)),+ (Field::Int(2), Field::Bool(false))+ ]+ )]+ )],+ row![(+ "a".to_string(),+ map![(+ Field::Str("b".to_string()),+ map![(Field::Int(1), Field::Bool(true))]+ )]+ )],+ row![(+ "a".to_string(),+ map![(Field::Str("c".to_string()), Field::Null)]+ )],+ row![("a".to_string(), map![(Field::Str("d".to_string()), map![])])],+ row![(+ "a".to_string(),+ map![(+ Field::Str("e".to_string()),+ map![(Field::Int(1), Field::Bool(true))]+ )]+ )],+ row![(+ "a".to_string(),+ map![(+ Field::Str("f".to_string()),+ map![+ (Field::Int(3), Field::Bool(true)),+ (Field::Int(4), Field::Bool(false)),+ (Field::Int(5), Field::Bool(true))+ ]+ )]+ )],+ ];+ assert_eq!(rows, expected_rows);+ }++ #[test]+ fn test_file_reader_rows_projection_list() {+ let schema = "+ message spark_schema {+ OPTIONAL group a (LIST) {+ REPEATED group list {+ OPTIONAL group element (LIST) {+ REPEATED group list {+ OPTIONAL group element (LIST) {+ REPEATED group list {+ OPTIONAL BYTE_ARRAY element (UTF8);+ }+ }+ }+ }+ }+ }+ }+ ";+ let schema = parse_message_type(&schema).unwrap();+ let rows = test_file_reader_rows("nested_lists.snappy.parquet", Some(schema)).unwrap();+ let expected_rows = vec![+ row![(+ "a".to_string(),+ list![+ list![+ list![Field::Str("a".to_string()), Field::Str("b".to_string())],+ list![Field::Str("c".to_string())]+ ],+ list![Field::Null, list![Field::Str("d".to_string())]]+ ]+ )],+ row![(+ "a".to_string(),+ list![+ list![+ list![Field::Str("a".to_string()), Field::Str("b".to_string())],+ list![Field::Str("c".to_string()), Field::Str("d".to_string())]+ ],+ list![Field::Null, list![Field::Str("e".to_string())]]+ ]+ )],+ row![(+ "a".to_string(),+ list![+ list![+ list![Field::Str("a".to_string()), Field::Str("b".to_string())],+ list![Field::Str("c".to_string()), Field::Str("d".to_string())],+ list![Field::Str("e".to_string())]+ ],+ list![Field::Null, list![Field::Str("f".to_string())]]+ ]+ )],+ ];+ assert_eq!(rows, expected_rows);+ }++ #[test]+ fn test_file_reader_rows_invalid_projection() {+ let schema = "+ message spark_schema {+ REQUIRED INT32 key;+ REQUIRED BOOLEAN value;+ }+ ";+ let schema = parse_message_type(&schema).unwrap();+ let res = test_file_reader_rows("nested_maps.snappy.parquet", Some(schema));+ assert!(res.is_err());+ assert_eq!(+ res.unwrap_err(),+ general_err!("Root schema does not contain projection")+ );+ }++ #[test]+ fn test_row_group_rows_invalid_projection() {+ let schema = "+ message spark_schema {+ REQUIRED INT32 key;+ REQUIRED BOOLEAN value;+ }+ ";+ let schema = parse_message_type(&schema).unwrap();+ let res = test_row_group_rows("nested_maps.snappy.parquet", Some(schema));+ assert!(res.is_err());+ assert_eq!(+ res.unwrap_err(),+ general_err!("Root schema does not contain projection")+ );+ }++ #[test]+ #[should_panic(expected = "Invalid map type")]+ fn test_file_reader_rows_invalid_map_type() {+ let schema = "+ message spark_schema {+ OPTIONAL group a (MAP) {+ REPEATED group key_value {+ REQUIRED BYTE_ARRAY key (UTF8);+ OPTIONAL group value (MAP) {+ REPEATED group key_value {+ REQUIRED INT32 key;+ }+ }+ }+ }+ }+ ";+ let schema = parse_message_type(&schema).unwrap();+ test_file_reader_rows("nested_maps.snappy.parquet", Some(schema)).unwrap();+ }++ #[test]+ fn test_tree_reader_handle_repeated_fields_with_no_annotation() {+ // Array field `phoneNumbers` does not contain LIST annotation.+ // We parse it as struct with `phone` repeated field as array.+ let rows = test_file_reader_rows("repeated_no_annotation.parquet", None).unwrap();+ let expected_rows = vec![+ row![+ ("id".to_string(), Field::Int(1)),+ ("phoneNumbers".to_string(), Field::Null)+ ],+ row![+ ("id".to_string(), Field::Int(2)),+ ("phoneNumbers".to_string(), Field::Null)+ ],+ row![+ ("id".to_string(), Field::Int(3)),+ (+ "phoneNumbers".to_string(),+ group![("phone".to_string(), list![])]+ )+ ],+ row![+ ("id".to_string(), Field::Int(4)),+ (+ "phoneNumbers".to_string(),+ group![(+ "phone".to_string(),+ list![group![+ ("number".to_string(), Field::Long(5555555555)),+ ("kind".to_string(), Field::Null)+ ]]+ )]+ )+ ],+ row![+ ("id".to_string(), Field::Int(5)),+ (+ "phoneNumbers".to_string(),+ group![(+ "phone".to_string(),+ list![group![+ ("number".to_string(), Field::Long(1111111111)),+ ("kind".to_string(), Field::Str("home".to_string()))+ ]]+ )]+ )+ ],+ row![+ ("id".to_string(), Field::Int(6)),+ (+ "phoneNumbers".to_string(),+ group![(+ "phone".to_string(),+ list![+ group![+ ("number".to_string(), Field::Long(1111111111)),+ ("kind".to_string(), Field::Str("home".to_string()))+ ],+ group![+ ("number".to_string(), Field::Long(2222222222)),+ ("kind".to_string(), Field::Null)+ ],+ group![+ ("number".to_string(), Field::Long(3333333333)),+ ("kind".to_string(), Field::Str("mobile".to_string()))+ ]+ ]+ )]+ )+ ],+ ];++ assert_eq!(rows, expected_rows);+ }++ fn test_file_reader_rows(file_name: &str, schema: Option<Type>) -> Result<Vec<Row>> {+ let file = get_test_file(file_name);+ let file_reader: Box<FileReader> = Box::new(SerializedFileReader::new(file)?);+ let iter = file_reader.get_row_iter(schema)?;+ Ok(iter.collect())+ }++ fn test_row_group_rows(file_name: &str, schema: Option<Type>) -> Result<Vec<Row>> {+ let file = get_test_file(file_name);+ let file_reader: Box<FileReader> = Box::new(SerializedFileReader::new(file)?);+ // Check the first row group only, because files will contain only single row group+ let row_group_reader = file_reader.get_row_group(0).unwrap();+ let iter = row_group_reader.get_row_iter(schema)?;+ Ok(iter.collect())+ }+}diff --git a/rust/src/parquet/record/triplet.rs b/rust/src/parquet/record/triplet.rsnew file mode 100644index 0000000000..fadcbbce9b--- /dev/null+++ b/rust/src/parquet/record/triplet.rs@@ -0,0 +1,561 @@+// Licensed to the Apache Software Foundation (ASF) under one+// or more contributor license agreements. See the NOTICE file+// distributed with this work for additional information+// regarding copyright ownership. The ASF licenses this file+// to you under the Apache License, Version 2.0 (the+// "License"); you may not use this file except in compliance+// with the License. You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing,+// software distributed under the License is distributed on an+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+// KIND, either express or implied. See the License for the+// specific language governing permissions and limitations+// under the License.++use crate::parquet::basic::Type as PhysicalType;+use crate::parquet::column::reader::{get_typed_column_reader, ColumnReader, ColumnReaderImpl};+use crate::parquet::data_type::*;+use crate::parquet::errors::{ParquetError, Result};+use crate::parquet::record::api::Field;+use crate::parquet::schema::types::ColumnDescPtr;++/// Macro to generate simple functions that cover all types of triplet iterator.+/// $func is a function of a typed triplet iterator and $token is a either {`ref`} or+/// {`ref`, `mut`}+macro_rules! triplet_enum_func {+ ($self:ident, $func:ident, $( $token:tt ),*) => ({+ match *$self {+ TripletIter::BoolTripletIter($($token)* typed) => typed.$func(),+ TripletIter::Int32TripletIter($($token)* typed) => typed.$func(),+ TripletIter::Int64TripletIter($($token)* typed) => typed.$func(),+ TripletIter::Int96TripletIter($($token)* typed) => typed.$func(),+ TripletIter::FloatTripletIter($($token)* typed) => typed.$func(),+ TripletIter::DoubleTripletIter($($token)* typed) => typed.$func(),+ TripletIter::ByteArrayTripletIter($($token)* typed) => typed.$func(),+ TripletIter::FixedLenByteArrayTripletIter($($token)* typed) => typed.$func()+ }+ });+}++/// High level API wrapper on column reader.+/// Provides per-element access for each primitive column.+pub enum TripletIter {+ BoolTripletIter(TypedTripletIter<BoolType>),+ Int32TripletIter(TypedTripletIter<Int32Type>),+ Int64TripletIter(TypedTripletIter<Int64Type>),+ Int96TripletIter(TypedTripletIter<Int96Type>),+ FloatTripletIter(TypedTripletIter<FloatType>),+ DoubleTripletIter(TypedTripletIter<DoubleType>),+ ByteArrayTripletIter(TypedTripletIter<ByteArrayType>),+ FixedLenByteArrayTripletIter(TypedTripletIter<FixedLenByteArrayType>),+}++impl TripletIter {+ /// Creates new triplet for column reader+ pub fn new(descr: ColumnDescPtr, reader: ColumnReader, batch_size: usize) -> Self {+ match descr.physical_type() {+ PhysicalType::BOOLEAN => {+ TripletIter::BoolTripletIter(TypedTripletIter::new(descr, batch_size, reader))+ }+ PhysicalType::INT32 => {+ TripletIter::Int32TripletIter(TypedTripletIter::new(descr, batch_size, reader))+ }+ PhysicalType::INT64 => {+ TripletIter::Int64TripletIter(TypedTripletIter::new(descr, batch_size, reader))+ }+ PhysicalType::INT96 => {+ TripletIter::Int96TripletIter(TypedTripletIter::new(descr, batch_size, reader))+ }+ PhysicalType::FLOAT => {+ TripletIter::FloatTripletIter(TypedTripletIter::new(descr, batch_size, reader))+ }+ PhysicalType::DOUBLE => {+ TripletIter::DoubleTripletIter(TypedTripletIter::new(descr, batch_size, reader))+ }+ PhysicalType::BYTE_ARRAY => {+ TripletIter::ByteArrayTripletIter(TypedTripletIter::new(descr, batch_size, reader))+ }+ PhysicalType::FIXED_LEN_BYTE_ARRAY => TripletIter::FixedLenByteArrayTripletIter(+ TypedTripletIter::new(descr, batch_size, reader),+ ),+ }+ }++ /// Invokes underlying typed triplet iterator to buffer current value.+ /// Should be called once - either before `is_null` or `current_value`.+ #[inline]+ pub fn read_next(&mut self) -> Result<bool> {+ triplet_enum_func!(self, read_next, ref, mut)+ }++ /// Provides check on values/levels left without invoking the underlying typed triplet+ /// iterator.+ /// Returns true if more values/levels exist, false otherwise.+ /// It is always in sync with `read_next` method.+ #[inline]+ pub fn has_next(&self) -> bool {+ triplet_enum_func!(self, has_next, ref)+ }++ /// Returns current definition level for a leaf triplet iterator+ #[inline]+ pub fn current_def_level(&self) -> i16 {+ triplet_enum_func!(self, current_def_level, ref)+ }++ /// Returns max definition level for a leaf triplet iterator+ #[inline]+ pub fn max_def_level(&self) -> i16 {+ triplet_enum_func!(self, max_def_level, ref)+ }++ /// Returns current repetition level for a leaf triplet iterator+ #[inline]+ pub fn current_rep_level(&self) -> i16 {+ triplet_enum_func!(self, current_rep_level, ref)+ }++ /// Returns max repetition level for a leaf triplet iterator+ #[inline]+ pub fn max_rep_level(&self) -> i16 {+ triplet_enum_func!(self, max_rep_level, ref)+ }++ /// Returns true, if current value is null.+ /// Based on the fact that for non-null value current definition level+ /// equals to max definition level.+ #[inline]+ pub fn is_null(&self) -> bool {+ self.current_def_level() < self.max_def_level()+ }++ /// Updates non-null value for current row.+ pub fn current_value(&self) -> Field {+ assert!(!self.is_null(), "Value is null");+ match *self {+ TripletIter::BoolTripletIter(ref typed) => {+ Field::convert_bool(typed.column_descr(), *typed.current_value())+ }+ TripletIter::Int32TripletIter(ref typed) => {+ Field::convert_int32(typed.column_descr(), *typed.current_value())+ }+ TripletIter::Int64TripletIter(ref typed) => {+ Field::convert_int64(typed.column_descr(), *typed.current_value())+ }+ TripletIter::Int96TripletIter(ref typed) => {+ Field::convert_int96(typed.column_descr(), typed.current_value().clone())+ }+ TripletIter::FloatTripletIter(ref typed) => {+ Field::convert_float(typed.column_descr(), *typed.current_value())+ }+ TripletIter::DoubleTripletIter(ref typed) => {+ Field::convert_double(typed.column_descr(), *typed.current_value())+ }+ TripletIter::ByteArrayTripletIter(ref typed) => {+ Field::convert_byte_array(typed.column_descr(), typed.current_value().clone())+ }+ TripletIter::FixedLenByteArrayTripletIter(ref typed) => {+ Field::convert_byte_array(typed.column_descr(), typed.current_value().clone())+ }+ }+ }+}++/// Internal typed triplet iterator as a wrapper for column reader+/// (primitive leaf column), provides per-element access.+pub struct TypedTripletIter<T: DataType> {+ reader: ColumnReaderImpl<T>,+ column_descr: ColumnDescPtr,+ batch_size: usize,+ // type properties+ max_def_level: i16,+ max_rep_level: i16,+ // values and levels+ values: Vec<T::T>,+ def_levels: Option<Vec<i16>>,+ rep_levels: Option<Vec<i16>>,+ // current index for the triplet (value, def, rep)+ curr_triplet_index: usize,+ // how many triplets are left before we need to buffer+ triplets_left: usize,+ // helper flag to quickly check if we have more values/levels to read+ has_next: bool,+}++impl<T: DataType> TypedTripletIter<T> {+ /// Creates new typed triplet iterator based on provided column reader.+ /// Use batch size to specify the amount of values to buffer from column reader.+ fn new(descr: ColumnDescPtr, batch_size: usize, column_reader: ColumnReader) -> Self {+ assert!(+ batch_size > 0,+ "Expected positive batch size, found: {}",+ batch_size+ );++ let max_def_level = descr.max_def_level();+ let max_rep_level = descr.max_rep_level();++ let def_levels = if max_def_level == 0 {+ None+ } else {+ Some(vec![0; batch_size])+ };+ let rep_levels = if max_rep_level == 0 {+ None+ } else {+ Some(vec![0; batch_size])+ };++ Self {+ reader: get_typed_column_reader(column_reader),+ column_descr: descr,+ batch_size,+ max_def_level,+ max_rep_level,+ values: vec![T::T::default(); batch_size],+ def_levels,+ rep_levels,+ curr_triplet_index: 0,+ triplets_left: 0,+ has_next: false,+ }+ }++ /// Returns column descriptor reference for the current typed triplet iterator.+ #[inline]+ pub fn column_descr(&self) -> &ColumnDescPtr {+ &self.column_descr+ }++ /// Returns maximum definition level for the triplet iterator (leaf column).+ #[inline]+ fn max_def_level(&self) -> i16 {+ self.max_def_level+ }++ /// Returns maximum repetition level for the triplet iterator (leaf column).+ #[inline]+ fn max_rep_level(&self) -> i16 {+ self.max_rep_level+ }++ /// Returns current value.+ /// Method does not advance the iterator, therefore can be called multiple times.+ #[inline]+ fn current_value(&self) -> &T::T {+ assert!(+ self.current_def_level() == self.max_def_level(),+ "Cannot extract value, max definition level: {}, current level: {}",+ self.max_def_level(),+ self.current_def_level()+ );+ &self.values[self.curr_triplet_index]+ }++ /// Returns current definition level.+ /// If field is required, then maximum definition level is returned.+ #[inline]+ fn current_def_level(&self) -> i16 {+ match self.def_levels {+ Some(ref vec) => vec[self.curr_triplet_index],+ None => self.max_def_level,+ }+ }++ /// Returns current repetition level.+ /// If field is required, then maximum repetition level is returned.+ #[inline]+ fn current_rep_level(&self) -> i16 {+ match self.rep_levels {+ Some(ref vec) => vec[self.curr_triplet_index],+ None => self.max_rep_level,+ }+ }++ /// Quick check if iterator has more values/levels to read.+ /// It is updated as a result of `read_next` method, so they are synchronized.+ #[inline]+ fn has_next(&self) -> bool {+ self.has_next+ }++ /// Advances to the next triplet.+ /// Returns true, if there are more records to read, false there are no records left.+ fn read_next(&mut self) -> Result<bool> {+ self.curr_triplet_index += 1;++ if self.curr_triplet_index >= self.triplets_left {+ let (values_read, levels_read) = {+ // Get slice of definition levels, if available+ let def_levels = match self.def_levels {+ Some(ref mut vec) => Some(&mut vec[..]),+ None => None,+ };++ // Get slice of repetition levels, if available+ let rep_levels = match self.rep_levels {+ Some(ref mut vec) => Some(&mut vec[..]),+ None => None,+ };++ // Buffer triplets+ self.reader+ .read_batch(self.batch_size, def_levels, rep_levels, &mut self.values)?+ };++ // No more values or levels to read+ if values_read == 0 && levels_read == 0 {+ self.has_next = false;+ return Ok(false);+ }++ // We never read values more than levels+ if levels_read == 0 || values_read == levels_read {+ // There are no definition levels to read, column is required+ // or definition levels match values, so it does not require spacing+ self.curr_triplet_index = 0;+ self.triplets_left = values_read;+ } else if values_read < levels_read {+ // Add spacing for triplets.+ // The idea is setting values for positions in def_levels when current definition+ // level equals to maximum definition level. Values and levels are guaranteed to+ // line up, because of the column reader method.++ // Note: if values_read == 0, then spacing will not be triggered+ let mut idx = values_read;+ let def_levels = self.def_levels.as_ref().unwrap();+ for i in 0..levels_read {+ if def_levels[levels_read - i - 1] == self.max_def_level {+ idx -= 1; // This is done to avoid usize becoming a negative value+ self.values.swap(levels_read - i - 1, idx);+ }+ }+ self.curr_triplet_index = 0;+ self.triplets_left = levels_read;+ } else {+ return Err(general_err!(+ "Spacing of values/levels is wrong, values_read: {}, levels_read: {}",+ values_read,+ levels_read+ ));+ }+ }++ self.has_next = true;+ Ok(true)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ use crate::parquet::file::reader::{FileReader, SerializedFileReader};+ use crate::parquet::schema::types::ColumnPath;+ use crate::parquet::util::test_common::get_test_file;++ #[test]+ #[should_panic(expected = "Expected positive batch size, found: 0")]+ fn test_triplet_zero_batch_size() {+ let column_path = ColumnPath::from(vec!["b_struct".to_string(), "b_c_int".to_string()]);+ test_column_in_file(+ "nulls.snappy.parquet",+ 0,+ &column_path,+ &vec![],+ &vec![],+ &vec![],+ );+ }++ #[test]+ fn test_triplet_null_column() {+ let path = vec!["b_struct", "b_c_int"];+ let values = vec![];+ let def_levels = vec![1, 1, 1, 1, 1, 1, 1, 1];+ let rep_levels = vec![0, 0, 0, 0, 0, 0, 0, 0];+ test_triplet_iter(+ "nulls.snappy.parquet",+ path,+ &values,+ &def_levels,+ &rep_levels,+ );+ }++ #[test]+ fn test_triplet_required_column() {+ let path = vec!["ID"];+ let values = vec![Field::Long(8)];+ let def_levels = vec![0];+ let rep_levels = vec![0];+ test_triplet_iter(+ "nonnullable.impala.parquet",+ path,+ &values,+ &def_levels,+ &rep_levels,+ );+ }++ #[test]+ fn test_triplet_optional_column() {+ let path = vec!["nested_struct", "A"];+ let values = vec![Field::Int(1), Field::Int(7)];+ let def_levels = vec![2, 1, 1, 1, 1, 0, 2];+ let rep_levels = vec![0, 0, 0, 0, 0, 0, 0];+ test_triplet_iter(+ "nullable.impala.parquet",+ path,+ &values,+ &def_levels,+ &rep_levels,+ );+ }++ #[test]+ fn test_triplet_optional_list_column() {+ let path = vec!["a", "list", "element", "list", "element", "list", "element"];+ let values = vec![+ Field::Str("a".to_string()),+ Field::Str("b".to_string()),+ Field::Str("c".to_string()),+ Field::Str("d".to_string()),+ Field::Str("a".to_string()),+ Field::Str("b".to_string()),+ Field::Str("c".to_string()),+ Field::Str("d".to_string()),+ Field::Str("e".to_string()),+ Field::Str("a".to_string()),+ Field::Str("b".to_string()),+ Field::Str("c".to_string()),+ Field::Str("d".to_string()),+ Field::Str("e".to_string()),+ Field::Str("f".to_string()),+ ];+ let def_levels = vec![7, 7, 7, 4, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 4, 7];+ let rep_levels = vec![0, 3, 2, 1, 2, 0, 3, 2, 3, 1, 2, 0, 3, 2, 3, 2, 1, 2];+ test_triplet_iter(+ "nested_lists.snappy.parquet",+ path,+ &values,+ &def_levels,+ &rep_levels,+ );+ }++ #[test]+ fn test_triplet_optional_map_column() {+ let path = vec!["a", "key_value", "value", "key_value", "key"];+ let values = vec![+ Field::Int(1),+ Field::Int(2),+ Field::Int(1),+ Field::Int(1),+ Field::Int(3),+ Field::Int(4),+ Field::Int(5),+ ];+ let def_levels = vec![4, 4, 4, 2, 3, 4, 4, 4, 4];+ let rep_levels = vec![0, 2, 0, 0, 0, 0, 0, 2, 2];+ test_triplet_iter(+ "nested_maps.snappy.parquet",+ path,+ &values,+ &def_levels,+ &rep_levels,+ );+ }++ // Check triplet iterator across different batch sizes+ fn test_triplet_iter(+ file_name: &str,+ column_path: Vec<&str>,+ expected_values: &[Field],+ expected_def_levels: &[i16],+ expected_rep_levels: &[i16],+ ) {+ // Convert path into column path+ let path: Vec<String> = column_path.iter().map(|x| x.to_string()).collect();+ let column_path = ColumnPath::from(path);++ let batch_sizes = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 128, 256];+ for batch_size in batch_sizes {+ test_column_in_file(+ file_name,+ batch_size,+ &column_path,+ expected_values,+ expected_def_levels,+ expected_rep_levels,+ );+ }+ }++ // Check values of a selectd column in a file+ fn test_column_in_file(+ file_name: &str,+ batch_size: usize,+ column_path: &ColumnPath,+ expected_values: &[Field],+ expected_def_levels: &[i16],+ expected_rep_levels: &[i16],+ ) {+ let file = get_test_file(file_name);+ let file_reader = SerializedFileReader::new(file).unwrap();+ // Get schema descriptor+ let file_metadata = file_reader.metadata().file_metadata();+ let schema = file_metadata.schema_descr();+ // Get first row group+ let row_group_reader = file_reader.get_row_group(0).unwrap();++ for i in 0..schema.num_columns() {+ let descr = schema.column(i);+ if descr.path() == column_path {+ let reader = row_group_reader.get_column_reader(i).unwrap();+ test_triplet_column(+ descr,+ reader,+ batch_size,+ expected_values,+ expected_def_levels,+ expected_rep_levels,+ );+ }+ }+ }++ // Check values for individual triplet iterator+ fn test_triplet_column(+ descr: ColumnDescPtr,+ reader: ColumnReader,+ batch_size: usize,+ expected_values: &[Field],+ expected_def_levels: &[i16],+ expected_rep_levels: &[i16],+ ) {+ let mut iter = TripletIter::new(descr.clone(), reader, batch_size);+ let mut values: Vec<Field> = Vec::new();+ let mut def_levels: Vec<i16> = Vec::new();+ let mut rep_levels: Vec<i16> = Vec::new();++ assert_eq!(iter.max_def_level(), descr.max_def_level());+ assert_eq!(iter.max_rep_level(), descr.max_rep_level());++ while let Ok(true) = iter.read_next() {+ assert!(iter.has_next());+ if !iter.is_null() {+ values.push(iter.current_value());+ }+ def_levels.push(iter.current_def_level());+ rep_levels.push(iter.current_rep_level());+ }++ assert_eq!(values, expected_values);+ assert_eq!(def_levels, expected_def_levels);+ assert_eq!(rep_levels, expected_rep_levels);+ }+}diff --git a/rust/src/parquet/schema/mod.rs b/rust/src/parquet/schema/mod.rsnew file mode 100644index 0000000000..5319504964--- /dev/null+++ b/rust/src/parquet/schema/mod.rs@@ -0,0 +1,66 @@+// 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.++//! Parquet schema definitions and methods to print and parse schema.+//!+//! # Example+//!+//! ```rust+//! use arrow::parquet::{+//! basic::{LogicalType, Repetition, Type as PhysicalType},+//! schema::{parser, printer, types::Type},+//! };+//! use std::rc::Rc;+//!+//! // Create the following schema:+//! //+//! // message schema {+//! // OPTIONAL BYTE_ARRAY a (UTF8);+//! // REQUIRED INT32 b;+//! // }+//!+//! let field_a = Type::primitive_type_builder("a", PhysicalType::BYTE_ARRAY)+//! .with_logical_type(LogicalType::UTF8)+//! .with_repetition(Repetition::OPTIONAL)+//! .build()+//! .unwrap();+//!+//! let field_b = Type::primitive_type_builder("b", PhysicalType::INT32)+//! .with_repetition(Repetition::REQUIRED)+//! .build()+//! .unwrap();+//!+//! let schema = Type::group_type_builder("schema")+//! .with_fields(&mut vec![Rc::new(field_a), Rc::new(field_b)])+//! .build()+//! .unwrap();+//!+//! let mut buf = Vec::new();+//!+//! // Print schema into buffer+//! printer::print_schema(&mut buf, &schema);+//!+//! // Parse schema from the string+//! let string_schema = String::from_utf8(buf).unwrap();+//! let parsed_schema = parser::parse_message_type(&string_schema).unwrap();+//!+//! assert_eq!(schema, parsed_schema);+//! ```++pub mod parser;+pub mod printer;+pub mod types;diff --git a/rust/src/parquet/schema/parser.rs b/rust/src/parquet/schema/parser.rsnew file mode 100644index 0000000000..2890c84a75--- /dev/null+++ b/rust/src/parquet/schema/parser.rs@@ -0,0 +1,764 @@+// 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.++//! Parquet schema parser.+//! Provides methods to parse and validate string message type into Parquet+//! [`Type`](`::schema::types::Type`).+//!+//! # Example+//!+//! ```rust+//! use arrow::parquet::schema::parser::parse_message_type;+//!+//! let message_type = "+//! message spark_schema {+//! OPTIONAL BYTE_ARRAY a (UTF8);+//! REQUIRED INT32 b;+//! REQUIRED DOUBLE c;+//! REQUIRED BOOLEAN d;+//! OPTIONAL group e (LIST) {+//! REPEATED group list {+//! REQUIRED INT32 element;+//! }+//! }+//! }+//! ";+//!+//! let schema = parse_message_type(message_type).expect("Expected valid schema");+//! println!("{:?}", schema);+//! ```++use std::rc::Rc;++use crate::parquet::basic::{LogicalType, Repetition, Type as PhysicalType};+use crate::parquet::errors::{ParquetError, Result};+use crate::parquet::schema::types::{Type, TypePtr};++/// Parses message type as string into a Parquet [`Type`](`::schema::types::Type`) which,+/// for example, could be used to extract individual columns. Returns Parquet general+/// error when parsing or validation fails.+pub fn parse_message_type<'a>(message_type: &'a str) -> Result<Type> {+ let mut parser = Parser {+ tokenizer: &mut Tokenizer::from_str(message_type),+ };+ parser.parse_message_type()+}++/// Tokenizer to split message type string into tokens that are separated using characters+/// defined in `is_schema_delim` method. Tokenizer also preserves delimiters as tokens.+/// Tokenizer provides Iterator interface to process tokens; it also allows to step back+/// to reprocess previous tokens.+struct Tokenizer<'a> {+ // List of all tokens for a string+ tokens: Vec<&'a str>,+ // Current index of vector+ index: usize,+}++impl<'a> Tokenizer<'a> {+ // Create tokenizer from message type string+ pub fn from_str(string: &'a str) -> Self {+ let vec = string+ .split_whitespace()+ .flat_map(|t| Self::split_token(t))+ .collect();+ Tokenizer {+ tokens: vec,+ index: 0,+ }+ }++ // List of all special characters in schema+ fn is_schema_delim(c: char) -> bool {+ c == ';' || c == '{' || c == '}' || c == '(' || c == ')' || c == '=' || c == ','+ }++ /// Splits string into tokens; input string can already be token or can contain+ /// delimiters, e.g. required" -> Vec("required") and+ /// "(UTF8);" -> Vec("(", "UTF8", ")", ";")+ fn split_token(string: &str) -> Vec<&str> {+ let mut buffer: Vec<&str> = Vec::new();+ let mut tail = string;+ while let Some(index) = tail.find(Self::is_schema_delim) {+ let (h, t) = tail.split_at(index);+ if !h.is_empty() {+ buffer.push(h);+ }+ buffer.push(&t[0..1]);+ tail = &t[1..];+ }+ if !tail.is_empty() {+ buffer.push(tail);+ }+ buffer+ }++ // Move pointer to a previous element+ fn backtrack(&mut self) {+ self.index -= 1;+ }+}++impl<'a> Iterator for Tokenizer<'a> {+ type Item = &'a str;++ fn next(&mut self) -> Option<&'a str> {+ if self.index < self.tokens.len() {+ self.index += 1;+ Some(self.tokens[self.index - 1])+ } else {+ None+ }+ }+}++/// Internal Schema parser.+/// Traverses message type using tokenizer and parses each group/primitive type+/// recursively.+struct Parser<'a> {+ tokenizer: &'a mut Tokenizer<'a>,+}++// Utility function to assert token on validity.+fn assert_token(token: Option<&str>, expected: &str) -> Result<()> {+ match token {+ Some(value) if value == expected => Ok(()),+ Some(other) => Err(general_err!(+ "Expected '{}', found token '{}'",+ expected,+ other+ )),+ None => Err(general_err!(+ "Expected '{}', but no token found (None)",+ expected+ )),+ }+}++// Utility function to parse i32 or return general error.+fn parse_i32(value: Option<&str>, not_found_msg: &str, parse_fail_msg: &str) -> Result<i32> {+ value+ .ok_or(general_err!(not_found_msg))+ .and_then(|v| v.parse::<i32>().map_err(|_| general_err!(parse_fail_msg)))+}++impl<'a> Parser<'a> {+ // Entry function to parse message type, uses internal tokenizer.+ fn parse_message_type(&mut self) -> Result<Type> {+ // Check that message type starts with "message".+ match self.tokenizer.next() {+ Some("message") => {+ let name = self+ .tokenizer+ .next()+ .ok_or(general_err!("Expected name, found None"))?;+ let mut fields = self.parse_child_types()?;+ Type::group_type_builder(name)+ .with_fields(&mut fields)+ .build()+ }+ _ => Err(general_err!("Message type does not start with 'message'")),+ }+ }++ // Parses child types for a current group type.+ // This is only invoked on root and group types.+ fn parse_child_types(&mut self) -> Result<Vec<TypePtr>> {+ assert_token(self.tokenizer.next(), "{")?;+ let mut vec = Vec::new();+ while let Some(value) = self.tokenizer.next() {+ if value == "}" {+ break;+ } else {+ self.tokenizer.backtrack();+ vec.push(Rc::new(self.add_type()?));+ }+ }+ Ok(vec)+ }++ fn add_type(&mut self) -> Result<Type> {+ // Parse repetition+ let repetition = self+ .tokenizer+ .next()+ .ok_or(general_err!("Expected repetition, found None"))+ .and_then(|v| v.to_uppercase().parse::<Repetition>())?;++ match self.tokenizer.next() {+ Some(group) if group.to_uppercase() == "GROUP" => self.add_group_type(Some(repetition)),+ Some(type_string) => {+ let physical_type = type_string.to_uppercase().parse::<PhysicalType>()?;+ self.add_primitive_type(repetition, physical_type)+ }+ None => Err(general_err!("Invalid type, could not extract next token")),+ }+ }++ fn add_group_type(&mut self, repetition: Option<Repetition>) -> Result<Type> {+ // Parse name of the group type+ let name = self+ .tokenizer+ .next()+ .ok_or(general_err!("Expected name, found None"))?;++ // Parse logical type if exists+ let logical_type = if let Some("(") = self.tokenizer.next() {+ let tpe = self+ .tokenizer+ .next()+ .ok_or(general_err!("Expected logical type, found None"))+ .and_then(|v| v.to_uppercase().parse::<LogicalType>())?;+ assert_token(self.tokenizer.next(), ")")?;+ tpe+ } else {+ self.tokenizer.backtrack();+ LogicalType::NONE+ };++ // Parse optional id+ let id = if let Some("=") = self.tokenizer.next() {+ self.tokenizer.next().and_then(|v| v.parse::<i32>().ok())+ } else {+ self.tokenizer.backtrack();+ None+ };++ let mut fields = self.parse_child_types()?;+ let mut builder = Type::group_type_builder(name)+ .with_logical_type(logical_type)+ .with_fields(&mut fields);+ if let Some(rep) = repetition {+ builder = builder.with_repetition(rep);+ }+ if let Some(id) = id {+ builder = builder.with_id(id);+ }+ builder.build()+ }++ fn add_primitive_type(+ &mut self,+ repetition: Repetition,+ physical_type: PhysicalType,+ ) -> Result<Type> {+ // Read type length if the type is FIXED_LEN_BYTE_ARRAY.+ let mut length: i32 = -1;+ if physical_type == PhysicalType::FIXED_LEN_BYTE_ARRAY {+ assert_token(self.tokenizer.next(), "(")?;+ length = parse_i32(+ self.tokenizer.next(),+ "Expected length for FIXED_LEN_BYTE_ARRAY, found None",+ "Failed to parse length for FIXED_LEN_BYTE_ARRAY",+ )?;+ assert_token(self.tokenizer.next(), ")")?;+ }++ // Parse name of the primitive type+ let name = self+ .tokenizer+ .next()+ .ok_or(general_err!("Expected name, found None"))?;++ // Parse logical type+ let (logical_type, precision, scale) = if let Some("(") = self.tokenizer.next() {+ let tpe = self+ .tokenizer+ .next()+ .ok_or(general_err!("Expected logical type, found None"))+ .and_then(|v| v.to_uppercase().parse::<LogicalType>())?;++ // Parse precision and scale for decimals+ let mut precision: i32 = -1;+ let mut scale: i32 = -1;++ if tpe == LogicalType::DECIMAL {+ if let Some("(") = self.tokenizer.next() {+ // Parse precision+ precision = parse_i32(+ self.tokenizer.next(),+ "Expected precision, found None",+ "Failed to parse precision for DECIMAL type",+ )?;++ // Parse scale+ scale = if let Some(",") = self.tokenizer.next() {+ parse_i32(+ self.tokenizer.next(),+ "Expected scale, found None",+ "Failed to parse scale for DECIMAL type",+ )?+ } else {+ // Scale is not provided, set it to 0.+ self.tokenizer.backtrack();+ 0+ };++ assert_token(self.tokenizer.next(), ")")?;+ } else {+ self.tokenizer.backtrack();+ }+ }++ assert_token(self.tokenizer.next(), ")")?;+ (tpe, precision, scale)+ } else {+ self.tokenizer.backtrack();+ (LogicalType::NONE, -1, -1)+ };++ // Parse optional id+ let id = if let Some("=") = self.tokenizer.next() {+ self.tokenizer.next().and_then(|v| v.parse::<i32>().ok())+ } else {+ self.tokenizer.backtrack();+ None+ };+ assert_token(self.tokenizer.next(), ";")?;++ let mut builder = Type::primitive_type_builder(name, physical_type)+ .with_repetition(repetition)+ .with_logical_type(logical_type)+ .with_length(length)+ .with_precision(precision)+ .with_scale(scale);+ if let Some(id) = id {+ builder = builder.with_id(id);+ }+ Ok(builder.build()?)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_tokenize_empty_string() {+ assert_eq!(Tokenizer::from_str("").next(), None);+ }++ #[test]+ fn test_tokenize_delimiters() {+ let mut iter = Tokenizer::from_str(",;{}()=");+ assert_eq!(iter.next(), Some(","));+ assert_eq!(iter.next(), Some(";"));+ assert_eq!(iter.next(), Some("{"));+ assert_eq!(iter.next(), Some("}"));+ assert_eq!(iter.next(), Some("("));+ assert_eq!(iter.next(), Some(")"));+ assert_eq!(iter.next(), Some("="));+ assert_eq!(iter.next(), None);+ }++ #[test]+ fn test_tokenize_delimiters_with_whitespaces() {+ let mut iter = Tokenizer::from_str(" , ; { } ( ) = ");+ assert_eq!(iter.next(), Some(","));+ assert_eq!(iter.next(), Some(";"));+ assert_eq!(iter.next(), Some("{"));+ assert_eq!(iter.next(), Some("}"));+ assert_eq!(iter.next(), Some("("));+ assert_eq!(iter.next(), Some(")"));+ assert_eq!(iter.next(), Some("="));+ assert_eq!(iter.next(), None);+ }++ #[test]+ fn test_tokenize_words() {+ let mut iter = Tokenizer::from_str("abc def ghi jkl mno");+ assert_eq!(iter.next(), Some("abc"));+ assert_eq!(iter.next(), Some("def"));+ assert_eq!(iter.next(), Some("ghi"));+ assert_eq!(iter.next(), Some("jkl"));+ assert_eq!(iter.next(), Some("mno"));+ assert_eq!(iter.next(), None);+ }++ #[test]+ fn test_tokenize_backtrack() {+ let mut iter = Tokenizer::from_str("abc;");+ assert_eq!(iter.next(), Some("abc"));+ assert_eq!(iter.next(), Some(";"));+ iter.backtrack();+ assert_eq!(iter.next(), Some(";"));+ assert_eq!(iter.next(), None);+ }++ #[test]+ fn test_tokenize_message_type() {+ let schema = "+ message schema {+ required int32 a;+ optional binary c (UTF8);+ required group d {+ required int32 a;+ optional binary c (UTF8);+ }+ required group e (LIST) {+ repeated group list {+ required int32 element;+ }+ }+ }+ ";+ let mut iter = Tokenizer::from_str(schema);+ let mut res = Vec::new();+ while let Some(token) = iter.next() {+ res.push(token);+ }+ assert_eq!(+ res,+ vec![+ "message", "schema", "{", "required", "int32", "a", ";", "optional", "binary", "c",+ "(", "UTF8", ")", ";", "required", "group", "d", "{", "required", "int32", "a",+ ";", "optional", "binary", "c", "(", "UTF8", ")", ";", "}", "required", "group",+ "e", "(", "LIST", ")", "{", "repeated", "group", "list", "{", "required", "int32",+ "element", ";", "}", "}", "}"+ ]+ );+ }++ #[test]+ fn test_assert_token() {+ assert!(assert_token(Some("a"), "a").is_ok());+ assert!(assert_token(Some("a"), "b").is_err());+ assert!(assert_token(None, "b").is_err());+ }++ #[test]+ fn test_parse_message_type_invalid() {+ let mut iter = Tokenizer::from_str("test");+ let result = Parser {+ tokenizer: &mut iter,+ }+ .parse_message_type();+ assert!(result.is_err());+ assert_eq!(+ result.unwrap_err().to_string(),+ "Parquet error: Message type does not start with 'message'"+ );+ }++ #[test]+ fn test_parse_message_type_no_name() {+ let mut iter = Tokenizer::from_str("message");+ let result = Parser {+ tokenizer: &mut iter,+ }+ .parse_message_type();+ assert!(result.is_err());+ assert_eq!(+ result.unwrap_err().to_string(),+ "Parquet error: Expected name, found None"+ );+ }++ #[test]+ fn test_parse_message_type_fixed_byte_array() {+ let schema = "+ message schema {+ REQUIRED FIXED_LEN_BYTE_ARRAY col;+ }+ ";+ let mut iter = Tokenizer::from_str(schema);+ let result = Parser {+ tokenizer: &mut iter,+ }+ .parse_message_type();+ assert!(result.is_err());++ let schema = "+ message schema {+ REQUIRED FIXED_LEN_BYTE_ARRAY(16) col;+ }+ ";+ let mut iter = Tokenizer::from_str(schema);+ let result = Parser {+ tokenizer: &mut iter,+ }+ .parse_message_type();+ assert!(result.is_ok());+ }++ #[test]+ fn test_parse_message_type_decimal() {+ // It is okay for decimal to omit precision and scale with right syntax.+ // Here we test wrong syntax of decimal type++ // Invalid decimal syntax+ let schema = "+ message root {+ optional int32 f1 (DECIMAL();+ }+ ";+ let mut iter = Tokenizer::from_str(schema);+ let result = Parser {+ tokenizer: &mut iter,+ }+ .parse_message_type();+ assert!(result.is_err());++ // Invalid decimal, need precision and scale+ let schema = "+ message root {+ optional int32 f1 (DECIMAL());+ }+ ";+ let mut iter = Tokenizer::from_str(schema);+ let result = Parser {+ tokenizer: &mut iter,+ }+ .parse_message_type();+ assert!(result.is_err());++ // Invalid decimal because of `,` - has precision, needs scale+ let schema = "+ message root {+ optional int32 f1 (DECIMAL(8,));+ }+ ";+ let mut iter = Tokenizer::from_str(schema);+ let result = Parser {+ tokenizer: &mut iter,+ }+ .parse_message_type();+ assert!(result.is_err());++ // Invalid decimal because, we always require either precision or scale to be+ // specified as part of logical type+ let schema = "+ message root {+ optional int32 f3 (DECIMAL);+ }+ ";+ let mut iter = Tokenizer::from_str(schema);+ let result = Parser {+ tokenizer: &mut iter,+ }+ .parse_message_type();+ assert!(result.is_err());++ // Valid decimal (precision, scale)+ let schema = "+ message root {+ optional int32 f1 (DECIMAL(8, 3));+ optional int32 f2 (DECIMAL(8));+ }+ ";+ let mut iter = Tokenizer::from_str(schema);+ let result = Parser {+ tokenizer: &mut iter,+ }+ .parse_message_type();+ assert!(result.is_ok());+ }++ #[test]+ fn test_parse_message_type_compare_1() {+ let schema = "+ message root {+ optional fixed_len_byte_array(5) f1 (DECIMAL(9, 3));+ optional fixed_len_byte_array (16) f2 (DECIMAL (38, 18));+ }+ ";+ let mut iter = Tokenizer::from_str(schema);+ let message = Parser {+ tokenizer: &mut iter,+ }+ .parse_message_type()+ .unwrap();++ let expected = Type::group_type_builder("root")+ .with_fields(&mut vec![+ Rc::new(+ Type::primitive_type_builder("f1", PhysicalType::FIXED_LEN_BYTE_ARRAY)+ .with_logical_type(LogicalType::DECIMAL)+ .with_length(5)+ .with_precision(9)+ .with_scale(3)+ .build()+ .unwrap(),+ ),+ Rc::new(+ Type::primitive_type_builder("f2", PhysicalType::FIXED_LEN_BYTE_ARRAY)+ .with_logical_type(LogicalType::DECIMAL)+ .with_length(16)+ .with_precision(38)+ .with_scale(18)+ .build()+ .unwrap(),+ ),+ ])+ .build()+ .unwrap();++ assert_eq!(message, expected);+ }++ #[test]+ fn test_parse_message_type_compare_2() {+ let schema = "+ message root {+ required group a0 {+ optional group a1 (LIST) {+ repeated binary a2 (UTF8);+ }++ optional group b1 (LIST) {+ repeated group b2 {+ optional int32 b3;+ optional double b4;+ }+ }+ }+ }+ ";+ let mut iter = Tokenizer::from_str(schema);+ let message = Parser {+ tokenizer: &mut iter,+ }+ .parse_message_type()+ .unwrap();++ let expected = Type::group_type_builder("root")+ .with_fields(&mut vec![Rc::new(+ Type::group_type_builder("a0")+ .with_repetition(Repetition::REQUIRED)+ .with_fields(&mut vec![+ Rc::new(+ Type::group_type_builder("a1")+ .with_repetition(Repetition::OPTIONAL)+ .with_logical_type(LogicalType::LIST)+ .with_fields(&mut vec![Rc::new(+ Type::primitive_type_builder("a2", PhysicalType::BYTE_ARRAY)+ .with_repetition(Repetition::REPEATED)+ .with_logical_type(LogicalType::UTF8)+ .build()+ .unwrap(),+ )])+ .build()+ .unwrap(),+ ),+ Rc::new(+ Type::group_type_builder("b1")+ .with_repetition(Repetition::OPTIONAL)+ .with_logical_type(LogicalType::LIST)+ .with_fields(&mut vec![Rc::new(+ Type::group_type_builder("b2")+ .with_repetition(Repetition::REPEATED)+ .with_fields(&mut vec![+ Rc::new(+ Type::primitive_type_builder(+ "b3",+ PhysicalType::INT32,+ )+ .build()+ .unwrap(),+ ),+ Rc::new(+ Type::primitive_type_builder(+ "b4",+ PhysicalType::DOUBLE,+ )+ .build()+ .unwrap(),+ ),+ ])+ .build()+ .unwrap(),+ )])+ .build()+ .unwrap(),+ ),+ ])+ .build()+ .unwrap(),+ )])+ .build()+ .unwrap();++ assert_eq!(message, expected);+ }++ #[test]+ fn test_parse_message_type_compare_3() {+ let schema = "+ message root {+ required int32 _1 (INT_8);+ required int32 _2 (INT_16);+ required float _3;+ required double _4;+ optional int32 _5 (DATE);+ optional binary _6 (UTF8);+ }+ ";+ let mut iter = Tokenizer::from_str(schema);+ let message = Parser {+ tokenizer: &mut iter,+ }+ .parse_message_type()+ .unwrap();++ let mut fields = vec![+ Rc::new(+ Type::primitive_type_builder("_1", PhysicalType::INT32)+ .with_repetition(Repetition::REQUIRED)+ .with_logical_type(LogicalType::INT_8)+ .build()+ .unwrap(),+ ),+ Rc::new(+ Type::primitive_type_builder("_2", PhysicalType::INT32)+ .with_repetition(Repetition::REQUIRED)+ .with_logical_type(LogicalType::INT_16)+ .build()+ .unwrap(),+ ),+ Rc::new(+ Type::primitive_type_builder("_3", PhysicalType::FLOAT)+ .with_repetition(Repetition::REQUIRED)+ .build()+ .unwrap(),+ ),+ Rc::new(+ Type::primitive_type_builder("_4", PhysicalType::DOUBLE)+ .with_repetition(Repetition::REQUIRED)+ .build()+ .unwrap(),+ ),+ Rc::new(+ Type::primitive_type_builder("_5", PhysicalType::INT32)+ .with_logical_type(LogicalType::DATE)+ .build()+ .unwrap(),+ ),+ Rc::new(+ Type::primitive_type_builder("_6", PhysicalType::BYTE_ARRAY)+ .with_logical_type(LogicalType::UTF8)+ .build()+ .unwrap(),+ ),+ ];++ let expected = Type::group_type_builder("root")+ .with_fields(&mut fields)+ .build()+ .unwrap();+ assert_eq!(message, expected);+ }+}diff --git a/rust/src/parquet/schema/printer.rs b/rust/src/parquet/schema/printer.rsnew file mode 100644index 0000000000..d61f116eb9--- /dev/null+++ b/rust/src/parquet/schema/printer.rs@@ -0,0 +1,467 @@+// 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.++//! Parquet schema printer.+//! Provides methods to print Parquet file schema and list file metadata.+//!+//! # Example+//!+//! ```rust+//! use arrow::parquet::{+//! file::reader::{FileReader, SerializedFileReader},+//! schema::printer::{print_file_metadata, print_parquet_metadata, print_schema},+//! };+//! use std::{fs::File, path::Path};+//!+//! // Open a file+//! let path = Path::new("test.parquet");+//! if let Ok(file) = File::open(&path) {+//! let reader = SerializedFileReader::new(file).unwrap();+//! let parquet_metadata = reader.metadata();+//!+//! print_parquet_metadata(&mut std::io::stdout(), &parquet_metadata);+//! print_file_metadata(&mut std::io::stdout(), &parquet_metadata.file_metadata());+//!+//! print_schema(+//! &mut std::io::stdout(),+//! &parquet_metadata.file_metadata().schema(),+//! );+//! }+//! ```++use std::{fmt, io};++use crate::parquet::basic::{LogicalType, Type as PhysicalType};+use crate::parquet::file::metadata::{+ ColumnChunkMetaData, FileMetaData, ParquetMetaData, RowGroupMetaData,+};+use crate::parquet::schema::types::Type;++/// Prints Parquet metadata [`ParquetMetaData`](`::file::metadata::ParquetMetaData`)+/// information.+#[allow(unused_must_use)]+pub fn print_parquet_metadata(out: &mut io::Write, metadata: &ParquetMetaData) {+ print_file_metadata(out, &metadata.file_metadata());+ writeln!(out, "");+ writeln!(out, "");+ writeln!(out, "num of row groups: {}", metadata.num_row_groups());+ writeln!(out, "row groups:");+ writeln!(out, "");+ for (i, rg) in metadata.row_groups().iter().enumerate() {+ writeln!(out, "row group {}:", i);+ print_dashes(out, 80);+ print_row_group_metadata(out, rg);+ }+}++/// Prints file metadata [`FileMetaData`](`::file::metadata::FileMetaData`) information.+#[allow(unused_must_use)]+pub fn print_file_metadata(out: &mut io::Write, file_metadata: &FileMetaData) {+ writeln!(out, "version: {}", file_metadata.version());+ writeln!(out, "num of rows: {}", file_metadata.num_rows());+ if let Some(created_by) = file_metadata.created_by().as_ref() {+ writeln!(out, "created by: {}", created_by);+ }+ let schema = file_metadata.schema();+ print_schema(out, schema);+}++/// Prints Parquet [`Type`](`::schema::types::Type`) information.+#[allow(unused_must_use)]+pub fn print_schema(out: &mut io::Write, tp: &Type) {+ // TODO: better if we can pass fmt::Write to Printer.+ // But how can we make it to accept both io::Write & fmt::Write?+ let mut s = String::new();+ {+ let mut printer = Printer::new(&mut s);+ printer.print(tp);+ }+ writeln!(out, "{}", s);+}++#[allow(unused_must_use)]+fn print_row_group_metadata(out: &mut io::Write, rg_metadata: &RowGroupMetaData) {+ writeln!(out, "total byte size: {}", rg_metadata.total_byte_size());+ writeln!(out, "num of rows: {}", rg_metadata.num_rows());+ writeln!(out, "");+ writeln!(out, "num of columns: {}", rg_metadata.num_columns());+ writeln!(out, "columns: ");+ for (i, cc) in rg_metadata.columns().iter().enumerate() {+ writeln!(out, "");+ writeln!(out, "column {}:", i);+ print_dashes(out, 80);+ print_column_chunk_metadata(out, cc);+ }+}++#[allow(unused_must_use)]+fn print_column_chunk_metadata(out: &mut io::Write, cc_metadata: &ColumnChunkMetaData) {+ writeln!(out, "column type: {}", cc_metadata.column_type());+ writeln!(out, "column path: {}", cc_metadata.column_path());+ let encoding_strs: Vec<_> = cc_metadata+ .encodings()+ .iter()+ .map(|e| format!("{}", e))+ .collect();+ writeln!(out, "encodings: {}", encoding_strs.join(" "));+ let file_path_str = match cc_metadata.file_path() {+ None => "N/A",+ Some(ref fp) => *fp,+ };+ writeln!(out, "file path: {}", file_path_str);+ writeln!(out, "file offset: {}", cc_metadata.file_offset());+ writeln!(out, "num of values: {}", cc_metadata.num_values());+ writeln!(+ out,+ "total compressed size (in bytes): {}",+ cc_metadata.compressed_size()+ );+ writeln!(+ out,+ "total uncompressed size (in bytes): {}",+ cc_metadata.uncompressed_size()+ );+ writeln!(out, "data page offset: {}", cc_metadata.data_page_offset());+ let index_page_offset_str = match cc_metadata.index_page_offset() {+ None => "N/A".to_owned(),+ Some(ipo) => ipo.to_string(),+ };+ writeln!(out, "index page offset: {}", index_page_offset_str);+ let dict_page_offset_str = match cc_metadata.dictionary_page_offset() {+ None => "N/A".to_owned(),+ Some(dpo) => dpo.to_string(),+ };+ writeln!(out, "dictionary page offset: {}", dict_page_offset_str);+ let statistics_str = match cc_metadata.statistics() {+ None => "N/A".to_owned(),+ Some(stats) => stats.to_string(),+ };+ writeln!(out, "statistics: {}", statistics_str);+ writeln!(out, "");+}++#[allow(unused_must_use)]+fn print_dashes(out: &mut io::Write, num: i32) {+ for _ in 0..num {+ write!(out, "-");+ }+ writeln!(out, "");+}++const INDENT_WIDTH: i32 = 2;++/// Struct for printing Parquet message type.+struct Printer<'a> {+ output: &'a mut fmt::Write,+ indent: i32,+}++#[allow(unused_must_use)]+impl<'a> Printer<'a> {+ fn new(output: &'a mut fmt::Write) -> Self {+ Printer { output, indent: 0 }+ }++ fn print_indent(&mut self) {+ for _ in 0..self.indent {+ write!(self.output, " ");+ }+ }+}++#[allow(unused_must_use)]+impl<'a> Printer<'a> {+ pub fn print(&mut self, tp: &Type) {+ self.print_indent();+ match tp {+ &Type::PrimitiveType {+ ref basic_info,+ physical_type,+ type_length,+ scale,+ precision,+ } => {+ let phys_type_str = match physical_type {+ PhysicalType::FIXED_LEN_BYTE_ARRAY => {+ // We need to include length for fixed byte array+ format!("{} ({})", physical_type, type_length)+ }+ _ => format!("{}", physical_type),+ };+ // Also print logical type if it is available+ let logical_type_str = match basic_info.logical_type() {+ LogicalType::NONE => format!(""),+ decimal @ LogicalType::DECIMAL => {+ // For decimal type we should print precision and scale if they are > 0, e.g.+ // DECIMAL(9, 2) - DECIMAL(9) - DECIMAL+ let precision_scale = match (precision, scale) {+ (p, s) if p > 0 && s > 0 => format!(" ({}, {})", p, s),+ (p, 0) if p > 0 => format!(" ({})", p),+ _ => format!(""),+ };+ format!(" ({}{})", decimal, precision_scale)+ }+ other_logical_type => format!(" ({})", other_logical_type),+ };+ write!(+ self.output,+ "{} {} {}{};",+ basic_info.repetition(),+ phys_type_str,+ basic_info.name(),+ logical_type_str+ );+ }+ &Type::GroupType {+ ref basic_info,+ ref fields,+ } => {+ if basic_info.has_repetition() {+ let r = basic_info.repetition();+ write!(self.output, "{} group {} ", r, basic_info.name());+ if basic_info.logical_type() != LogicalType::NONE {+ write!(self.output, "({}) ", basic_info.logical_type());+ }+ writeln!(self.output, "{{");+ } else {+ writeln!(self.output, "message {} {{", basic_info.name());+ }++ self.indent += INDENT_WIDTH;+ for c in fields {+ self.print(&c);+ writeln!(self.output, "");+ }+ self.indent -= INDENT_WIDTH;+ self.print_indent();+ write!(self.output, "}}");+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ use std::rc::Rc;++ use crate::parquet::basic::{Repetition, Type as PhysicalType};+ use crate::parquet::schema::{parser::parse_message_type, types::Type};++ fn assert_print_parse_message(message: Type) {+ let mut s = String::new();+ {+ let mut p = Printer::new(&mut s);+ p.print(&message);+ }+ let parsed = parse_message_type(&s).unwrap();+ assert_eq!(message, parsed);+ }++ #[test]+ fn test_print_primitive_type() {+ let mut s = String::new();+ {+ let mut p = Printer::new(&mut s);+ let foo = Type::primitive_type_builder("foo", PhysicalType::INT32)+ .with_repetition(Repetition::REQUIRED)+ .with_logical_type(LogicalType::INT_32)+ .build()+ .unwrap();+ p.print(&foo);+ }+ assert_eq!(&mut s, "REQUIRED INT32 foo (INT_32);");+ }++ #[test]+ fn test_print_primitive_type_without_logical() {+ let mut s = String::new();+ {+ let mut p = Printer::new(&mut s);+ let foo = Type::primitive_type_builder("foo", PhysicalType::DOUBLE)+ .with_repetition(Repetition::REQUIRED)+ .build()+ .unwrap();+ p.print(&foo);+ }+ assert_eq!(&mut s, "REQUIRED DOUBLE foo;");+ }++ #[test]+ fn test_print_group_type() {+ let mut s = String::new();+ {+ let mut p = Printer::new(&mut s);+ let f1 = Type::primitive_type_builder("f1", PhysicalType::INT32)+ .with_repetition(Repetition::REQUIRED)+ .with_logical_type(LogicalType::INT_32)+ .with_id(0)+ .build();+ let f2 = Type::primitive_type_builder("f2", PhysicalType::BYTE_ARRAY)+ .with_logical_type(LogicalType::UTF8)+ .with_id(1)+ .build();+ let f3 = Type::primitive_type_builder("f3", PhysicalType::FIXED_LEN_BYTE_ARRAY)+ .with_repetition(Repetition::REPEATED)+ .with_logical_type(LogicalType::INTERVAL)+ .with_length(12)+ .with_id(2)+ .build();+ let mut struct_fields = Vec::new();+ struct_fields.push(Rc::new(f1.unwrap()));+ struct_fields.push(Rc::new(f2.unwrap()));+ let foo = Type::group_type_builder("foo")+ .with_repetition(Repetition::OPTIONAL)+ .with_fields(&mut struct_fields)+ .with_id(1)+ .build()+ .unwrap();+ let mut fields = Vec::new();+ fields.push(Rc::new(foo));+ fields.push(Rc::new(f3.unwrap()));+ let message = Type::group_type_builder("schema")+ .with_fields(&mut fields)+ .with_id(2)+ .build()+ .unwrap();+ p.print(&message);+ }+ let expected = "message schema {+ OPTIONAL group foo {+ REQUIRED INT32 f1 (INT_32);+ OPTIONAL BYTE_ARRAY f2 (UTF8);+ }+ REPEATED FIXED_LEN_BYTE_ARRAY (12) f3 (INTERVAL);+}";+ assert_eq!(&mut s, expected);+ }++ #[test]+ fn test_print_and_parse_primitive() {+ let a2 = Type::primitive_type_builder("a2", PhysicalType::BYTE_ARRAY)+ .with_repetition(Repetition::REPEATED)+ .with_logical_type(LogicalType::UTF8)+ .build()+ .unwrap();++ let a1 = Type::group_type_builder("a1")+ .with_repetition(Repetition::OPTIONAL)+ .with_logical_type(LogicalType::LIST)+ .with_fields(&mut vec![Rc::new(a2)])+ .build()+ .unwrap();++ let b3 = Type::primitive_type_builder("b3", PhysicalType::INT32)+ .with_repetition(Repetition::OPTIONAL)+ .build()+ .unwrap();++ let b4 = Type::primitive_type_builder("b4", PhysicalType::DOUBLE)+ .with_repetition(Repetition::OPTIONAL)+ .build()+ .unwrap();++ let b2 = Type::group_type_builder("b2")+ .with_repetition(Repetition::REPEATED)+ .with_logical_type(LogicalType::NONE)+ .with_fields(&mut vec![Rc::new(b3), Rc::new(b4)])+ .build()+ .unwrap();++ let b1 = Type::group_type_builder("b1")+ .with_repetition(Repetition::OPTIONAL)+ .with_logical_type(LogicalType::LIST)+ .with_fields(&mut vec![Rc::new(b2)])+ .build()+ .unwrap();++ let a0 = Type::group_type_builder("a0")+ .with_repetition(Repetition::REQUIRED)+ .with_fields(&mut vec![Rc::new(a1), Rc::new(b1)])+ .build()+ .unwrap();++ let message = Type::group_type_builder("root")+ .with_fields(&mut vec![Rc::new(a0)])+ .build()+ .unwrap();++ assert_print_parse_message(message);+ }++ #[test]+ fn test_print_and_parse_nested() {+ let f1 = Type::primitive_type_builder("f1", PhysicalType::INT32)+ .with_repetition(Repetition::REQUIRED)+ .with_logical_type(LogicalType::INT_32)+ .build()+ .unwrap();++ let f2 = Type::primitive_type_builder("f2", PhysicalType::BYTE_ARRAY)+ .with_repetition(Repetition::OPTIONAL)+ .with_logical_type(LogicalType::UTF8)+ .build()+ .unwrap();++ let foo = Type::group_type_builder("foo")+ .with_repetition(Repetition::OPTIONAL)+ .with_fields(&mut vec![Rc::new(f1), Rc::new(f2)])+ .build()+ .unwrap();++ let f3 = Type::primitive_type_builder("f3", PhysicalType::FIXED_LEN_BYTE_ARRAY)+ .with_repetition(Repetition::REPEATED)+ .with_logical_type(LogicalType::INTERVAL)+ .with_length(12)+ .build()+ .unwrap();++ let message = Type::group_type_builder("schema")+ .with_fields(&mut vec![Rc::new(foo), Rc::new(f3)])+ .build()+ .unwrap();++ assert_print_parse_message(message);+ }++ #[test]+ fn test_print_and_parse_decimal() {+ let f1 = Type::primitive_type_builder("f1", PhysicalType::INT32)+ .with_repetition(Repetition::OPTIONAL)+ .with_logical_type(LogicalType::DECIMAL)+ .with_precision(9)+ .with_scale(2)+ .build()+ .unwrap();++ let f2 = Type::primitive_type_builder("f2", PhysicalType::INT32)+ .with_repetition(Repetition::OPTIONAL)+ .with_logical_type(LogicalType::DECIMAL)+ .with_precision(9)+ .with_scale(0)+ .build()+ .unwrap();++ let message = Type::group_type_builder("schema")+ .with_fields(&mut vec![Rc::new(f1), Rc::new(f2)])+ .build()+ .unwrap();++ assert_print_parse_message(message);+ }+}diff --git a/rust/src/parquet/schema/types.rs b/rust/src/parquet/schema/types.rsnew file mode 100644index 0000000000..90c767c093--- /dev/null+++ b/rust/src/parquet/schema/types.rs@@ -0,0 +1,1830 @@+// 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.++//! Contains structs and methods to build Parquet schema and schema descriptors.++use std::{collections::HashMap, convert::From, fmt, rc::Rc};++use parquet_format::SchemaElement;++use crate::parquet::basic::{LogicalType, Repetition, Type as PhysicalType};+use crate::parquet::errors::{ParquetError, Result};++// ----------------------------------------------------------------------+// Parquet Type definitions++/// Type alias for `Rc<Type>`.+pub type TypePtr = Rc<Type>;+/// Type alias for `Rc<SchemaDescriptor>`.+pub type SchemaDescPtr = Rc<SchemaDescriptor>;+/// Type alias for `Rc<ColumnDescriptor>`.+pub type ColumnDescPtr = Rc<ColumnDescriptor>;++/// Representation of a Parquet type.+/// Used to describe primitive leaf fields and structs, including top-level schema.+/// Note that the top-level schema type is represented using `GroupType` whose+/// repetition is `None`.+#[derive(Debug, PartialEq)]+pub enum Type {+ PrimitiveType {+ basic_info: BasicTypeInfo,+ physical_type: PhysicalType,+ type_length: i32,+ scale: i32,+ precision: i32,+ },+ GroupType {+ basic_info: BasicTypeInfo,+ fields: Vec<TypePtr>,+ },+}++impl Type {+ /// Creates primitive type builder with provided field name and physical type.+ pub fn primitive_type_builder(name: &str, physical_type: PhysicalType) -> PrimitiveTypeBuilder {+ PrimitiveTypeBuilder::new(name, physical_type)+ }++ /// Creates group type builder with provided column name.+ pub fn group_type_builder(name: &str) -> GroupTypeBuilder {+ GroupTypeBuilder::new(name)+ }++ /// Returns [`BasicTypeInfo`] information about the type.+ pub fn get_basic_info(&self) -> &BasicTypeInfo {+ match *self {+ Type::PrimitiveType { ref basic_info, .. } => &basic_info,+ Type::GroupType { ref basic_info, .. } => &basic_info,+ }+ }++ /// Returns this type's field name.+ pub fn name(&self) -> &str {+ self.get_basic_info().name()+ }++ /// Gets the fields from this group type.+ /// Note that this will panic if called on a non-group type.+ // TODO: should we return `&[&Type]` here?+ pub fn get_fields(&self) -> &[TypePtr] {+ match *self {+ Type::GroupType { ref fields, .. } => &fields[..],+ _ => panic!("Cannot call get_fields() on a non-group type"),+ }+ }++ /// Gets physical type of this primitive type.+ /// Note that this will panic if called on a non-primitive type.+ pub fn get_physical_type(&self) -> PhysicalType {+ match *self {+ Type::PrimitiveType {+ basic_info: _,+ physical_type,+ ..+ } => physical_type,+ _ => panic!("Cannot call get_physical_type() on a non-primitive type"),+ }+ }++ /// Checks if `sub_type` schema is part of current schema.+ /// This method can be used to check if projected columns are part of the root schema.+ pub fn check_contains(&self, sub_type: &Type) -> bool {+ // Names match, and repetitions match or not set for both+ let basic_match = self.get_basic_info().name() == sub_type.get_basic_info().name()+ && (self.is_schema() && sub_type.is_schema()+ || !self.is_schema()+ && !sub_type.is_schema()+ && self.get_basic_info().repetition()+ == sub_type.get_basic_info().repetition());++ match *self {+ Type::PrimitiveType { .. } if basic_match && sub_type.is_primitive() => {+ self.get_physical_type() == sub_type.get_physical_type()+ }+ Type::GroupType { .. } if basic_match && sub_type.is_group() => {+ // build hashmap of name -> TypePtr+ let mut field_map = HashMap::new();+ for field in self.get_fields() {+ field_map.insert(field.name(), field);+ }++ for field in sub_type.get_fields() {+ if !field_map+ .get(field.name())+ .map(|tpe| tpe.check_contains(field))+ .unwrap_or(false)+ {+ return false;+ }+ }+ true+ }+ _ => false,+ }+ }++ /// Returns `true` if this type is a primitive type, `false` otherwise.+ pub fn is_primitive(&self) -> bool {+ match *self {+ Type::PrimitiveType { .. } => true,+ _ => false,+ }+ }++ /// Returns `true` if this type is a group type, `false` otherwise.+ pub fn is_group(&self) -> bool {+ match *self {+ Type::GroupType { .. } => true,+ _ => false,+ }+ }++ /// Returns `true` if this type is the top-level schema type (message type).+ pub fn is_schema(&self) -> bool {+ match *self {+ Type::GroupType { ref basic_info, .. } => !basic_info.has_repetition(),+ _ => false,+ }+ }+}++/// A builder for primitive types. All attributes are optional+/// except the name and physical type.+/// Note that if not specified explicitly, `Repetition::OPTIONAL` is used.+pub struct PrimitiveTypeBuilder<'a> {+ name: &'a str,+ repetition: Repetition,+ physical_type: PhysicalType,+ logical_type: LogicalType,+ length: i32,+ precision: i32,+ scale: i32,+ id: Option<i32>,+}++impl<'a> PrimitiveTypeBuilder<'a> {+ /// Creates new primitive type builder with provided field name and physical type.+ pub fn new(name: &'a str, physical_type: PhysicalType) -> Self {+ Self {+ name,+ repetition: Repetition::OPTIONAL,+ physical_type,+ logical_type: LogicalType::NONE,+ length: -1,+ precision: -1,+ scale: -1,+ id: None,+ }+ }++ /// Sets [`Repetition`](`::basic::Repetition`) for this field and returns itself.+ pub fn with_repetition(mut self, repetition: Repetition) -> Self {+ self.repetition = repetition;+ self+ }++ /// Sets [`LogicalType`](`::basic::LogicalType`) for this field and returns itself.+ pub fn with_logical_type(mut self, logical_type: LogicalType) -> Self {+ self.logical_type = logical_type;+ self+ }++ /// Sets type length and returns itself.+ /// This is only applied to FIXED_LEN_BYTE_ARRAY and INT96 (INTERVAL) types, because+ /// they maintain fixed size underlying byte array.+ /// By default, value is `0`.+ pub fn with_length(mut self, length: i32) -> Self {+ self.length = length;+ self+ }++ /// Sets precision for Parquet DECIMAL physical type and returns itself.+ /// By default, it equals to `0` and used only for decimal context.+ pub fn with_precision(mut self, precision: i32) -> Self {+ self.precision = precision;+ self+ }++ /// Sets scale for Parquet DECIMAL physical type and returns itself.+ /// By default, it equals to `0` and used only for decimal context.+ pub fn with_scale(mut self, scale: i32) -> Self {+ self.scale = scale;+ self+ }++ /// Sets optional field id and returns itself.+ pub fn with_id(mut self, id: i32) -> Self {+ self.id = Some(id);+ self+ }++ /// Creates a new `PrimitiveType` instance from the collected attributes.+ /// Returns `Err` in case of any building conditions are not met.+ pub fn build(self) -> Result<Type> {+ let basic_info = BasicTypeInfo {+ name: String::from(self.name),+ repetition: Some(self.repetition),+ logical_type: self.logical_type,+ id: self.id,+ };++ // Check length before logical type, since it is used for logical type validation.+ if self.physical_type == PhysicalType::FIXED_LEN_BYTE_ARRAY && self.length < 0 {+ return Err(general_err!(+ "Invalid FIXED_LEN_BYTE_ARRAY length: {}",+ self.length+ ));+ }++ match self.logical_type {+ LogicalType::NONE => {}+ LogicalType::UTF8 | LogicalType::BSON | LogicalType::JSON => {+ if self.physical_type != PhysicalType::BYTE_ARRAY {+ return Err(general_err!(+ "{} can only annotate BYTE_ARRAY fields",+ self.logical_type+ ));+ }+ }+ LogicalType::DECIMAL => {+ match self.physical_type {+ PhysicalType::INT32+ | PhysicalType::INT64+ | PhysicalType::BYTE_ARRAY+ | PhysicalType::FIXED_LEN_BYTE_ARRAY => (),+ _ => {+ return Err(general_err!(+ "DECIMAL can only annotate INT32, INT64, BYTE_ARRAY and FIXED"+ ));+ }+ }++ // Precision is required and must be a non-zero positive integer.+ if self.precision < 1 {+ return Err(general_err!(+ "Invalid DECIMAL precision: {}",+ self.precision+ ));+ }++ // Scale must be zero or a positive integer less than the precision.+ if self.scale < 0 {+ return Err(general_err!("Invalid DECIMAL scale: {}", self.scale));+ }++ if self.scale >= self.precision {+ return Err(general_err!(+ "Invalid DECIMAL: scale ({}) cannot be greater than or equal to precision \+ ({})",+ self.scale,+ self.precision+ ));+ }++ // Check precision and scale based on physical type limitations.+ match self.physical_type {+ PhysicalType::INT32 => {+ if self.precision > 9 {+ return Err(general_err!(+ "Cannot represent INT32 as DECIMAL with precision {}",+ self.precision+ ));+ }+ }+ PhysicalType::INT64 => {+ if self.precision > 18 {+ return Err(general_err!(+ "Cannot represent INT64 as DECIMAL with precision {}",+ self.precision+ ));+ }+ }+ PhysicalType::FIXED_LEN_BYTE_ARRAY => {+ let max_precision =+ (2f64.powi(8 * self.length - 1) - 1f64).log10().floor() as i32;++ if self.precision > max_precision {+ return Err(general_err!(+ "Cannot represent FIXED_LEN_BYTE_ARRAY as DECIMAL with length {} and \+ precision {}",+ self.length,+ self.precision+ ));+ }+ }+ _ => (), // For BYTE_ARRAY precision is not limited+ }+ }+ LogicalType::DATE+ | LogicalType::TIME_MILLIS+ | LogicalType::UINT_8+ | LogicalType::UINT_16+ | LogicalType::UINT_32+ | LogicalType::INT_8+ | LogicalType::INT_16+ | LogicalType::INT_32 => {+ if self.physical_type != PhysicalType::INT32 {+ return Err(general_err!(+ "{} can only annotate INT32",+ self.logical_type+ ));+ }+ }+ LogicalType::TIME_MICROS+ | LogicalType::TIMESTAMP_MILLIS+ | LogicalType::TIMESTAMP_MICROS+ | LogicalType::UINT_64+ | LogicalType::INT_64 => {+ if self.physical_type != PhysicalType::INT64 {+ return Err(general_err!(+ "{} can only annotate INT64",+ self.logical_type+ ));+ }+ }+ LogicalType::INTERVAL => {+ if self.physical_type != PhysicalType::FIXED_LEN_BYTE_ARRAY || self.length != 12 {+ return Err(general_err!(+ "INTERVAL can only annotate FIXED_LEN_BYTE_ARRAY(12)"+ ));+ }+ }+ LogicalType::ENUM => {+ if self.physical_type != PhysicalType::BYTE_ARRAY {+ return Err(general_err!("ENUM can only annotate BYTE_ARRAY fields"));+ }+ }+ _ => {+ return Err(general_err!(+ "{} cannot be applied to a primitive type",+ self.logical_type+ ));+ }+ }++ Ok(Type::PrimitiveType {+ basic_info,+ physical_type: self.physical_type,+ type_length: self.length,+ scale: self.scale,+ precision: self.precision,+ })+ }+}++/// A builder for group types. All attributes are optional except the name.+/// Note that if not specified explicitly, `None` is used as the repetition of the group,+/// which means it is a root (message) type.+pub struct GroupTypeBuilder<'a> {+ name: &'a str,+ repetition: Option<Repetition>,+ logical_type: LogicalType,+ fields: Vec<TypePtr>,+ id: Option<i32>,+}++impl<'a> GroupTypeBuilder<'a> {+ /// Creates new group type builder with provided field name.+ pub fn new(name: &'a str) -> Self {+ Self {+ name,+ repetition: None,+ logical_type: LogicalType::NONE,+ fields: Vec::new(),+ id: None,+ }+ }++ /// Sets [`Repetition`](`::basic::Repetition`) for this field and returns itself.+ pub fn with_repetition(mut self, repetition: Repetition) -> Self {+ self.repetition = Some(repetition);+ self+ }++ /// Sets [`LogicalType`](`::basic::LogicalType`) for this field and returns itself.+ pub fn with_logical_type(mut self, logical_type: LogicalType) -> Self {+ self.logical_type = logical_type;+ self+ }++ /// Sets a list of fields that should be child nodes of this field.+ /// Returns updated self.+ pub fn with_fields(mut self, fields: &mut Vec<TypePtr>) -> Self {+ self.fields.append(fields);+ self+ }++ /// Sets optional field id and returns itself.+ pub fn with_id(mut self, id: i32) -> Self {+ self.id = Some(id);+ self+ }++ /// Creates a new `GroupType` instance from the gathered attributes.+ pub fn build(self) -> Result<Type> {+ let basic_info = BasicTypeInfo {+ name: String::from(self.name),+ repetition: self.repetition,+ logical_type: self.logical_type,+ id: self.id,+ };+ Ok(Type::GroupType {+ basic_info,+ fields: self.fields,+ })+ }+}++/// Basic type info. This contains information such as the name of the type,+/// the repetition level, the logical type and the kind of the type (group, primitive).+#[derive(Debug, PartialEq)]+pub struct BasicTypeInfo {+ name: String,+ repetition: Option<Repetition>,+ logical_type: LogicalType,+ id: Option<i32>,+}++impl BasicTypeInfo {+ /// Returns field name.+ pub fn name(&self) -> &str {+ &self.name+ }++ /// Returns `true` if type has repetition field set, `false` otherwise.+ /// This is mostly applied to group type, because primitive type always has+ /// repetition set.+ pub fn has_repetition(&self) -> bool {+ self.repetition.is_some()+ }++ /// Returns [`Repetition`](`::basic::Repetition`) value for the type.+ pub fn repetition(&self) -> Repetition {+ assert!(self.repetition.is_some());+ self.repetition.unwrap()+ }++ /// Returns [`LogicalType`](`::basic::LogicalType`) value for the type.+ pub fn logical_type(&self) -> LogicalType {+ self.logical_type+ }++ /// Returns `true` if id is set, `false` otherwise.+ pub fn has_id(&self) -> bool {+ self.id.is_some()+ }++ /// Returns id value for the type.+ pub fn id(&self) -> i32 {+ assert!(self.id.is_some());+ self.id.unwrap()+ }+}++// ----------------------------------------------------------------------+// Parquet descriptor definitions++/// Represents a path in a nested schema+#[derive(Clone, PartialEq, Debug, Eq, Hash)]+pub struct ColumnPath {+ parts: Vec<String>,+}++impl ColumnPath {+ /// Creates new column path from vector of field names.+ pub fn new(parts: Vec<String>) -> Self {+ ColumnPath { parts }+ }++ /// Returns string representation of this column path.+ /// ```rust+ /// use arrow::parquet::schema::types::ColumnPath;+ ///+ /// let path = ColumnPath::new(vec!["a".to_string(), "b".to_string(), "c".to_string()]);+ /// assert_eq!(&path.string(), "a.b.c");+ /// ```+ pub fn string(&self) -> String {+ self.parts.join(".")+ }+}++impl fmt::Display for ColumnPath {+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {+ write!(f, "{:?}", self.string())+ }+}++impl From<Vec<String>> for ColumnPath {+ fn from(parts: Vec<String>) -> Self {+ ColumnPath { parts }+ }+}++impl<'a> From<&'a str> for ColumnPath {+ fn from(single_path: &str) -> Self {+ let s = String::from(single_path);+ ColumnPath::from(s)+ }+}++impl From<String> for ColumnPath {+ fn from(single_path: String) -> Self {+ let mut v = vec![];+ v.push(single_path);+ ColumnPath { parts: v }+ }+}++impl AsRef<[String]> for ColumnPath {+ fn as_ref(&self) -> &[String] {+ &self.parts+ }+}++/// A descriptor for leaf-level primitive columns.+/// This encapsulates information such as definition and repetition levels and is used to+/// re-assemble nested data.+pub struct ColumnDescriptor {+ // The "leaf" primitive type of this column+ primitive_type: TypePtr,++ // The root type of this column. For instance, if the column is "a.b.c.d", then the+ // primitive type is 'd' while the root_type is 'a'.+ //+ // NOTE: this is sometimes `None` for the convenience of testing. It should NEVER be+ // `None` when running in production.+ root_type: Option<TypePtr>,++ // The maximum definition level for this column+ max_def_level: i16,++ // The maximum repetition level for this column+ max_rep_level: i16,++ // The path of this column. For instance, "a.b.c.d".+ path: ColumnPath,+}++impl ColumnDescriptor {+ /// Creates new descriptor for leaf-level column.+ pub fn new(+ primitive_type: TypePtr,+ root_type: Option<TypePtr>,+ max_def_level: i16,+ max_rep_level: i16,+ path: ColumnPath,+ ) -> Self {+ Self {+ primitive_type,+ root_type,+ max_def_level,+ max_rep_level,+ path,+ }+ }++ /// Returns maximum definition level for this column.+ pub fn max_def_level(&self) -> i16 {+ self.max_def_level+ }++ /// Returns maximum repetition level for this column.+ pub fn max_rep_level(&self) -> i16 {+ self.max_rep_level+ }++ /// Returns [`ColumnPath`] for this column.+ pub fn path(&self) -> &ColumnPath {+ &self.path+ }++ /// Returns self type [`Type`](`::schema::types::Type`) for this leaf column.+ pub fn self_type(&self) -> &Type {+ self.primitive_type.as_ref()+ }++ /// Returns root [`Type`](`::schema::types::Type`) (most top-level parent field) for+ /// this leaf column.+ pub fn root_type(&self) -> &Type {+ assert!(self.root_type.is_some());+ self.root_type.as_ref().unwrap()+ }++ /// Returns column name.+ pub fn name(&self) -> &str {+ self.primitive_type.name()+ }++ /// Returns [`LogicalType`](`::basic::LogicalType`) for this column.+ pub fn logical_type(&self) -> LogicalType {+ self.primitive_type.get_basic_info().logical_type()+ }++ /// Returns physical type for this column.+ /// Note that it will panic if called on a non-primitive type.+ pub fn physical_type(&self) -> PhysicalType {+ match self.primitive_type.as_ref() {+ &Type::PrimitiveType { physical_type, .. } => physical_type,+ _ => panic!("Expected primitive type!"),+ }+ }++ /// Returns type length for this column.+ /// Note that it will panic if called on a non-primitive type.+ pub fn type_length(&self) -> i32 {+ match self.primitive_type.as_ref() {+ &Type::PrimitiveType { type_length, .. } => type_length,+ _ => panic!("Expected primitive type!"),+ }+ }++ /// Returns type precision for this column.+ /// Note that it will panic if called on a non-primitive type.+ pub fn type_precision(&self) -> i32 {+ match self.primitive_type.as_ref() {+ &Type::PrimitiveType { precision, .. } => precision,+ _ => panic!("Expected primitive type!"),+ }+ }++ /// Returns type scale for this column.+ /// Note that it will panic if called on a non-primitive type.+ pub fn type_scale(&self) -> i32 {+ match self.primitive_type.as_ref() {+ &Type::PrimitiveType { scale, .. } => scale,+ _ => panic!("Expected primitive type!"),+ }+ }+}++/// A schema descriptor. This encapsulates the top-level schemas for all the columns,+/// as well as all descriptors for all the primitive columns.+pub struct SchemaDescriptor {+ // The top-level schema (the "message" type).+ // This must be a `GroupType` where each field is a root column type in the schema.+ schema: TypePtr,++ // All the descriptors for primitive columns in this schema, constructed from+ // `schema` in DFS order.+ leaves: Vec<ColumnDescPtr>,++ // Mapping from a leaf column's index to the root column type that it+ // comes from. For instance: the leaf `a.b.c.d` would have a link back to `a`:+ // -- a <-----++ // -- -- b |+ // -- -- -- c |+ // -- -- -- -- d+ leaf_to_base: HashMap<usize, TypePtr>,+}++impl SchemaDescriptor {+ /// Creates new schema descriptor from Parquet schema.+ pub fn new(tp: TypePtr) -> Self {+ assert!(tp.is_group(), "SchemaDescriptor should take a GroupType");+ let mut leaves = vec![];+ let mut leaf_to_base = HashMap::new();+ for f in tp.get_fields() {+ let mut path = vec![];+ build_tree(+ f.clone(),+ tp.clone(),+ f.clone(),+ 0,+ 0,+ &mut leaves,+ &mut leaf_to_base,+ &mut path,+ );+ }++ Self {+ schema: tp,+ leaves,+ leaf_to_base,+ }+ }++ /// Returns [`ColumnDescriptor`] for a field position.+ pub fn column(&self, i: usize) -> ColumnDescPtr {+ assert!(+ i < self.leaves.len(),+ "Index out of bound: {} not in [0, {})",+ i,+ self.leaves.len()+ );+ self.leaves[i].clone()+ }++ /// Returns slice of [`ColumnDescriptor`].+ pub fn columns(&self) -> &[ColumnDescPtr] {+ &self.leaves+ }++ /// Returns number of leaf-level columns.+ pub fn num_columns(&self) -> usize {+ self.leaves.len()+ }++ /// Returns column root [`Type`](`::schema::types::Type`) for a field position.+ pub fn get_column_root(&self, i: usize) -> &Type {+ assert!(+ i < self.leaves.len(),+ "Index out of bound: {} not in [0, {})",+ i,+ self.leaves.len()+ );+ let result = self.leaf_to_base.get(&i);+ assert!(+ result.is_some(),+ "Expected a value for index {} but found None",+ i+ );+ result.unwrap().as_ref()+ }++ /// Returns schema as [`Type`](`::schema::types::Type`).+ pub fn root_schema(&self) -> &Type {+ self.schema.as_ref()+ }++ /// Returns schema name.+ pub fn name(&self) -> &str {+ self.schema.name()+ }+}++fn build_tree(+ tp: TypePtr,+ root_tp: TypePtr,+ base_tp: TypePtr,+ mut max_rep_level: i16,+ mut max_def_level: i16,+ leaves: &mut Vec<ColumnDescPtr>,+ leaf_to_base: &mut HashMap<usize, TypePtr>,+ path_so_far: &mut Vec<String>,+) {+ assert!(tp.get_basic_info().has_repetition());++ path_so_far.push(String::from(tp.name()));+ match tp.get_basic_info().repetition() {+ Repetition::OPTIONAL => {+ max_def_level += 1;+ }+ Repetition::REPEATED => {+ max_def_level += 1;+ max_rep_level += 1;+ }+ _ => {}+ }++ match tp.as_ref() {+ &Type::PrimitiveType { .. } => {+ let mut path: Vec<String> = vec![];+ path.extend_from_slice(&path_so_far[..]);+ leaves.push(Rc::new(ColumnDescriptor::new(+ tp.clone(),+ Some(root_tp),+ max_def_level,+ max_rep_level,+ ColumnPath::new(path),+ )));+ leaf_to_base.insert(leaves.len() - 1, base_tp);+ }+ &Type::GroupType { ref fields, .. } => {+ for f in fields {+ build_tree(+ f.clone(),+ root_tp.clone(),+ base_tp.clone(),+ max_rep_level,+ max_def_level,+ leaves,+ leaf_to_base,+ path_so_far,+ );+ let idx = path_so_far.len() - 1;+ path_so_far.remove(idx);+ }+ }+ }+}++/// Method to convert from Thrift.+pub fn from_thrift(elements: &[SchemaElement]) -> Result<TypePtr> {+ let mut index = 0;+ let mut schema_nodes = Vec::new();+ while index < elements.len() {+ let t = from_thrift_helper(elements, index)?;+ index = t.0;+ schema_nodes.push(t.1);+ }+ if schema_nodes.len() != 1 {+ return Err(general_err!(+ "Expected exactly one root node, but found {}",+ schema_nodes.len()+ ));+ }++ Ok(schema_nodes.remove(0))+}++/// Constructs a new Type from the `elements`, starting at index `index`.+/// The first result is the starting index for the next Type after this one. If it is+/// equal to `elements.len()`, then this Type is the last one.+/// The second result is the result Type.+fn from_thrift_helper(elements: &[SchemaElement], index: usize) -> Result<(usize, TypePtr)> {+ // Whether or not the current node is root (message type).+ // There is only one message type node in the schema tree.+ let is_root_node = index == 0;++ if index > elements.len() {+ return Err(general_err!(+ "Index out of bound, index = {}, len = {}",+ index,+ elements.len()+ ));+ }+ let logical_type = LogicalType::from(elements[index].converted_type);+ let field_id = elements[index].field_id;+ match elements[index].num_children {+ // From parquet-format:+ // The children count is used to construct the nested relationship.+ // This field is not set when the element is a primitive type+ // Sometimes parquet-cpp sets num_children field to 0 for primitive types, so we+ // have to handle this case too.+ None | Some(0) => {+ // primitive type+ if elements[index].repetition_type.is_none() {+ return Err(general_err!(+ "Repetition level must be defined for a primitive type"+ ));+ }+ let repetition = Repetition::from(elements[index].repetition_type.unwrap());+ let physical_type = PhysicalType::from(elements[index].type_.unwrap());+ let length = elements[index].type_length.unwrap_or(-1);+ let scale = elements[index].scale.unwrap_or(-1);+ let precision = elements[index].precision.unwrap_or(-1);+ let name = &elements[index].name;+ let mut builder = Type::primitive_type_builder(name, physical_type)+ .with_repetition(repetition)+ .with_logical_type(logical_type)+ .with_length(length)+ .with_precision(precision)+ .with_scale(scale);+ if let Some(id) = field_id {+ builder = builder.with_id(id);+ }+ Ok((index + 1, Rc::new(builder.build()?)))+ }+ Some(n) => {+ let repetition = elements[index].repetition_type.map(|r| Repetition::from(r));+ let mut fields = vec![];+ let mut next_index = index + 1;+ for _ in 0..n {+ let child_result = from_thrift_helper(elements, next_index as usize)?;+ next_index = child_result.0;+ fields.push(child_result.1);+ }++ let mut builder = Type::group_type_builder(&elements[index].name)+ .with_logical_type(logical_type)+ .with_fields(&mut fields);+ if let Some(rep) = repetition {+ // Sometimes parquet-cpp and parquet-mr set repetition level REQUIRED or REPEATED+ // for root node.+ //+ // We only set repetition for group types that are not top-level message type.+ // According to parquet-format:+ // Root of the schema does not have a repetition_type.+ // All other types must have one.+ if !is_root_node {+ builder = builder.with_repetition(rep);+ }+ }+ if let Some(id) = field_id {+ builder = builder.with_id(id);+ }+ Ok((next_index, Rc::new(builder.build().unwrap())))+ }+ }+}++/// Method to convert to Thrift.+pub fn to_thrift(schema: &Type) -> Result<Vec<SchemaElement>> {+ if !schema.is_group() {+ return Err(general_err!("Root schema must be Group type"));+ }+ let mut elements: Vec<SchemaElement> = Vec::new();+ to_thrift_helper(schema, &mut elements);+ Ok(elements)+}++/// Constructs list of `SchemaElement` from the schema using depth-first traversal.+/// Here we assume that schema is always valid and starts with group type.+fn to_thrift_helper(schema: &Type, elements: &mut Vec<SchemaElement>) {+ match *schema {+ Type::PrimitiveType {+ ref basic_info,+ physical_type,+ type_length,+ scale,+ precision,+ } => {+ let element = SchemaElement {+ type_: Some(physical_type.into()),+ type_length: if type_length >= 0 {+ Some(type_length)+ } else {+ None+ },+ repetition_type: Some(basic_info.repetition().into()),+ name: basic_info.name().to_owned(),+ num_children: None,+ converted_type: basic_info.logical_type().into(),+ scale: if scale >= 0 { Some(scale) } else { None },+ precision: if precision >= 0 {+ Some(precision)+ } else {+ None+ },+ field_id: if basic_info.has_id() {+ Some(basic_info.id())+ } else {+ None+ },+ logical_type: None,+ };++ elements.push(element);+ }+ Type::GroupType {+ ref basic_info,+ ref fields,+ } => {+ let repetition = if basic_info.has_repetition() {+ Some(basic_info.repetition().into())+ } else {+ None+ };++ let element = SchemaElement {+ type_: None,+ type_length: None,+ repetition_type: repetition,+ name: basic_info.name().to_owned(),+ num_children: Some(fields.len() as i32),+ converted_type: basic_info.logical_type().into(),+ scale: None,+ precision: None,+ field_id: if basic_info.has_id() {+ Some(basic_info.id())+ } else {+ None+ },+ logical_type: None,+ };++ elements.push(element);++ // Add child elements for a group+ for field in fields {+ to_thrift_helper(field, elements);+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ use std::error::Error;++ use crate::parquet::schema::parser::parse_message_type;++ #[test]+ fn test_primitive_type() {+ let mut result = Type::primitive_type_builder("foo", PhysicalType::INT32)+ .with_logical_type(LogicalType::INT_32)+ .with_id(0)+ .build();+ assert!(result.is_ok());++ if let Ok(tp) = result {+ assert!(tp.is_primitive());+ assert!(!tp.is_group());+ let basic_info = tp.get_basic_info();+ assert_eq!(basic_info.repetition(), Repetition::OPTIONAL);+ assert_eq!(basic_info.logical_type(), LogicalType::INT_32);+ assert_eq!(basic_info.id(), 0);+ match tp {+ Type::PrimitiveType { physical_type, .. } => {+ assert_eq!(physical_type, PhysicalType::INT32);+ }+ _ => assert!(false),+ }+ }++ // Test illegal inputs+ result = Type::primitive_type_builder("foo", PhysicalType::INT64)+ .with_repetition(Repetition::REPEATED)+ .with_logical_type(LogicalType::BSON)+ .build();+ assert!(result.is_err());+ if let Err(e) = result {+ assert_eq!(e.description(), "BSON can only annotate BYTE_ARRAY fields");+ }++ result = Type::primitive_type_builder("foo", PhysicalType::INT96)+ .with_repetition(Repetition::REQUIRED)+ .with_logical_type(LogicalType::DECIMAL)+ .with_precision(-1)+ .with_scale(-1)+ .build();+ assert!(result.is_err());+ if let Err(e) = result {+ assert_eq!(+ e.description(),+ "DECIMAL can only annotate INT32, INT64, BYTE_ARRAY and FIXED"+ );+ }++ result = Type::primitive_type_builder("foo", PhysicalType::BYTE_ARRAY)+ .with_repetition(Repetition::REQUIRED)+ .with_logical_type(LogicalType::DECIMAL)+ .with_precision(-1)+ .with_scale(-1)+ .build();+ assert!(result.is_err());+ if let Err(e) = result {+ assert_eq!(e.description(), "Invalid DECIMAL precision: -1");+ }++ result = Type::primitive_type_builder("foo", PhysicalType::BYTE_ARRAY)+ .with_repetition(Repetition::REQUIRED)+ .with_logical_type(LogicalType::DECIMAL)+ .with_precision(0)+ .with_scale(-1)+ .build();+ assert!(result.is_err());+ if let Err(e) = result {+ assert_eq!(e.description(), "Invalid DECIMAL precision: 0");+ }++ result = Type::primitive_type_builder("foo", PhysicalType::BYTE_ARRAY)+ .with_repetition(Repetition::REQUIRED)+ .with_logical_type(LogicalType::DECIMAL)+ .with_precision(1)+ .with_scale(-1)+ .build();+ assert!(result.is_err());+ if let Err(e) = result {+ assert_eq!(e.description(), "Invalid DECIMAL scale: -1");+ }++ result = Type::primitive_type_builder("foo", PhysicalType::BYTE_ARRAY)+ .with_repetition(Repetition::REQUIRED)+ .with_logical_type(LogicalType::DECIMAL)+ .with_precision(1)+ .with_scale(2)+ .build();+ assert!(result.is_err());+ if let Err(e) = result {+ assert_eq!(+ e.description(),+ "Invalid DECIMAL: scale (2) cannot be greater than or equal to precision (1)"+ );+ }++ result = Type::primitive_type_builder("foo", PhysicalType::INT32)+ .with_repetition(Repetition::REQUIRED)+ .with_logical_type(LogicalType::DECIMAL)+ .with_precision(18)+ .with_scale(2)+ .build();+ assert!(result.is_err());+ if let Err(e) = result {+ assert_eq!(+ e.description(),+ "Cannot represent INT32 as DECIMAL with precision 18"+ );+ }++ result = Type::primitive_type_builder("foo", PhysicalType::INT64)+ .with_repetition(Repetition::REQUIRED)+ .with_logical_type(LogicalType::DECIMAL)+ .with_precision(32)+ .with_scale(2)+ .build();+ assert!(result.is_err());+ if let Err(e) = result {+ assert_eq!(+ e.description(),+ "Cannot represent INT64 as DECIMAL with precision 32"+ );+ }++ result = Type::primitive_type_builder("foo", PhysicalType::FIXED_LEN_BYTE_ARRAY)+ .with_repetition(Repetition::REQUIRED)+ .with_logical_type(LogicalType::DECIMAL)+ .with_length(5)+ .with_precision(12)+ .with_scale(2)+ .build();+ assert!(result.is_err());+ if let Err(e) = result {+ assert_eq!(+ e.description(),+ "Cannot represent FIXED_LEN_BYTE_ARRAY as DECIMAL with length 5 and precision 12"+ );+ }++ result = Type::primitive_type_builder("foo", PhysicalType::INT64)+ .with_repetition(Repetition::REQUIRED)+ .with_logical_type(LogicalType::UINT_8)+ .build();+ assert!(result.is_err());+ if let Err(e) = result {+ assert_eq!(e.description(), "UINT_8 can only annotate INT32");+ }++ result = Type::primitive_type_builder("foo", PhysicalType::INT32)+ .with_repetition(Repetition::REQUIRED)+ .with_logical_type(LogicalType::TIME_MICROS)+ .build();+ assert!(result.is_err());+ if let Err(e) = result {+ assert_eq!(e.description(), "TIME_MICROS can only annotate INT64");+ }++ result = Type::primitive_type_builder("foo", PhysicalType::BYTE_ARRAY)+ .with_repetition(Repetition::REQUIRED)+ .with_logical_type(LogicalType::INTERVAL)+ .build();+ assert!(result.is_err());+ if let Err(e) = result {+ assert_eq!(+ e.description(),+ "INTERVAL can only annotate FIXED_LEN_BYTE_ARRAY(12)"+ );+ }++ result = Type::primitive_type_builder("foo", PhysicalType::FIXED_LEN_BYTE_ARRAY)+ .with_repetition(Repetition::REQUIRED)+ .with_logical_type(LogicalType::INTERVAL)+ .with_length(1)+ .build();+ assert!(result.is_err());+ if let Err(e) = result {+ assert_eq!(+ e.description(),+ "INTERVAL can only annotate FIXED_LEN_BYTE_ARRAY(12)"+ );+ }++ result = Type::primitive_type_builder("foo", PhysicalType::INT32)+ .with_repetition(Repetition::REQUIRED)+ .with_logical_type(LogicalType::ENUM)+ .build();+ assert!(result.is_err());+ if let Err(e) = result {+ assert_eq!(e.description(), "ENUM can only annotate BYTE_ARRAY fields");+ }++ result = Type::primitive_type_builder("foo", PhysicalType::INT32)+ .with_repetition(Repetition::REQUIRED)+ .with_logical_type(LogicalType::MAP)+ .build();+ assert!(result.is_err());+ if let Err(e) = result {+ assert_eq!(e.description(), "MAP cannot be applied to a primitive type");+ }++ result = Type::primitive_type_builder("foo", PhysicalType::FIXED_LEN_BYTE_ARRAY)+ .with_repetition(Repetition::REQUIRED)+ .with_logical_type(LogicalType::DECIMAL)+ .with_length(-1)+ .build();+ assert!(result.is_err());+ if let Err(e) = result {+ assert_eq!(e.description(), "Invalid FIXED_LEN_BYTE_ARRAY length: -1");+ }+ }++ #[test]+ fn test_group_type() {+ let f1 = Type::primitive_type_builder("f1", PhysicalType::INT32)+ .with_logical_type(LogicalType::INT_32)+ .with_id(0)+ .build();+ assert!(f1.is_ok());+ let f2 = Type::primitive_type_builder("f2", PhysicalType::BYTE_ARRAY)+ .with_logical_type(LogicalType::UTF8)+ .with_id(1)+ .build();+ assert!(f2.is_ok());++ let mut fields = vec![];+ fields.push(Rc::new(f1.unwrap()));+ fields.push(Rc::new(f2.unwrap()));++ let result = Type::group_type_builder("foo")+ .with_repetition(Repetition::REPEATED)+ .with_fields(&mut fields)+ .with_id(1)+ .build();+ assert!(result.is_ok());++ let tp = result.unwrap();+ let basic_info = tp.get_basic_info();+ assert!(tp.is_group());+ assert!(!tp.is_primitive());+ assert_eq!(basic_info.repetition(), Repetition::REPEATED);+ assert_eq!(basic_info.logical_type(), LogicalType::NONE);+ assert_eq!(basic_info.id(), 1);+ assert_eq!(tp.get_fields().len(), 2);+ assert_eq!(tp.get_fields()[0].name(), "f1");+ assert_eq!(tp.get_fields()[1].name(), "f2");+ }++ #[test]+ fn test_column_descriptor() {+ let result = test_column_descriptor_helper();+ assert!(+ result.is_ok(),+ "Expected result to be OK but got err:\n {}",+ result.unwrap_err()+ );+ }++ fn test_column_descriptor_helper() -> Result<()> {+ let tp = Type::primitive_type_builder("name", PhysicalType::BYTE_ARRAY)+ .with_logical_type(LogicalType::UTF8)+ .build()?;++ let root_tp = Type::group_type_builder("root")+ .with_logical_type(LogicalType::LIST)+ .build()+ .unwrap();+ let root_tp_rc = Rc::new(root_tp);++ let descr = ColumnDescriptor::new(+ Rc::new(tp),+ Some(root_tp_rc.clone()),+ 4,+ 1,+ ColumnPath::from("name"),+ );++ assert_eq!(descr.path(), &ColumnPath::from("name"));+ assert_eq!(descr.logical_type(), LogicalType::UTF8);+ assert_eq!(descr.physical_type(), PhysicalType::BYTE_ARRAY);+ assert_eq!(descr.max_def_level(), 4);+ assert_eq!(descr.max_rep_level(), 1);+ assert_eq!(descr.name(), "name");+ assert_eq!(descr.type_length(), -1);+ assert_eq!(descr.type_precision(), -1);+ assert_eq!(descr.type_scale(), -1);+ assert_eq!(descr.root_type(), root_tp_rc.as_ref());++ Ok(())+ }++ #[test]+ fn test_schema_descriptor() {+ let result = test_schema_descriptor_helper();+ assert!(+ result.is_ok(),+ "Expected result to be OK but got err:\n {}",+ result.unwrap_err()+ );+ }++ // A helper fn to avoid handling the results from type creation+ fn test_schema_descriptor_helper() -> Result<()> {+ let mut fields = vec![];++ let inta = Type::primitive_type_builder("a", PhysicalType::INT32)+ .with_repetition(Repetition::REQUIRED)+ .with_logical_type(LogicalType::INT_32)+ .build()?;+ fields.push(Rc::new(inta));+ let intb = Type::primitive_type_builder("b", PhysicalType::INT64)+ .with_logical_type(LogicalType::INT_64)+ .build()?;+ fields.push(Rc::new(intb));+ let intc = Type::primitive_type_builder("c", PhysicalType::BYTE_ARRAY)+ .with_repetition(Repetition::REPEATED)+ .with_logical_type(LogicalType::UTF8)+ .build()?;+ fields.push(Rc::new(intc));++ // 3-level list encoding+ let item1 = Type::primitive_type_builder("item1", PhysicalType::INT64)+ .with_repetition(Repetition::REQUIRED)+ .with_logical_type(LogicalType::INT_64)+ .build()?;+ let item2 = Type::primitive_type_builder("item2", PhysicalType::BOOLEAN).build()?;+ let item3 = Type::primitive_type_builder("item3", PhysicalType::INT32)+ .with_repetition(Repetition::REPEATED)+ .with_logical_type(LogicalType::INT_32)+ .build()?;+ let list = Type::group_type_builder("records")+ .with_repetition(Repetition::REPEATED)+ .with_logical_type(LogicalType::LIST)+ .with_fields(&mut vec![Rc::new(item1), Rc::new(item2), Rc::new(item3)])+ .build()?;+ let bag = Type::group_type_builder("bag")+ .with_repetition(Repetition::OPTIONAL)+ .with_fields(&mut vec![Rc::new(list)])+ .build()?;+ fields.push(Rc::new(bag));++ let schema = Type::group_type_builder("schema")+ .with_repetition(Repetition::REPEATED)+ .with_fields(&mut fields)+ .build()?;+ let descr = SchemaDescriptor::new(Rc::new(schema));++ let nleaves = 6;+ assert_eq!(descr.num_columns(), nleaves);++ // mdef mrep+ // required int32 a 0 0+ // optional int64 b 1 0+ // repeated byte_array c 1 1+ // optional group bag 1 0+ // repeated group records 2 1+ // required int64 item1 2 1+ // optional boolean item2 3 1+ // repeated int32 item3 3 2+ let ex_max_def_levels = vec![0, 1, 1, 2, 3, 3];+ let ex_max_rep_levels = vec![0, 0, 1, 1, 1, 2];++ for i in 0..nleaves {+ let col = descr.column(i);+ assert_eq!(col.max_def_level(), ex_max_def_levels[i], "{}", i);+ assert_eq!(col.max_rep_level(), ex_max_rep_levels[i], "{}", i);+ }++ assert_eq!(descr.column(0).path().string(), "a");+ assert_eq!(descr.column(1).path().string(), "b");+ assert_eq!(descr.column(2).path().string(), "c");+ assert_eq!(descr.column(3).path().string(), "bag.records.item1");+ assert_eq!(descr.column(4).path().string(), "bag.records.item2");+ assert_eq!(descr.column(5).path().string(), "bag.records.item3");++ assert_eq!(descr.get_column_root(0).name(), "a");+ assert_eq!(descr.get_column_root(3).name(), "bag");+ assert_eq!(descr.get_column_root(4).name(), "bag");+ assert_eq!(descr.get_column_root(5).name(), "bag");++ Ok(())+ }++ #[test]+ fn test_schema_build_tree_def_rep_levels() {+ let message_type = "+ message spark_schema {+ REQUIRED INT32 a;+ OPTIONAL group b {+ OPTIONAL INT32 _1;+ OPTIONAL INT32 _2;+ }+ OPTIONAL group c (LIST) {+ REPEATED group list {+ OPTIONAL INT32 element;+ }+ }+ }+ ";+ let schema = parse_message_type(message_type).expect("should parse schema");+ let descr = SchemaDescriptor::new(Rc::new(schema));+ // required int32 a+ assert_eq!(descr.column(0).max_def_level(), 0);+ assert_eq!(descr.column(0).max_rep_level(), 0);+ // optional int32 b._1+ assert_eq!(descr.column(1).max_def_level(), 2);+ assert_eq!(descr.column(1).max_rep_level(), 0);+ // optional int32 b._2+ assert_eq!(descr.column(2).max_def_level(), 2);+ assert_eq!(descr.column(2).max_rep_level(), 0);+ // repeated optional int32 c.list.element+ assert_eq!(descr.column(3).max_def_level(), 3);+ assert_eq!(descr.column(3).max_rep_level(), 1);+ }++ #[test]+ #[should_panic(expected = "Cannot call get_physical_type() on a non-primitive type")]+ fn test_get_physical_type_panic() {+ let list = Type::group_type_builder("records")+ .with_repetition(Repetition::REPEATED)+ .build()+ .unwrap();+ list.get_physical_type();+ }++ #[test]+ fn test_get_physical_type_primitive() {+ let f = Type::primitive_type_builder("f", PhysicalType::INT64)+ .build()+ .unwrap();+ assert_eq!(f.get_physical_type(), PhysicalType::INT64);++ let f = Type::primitive_type_builder("f", PhysicalType::BYTE_ARRAY)+ .build()+ .unwrap();+ assert_eq!(f.get_physical_type(), PhysicalType::BYTE_ARRAY);+ }++ #[test]+ fn test_check_contains_primitive_primitive() {+ // OK+ let f1 = Type::primitive_type_builder("f", PhysicalType::INT32)+ .build()+ .unwrap();+ let f2 = Type::primitive_type_builder("f", PhysicalType::INT32)+ .build()+ .unwrap();+ assert!(f1.check_contains(&f2));++ // OK: different logical type does not affect check_contains+ let f1 = Type::primitive_type_builder("f", PhysicalType::INT32)+ .with_logical_type(LogicalType::UINT_8)+ .build()+ .unwrap();+ let f2 = Type::primitive_type_builder("f", PhysicalType::INT32)+ .with_logical_type(LogicalType::UINT_16)+ .build()+ .unwrap();+ assert!(f1.check_contains(&f2));++ // KO: different name+ let f1 = Type::primitive_type_builder("f1", PhysicalType::INT32)+ .build()+ .unwrap();+ let f2 = Type::primitive_type_builder("f2", PhysicalType::INT32)+ .build()+ .unwrap();+ assert!(!f1.check_contains(&f2));++ // KO: different type+ let f1 = Type::primitive_type_builder("f", PhysicalType::INT32)+ .build()+ .unwrap();+ let f2 = Type::primitive_type_builder("f", PhysicalType::INT64)+ .build()+ .unwrap();+ assert!(!f1.check_contains(&f2));++ // KO: different repetition+ let f1 = Type::primitive_type_builder("f", PhysicalType::INT32)+ .with_repetition(Repetition::REQUIRED)+ .build()+ .unwrap();+ let f2 = Type::primitive_type_builder("f", PhysicalType::INT32)+ .with_repetition(Repetition::OPTIONAL)+ .build()+ .unwrap();+ assert!(!f1.check_contains(&f2));+ }++ // function to create a new group type for testing+ fn test_new_group_type(name: &str, repetition: Repetition, types: Vec<Type>) -> Type {+ let mut fields = Vec::new();+ for tpe in types {+ fields.push(Rc::new(tpe))+ }+ Type::group_type_builder(name)+ .with_repetition(repetition)+ .with_fields(&mut fields)+ .build()+ .unwrap()+ }++ #[test]+ fn test_check_contains_group_group() {+ // OK: should match okay with empty fields+ let f1 = Type::group_type_builder("f").build().unwrap();+ let f2 = Type::group_type_builder("f").build().unwrap();+ assert!(f1.check_contains(&f2));++ // OK: fields match+ let f1 = test_new_group_type(+ "f",+ Repetition::REPEATED,+ vec![+ Type::primitive_type_builder("f1", PhysicalType::INT32)+ .build()+ .unwrap(),+ Type::primitive_type_builder("f2", PhysicalType::INT64)+ .build()+ .unwrap(),+ ],+ );+ let f2 = test_new_group_type(+ "f",+ Repetition::REPEATED,+ vec![+ Type::primitive_type_builder("f1", PhysicalType::INT32)+ .build()+ .unwrap(),+ Type::primitive_type_builder("f2", PhysicalType::INT64)+ .build()+ .unwrap(),+ ],+ );+ assert!(f1.check_contains(&f2));++ // OK: subset of fields+ let f1 = test_new_group_type(+ "f",+ Repetition::REPEATED,+ vec![+ Type::primitive_type_builder("f1", PhysicalType::INT32)+ .build()+ .unwrap(),+ Type::primitive_type_builder("f2", PhysicalType::INT64)+ .build()+ .unwrap(),+ ],+ );+ let f2 = test_new_group_type(+ "f",+ Repetition::REPEATED,+ vec![Type::primitive_type_builder("f2", PhysicalType::INT64)+ .build()+ .unwrap()],+ );+ assert!(f1.check_contains(&f2));++ // KO: different name+ let f1 = Type::group_type_builder("f1").build().unwrap();+ let f2 = Type::group_type_builder("f2").build().unwrap();+ assert!(!f1.check_contains(&f2));++ // KO: different repetition+ let f1 = Type::group_type_builder("f")+ .with_repetition(Repetition::OPTIONAL)+ .build()+ .unwrap();+ let f2 = Type::group_type_builder("f")+ .with_repetition(Repetition::REPEATED)+ .build()+ .unwrap();+ assert!(!f1.check_contains(&f2));++ // KO: different fields+ let f1 = test_new_group_type(+ "f",+ Repetition::REPEATED,+ vec![+ Type::primitive_type_builder("f1", PhysicalType::INT32)+ .build()+ .unwrap(),+ Type::primitive_type_builder("f2", PhysicalType::INT64)+ .build()+ .unwrap(),+ ],+ );+ let f2 = test_new_group_type(+ "f",+ Repetition::REPEATED,+ vec![+ Type::primitive_type_builder("f1", PhysicalType::INT32)+ .build()+ .unwrap(),+ Type::primitive_type_builder("f2", PhysicalType::BOOLEAN)+ .build()+ .unwrap(),+ ],+ );+ assert!(!f1.check_contains(&f2));++ // KO: different fields+ let f1 = test_new_group_type(+ "f",+ Repetition::REPEATED,+ vec![+ Type::primitive_type_builder("f1", PhysicalType::INT32)+ .build()+ .unwrap(),+ Type::primitive_type_builder("f2", PhysicalType::INT64)+ .build()+ .unwrap(),+ ],+ );+ let f2 = test_new_group_type(+ "f",+ Repetition::REPEATED,+ vec![Type::primitive_type_builder("f3", PhysicalType::INT32)+ .build()+ .unwrap()],+ );+ assert!(!f1.check_contains(&f2));+ }++ #[test]+ fn test_check_contains_group_primitive() {+ // KO: should not match+ let f1 = Type::group_type_builder("f").build().unwrap();+ let f2 = Type::primitive_type_builder("f", PhysicalType::INT64)+ .build()+ .unwrap();+ assert!(!f1.check_contains(&f2));+ assert!(!f2.check_contains(&f1));++ // KO: should not match when primitive field is part of group type+ let f1 = test_new_group_type(+ "f",+ Repetition::REPEATED,+ vec![Type::primitive_type_builder("f1", PhysicalType::INT32)+ .build()+ .unwrap()],+ );+ let f2 = Type::primitive_type_builder("f1", PhysicalType::INT32)+ .build()+ .unwrap();+ assert!(!f1.check_contains(&f2));+ assert!(!f2.check_contains(&f1));++ // OK: match nested types+ let f1 = test_new_group_type(+ "a",+ Repetition::REPEATED,+ vec![+ test_new_group_type(+ "b",+ Repetition::REPEATED,+ vec![Type::primitive_type_builder("c", PhysicalType::INT32)+ .build()+ .unwrap()],+ ),+ Type::primitive_type_builder("d", PhysicalType::INT64)+ .build()+ .unwrap(),+ Type::primitive_type_builder("e", PhysicalType::BOOLEAN)+ .build()+ .unwrap(),+ ],+ );+ let f2 = test_new_group_type(+ "a",+ Repetition::REPEATED,+ vec![test_new_group_type(+ "b",+ Repetition::REPEATED,+ vec![Type::primitive_type_builder("c", PhysicalType::INT32)+ .build()+ .unwrap()],+ )],+ );+ assert!(f1.check_contains(&f2)); // should match+ assert!(!f2.check_contains(&f1)); // should fail+ }++ #[test]+ fn test_schema_type_thrift_conversion_err() {+ let schema = Type::primitive_type_builder("col", PhysicalType::INT32)+ .build()+ .unwrap();+ let thrift_schema = to_thrift(&schema);+ assert!(thrift_schema.is_err());+ if let Err(e) = thrift_schema {+ assert_eq!(e.description(), "Root schema must be Group type");+ }+ }++ #[test]+ fn test_schema_type_thrift_conversion() {+ let message_type = "+ message conversions {+ REQUIRED INT64 id;+ OPTIONAL group int_array_Array (LIST) {+ REPEATED group list {+ OPTIONAL group element (LIST) {+ REPEATED group list {+ OPTIONAL INT32 element;+ }+ }+ }+ }+ OPTIONAL group int_map (MAP) {+ REPEATED group map (MAP_KEY_VALUE) {+ REQUIRED BYTE_ARRAY key (UTF8);+ OPTIONAL INT32 value;+ }+ }+ OPTIONAL group int_Map_Array (LIST) {+ REPEATED group list {+ OPTIONAL group g (MAP) {+ REPEATED group map (MAP_KEY_VALUE) {+ REQUIRED BYTE_ARRAY key (UTF8);+ OPTIONAL group value {+ OPTIONAL group H {+ OPTIONAL group i (LIST) {+ REPEATED group list {+ OPTIONAL DOUBLE element;+ }+ }+ }+ }+ }+ }+ }+ }+ OPTIONAL group nested_struct {+ OPTIONAL INT32 A;+ OPTIONAL group b (LIST) {+ REPEATED group list {+ REQUIRED FIXED_LEN_BYTE_ARRAY (16) element;+ }+ }+ }+ }+ ";+ let expected_schema = parse_message_type(message_type).unwrap();+ let thrift_schema = to_thrift(&expected_schema).unwrap();+ let result_schema = from_thrift(&thrift_schema).unwrap();+ assert_eq!(result_schema, Rc::new(expected_schema));+ }++ #[test]+ fn test_schema_type_thrift_conversion_decimal() {+ let message_type = "+ message decimals {+ OPTIONAL INT32 field0;+ OPTIONAL INT64 field1 (DECIMAL (18, 2));+ OPTIONAL FIXED_LEN_BYTE_ARRAY (16) field2 (DECIMAL (38, 18));+ OPTIONAL BYTE_ARRAY field3 (DECIMAL (9));+ }+ ";+ let expected_schema = parse_message_type(message_type).unwrap();+ let thrift_schema = to_thrift(&expected_schema).unwrap();+ let result_schema = from_thrift(&thrift_schema).unwrap();+ assert_eq!(result_schema, Rc::new(expected_schema));+ }++ // Tests schema conversion from thrift, when num_children is set to Some(0) for a+ // primitive type.+ #[test]+ fn test_schema_from_thrift_with_num_children_set() {+ // schema definition written by parquet-cpp version 1.3.2-SNAPSHOT+ let message_type = "+ message schema {+ OPTIONAL BYTE_ARRAY id (UTF8);+ OPTIONAL BYTE_ARRAY name (UTF8);+ OPTIONAL BYTE_ARRAY message (UTF8);+ OPTIONAL INT32 type (UINT_8);+ OPTIONAL INT64 author_time (TIMESTAMP_MILLIS);+ OPTIONAL INT64 __index_level_0__;+ }+ ";++ let expected_schema = parse_message_type(message_type).unwrap();+ let mut thrift_schema = to_thrift(&expected_schema).unwrap();+ // Change all of None to Some(0)+ for mut elem in &mut thrift_schema[..] {+ if elem.num_children == None {+ elem.num_children = Some(0);+ }+ }++ let result_schema = from_thrift(&thrift_schema).unwrap();+ assert_eq!(result_schema, Rc::new(expected_schema));+ }++ // Sometimes parquet-cpp sets repetition level for the root node, which is against+ // the format definition, but we need to handle it by setting it back to None.+ #[test]+ fn test_schema_from_thrift_root_has_repetition() {+ // schema definition written by parquet-cpp version 1.3.2-SNAPSHOT+ let message_type = "+ message schema {+ OPTIONAL BYTE_ARRAY a (UTF8);+ OPTIONAL INT32 b (UINT_8);+ }+ ";++ let expected_schema = parse_message_type(message_type).unwrap();+ let mut thrift_schema = to_thrift(&expected_schema).unwrap();+ thrift_schema[0].repetition_type = Some(Repetition::REQUIRED.into());++ let result_schema = from_thrift(&thrift_schema).unwrap();+ assert_eq!(result_schema, Rc::new(expected_schema));+ }+}diff --git a/rust/src/parquet/util/bit_packing.rs b/rust/src/parquet/util/bit_packing.rsnew file mode 100644index 0000000000..851fb36ea5--- /dev/null+++ b/rust/src/parquet/util/bit_packing.rs@@ -0,0 +1,3658 @@+// 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.++/// Unpack 32 values with bit width `num_bits` from `in_ptr`, and write to `out_ptr`.+/// Return the `in_ptr` where the starting offset points to the first byte after all the+/// bytes that were consumed.+// TODO: may be better to make these more compact using if-else conditions.+// However, this may require const generics:+// https://github.com/rust-lang/rust/issues/44580+// to eliminate the branching cost.+// TODO: we should use SIMD instructions to further optimize this. I have explored+// https://github.com/tantivy-search/bitpacking+// but the layout it uses for SIMD is different from Parquet.+// TODO: support packing as well, which is used for encoding.+pub unsafe fn unpack32(mut in_ptr: *const u32, out_ptr: *mut u32, num_bits: usize) -> *const u32 {+ in_ptr = match num_bits {+ 0 => nullunpacker32(in_ptr, out_ptr),+ 1 => unpack1_32(in_ptr, out_ptr),+ 2 => unpack2_32(in_ptr, out_ptr),+ 3 => unpack3_32(in_ptr, out_ptr),+ 4 => unpack4_32(in_ptr, out_ptr),+ 5 => unpack5_32(in_ptr, out_ptr),+ 6 => unpack6_32(in_ptr, out_ptr),+ 7 => unpack7_32(in_ptr, out_ptr),+ 8 => unpack8_32(in_ptr, out_ptr),+ 9 => unpack9_32(in_ptr, out_ptr),+ 10 => unpack10_32(in_ptr, out_ptr),+ 11 => unpack11_32(in_ptr, out_ptr),+ 12 => unpack12_32(in_ptr, out_ptr),+ 13 => unpack13_32(in_ptr, out_ptr),+ 14 => unpack14_32(in_ptr, out_ptr),+ 15 => unpack15_32(in_ptr, out_ptr),+ 16 => unpack16_32(in_ptr, out_ptr),+ 17 => unpack17_32(in_ptr, out_ptr),+ 18 => unpack18_32(in_ptr, out_ptr),+ 19 => unpack19_32(in_ptr, out_ptr),+ 20 => unpack20_32(in_ptr, out_ptr),+ 21 => unpack21_32(in_ptr, out_ptr),+ 22 => unpack22_32(in_ptr, out_ptr),+ 23 => unpack23_32(in_ptr, out_ptr),+ 24 => unpack24_32(in_ptr, out_ptr),+ 25 => unpack25_32(in_ptr, out_ptr),+ 26 => unpack26_32(in_ptr, out_ptr),+ 27 => unpack27_32(in_ptr, out_ptr),+ 28 => unpack28_32(in_ptr, out_ptr),+ 29 => unpack29_32(in_ptr, out_ptr),+ 30 => unpack30_32(in_ptr, out_ptr),+ 31 => unpack31_32(in_ptr, out_ptr),+ 32 => unpack32_32(in_ptr, out_ptr),+ _ => unimplemented!(),+ };+ in_ptr+}++unsafe fn nullunpacker32(in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ for _ in 0..32 {+ *out = 0;+ out = out.offset(1);+ }+ in_buf+}++unsafe fn unpack1_32(in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ *out = ((*in_buf) >> 0) & 1;+ out = out.offset(1);+ *out = ((*in_buf) >> 1) & 1;+ out = out.offset(1);+ *out = ((*in_buf) >> 2) & 1;+ out = out.offset(1);+ *out = ((*in_buf) >> 3) & 1;+ out = out.offset(1);+ *out = ((*in_buf) >> 4) & 1;+ out = out.offset(1);+ *out = ((*in_buf) >> 5) & 1;+ out = out.offset(1);+ *out = ((*in_buf) >> 6) & 1;+ out = out.offset(1);+ *out = ((*in_buf) >> 7) & 1;+ out = out.offset(1);+ *out = ((*in_buf) >> 8) & 1;+ out = out.offset(1);+ *out = ((*in_buf) >> 9) & 1;+ out = out.offset(1);+ *out = ((*in_buf) >> 10) & 1;+ out = out.offset(1);+ *out = ((*in_buf) >> 11) & 1;+ out = out.offset(1);+ *out = ((*in_buf) >> 12) & 1;+ out = out.offset(1);+ *out = ((*in_buf) >> 13) & 1;+ out = out.offset(1);+ *out = ((*in_buf) >> 14) & 1;+ out = out.offset(1);+ *out = ((*in_buf) >> 15) & 1;+ out = out.offset(1);+ *out = ((*in_buf) >> 16) & 1;+ out = out.offset(1);+ *out = ((*in_buf) >> 17) & 1;+ out = out.offset(1);+ *out = ((*in_buf) >> 18) & 1;+ out = out.offset(1);+ *out = ((*in_buf) >> 19) & 1;+ out = out.offset(1);+ *out = ((*in_buf) >> 20) & 1;+ out = out.offset(1);+ *out = ((*in_buf) >> 21) & 1;+ out = out.offset(1);+ *out = ((*in_buf) >> 22) & 1;+ out = out.offset(1);+ *out = ((*in_buf) >> 23) & 1;+ out = out.offset(1);+ *out = ((*in_buf) >> 24) & 1;+ out = out.offset(1);+ *out = ((*in_buf) >> 25) & 1;+ out = out.offset(1);+ *out = ((*in_buf) >> 26) & 1;+ out = out.offset(1);+ *out = ((*in_buf) >> 27) & 1;+ out = out.offset(1);+ *out = ((*in_buf) >> 28) & 1;+ out = out.offset(1);+ *out = ((*in_buf) >> 29) & 1;+ out = out.offset(1);+ *out = ((*in_buf) >> 30) & 1;+ out = out.offset(1);+ *out = (*in_buf) >> 31;++ in_buf.offset(1)+}++unsafe fn unpack2_32(mut in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ *out = ((*in_buf) >> 0) % (1u32 << 2);+ out = out.offset(1);+ *out = ((*in_buf) >> 2) % (1u32 << 2);+ out = out.offset(1);+ *out = ((*in_buf) >> 4) % (1u32 << 2);+ out = out.offset(1);+ *out = ((*in_buf) >> 6) % (1u32 << 2);+ out = out.offset(1);+ *out = ((*in_buf) >> 8) % (1u32 << 2);+ out = out.offset(1);+ *out = ((*in_buf) >> 10) % (1u32 << 2);+ out = out.offset(1);+ *out = ((*in_buf) >> 12) % (1u32 << 2);+ out = out.offset(1);+ *out = ((*in_buf) >> 14) % (1u32 << 2);+ out = out.offset(1);+ *out = ((*in_buf) >> 16) % (1u32 << 2);+ out = out.offset(1);+ *out = ((*in_buf) >> 18) % (1u32 << 2);+ out = out.offset(1);+ *out = ((*in_buf) >> 20) % (1u32 << 2);+ out = out.offset(1);+ *out = ((*in_buf) >> 22) % (1u32 << 2);+ out = out.offset(1);+ *out = ((*in_buf) >> 24) % (1u32 << 2);+ out = out.offset(1);+ *out = ((*in_buf) >> 26) % (1u32 << 2);+ out = out.offset(1);+ *out = ((*in_buf) >> 28) % (1u32 << 2);+ out = out.offset(1);+ *out = (*in_buf) >> 30;+ out = out.offset(1);+ in_buf = in_buf.offset(1);+ *out = ((*in_buf) >> 0) % (1u32 << 2);+ out = out.offset(1);+ *out = ((*in_buf) >> 2) % (1u32 << 2);+ out = out.offset(1);+ *out = ((*in_buf) >> 4) % (1u32 << 2);+ out = out.offset(1);+ *out = ((*in_buf) >> 6) % (1u32 << 2);+ out = out.offset(1);+ *out = ((*in_buf) >> 8) % (1u32 << 2);+ out = out.offset(1);+ *out = ((*in_buf) >> 10) % (1u32 << 2);+ out = out.offset(1);+ *out = ((*in_buf) >> 12) % (1u32 << 2);+ out = out.offset(1);+ *out = ((*in_buf) >> 14) % (1u32 << 2);+ out = out.offset(1);+ *out = ((*in_buf) >> 16) % (1u32 << 2);+ out = out.offset(1);+ *out = ((*in_buf) >> 18) % (1u32 << 2);+ out = out.offset(1);+ *out = ((*in_buf) >> 20) % (1u32 << 2);+ out = out.offset(1);+ *out = ((*in_buf) >> 22) % (1u32 << 2);+ out = out.offset(1);+ *out = ((*in_buf) >> 24) % (1u32 << 2);+ out = out.offset(1);+ *out = ((*in_buf) >> 26) % (1u32 << 2);+ out = out.offset(1);+ *out = ((*in_buf) >> 28) % (1u32 << 2);+ out = out.offset(1);+ *out = (*in_buf) >> 30;++ in_buf.offset(1)+}++unsafe fn unpack3_32(mut in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ *out = ((*in_buf) >> 0) % (1u32 << 3);+ out = out.offset(1);+ *out = ((*in_buf) >> 3) % (1u32 << 3);+ out = out.offset(1);+ *out = ((*in_buf) >> 6) % (1u32 << 3);+ out = out.offset(1);+ *out = ((*in_buf) >> 9) % (1u32 << 3);+ out = out.offset(1);+ *out = ((*in_buf) >> 12) % (1u32 << 3);+ out = out.offset(1);+ *out = ((*in_buf) >> 15) % (1u32 << 3);+ out = out.offset(1);+ *out = ((*in_buf) >> 18) % (1u32 << 3);+ out = out.offset(1);+ *out = ((*in_buf) >> 21) % (1u32 << 3);+ out = out.offset(1);+ *out = ((*in_buf) >> 24) % (1u32 << 3);+ out = out.offset(1);+ *out = ((*in_buf) >> 27) % (1u32 << 3);+ out = out.offset(1);+ *out = (*in_buf) >> 30;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 1)) << (3 - 1);+ out = out.offset(1);++ *out = ((*in_buf) >> 1) % (1u32 << 3);+ out = out.offset(1);+ *out = ((*in_buf) >> 4) % (1u32 << 3);+ out = out.offset(1);+ *out = ((*in_buf) >> 7) % (1u32 << 3);+ out = out.offset(1);+ *out = ((*in_buf) >> 10) % (1u32 << 3);+ out = out.offset(1);+ *out = ((*in_buf) >> 13) % (1u32 << 3);+ out = out.offset(1);+ *out = ((*in_buf) >> 16) % (1u32 << 3);+ out = out.offset(1);+ *out = ((*in_buf) >> 19) % (1u32 << 3);+ out = out.offset(1);+ *out = ((*in_buf) >> 22) % (1u32 << 3);+ out = out.offset(1);+ *out = ((*in_buf) >> 25) % (1u32 << 3);+ out = out.offset(1);+ *out = ((*in_buf) >> 28) % (1u32 << 3);+ out = out.offset(1);+ *out = (*in_buf) >> 31;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 2)) << (3 - 2);+ out = out.offset(1);++ *out = ((*in_buf) >> 2) % (1u32 << 3);+ out = out.offset(1);+ *out = ((*in_buf) >> 5) % (1u32 << 3);+ out = out.offset(1);+ *out = ((*in_buf) >> 8) % (1u32 << 3);+ out = out.offset(1);+ *out = ((*in_buf) >> 11) % (1u32 << 3);+ out = out.offset(1);+ *out = ((*in_buf) >> 14) % (1u32 << 3);+ out = out.offset(1);+ *out = ((*in_buf) >> 17) % (1u32 << 3);+ out = out.offset(1);+ *out = ((*in_buf) >> 20) % (1u32 << 3);+ out = out.offset(1);+ *out = ((*in_buf) >> 23) % (1u32 << 3);+ out = out.offset(1);+ *out = ((*in_buf) >> 26) % (1u32 << 3);+ out = out.offset(1);+ *out = (*in_buf) >> 29;++ in_buf.offset(1)+}++unsafe fn unpack4_32(mut in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ *out = ((*in_buf) >> 0) % (1u32 << 4);+ out = out.offset(1);+ *out = ((*in_buf) >> 4) % (1u32 << 4);+ out = out.offset(1);+ *out = ((*in_buf) >> 8) % (1u32 << 4);+ out = out.offset(1);+ *out = ((*in_buf) >> 12) % (1u32 << 4);+ out = out.offset(1);+ *out = ((*in_buf) >> 16) % (1u32 << 4);+ out = out.offset(1);+ *out = ((*in_buf) >> 20) % (1u32 << 4);+ out = out.offset(1);+ *out = ((*in_buf) >> 24) % (1u32 << 4);+ out = out.offset(1);+ *out = ((*in_buf) >> 28) % (1u32 << 4);+ out = out.offset(1);+ in_buf = in_buf.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 4);+ out = out.offset(1);+ *out = ((*in_buf) >> 4) % (1u32 << 4);+ out = out.offset(1);+ *out = ((*in_buf) >> 8) % (1u32 << 4);+ out = out.offset(1);+ *out = ((*in_buf) >> 12) % (1u32 << 4);+ out = out.offset(1);+ *out = ((*in_buf) >> 16) % (1u32 << 4);+ out = out.offset(1);+ *out = ((*in_buf) >> 20) % (1u32 << 4);+ out = out.offset(1);+ *out = ((*in_buf) >> 24) % (1u32 << 4);+ out = out.offset(1);+ *out = ((*in_buf) >> 28) % (1u32 << 4);+ out = out.offset(1);+ in_buf = in_buf.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 4);+ out = out.offset(1);+ *out = ((*in_buf) >> 4) % (1u32 << 4);+ out = out.offset(1);+ *out = ((*in_buf) >> 8) % (1u32 << 4);+ out = out.offset(1);+ *out = ((*in_buf) >> 12) % (1u32 << 4);+ out = out.offset(1);+ *out = ((*in_buf) >> 16) % (1u32 << 4);+ out = out.offset(1);+ *out = ((*in_buf) >> 20) % (1u32 << 4);+ out = out.offset(1);+ *out = ((*in_buf) >> 24) % (1u32 << 4);+ out = out.offset(1);+ *out = ((*in_buf) >> 28) % (1u32 << 4);+ out = out.offset(1);+ in_buf = in_buf.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 4);+ out = out.offset(1);+ *out = ((*in_buf) >> 4) % (1u32 << 4);+ out = out.offset(1);+ *out = ((*in_buf) >> 8) % (1u32 << 4);+ out = out.offset(1);+ *out = ((*in_buf) >> 12) % (1u32 << 4);+ out = out.offset(1);+ *out = ((*in_buf) >> 16) % (1u32 << 4);+ out = out.offset(1);+ *out = ((*in_buf) >> 20) % (1u32 << 4);+ out = out.offset(1);+ *out = ((*in_buf) >> 24) % (1u32 << 4);+ out = out.offset(1);+ *out = ((*in_buf) >> 28) % (1u32 << 4);++ in_buf.offset(1)+}++unsafe fn unpack5_32(mut in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ *out = ((*in_buf) >> 0) % (1u32 << 5);+ out = out.offset(1);+ *out = ((*in_buf) >> 5) % (1u32 << 5);+ out = out.offset(1);+ *out = ((*in_buf) >> 10) % (1u32 << 5);+ out = out.offset(1);+ *out = ((*in_buf) >> 15) % (1u32 << 5);+ out = out.offset(1);+ *out = ((*in_buf) >> 20) % (1u32 << 5);+ out = out.offset(1);+ *out = ((*in_buf) >> 25) % (1u32 << 5);+ out = out.offset(1);+ *out = (*in_buf) >> 30;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 3)) << (5 - 3);+ out = out.offset(1);++ *out = ((*in_buf) >> 3) % (1u32 << 5);+ out = out.offset(1);+ *out = ((*in_buf) >> 8) % (1u32 << 5);+ out = out.offset(1);+ *out = ((*in_buf) >> 13) % (1u32 << 5);+ out = out.offset(1);+ *out = ((*in_buf) >> 18) % (1u32 << 5);+ out = out.offset(1);+ *out = ((*in_buf) >> 23) % (1u32 << 5);+ out = out.offset(1);+ *out = ((*in_buf) >> 28) % (1u32 << 5);+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 1)) << (5 - 1);+ out = out.offset(1);++ *out = ((*in_buf) >> 1) % (1u32 << 5);+ out = out.offset(1);+ *out = ((*in_buf) >> 6) % (1u32 << 5);+ out = out.offset(1);+ *out = ((*in_buf) >> 11) % (1u32 << 5);+ out = out.offset(1);+ *out = ((*in_buf) >> 16) % (1u32 << 5);+ out = out.offset(1);+ *out = ((*in_buf) >> 21) % (1u32 << 5);+ out = out.offset(1);+ *out = ((*in_buf) >> 26) % (1u32 << 5);+ out = out.offset(1);+ *out = (*in_buf) >> 31;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (5 - 4);+ out = out.offset(1);++ *out = ((*in_buf) >> 4) % (1u32 << 5);+ out = out.offset(1);+ *out = ((*in_buf) >> 9) % (1u32 << 5);+ out = out.offset(1);+ *out = ((*in_buf) >> 14) % (1u32 << 5);+ out = out.offset(1);+ *out = ((*in_buf) >> 19) % (1u32 << 5);+ out = out.offset(1);+ *out = ((*in_buf) >> 24) % (1u32 << 5);+ out = out.offset(1);+ *out = (*in_buf) >> 29;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 2)) << (5 - 2);+ out = out.offset(1);++ *out = ((*in_buf) >> 2) % (1u32 << 5);+ out = out.offset(1);+ *out = ((*in_buf) >> 7) % (1u32 << 5);+ out = out.offset(1);+ *out = ((*in_buf) >> 12) % (1u32 << 5);+ out = out.offset(1);+ *out = ((*in_buf) >> 17) % (1u32 << 5);+ out = out.offset(1);+ *out = ((*in_buf) >> 22) % (1u32 << 5);+ out = out.offset(1);+ *out = (*in_buf) >> 27;++ in_buf.offset(1)+}++unsafe fn unpack6_32(mut in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ *out = ((*in_buf) >> 0) % (1u32 << 6);+ out = out.offset(1);+ *out = ((*in_buf) >> 6) % (1u32 << 6);+ out = out.offset(1);+ *out = ((*in_buf) >> 12) % (1u32 << 6);+ out = out.offset(1);+ *out = ((*in_buf) >> 18) % (1u32 << 6);+ out = out.offset(1);+ *out = ((*in_buf) >> 24) % (1u32 << 6);+ out = out.offset(1);+ *out = (*in_buf) >> 30;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (6 - 4);+ out = out.offset(1);++ *out = ((*in_buf) >> 4) % (1u32 << 6);+ out = out.offset(1);+ *out = ((*in_buf) >> 10) % (1u32 << 6);+ out = out.offset(1);+ *out = ((*in_buf) >> 16) % (1u32 << 6);+ out = out.offset(1);+ *out = ((*in_buf) >> 22) % (1u32 << 6);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 2)) << (6 - 2);+ out = out.offset(1);++ *out = ((*in_buf) >> 2) % (1u32 << 6);+ out = out.offset(1);+ *out = ((*in_buf) >> 8) % (1u32 << 6);+ out = out.offset(1);+ *out = ((*in_buf) >> 14) % (1u32 << 6);+ out = out.offset(1);+ *out = ((*in_buf) >> 20) % (1u32 << 6);+ out = out.offset(1);+ *out = (*in_buf) >> 26;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 6);+ out = out.offset(1);+ *out = ((*in_buf) >> 6) % (1u32 << 6);+ out = out.offset(1);+ *out = ((*in_buf) >> 12) % (1u32 << 6);+ out = out.offset(1);+ *out = ((*in_buf) >> 18) % (1u32 << 6);+ out = out.offset(1);+ *out = ((*in_buf) >> 24) % (1u32 << 6);+ out = out.offset(1);+ *out = (*in_buf) >> 30;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (6 - 4);+ out = out.offset(1);++ *out = ((*in_buf) >> 4) % (1u32 << 6);+ out = out.offset(1);+ *out = ((*in_buf) >> 10) % (1u32 << 6);+ out = out.offset(1);+ *out = ((*in_buf) >> 16) % (1u32 << 6);+ out = out.offset(1);+ *out = ((*in_buf) >> 22) % (1u32 << 6);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 2)) << (6 - 2);+ out = out.offset(1);++ *out = ((*in_buf) >> 2) % (1u32 << 6);+ out = out.offset(1);+ *out = ((*in_buf) >> 8) % (1u32 << 6);+ out = out.offset(1);+ *out = ((*in_buf) >> 14) % (1u32 << 6);+ out = out.offset(1);+ *out = ((*in_buf) >> 20) % (1u32 << 6);+ out = out.offset(1);+ *out = (*in_buf) >> 26;++ in_buf.offset(1)+}++unsafe fn unpack7_32(mut in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ *out = ((*in_buf) >> 0) % (1u32 << 7);+ out = out.offset(1);+ *out = ((*in_buf) >> 7) % (1u32 << 7);+ out = out.offset(1);+ *out = ((*in_buf) >> 14) % (1u32 << 7);+ out = out.offset(1);+ *out = ((*in_buf) >> 21) % (1u32 << 7);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 3)) << (7 - 3);+ out = out.offset(1);++ *out = ((*in_buf) >> 3) % (1u32 << 7);+ out = out.offset(1);+ *out = ((*in_buf) >> 10) % (1u32 << 7);+ out = out.offset(1);+ *out = ((*in_buf) >> 17) % (1u32 << 7);+ out = out.offset(1);+ *out = ((*in_buf) >> 24) % (1u32 << 7);+ out = out.offset(1);+ *out = (*in_buf) >> 31;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 6)) << (7 - 6);+ out = out.offset(1);++ *out = ((*in_buf) >> 6) % (1u32 << 7);+ out = out.offset(1);+ *out = ((*in_buf) >> 13) % (1u32 << 7);+ out = out.offset(1);+ *out = ((*in_buf) >> 20) % (1u32 << 7);+ out = out.offset(1);+ *out = (*in_buf) >> 27;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 2)) << (7 - 2);+ out = out.offset(1);++ *out = ((*in_buf) >> 2) % (1u32 << 7);+ out = out.offset(1);+ *out = ((*in_buf) >> 9) % (1u32 << 7);+ out = out.offset(1);+ *out = ((*in_buf) >> 16) % (1u32 << 7);+ out = out.offset(1);+ *out = ((*in_buf) >> 23) % (1u32 << 7);+ out = out.offset(1);+ *out = (*in_buf) >> 30;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 5)) << (7 - 5);+ out = out.offset(1);++ *out = ((*in_buf) >> 5) % (1u32 << 7);+ out = out.offset(1);+ *out = ((*in_buf) >> 12) % (1u32 << 7);+ out = out.offset(1);+ *out = ((*in_buf) >> 19) % (1u32 << 7);+ out = out.offset(1);+ *out = (*in_buf) >> 26;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 1)) << (7 - 1);+ out = out.offset(1);++ *out = ((*in_buf) >> 1) % (1u32 << 7);+ out = out.offset(1);+ *out = ((*in_buf) >> 8) % (1u32 << 7);+ out = out.offset(1);+ *out = ((*in_buf) >> 15) % (1u32 << 7);+ out = out.offset(1);+ *out = ((*in_buf) >> 22) % (1u32 << 7);+ out = out.offset(1);+ *out = (*in_buf) >> 29;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (7 - 4);+ out = out.offset(1);++ *out = ((*in_buf) >> 4) % (1u32 << 7);+ out = out.offset(1);+ *out = ((*in_buf) >> 11) % (1u32 << 7);+ out = out.offset(1);+ *out = ((*in_buf) >> 18) % (1u32 << 7);+ out = out.offset(1);+ *out = (*in_buf) >> 25;++ in_buf.offset(1)+}++unsafe fn unpack8_32(mut in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ *out = ((*in_buf) >> 0) % (1u32 << 8);+ out = out.offset(1);+ *out = ((*in_buf) >> 8) % (1u32 << 8);+ out = out.offset(1);+ *out = ((*in_buf) >> 16) % (1u32 << 8);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ out = out.offset(1);+ in_buf = in_buf.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 8);+ out = out.offset(1);+ *out = ((*in_buf) >> 8) % (1u32 << 8);+ out = out.offset(1);+ *out = ((*in_buf) >> 16) % (1u32 << 8);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ out = out.offset(1);+ in_buf = in_buf.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 8);+ out = out.offset(1);+ *out = ((*in_buf) >> 8) % (1u32 << 8);+ out = out.offset(1);+ *out = ((*in_buf) >> 16) % (1u32 << 8);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ out = out.offset(1);+ in_buf = in_buf.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 8);+ out = out.offset(1);+ *out = ((*in_buf) >> 8) % (1u32 << 8);+ out = out.offset(1);+ *out = ((*in_buf) >> 16) % (1u32 << 8);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ out = out.offset(1);+ in_buf = in_buf.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 8);+ out = out.offset(1);+ *out = ((*in_buf) >> 8) % (1u32 << 8);+ out = out.offset(1);+ *out = ((*in_buf) >> 16) % (1u32 << 8);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ out = out.offset(1);+ in_buf = in_buf.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 8);+ out = out.offset(1);+ *out = ((*in_buf) >> 8) % (1u32 << 8);+ out = out.offset(1);+ *out = ((*in_buf) >> 16) % (1u32 << 8);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ out = out.offset(1);+ in_buf = in_buf.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 8);+ out = out.offset(1);+ *out = ((*in_buf) >> 8) % (1u32 << 8);+ out = out.offset(1);+ *out = ((*in_buf) >> 16) % (1u32 << 8);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ out = out.offset(1);+ in_buf = in_buf.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 8);+ out = out.offset(1);+ *out = ((*in_buf) >> 8) % (1u32 << 8);+ out = out.offset(1);+ *out = ((*in_buf) >> 16) % (1u32 << 8);+ out = out.offset(1);+ *out = (*in_buf) >> 24;++ in_buf.offset(1)+}++unsafe fn unpack9_32(mut in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ *out = ((*in_buf) >> 0) % (1u32 << 9);+ out = out.offset(1);+ *out = ((*in_buf) >> 9) % (1u32 << 9);+ out = out.offset(1);+ *out = ((*in_buf) >> 18) % (1u32 << 9);+ out = out.offset(1);+ *out = (*in_buf) >> 27;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (9 - 4);+ out = out.offset(1);++ *out = ((*in_buf) >> 4) % (1u32 << 9);+ out = out.offset(1);+ *out = ((*in_buf) >> 13) % (1u32 << 9);+ out = out.offset(1);+ *out = ((*in_buf) >> 22) % (1u32 << 9);+ out = out.offset(1);+ *out = (*in_buf) >> 31;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (9 - 8);+ out = out.offset(1);++ *out = ((*in_buf) >> 8) % (1u32 << 9);+ out = out.offset(1);+ *out = ((*in_buf) >> 17) % (1u32 << 9);+ out = out.offset(1);+ *out = (*in_buf) >> 26;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 3)) << (9 - 3);+ out = out.offset(1);++ *out = ((*in_buf) >> 3) % (1u32 << 9);+ out = out.offset(1);+ *out = ((*in_buf) >> 12) % (1u32 << 9);+ out = out.offset(1);+ *out = ((*in_buf) >> 21) % (1u32 << 9);+ out = out.offset(1);+ *out = (*in_buf) >> 30;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 7)) << (9 - 7);+ out = out.offset(1);++ *out = ((*in_buf) >> 7) % (1u32 << 9);+ out = out.offset(1);+ *out = ((*in_buf) >> 16) % (1u32 << 9);+ out = out.offset(1);+ *out = (*in_buf) >> 25;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 2)) << (9 - 2);+ out = out.offset(1);++ *out = ((*in_buf) >> 2) % (1u32 << 9);+ out = out.offset(1);+ *out = ((*in_buf) >> 11) % (1u32 << 9);+ out = out.offset(1);+ *out = ((*in_buf) >> 20) % (1u32 << 9);+ out = out.offset(1);+ *out = (*in_buf) >> 29;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 6)) << (9 - 6);+ out = out.offset(1);++ *out = ((*in_buf) >> 6) % (1u32 << 9);+ out = out.offset(1);+ *out = ((*in_buf) >> 15) % (1u32 << 9);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 1)) << (9 - 1);+ out = out.offset(1);++ *out = ((*in_buf) >> 1) % (1u32 << 9);+ out = out.offset(1);+ *out = ((*in_buf) >> 10) % (1u32 << 9);+ out = out.offset(1);+ *out = ((*in_buf) >> 19) % (1u32 << 9);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 5)) << (9 - 5);+ out = out.offset(1);++ *out = ((*in_buf) >> 5) % (1u32 << 9);+ out = out.offset(1);+ *out = ((*in_buf) >> 14) % (1u32 << 9);+ out = out.offset(1);+ *out = (*in_buf) >> 23;++ in_buf.offset(1)+}++unsafe fn unpack10_32(mut in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ *out = ((*in_buf) >> 0) % (1u32 << 10);+ out = out.offset(1);+ *out = ((*in_buf) >> 10) % (1u32 << 10);+ out = out.offset(1);+ *out = ((*in_buf) >> 20) % (1u32 << 10);+ out = out.offset(1);+ *out = (*in_buf) >> 30;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (10 - 8);+ out = out.offset(1);++ *out = ((*in_buf) >> 8) % (1u32 << 10);+ out = out.offset(1);+ *out = ((*in_buf) >> 18) % (1u32 << 10);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 6)) << (10 - 6);+ out = out.offset(1);++ *out = ((*in_buf) >> 6) % (1u32 << 10);+ out = out.offset(1);+ *out = ((*in_buf) >> 16) % (1u32 << 10);+ out = out.offset(1);+ *out = (*in_buf) >> 26;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (10 - 4);+ out = out.offset(1);++ *out = ((*in_buf) >> 4) % (1u32 << 10);+ out = out.offset(1);+ *out = ((*in_buf) >> 14) % (1u32 << 10);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 2)) << (10 - 2);+ out = out.offset(1);++ *out = ((*in_buf) >> 2) % (1u32 << 10);+ out = out.offset(1);+ *out = ((*in_buf) >> 12) % (1u32 << 10);+ out = out.offset(1);+ *out = (*in_buf) >> 22;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 10);+ out = out.offset(1);+ *out = ((*in_buf) >> 10) % (1u32 << 10);+ out = out.offset(1);+ *out = ((*in_buf) >> 20) % (1u32 << 10);+ out = out.offset(1);+ *out = (*in_buf) >> 30;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (10 - 8);+ out = out.offset(1);++ *out = ((*in_buf) >> 8) % (1u32 << 10);+ out = out.offset(1);+ *out = ((*in_buf) >> 18) % (1u32 << 10);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 6)) << (10 - 6);+ out = out.offset(1);++ *out = ((*in_buf) >> 6) % (1u32 << 10);+ out = out.offset(1);+ *out = ((*in_buf) >> 16) % (1u32 << 10);+ out = out.offset(1);+ *out = (*in_buf) >> 26;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (10 - 4);+ out = out.offset(1);++ *out = ((*in_buf) >> 4) % (1u32 << 10);+ out = out.offset(1);+ *out = ((*in_buf) >> 14) % (1u32 << 10);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 2)) << (10 - 2);+ out = out.offset(1);++ *out = ((*in_buf) >> 2) % (1u32 << 10);+ out = out.offset(1);+ *out = ((*in_buf) >> 12) % (1u32 << 10);+ out = out.offset(1);+ *out = (*in_buf) >> 22;++ in_buf.offset(1)+}++unsafe fn unpack11_32(mut in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ *out = ((*in_buf) >> 0) % (1u32 << 11);+ out = out.offset(1);+ *out = ((*in_buf) >> 11) % (1u32 << 11);+ out = out.offset(1);+ *out = (*in_buf) >> 22;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 1)) << (11 - 1);+ out = out.offset(1);++ *out = ((*in_buf) >> 1) % (1u32 << 11);+ out = out.offset(1);+ *out = ((*in_buf) >> 12) % (1u32 << 11);+ out = out.offset(1);+ *out = (*in_buf) >> 23;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 2)) << (11 - 2);+ out = out.offset(1);++ *out = ((*in_buf) >> 2) % (1u32 << 11);+ out = out.offset(1);+ *out = ((*in_buf) >> 13) % (1u32 << 11);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 3)) << (11 - 3);+ out = out.offset(1);++ *out = ((*in_buf) >> 3) % (1u32 << 11);+ out = out.offset(1);+ *out = ((*in_buf) >> 14) % (1u32 << 11);+ out = out.offset(1);+ *out = (*in_buf) >> 25;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (11 - 4);+ out = out.offset(1);++ *out = ((*in_buf) >> 4) % (1u32 << 11);+ out = out.offset(1);+ *out = ((*in_buf) >> 15) % (1u32 << 11);+ out = out.offset(1);+ *out = (*in_buf) >> 26;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 5)) << (11 - 5);+ out = out.offset(1);++ *out = ((*in_buf) >> 5) % (1u32 << 11);+ out = out.offset(1);+ *out = ((*in_buf) >> 16) % (1u32 << 11);+ out = out.offset(1);+ *out = (*in_buf) >> 27;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 6)) << (11 - 6);+ out = out.offset(1);++ *out = ((*in_buf) >> 6) % (1u32 << 11);+ out = out.offset(1);+ *out = ((*in_buf) >> 17) % (1u32 << 11);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 7)) << (11 - 7);+ out = out.offset(1);++ *out = ((*in_buf) >> 7) % (1u32 << 11);+ out = out.offset(1);+ *out = ((*in_buf) >> 18) % (1u32 << 11);+ out = out.offset(1);+ *out = (*in_buf) >> 29;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (11 - 8);+ out = out.offset(1);++ *out = ((*in_buf) >> 8) % (1u32 << 11);+ out = out.offset(1);+ *out = ((*in_buf) >> 19) % (1u32 << 11);+ out = out.offset(1);+ *out = (*in_buf) >> 30;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 9)) << (11 - 9);+ out = out.offset(1);++ *out = ((*in_buf) >> 9) % (1u32 << 11);+ out = out.offset(1);+ *out = ((*in_buf) >> 20) % (1u32 << 11);+ out = out.offset(1);+ *out = (*in_buf) >> 31;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 10)) << (11 - 10);+ out = out.offset(1);++ *out = ((*in_buf) >> 10) % (1u32 << 11);+ out = out.offset(1);+ *out = (*in_buf) >> 21;++ in_buf.offset(1)+}++unsafe fn unpack12_32(mut in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ *out = ((*in_buf) >> 0) % (1u32 << 12);+ out = out.offset(1);+ *out = ((*in_buf) >> 12) % (1u32 << 12);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (12 - 4);+ out = out.offset(1);++ *out = ((*in_buf) >> 4) % (1u32 << 12);+ out = out.offset(1);+ *out = ((*in_buf) >> 16) % (1u32 << 12);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (12 - 8);+ out = out.offset(1);++ *out = ((*in_buf) >> 8) % (1u32 << 12);+ out = out.offset(1);+ *out = (*in_buf) >> 20;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 12);+ out = out.offset(1);+ *out = ((*in_buf) >> 12) % (1u32 << 12);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (12 - 4);+ out = out.offset(1);++ *out = ((*in_buf) >> 4) % (1u32 << 12);+ out = out.offset(1);+ *out = ((*in_buf) >> 16) % (1u32 << 12);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (12 - 8);+ out = out.offset(1);++ *out = ((*in_buf) >> 8) % (1u32 << 12);+ out = out.offset(1);+ *out = (*in_buf) >> 20;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 12);+ out = out.offset(1);+ *out = ((*in_buf) >> 12) % (1u32 << 12);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (12 - 4);+ out = out.offset(1);++ *out = ((*in_buf) >> 4) % (1u32 << 12);+ out = out.offset(1);+ *out = ((*in_buf) >> 16) % (1u32 << 12);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (12 - 8);+ out = out.offset(1);++ *out = ((*in_buf) >> 8) % (1u32 << 12);+ out = out.offset(1);+ *out = (*in_buf) >> 20;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 12);+ out = out.offset(1);+ *out = ((*in_buf) >> 12) % (1u32 << 12);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (12 - 4);+ out = out.offset(1);++ *out = ((*in_buf) >> 4) % (1u32 << 12);+ out = out.offset(1);+ *out = ((*in_buf) >> 16) % (1u32 << 12);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (12 - 8);+ out = out.offset(1);++ *out = ((*in_buf) >> 8) % (1u32 << 12);+ out = out.offset(1);+ *out = (*in_buf) >> 20;++ in_buf.offset(1)+}++unsafe fn unpack13_32(mut in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ *out = ((*in_buf) >> 0) % (1u32 << 13);+ out = out.offset(1);+ *out = ((*in_buf) >> 13) % (1u32 << 13);+ out = out.offset(1);+ *out = (*in_buf) >> 26;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 7)) << (13 - 7);+ out = out.offset(1);++ *out = ((*in_buf) >> 7) % (1u32 << 13);+ out = out.offset(1);+ *out = (*in_buf) >> 20;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 1)) << (13 - 1);+ out = out.offset(1);++ *out = ((*in_buf) >> 1) % (1u32 << 13);+ out = out.offset(1);+ *out = ((*in_buf) >> 14) % (1u32 << 13);+ out = out.offset(1);+ *out = (*in_buf) >> 27;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (13 - 8);+ out = out.offset(1);++ *out = ((*in_buf) >> 8) % (1u32 << 13);+ out = out.offset(1);+ *out = (*in_buf) >> 21;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 2)) << (13 - 2);+ out = out.offset(1);++ *out = ((*in_buf) >> 2) % (1u32 << 13);+ out = out.offset(1);+ *out = ((*in_buf) >> 15) % (1u32 << 13);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 9)) << (13 - 9);+ out = out.offset(1);++ *out = ((*in_buf) >> 9) % (1u32 << 13);+ out = out.offset(1);+ *out = (*in_buf) >> 22;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 3)) << (13 - 3);+ out = out.offset(1);++ *out = ((*in_buf) >> 3) % (1u32 << 13);+ out = out.offset(1);+ *out = ((*in_buf) >> 16) % (1u32 << 13);+ out = out.offset(1);+ *out = (*in_buf) >> 29;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 10)) << (13 - 10);+ out = out.offset(1);++ *out = ((*in_buf) >> 10) % (1u32 << 13);+ out = out.offset(1);+ *out = (*in_buf) >> 23;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (13 - 4);+ out = out.offset(1);++ *out = ((*in_buf) >> 4) % (1u32 << 13);+ out = out.offset(1);+ *out = ((*in_buf) >> 17) % (1u32 << 13);+ out = out.offset(1);+ *out = (*in_buf) >> 30;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 11)) << (13 - 11);+ out = out.offset(1);++ *out = ((*in_buf) >> 11) % (1u32 << 13);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 5)) << (13 - 5);+ out = out.offset(1);++ *out = ((*in_buf) >> 5) % (1u32 << 13);+ out = out.offset(1);+ *out = ((*in_buf) >> 18) % (1u32 << 13);+ out = out.offset(1);+ *out = (*in_buf) >> 31;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 12)) << (13 - 12);+ out = out.offset(1);++ *out = ((*in_buf) >> 12) % (1u32 << 13);+ out = out.offset(1);+ *out = (*in_buf) >> 25;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 6)) << (13 - 6);+ out = out.offset(1);++ *out = ((*in_buf) >> 6) % (1u32 << 13);+ out = out.offset(1);+ *out = (*in_buf) >> 19;++ in_buf.offset(1)+}++unsafe fn unpack14_32(mut in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ *out = ((*in_buf) >> 0) % (1u32 << 14);+ out = out.offset(1);+ *out = ((*in_buf) >> 14) % (1u32 << 14);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 10)) << (14 - 10);+ out = out.offset(1);++ *out = ((*in_buf) >> 10) % (1u32 << 14);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 6)) << (14 - 6);+ out = out.offset(1);++ *out = ((*in_buf) >> 6) % (1u32 << 14);+ out = out.offset(1);+ *out = (*in_buf) >> 20;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 2)) << (14 - 2);+ out = out.offset(1);++ *out = ((*in_buf) >> 2) % (1u32 << 14);+ out = out.offset(1);+ *out = ((*in_buf) >> 16) % (1u32 << 14);+ out = out.offset(1);+ *out = (*in_buf) >> 30;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 12)) << (14 - 12);+ out = out.offset(1);++ *out = ((*in_buf) >> 12) % (1u32 << 14);+ out = out.offset(1);+ *out = (*in_buf) >> 26;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (14 - 8);+ out = out.offset(1);++ *out = ((*in_buf) >> 8) % (1u32 << 14);+ out = out.offset(1);+ *out = (*in_buf) >> 22;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (14 - 4);+ out = out.offset(1);++ *out = ((*in_buf) >> 4) % (1u32 << 14);+ out = out.offset(1);+ *out = (*in_buf) >> 18;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 14);+ out = out.offset(1);+ *out = ((*in_buf) >> 14) % (1u32 << 14);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 10)) << (14 - 10);+ out = out.offset(1);++ *out = ((*in_buf) >> 10) % (1u32 << 14);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 6)) << (14 - 6);+ out = out.offset(1);++ *out = ((*in_buf) >> 6) % (1u32 << 14);+ out = out.offset(1);+ *out = (*in_buf) >> 20;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 2)) << (14 - 2);+ out = out.offset(1);++ *out = ((*in_buf) >> 2) % (1u32 << 14);+ out = out.offset(1);+ *out = ((*in_buf) >> 16) % (1u32 << 14);+ out = out.offset(1);+ *out = (*in_buf) >> 30;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 12)) << (14 - 12);+ out = out.offset(1);++ *out = ((*in_buf) >> 12) % (1u32 << 14);+ out = out.offset(1);+ *out = (*in_buf) >> 26;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (14 - 8);+ out = out.offset(1);++ *out = ((*in_buf) >> 8) % (1u32 << 14);+ out = out.offset(1);+ *out = (*in_buf) >> 22;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (14 - 4);+ out = out.offset(1);++ *out = ((*in_buf) >> 4) % (1u32 << 14);+ out = out.offset(1);+ *out = (*in_buf) >> 18;++ in_buf.offset(1)+}++unsafe fn unpack15_32(mut in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ *out = ((*in_buf) >> 0) % (1u32 << 15);+ out = out.offset(1);+ *out = ((*in_buf) >> 15) % (1u32 << 15);+ out = out.offset(1);+ *out = (*in_buf) >> 30;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 13)) << (15 - 13);+ out = out.offset(1);++ *out = ((*in_buf) >> 13) % (1u32 << 15);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 11)) << (15 - 11);+ out = out.offset(1);++ *out = ((*in_buf) >> 11) % (1u32 << 15);+ out = out.offset(1);+ *out = (*in_buf) >> 26;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 9)) << (15 - 9);+ out = out.offset(1);++ *out = ((*in_buf) >> 9) % (1u32 << 15);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 7)) << (15 - 7);+ out = out.offset(1);++ *out = ((*in_buf) >> 7) % (1u32 << 15);+ out = out.offset(1);+ *out = (*in_buf) >> 22;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 5)) << (15 - 5);+ out = out.offset(1);++ *out = ((*in_buf) >> 5) % (1u32 << 15);+ out = out.offset(1);+ *out = (*in_buf) >> 20;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 3)) << (15 - 3);+ out = out.offset(1);++ *out = ((*in_buf) >> 3) % (1u32 << 15);+ out = out.offset(1);+ *out = (*in_buf) >> 18;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 1)) << (15 - 1);+ out = out.offset(1);++ *out = ((*in_buf) >> 1) % (1u32 << 15);+ out = out.offset(1);+ *out = ((*in_buf) >> 16) % (1u32 << 15);+ out = out.offset(1);+ *out = (*in_buf) >> 31;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 14)) << (15 - 14);+ out = out.offset(1);++ *out = ((*in_buf) >> 14) % (1u32 << 15);+ out = out.offset(1);+ *out = (*in_buf) >> 29;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 12)) << (15 - 12);+ out = out.offset(1);++ *out = ((*in_buf) >> 12) % (1u32 << 15);+ out = out.offset(1);+ *out = (*in_buf) >> 27;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 10)) << (15 - 10);+ out = out.offset(1);++ *out = ((*in_buf) >> 10) % (1u32 << 15);+ out = out.offset(1);+ *out = (*in_buf) >> 25;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (15 - 8);+ out = out.offset(1);++ *out = ((*in_buf) >> 8) % (1u32 << 15);+ out = out.offset(1);+ *out = (*in_buf) >> 23;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 6)) << (15 - 6);+ out = out.offset(1);++ *out = ((*in_buf) >> 6) % (1u32 << 15);+ out = out.offset(1);+ *out = (*in_buf) >> 21;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (15 - 4);+ out = out.offset(1);++ *out = ((*in_buf) >> 4) % (1u32 << 15);+ out = out.offset(1);+ *out = (*in_buf) >> 19;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 2)) << (15 - 2);+ out = out.offset(1);++ *out = ((*in_buf) >> 2) % (1u32 << 15);+ out = out.offset(1);+ *out = (*in_buf) >> 17;++ in_buf.offset(1)+}++unsafe fn unpack16_32(mut in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ *out = ((*in_buf) >> 0) % (1u32 << 16);+ out = out.offset(1);+ *out = (*in_buf) >> 16;+ out = out.offset(1);+ in_buf = in_buf.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 16);+ out = out.offset(1);+ *out = (*in_buf) >> 16;+ out = out.offset(1);+ in_buf = in_buf.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 16);+ out = out.offset(1);+ *out = (*in_buf) >> 16;+ out = out.offset(1);+ in_buf = in_buf.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 16);+ out = out.offset(1);+ *out = (*in_buf) >> 16;+ out = out.offset(1);+ in_buf = in_buf.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 16);+ out = out.offset(1);+ *out = (*in_buf) >> 16;+ out = out.offset(1);+ in_buf = in_buf.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 16);+ out = out.offset(1);+ *out = (*in_buf) >> 16;+ out = out.offset(1);+ in_buf = in_buf.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 16);+ out = out.offset(1);+ *out = (*in_buf) >> 16;+ out = out.offset(1);+ in_buf = in_buf.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 16);+ out = out.offset(1);+ *out = (*in_buf) >> 16;+ out = out.offset(1);+ in_buf = in_buf.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 16);+ out = out.offset(1);+ *out = (*in_buf) >> 16;+ out = out.offset(1);+ in_buf = in_buf.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 16);+ out = out.offset(1);+ *out = (*in_buf) >> 16;+ out = out.offset(1);+ in_buf = in_buf.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 16);+ out = out.offset(1);+ *out = (*in_buf) >> 16;+ out = out.offset(1);+ in_buf = in_buf.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 16);+ out = out.offset(1);+ *out = (*in_buf) >> 16;+ out = out.offset(1);+ in_buf = in_buf.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 16);+ out = out.offset(1);+ *out = (*in_buf) >> 16;+ out = out.offset(1);+ in_buf = in_buf.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 16);+ out = out.offset(1);+ *out = (*in_buf) >> 16;+ out = out.offset(1);+ in_buf = in_buf.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 16);+ out = out.offset(1);+ *out = (*in_buf) >> 16;+ out = out.offset(1);+ in_buf = in_buf.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 16);+ out = out.offset(1);+ *out = (*in_buf) >> 16;++ in_buf.offset(1)+}++unsafe fn unpack17_32(mut in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ *out = ((*in_buf) >> 0) % (1u32 << 17);+ out = out.offset(1);+ *out = (*in_buf) >> 17;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 2)) << (17 - 2);+ out = out.offset(1);++ *out = ((*in_buf) >> 2) % (1u32 << 17);+ out = out.offset(1);+ *out = (*in_buf) >> 19;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (17 - 4);+ out = out.offset(1);++ *out = ((*in_buf) >> 4) % (1u32 << 17);+ out = out.offset(1);+ *out = (*in_buf) >> 21;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 6)) << (17 - 6);+ out = out.offset(1);++ *out = ((*in_buf) >> 6) % (1u32 << 17);+ out = out.offset(1);+ *out = (*in_buf) >> 23;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (17 - 8);+ out = out.offset(1);++ *out = ((*in_buf) >> 8) % (1u32 << 17);+ out = out.offset(1);+ *out = (*in_buf) >> 25;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 10)) << (17 - 10);+ out = out.offset(1);++ *out = ((*in_buf) >> 10) % (1u32 << 17);+ out = out.offset(1);+ *out = (*in_buf) >> 27;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 12)) << (17 - 12);+ out = out.offset(1);++ *out = ((*in_buf) >> 12) % (1u32 << 17);+ out = out.offset(1);+ *out = (*in_buf) >> 29;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 14)) << (17 - 14);+ out = out.offset(1);++ *out = ((*in_buf) >> 14) % (1u32 << 17);+ out = out.offset(1);+ *out = (*in_buf) >> 31;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 16)) << (17 - 16);+ out = out.offset(1);++ *out = (*in_buf) >> 16;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 1)) << (17 - 1);+ out = out.offset(1);++ *out = ((*in_buf) >> 1) % (1u32 << 17);+ out = out.offset(1);+ *out = (*in_buf) >> 18;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 3)) << (17 - 3);+ out = out.offset(1);++ *out = ((*in_buf) >> 3) % (1u32 << 17);+ out = out.offset(1);+ *out = (*in_buf) >> 20;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 5)) << (17 - 5);+ out = out.offset(1);++ *out = ((*in_buf) >> 5) % (1u32 << 17);+ out = out.offset(1);+ *out = (*in_buf) >> 22;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 7)) << (17 - 7);+ out = out.offset(1);++ *out = ((*in_buf) >> 7) % (1u32 << 17);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 9)) << (17 - 9);+ out = out.offset(1);++ *out = ((*in_buf) >> 9) % (1u32 << 17);+ out = out.offset(1);+ *out = (*in_buf) >> 26;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 11)) << (17 - 11);+ out = out.offset(1);++ *out = ((*in_buf) >> 11) % (1u32 << 17);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 13)) << (17 - 13);+ out = out.offset(1);++ *out = ((*in_buf) >> 13) % (1u32 << 17);+ out = out.offset(1);+ *out = (*in_buf) >> 30;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 15)) << (17 - 15);+ out = out.offset(1);++ *out = (*in_buf) >> 15;++ in_buf.offset(1)+}++unsafe fn unpack18_32(mut in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ *out = ((*in_buf) >> 0) % (1u32 << 18);+ out = out.offset(1);+ *out = (*in_buf) >> 18;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (18 - 4);+ out = out.offset(1);++ *out = ((*in_buf) >> 4) % (1u32 << 18);+ out = out.offset(1);+ *out = (*in_buf) >> 22;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (18 - 8);+ out = out.offset(1);++ *out = ((*in_buf) >> 8) % (1u32 << 18);+ out = out.offset(1);+ *out = (*in_buf) >> 26;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 12)) << (18 - 12);+ out = out.offset(1);++ *out = ((*in_buf) >> 12) % (1u32 << 18);+ out = out.offset(1);+ *out = (*in_buf) >> 30;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 16)) << (18 - 16);+ out = out.offset(1);++ *out = (*in_buf) >> 16;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 2)) << (18 - 2);+ out = out.offset(1);++ *out = ((*in_buf) >> 2) % (1u32 << 18);+ out = out.offset(1);+ *out = (*in_buf) >> 20;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 6)) << (18 - 6);+ out = out.offset(1);++ *out = ((*in_buf) >> 6) % (1u32 << 18);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 10)) << (18 - 10);+ out = out.offset(1);++ *out = ((*in_buf) >> 10) % (1u32 << 18);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 14)) << (18 - 14);+ out = out.offset(1);++ *out = (*in_buf) >> 14;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 18);+ out = out.offset(1);+ *out = (*in_buf) >> 18;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (18 - 4);+ out = out.offset(1);++ *out = ((*in_buf) >> 4) % (1u32 << 18);+ out = out.offset(1);+ *out = (*in_buf) >> 22;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (18 - 8);+ out = out.offset(1);++ *out = ((*in_buf) >> 8) % (1u32 << 18);+ out = out.offset(1);+ *out = (*in_buf) >> 26;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 12)) << (18 - 12);+ out = out.offset(1);++ *out = ((*in_buf) >> 12) % (1u32 << 18);+ out = out.offset(1);+ *out = (*in_buf) >> 30;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 16)) << (18 - 16);+ out = out.offset(1);++ *out = (*in_buf) >> 16;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 2)) << (18 - 2);+ out = out.offset(1);++ *out = ((*in_buf) >> 2) % (1u32 << 18);+ out = out.offset(1);+ *out = (*in_buf) >> 20;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 6)) << (18 - 6);+ out = out.offset(1);++ *out = ((*in_buf) >> 6) % (1u32 << 18);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 10)) << (18 - 10);+ out = out.offset(1);++ *out = ((*in_buf) >> 10) % (1u32 << 18);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 14)) << (18 - 14);+ out = out.offset(1);++ *out = (*in_buf) >> 14;++ in_buf.offset(1)+}++unsafe fn unpack19_32(mut in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ *out = ((*in_buf) >> 0) % (1u32 << 19);+ out = out.offset(1);+ *out = (*in_buf) >> 19;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 6)) << (19 - 6);+ out = out.offset(1);++ *out = ((*in_buf) >> 6) % (1u32 << 19);+ out = out.offset(1);+ *out = (*in_buf) >> 25;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 12)) << (19 - 12);+ out = out.offset(1);++ *out = ((*in_buf) >> 12) % (1u32 << 19);+ out = out.offset(1);+ *out = (*in_buf) >> 31;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 18)) << (19 - 18);+ out = out.offset(1);++ *out = (*in_buf) >> 18;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 5)) << (19 - 5);+ out = out.offset(1);++ *out = ((*in_buf) >> 5) % (1u32 << 19);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 11)) << (19 - 11);+ out = out.offset(1);++ *out = ((*in_buf) >> 11) % (1u32 << 19);+ out = out.offset(1);+ *out = (*in_buf) >> 30;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 17)) << (19 - 17);+ out = out.offset(1);++ *out = (*in_buf) >> 17;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (19 - 4);+ out = out.offset(1);++ *out = ((*in_buf) >> 4) % (1u32 << 19);+ out = out.offset(1);+ *out = (*in_buf) >> 23;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 10)) << (19 - 10);+ out = out.offset(1);++ *out = ((*in_buf) >> 10) % (1u32 << 19);+ out = out.offset(1);+ *out = (*in_buf) >> 29;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 16)) << (19 - 16);+ out = out.offset(1);++ *out = (*in_buf) >> 16;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 3)) << (19 - 3);+ out = out.offset(1);++ *out = ((*in_buf) >> 3) % (1u32 << 19);+ out = out.offset(1);+ *out = (*in_buf) >> 22;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 9)) << (19 - 9);+ out = out.offset(1);++ *out = ((*in_buf) >> 9) % (1u32 << 19);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 15)) << (19 - 15);+ out = out.offset(1);++ *out = (*in_buf) >> 15;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 2)) << (19 - 2);+ out = out.offset(1);++ *out = ((*in_buf) >> 2) % (1u32 << 19);+ out = out.offset(1);+ *out = (*in_buf) >> 21;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (19 - 8);+ out = out.offset(1);++ *out = ((*in_buf) >> 8) % (1u32 << 19);+ out = out.offset(1);+ *out = (*in_buf) >> 27;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 14)) << (19 - 14);+ out = out.offset(1);++ *out = (*in_buf) >> 14;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 1)) << (19 - 1);+ out = out.offset(1);++ *out = ((*in_buf) >> 1) % (1u32 << 19);+ out = out.offset(1);+ *out = (*in_buf) >> 20;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 7)) << (19 - 7);+ out = out.offset(1);++ *out = ((*in_buf) >> 7) % (1u32 << 19);+ out = out.offset(1);+ *out = (*in_buf) >> 26;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 13)) << (19 - 13);+ out = out.offset(1);++ *out = (*in_buf) >> 13;++ in_buf.offset(1)+}++unsafe fn unpack20_32(mut in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ *out = ((*in_buf) >> 0) % (1u32 << 20);+ out = out.offset(1);+ *out = (*in_buf) >> 20;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (20 - 8);+ out = out.offset(1);++ *out = ((*in_buf) >> 8) % (1u32 << 20);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 16)) << (20 - 16);+ out = out.offset(1);++ *out = (*in_buf) >> 16;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (20 - 4);+ out = out.offset(1);++ *out = ((*in_buf) >> 4) % (1u32 << 20);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 12)) << (20 - 12);+ out = out.offset(1);++ *out = (*in_buf) >> 12;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 20);+ out = out.offset(1);+ *out = (*in_buf) >> 20;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (20 - 8);+ out = out.offset(1);++ *out = ((*in_buf) >> 8) % (1u32 << 20);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 16)) << (20 - 16);+ out = out.offset(1);++ *out = (*in_buf) >> 16;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (20 - 4);+ out = out.offset(1);++ *out = ((*in_buf) >> 4) % (1u32 << 20);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 12)) << (20 - 12);+ out = out.offset(1);++ *out = (*in_buf) >> 12;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 20);+ out = out.offset(1);+ *out = (*in_buf) >> 20;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (20 - 8);+ out = out.offset(1);++ *out = ((*in_buf) >> 8) % (1u32 << 20);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 16)) << (20 - 16);+ out = out.offset(1);++ *out = (*in_buf) >> 16;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (20 - 4);+ out = out.offset(1);++ *out = ((*in_buf) >> 4) % (1u32 << 20);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 12)) << (20 - 12);+ out = out.offset(1);++ *out = (*in_buf) >> 12;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 20);+ out = out.offset(1);+ *out = (*in_buf) >> 20;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (20 - 8);+ out = out.offset(1);++ *out = ((*in_buf) >> 8) % (1u32 << 20);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 16)) << (20 - 16);+ out = out.offset(1);++ *out = (*in_buf) >> 16;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (20 - 4);+ out = out.offset(1);++ *out = ((*in_buf) >> 4) % (1u32 << 20);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 12)) << (20 - 12);+ out = out.offset(1);++ *out = (*in_buf) >> 12;++ in_buf.offset(1)+}++unsafe fn unpack21_32(mut in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ *out = ((*in_buf) >> 0) % (1u32 << 21);+ out = out.offset(1);+ *out = (*in_buf) >> 21;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 10)) << (21 - 10);+ out = out.offset(1);++ *out = ((*in_buf) >> 10) % (1u32 << 21);+ out = out.offset(1);+ *out = (*in_buf) >> 31;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 20)) << (21 - 20);+ out = out.offset(1);++ *out = (*in_buf) >> 20;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 9)) << (21 - 9);+ out = out.offset(1);++ *out = ((*in_buf) >> 9) % (1u32 << 21);+ out = out.offset(1);+ *out = (*in_buf) >> 30;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 19)) << (21 - 19);+ out = out.offset(1);++ *out = (*in_buf) >> 19;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (21 - 8);+ out = out.offset(1);++ *out = ((*in_buf) >> 8) % (1u32 << 21);+ out = out.offset(1);+ *out = (*in_buf) >> 29;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 18)) << (21 - 18);+ out = out.offset(1);++ *out = (*in_buf) >> 18;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 7)) << (21 - 7);+ out = out.offset(1);++ *out = ((*in_buf) >> 7) % (1u32 << 21);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 17)) << (21 - 17);+ out = out.offset(1);++ *out = (*in_buf) >> 17;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 6)) << (21 - 6);+ out = out.offset(1);++ *out = ((*in_buf) >> 6) % (1u32 << 21);+ out = out.offset(1);+ *out = (*in_buf) >> 27;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 16)) << (21 - 16);+ out = out.offset(1);++ *out = (*in_buf) >> 16;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 5)) << (21 - 5);+ out = out.offset(1);++ *out = ((*in_buf) >> 5) % (1u32 << 21);+ out = out.offset(1);+ *out = (*in_buf) >> 26;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 15)) << (21 - 15);+ out = out.offset(1);++ *out = (*in_buf) >> 15;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (21 - 4);+ out = out.offset(1);++ *out = ((*in_buf) >> 4) % (1u32 << 21);+ out = out.offset(1);+ *out = (*in_buf) >> 25;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 14)) << (21 - 14);+ out = out.offset(1);++ *out = (*in_buf) >> 14;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 3)) << (21 - 3);+ out = out.offset(1);++ *out = ((*in_buf) >> 3) % (1u32 << 21);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 13)) << (21 - 13);+ out = out.offset(1);++ *out = (*in_buf) >> 13;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 2)) << (21 - 2);+ out = out.offset(1);++ *out = ((*in_buf) >> 2) % (1u32 << 21);+ out = out.offset(1);+ *out = (*in_buf) >> 23;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 12)) << (21 - 12);+ out = out.offset(1);++ *out = (*in_buf) >> 12;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 1)) << (21 - 1);+ out = out.offset(1);++ *out = ((*in_buf) >> 1) % (1u32 << 21);+ out = out.offset(1);+ *out = (*in_buf) >> 22;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 11)) << (21 - 11);+ out = out.offset(1);++ *out = (*in_buf) >> 11;++ in_buf.offset(1)+}++unsafe fn unpack22_32(mut in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ *out = ((*in_buf) >> 0) % (1u32 << 22);+ out = out.offset(1);+ *out = (*in_buf) >> 22;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 12)) << (22 - 12);+ out = out.offset(1);++ *out = (*in_buf) >> 12;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 2)) << (22 - 2);+ out = out.offset(1);++ *out = ((*in_buf) >> 2) % (1u32 << 22);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 14)) << (22 - 14);+ out = out.offset(1);++ *out = (*in_buf) >> 14;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (22 - 4);+ out = out.offset(1);++ *out = ((*in_buf) >> 4) % (1u32 << 22);+ out = out.offset(1);+ *out = (*in_buf) >> 26;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 16)) << (22 - 16);+ out = out.offset(1);++ *out = (*in_buf) >> 16;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 6)) << (22 - 6);+ out = out.offset(1);++ *out = ((*in_buf) >> 6) % (1u32 << 22);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 18)) << (22 - 18);+ out = out.offset(1);++ *out = (*in_buf) >> 18;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (22 - 8);+ out = out.offset(1);++ *out = ((*in_buf) >> 8) % (1u32 << 22);+ out = out.offset(1);+ *out = (*in_buf) >> 30;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 20)) << (22 - 20);+ out = out.offset(1);++ *out = (*in_buf) >> 20;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 10)) << (22 - 10);+ out = out.offset(1);++ *out = (*in_buf) >> 10;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 22);+ out = out.offset(1);+ *out = (*in_buf) >> 22;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 12)) << (22 - 12);+ out = out.offset(1);++ *out = (*in_buf) >> 12;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 2)) << (22 - 2);+ out = out.offset(1);++ *out = ((*in_buf) >> 2) % (1u32 << 22);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 14)) << (22 - 14);+ out = out.offset(1);++ *out = (*in_buf) >> 14;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (22 - 4);+ out = out.offset(1);++ *out = ((*in_buf) >> 4) % (1u32 << 22);+ out = out.offset(1);+ *out = (*in_buf) >> 26;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 16)) << (22 - 16);+ out = out.offset(1);++ *out = (*in_buf) >> 16;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 6)) << (22 - 6);+ out = out.offset(1);++ *out = ((*in_buf) >> 6) % (1u32 << 22);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 18)) << (22 - 18);+ out = out.offset(1);++ *out = (*in_buf) >> 18;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (22 - 8);+ out = out.offset(1);++ *out = ((*in_buf) >> 8) % (1u32 << 22);+ out = out.offset(1);+ *out = (*in_buf) >> 30;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 20)) << (22 - 20);+ out = out.offset(1);++ *out = (*in_buf) >> 20;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 10)) << (22 - 10);+ out = out.offset(1);++ *out = (*in_buf) >> 10;++ in_buf.offset(1)+}++unsafe fn unpack23_32(mut in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ *out = ((*in_buf) >> 0) % (1u32 << 23);+ out = out.offset(1);+ *out = (*in_buf) >> 23;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 14)) << (23 - 14);+ out = out.offset(1);++ *out = (*in_buf) >> 14;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 5)) << (23 - 5);+ out = out.offset(1);++ *out = ((*in_buf) >> 5) % (1u32 << 23);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 19)) << (23 - 19);+ out = out.offset(1);++ *out = (*in_buf) >> 19;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 10)) << (23 - 10);+ out = out.offset(1);++ *out = (*in_buf) >> 10;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 1)) << (23 - 1);+ out = out.offset(1);++ *out = ((*in_buf) >> 1) % (1u32 << 23);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 15)) << (23 - 15);+ out = out.offset(1);++ *out = (*in_buf) >> 15;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 6)) << (23 - 6);+ out = out.offset(1);++ *out = ((*in_buf) >> 6) % (1u32 << 23);+ out = out.offset(1);+ *out = (*in_buf) >> 29;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 20)) << (23 - 20);+ out = out.offset(1);++ *out = (*in_buf) >> 20;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 11)) << (23 - 11);+ out = out.offset(1);++ *out = (*in_buf) >> 11;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 2)) << (23 - 2);+ out = out.offset(1);++ *out = ((*in_buf) >> 2) % (1u32 << 23);+ out = out.offset(1);+ *out = (*in_buf) >> 25;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 16)) << (23 - 16);+ out = out.offset(1);++ *out = (*in_buf) >> 16;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 7)) << (23 - 7);+ out = out.offset(1);++ *out = ((*in_buf) >> 7) % (1u32 << 23);+ out = out.offset(1);+ *out = (*in_buf) >> 30;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 21)) << (23 - 21);+ out = out.offset(1);++ *out = (*in_buf) >> 21;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 12)) << (23 - 12);+ out = out.offset(1);++ *out = (*in_buf) >> 12;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 3)) << (23 - 3);+ out = out.offset(1);++ *out = ((*in_buf) >> 3) % (1u32 << 23);+ out = out.offset(1);+ *out = (*in_buf) >> 26;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 17)) << (23 - 17);+ out = out.offset(1);++ *out = (*in_buf) >> 17;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (23 - 8);+ out = out.offset(1);++ *out = ((*in_buf) >> 8) % (1u32 << 23);+ out = out.offset(1);+ *out = (*in_buf) >> 31;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 22)) << (23 - 22);+ out = out.offset(1);++ *out = (*in_buf) >> 22;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 13)) << (23 - 13);+ out = out.offset(1);++ *out = (*in_buf) >> 13;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (23 - 4);+ out = out.offset(1);++ *out = ((*in_buf) >> 4) % (1u32 << 23);+ out = out.offset(1);+ *out = (*in_buf) >> 27;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 18)) << (23 - 18);+ out = out.offset(1);++ *out = (*in_buf) >> 18;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 9)) << (23 - 9);+ out = out.offset(1);++ *out = (*in_buf) >> 9;++ in_buf.offset(1)+}++unsafe fn unpack24_32(mut in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ *out = ((*in_buf) >> 0) % (1u32 << 24);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 16)) << (24 - 16);+ out = out.offset(1);++ *out = (*in_buf) >> 16;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (24 - 8);+ out = out.offset(1);++ *out = (*in_buf) >> 8;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 24);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 16)) << (24 - 16);+ out = out.offset(1);++ *out = (*in_buf) >> 16;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (24 - 8);+ out = out.offset(1);++ *out = (*in_buf) >> 8;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 24);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 16)) << (24 - 16);+ out = out.offset(1);++ *out = (*in_buf) >> 16;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (24 - 8);+ out = out.offset(1);++ *out = (*in_buf) >> 8;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 24);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 16)) << (24 - 16);+ out = out.offset(1);++ *out = (*in_buf) >> 16;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (24 - 8);+ out = out.offset(1);++ *out = (*in_buf) >> 8;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 24);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 16)) << (24 - 16);+ out = out.offset(1);++ *out = (*in_buf) >> 16;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (24 - 8);+ out = out.offset(1);++ *out = (*in_buf) >> 8;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 24);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 16)) << (24 - 16);+ out = out.offset(1);++ *out = (*in_buf) >> 16;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (24 - 8);+ out = out.offset(1);++ *out = (*in_buf) >> 8;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 24);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 16)) << (24 - 16);+ out = out.offset(1);++ *out = (*in_buf) >> 16;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (24 - 8);+ out = out.offset(1);++ *out = (*in_buf) >> 8;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 24);+ out = out.offset(1);+ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 16)) << (24 - 16);+ out = out.offset(1);++ *out = (*in_buf) >> 16;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (24 - 8);+ out = out.offset(1);++ *out = (*in_buf) >> 8;++ in_buf.offset(1)+}++unsafe fn unpack25_32(mut in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ *out = ((*in_buf) >> 0) % (1u32 << 25);+ out = out.offset(1);+ *out = (*in_buf) >> 25;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 18)) << (25 - 18);+ out = out.offset(1);++ *out = (*in_buf) >> 18;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 11)) << (25 - 11);+ out = out.offset(1);++ *out = (*in_buf) >> 11;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (25 - 4);+ out = out.offset(1);++ *out = ((*in_buf) >> 4) % (1u32 << 25);+ out = out.offset(1);+ *out = (*in_buf) >> 29;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 22)) << (25 - 22);+ out = out.offset(1);++ *out = (*in_buf) >> 22;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 15)) << (25 - 15);+ out = out.offset(1);++ *out = (*in_buf) >> 15;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (25 - 8);+ out = out.offset(1);++ *out = (*in_buf) >> 8;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 1)) << (25 - 1);+ out = out.offset(1);++ *out = ((*in_buf) >> 1) % (1u32 << 25);+ out = out.offset(1);+ *out = (*in_buf) >> 26;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 19)) << (25 - 19);+ out = out.offset(1);++ *out = (*in_buf) >> 19;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 12)) << (25 - 12);+ out = out.offset(1);++ *out = (*in_buf) >> 12;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 5)) << (25 - 5);+ out = out.offset(1);++ *out = ((*in_buf) >> 5) % (1u32 << 25);+ out = out.offset(1);+ *out = (*in_buf) >> 30;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 23)) << (25 - 23);+ out = out.offset(1);++ *out = (*in_buf) >> 23;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 16)) << (25 - 16);+ out = out.offset(1);++ *out = (*in_buf) >> 16;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 9)) << (25 - 9);+ out = out.offset(1);++ *out = (*in_buf) >> 9;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 2)) << (25 - 2);+ out = out.offset(1);++ *out = ((*in_buf) >> 2) % (1u32 << 25);+ out = out.offset(1);+ *out = (*in_buf) >> 27;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 20)) << (25 - 20);+ out = out.offset(1);++ *out = (*in_buf) >> 20;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 13)) << (25 - 13);+ out = out.offset(1);++ *out = (*in_buf) >> 13;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 6)) << (25 - 6);+ out = out.offset(1);++ *out = ((*in_buf) >> 6) % (1u32 << 25);+ out = out.offset(1);+ *out = (*in_buf) >> 31;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 24)) << (25 - 24);+ out = out.offset(1);++ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 17)) << (25 - 17);+ out = out.offset(1);++ *out = (*in_buf) >> 17;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 10)) << (25 - 10);+ out = out.offset(1);++ *out = (*in_buf) >> 10;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 3)) << (25 - 3);+ out = out.offset(1);++ *out = ((*in_buf) >> 3) % (1u32 << 25);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 21)) << (25 - 21);+ out = out.offset(1);++ *out = (*in_buf) >> 21;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 14)) << (25 - 14);+ out = out.offset(1);++ *out = (*in_buf) >> 14;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 7)) << (25 - 7);+ out = out.offset(1);++ *out = (*in_buf) >> 7;++ in_buf.offset(1)+}++unsafe fn unpack26_32(mut in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ *out = ((*in_buf) >> 0) % (1u32 << 26);+ out = out.offset(1);+ *out = (*in_buf) >> 26;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 20)) << (26 - 20);+ out = out.offset(1);++ *out = (*in_buf) >> 20;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 14)) << (26 - 14);+ out = out.offset(1);++ *out = (*in_buf) >> 14;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (26 - 8);+ out = out.offset(1);++ *out = (*in_buf) >> 8;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 2)) << (26 - 2);+ out = out.offset(1);++ *out = ((*in_buf) >> 2) % (1u32 << 26);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 22)) << (26 - 22);+ out = out.offset(1);++ *out = (*in_buf) >> 22;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 16)) << (26 - 16);+ out = out.offset(1);++ *out = (*in_buf) >> 16;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 10)) << (26 - 10);+ out = out.offset(1);++ *out = (*in_buf) >> 10;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (26 - 4);+ out = out.offset(1);++ *out = ((*in_buf) >> 4) % (1u32 << 26);+ out = out.offset(1);+ *out = (*in_buf) >> 30;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 24)) << (26 - 24);+ out = out.offset(1);++ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 18)) << (26 - 18);+ out = out.offset(1);++ *out = (*in_buf) >> 18;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 12)) << (26 - 12);+ out = out.offset(1);++ *out = (*in_buf) >> 12;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 6)) << (26 - 6);+ out = out.offset(1);++ *out = (*in_buf) >> 6;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 26);+ out = out.offset(1);+ *out = (*in_buf) >> 26;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 20)) << (26 - 20);+ out = out.offset(1);++ *out = (*in_buf) >> 20;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 14)) << (26 - 14);+ out = out.offset(1);++ *out = (*in_buf) >> 14;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (26 - 8);+ out = out.offset(1);++ *out = (*in_buf) >> 8;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 2)) << (26 - 2);+ out = out.offset(1);++ *out = ((*in_buf) >> 2) % (1u32 << 26);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 22)) << (26 - 22);+ out = out.offset(1);++ *out = (*in_buf) >> 22;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 16)) << (26 - 16);+ out = out.offset(1);++ *out = (*in_buf) >> 16;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 10)) << (26 - 10);+ out = out.offset(1);++ *out = (*in_buf) >> 10;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (26 - 4);+ out = out.offset(1);++ *out = ((*in_buf) >> 4) % (1u32 << 26);+ out = out.offset(1);+ *out = (*in_buf) >> 30;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 24)) << (26 - 24);+ out = out.offset(1);++ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 18)) << (26 - 18);+ out = out.offset(1);++ *out = (*in_buf) >> 18;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 12)) << (26 - 12);+ out = out.offset(1);++ *out = (*in_buf) >> 12;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 6)) << (26 - 6);+ out = out.offset(1);++ *out = (*in_buf) >> 6;++ in_buf.offset(1)+}++unsafe fn unpack27_32(mut in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ *out = ((*in_buf) >> 0) % (1u32 << 27);+ out = out.offset(1);+ *out = (*in_buf) >> 27;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 22)) << (27 - 22);+ out = out.offset(1);++ *out = (*in_buf) >> 22;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 17)) << (27 - 17);+ out = out.offset(1);++ *out = (*in_buf) >> 17;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 12)) << (27 - 12);+ out = out.offset(1);++ *out = (*in_buf) >> 12;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 7)) << (27 - 7);+ out = out.offset(1);++ *out = (*in_buf) >> 7;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 2)) << (27 - 2);+ out = out.offset(1);++ *out = ((*in_buf) >> 2) % (1u32 << 27);+ out = out.offset(1);+ *out = (*in_buf) >> 29;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 24)) << (27 - 24);+ out = out.offset(1);++ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 19)) << (27 - 19);+ out = out.offset(1);++ *out = (*in_buf) >> 19;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 14)) << (27 - 14);+ out = out.offset(1);++ *out = (*in_buf) >> 14;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 9)) << (27 - 9);+ out = out.offset(1);++ *out = (*in_buf) >> 9;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (27 - 4);+ out = out.offset(1);++ *out = ((*in_buf) >> 4) % (1u32 << 27);+ out = out.offset(1);+ *out = (*in_buf) >> 31;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 26)) << (27 - 26);+ out = out.offset(1);++ *out = (*in_buf) >> 26;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 21)) << (27 - 21);+ out = out.offset(1);++ *out = (*in_buf) >> 21;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 16)) << (27 - 16);+ out = out.offset(1);++ *out = (*in_buf) >> 16;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 11)) << (27 - 11);+ out = out.offset(1);++ *out = (*in_buf) >> 11;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 6)) << (27 - 6);+ out = out.offset(1);++ *out = (*in_buf) >> 6;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 1)) << (27 - 1);+ out = out.offset(1);++ *out = ((*in_buf) >> 1) % (1u32 << 27);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 23)) << (27 - 23);+ out = out.offset(1);++ *out = (*in_buf) >> 23;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 18)) << (27 - 18);+ out = out.offset(1);++ *out = (*in_buf) >> 18;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 13)) << (27 - 13);+ out = out.offset(1);++ *out = (*in_buf) >> 13;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (27 - 8);+ out = out.offset(1);++ *out = (*in_buf) >> 8;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 3)) << (27 - 3);+ out = out.offset(1);++ *out = ((*in_buf) >> 3) % (1u32 << 27);+ out = out.offset(1);+ *out = (*in_buf) >> 30;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 25)) << (27 - 25);+ out = out.offset(1);++ *out = (*in_buf) >> 25;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 20)) << (27 - 20);+ out = out.offset(1);++ *out = (*in_buf) >> 20;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 15)) << (27 - 15);+ out = out.offset(1);++ *out = (*in_buf) >> 15;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 10)) << (27 - 10);+ out = out.offset(1);++ *out = (*in_buf) >> 10;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 5)) << (27 - 5);+ out = out.offset(1);++ *out = (*in_buf) >> 5;++ in_buf.offset(1)+}++unsafe fn unpack28_32(mut in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ *out = ((*in_buf) >> 0) % (1u32 << 28);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 24)) << (28 - 24);+ out = out.offset(1);++ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 20)) << (28 - 20);+ out = out.offset(1);++ *out = (*in_buf) >> 20;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 16)) << (28 - 16);+ out = out.offset(1);++ *out = (*in_buf) >> 16;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 12)) << (28 - 12);+ out = out.offset(1);++ *out = (*in_buf) >> 12;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (28 - 8);+ out = out.offset(1);++ *out = (*in_buf) >> 8;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (28 - 4);+ out = out.offset(1);++ *out = (*in_buf) >> 4;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 28);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 24)) << (28 - 24);+ out = out.offset(1);++ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 20)) << (28 - 20);+ out = out.offset(1);++ *out = (*in_buf) >> 20;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 16)) << (28 - 16);+ out = out.offset(1);++ *out = (*in_buf) >> 16;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 12)) << (28 - 12);+ out = out.offset(1);++ *out = (*in_buf) >> 12;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (28 - 8);+ out = out.offset(1);++ *out = (*in_buf) >> 8;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (28 - 4);+ out = out.offset(1);++ *out = (*in_buf) >> 4;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 28);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 24)) << (28 - 24);+ out = out.offset(1);++ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 20)) << (28 - 20);+ out = out.offset(1);++ *out = (*in_buf) >> 20;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 16)) << (28 - 16);+ out = out.offset(1);++ *out = (*in_buf) >> 16;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 12)) << (28 - 12);+ out = out.offset(1);++ *out = (*in_buf) >> 12;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (28 - 8);+ out = out.offset(1);++ *out = (*in_buf) >> 8;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (28 - 4);+ out = out.offset(1);++ *out = (*in_buf) >> 4;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 28);+ out = out.offset(1);+ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 24)) << (28 - 24);+ out = out.offset(1);++ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 20)) << (28 - 20);+ out = out.offset(1);++ *out = (*in_buf) >> 20;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 16)) << (28 - 16);+ out = out.offset(1);++ *out = (*in_buf) >> 16;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 12)) << (28 - 12);+ out = out.offset(1);++ *out = (*in_buf) >> 12;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (28 - 8);+ out = out.offset(1);++ *out = (*in_buf) >> 8;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (28 - 4);+ out = out.offset(1);++ *out = (*in_buf) >> 4;++ in_buf.offset(1)+}++unsafe fn unpack29_32(mut in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ *out = ((*in_buf) >> 0) % (1u32 << 29);+ out = out.offset(1);+ *out = (*in_buf) >> 29;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 26)) << (29 - 26);+ out = out.offset(1);++ *out = (*in_buf) >> 26;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 23)) << (29 - 23);+ out = out.offset(1);++ *out = (*in_buf) >> 23;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 20)) << (29 - 20);+ out = out.offset(1);++ *out = (*in_buf) >> 20;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 17)) << (29 - 17);+ out = out.offset(1);++ *out = (*in_buf) >> 17;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 14)) << (29 - 14);+ out = out.offset(1);++ *out = (*in_buf) >> 14;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 11)) << (29 - 11);+ out = out.offset(1);++ *out = (*in_buf) >> 11;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (29 - 8);+ out = out.offset(1);++ *out = (*in_buf) >> 8;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 5)) << (29 - 5);+ out = out.offset(1);++ *out = (*in_buf) >> 5;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 2)) << (29 - 2);+ out = out.offset(1);++ *out = ((*in_buf) >> 2) % (1u32 << 29);+ out = out.offset(1);+ *out = (*in_buf) >> 31;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 28)) << (29 - 28);+ out = out.offset(1);++ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 25)) << (29 - 25);+ out = out.offset(1);++ *out = (*in_buf) >> 25;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 22)) << (29 - 22);+ out = out.offset(1);++ *out = (*in_buf) >> 22;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 19)) << (29 - 19);+ out = out.offset(1);++ *out = (*in_buf) >> 19;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 16)) << (29 - 16);+ out = out.offset(1);++ *out = (*in_buf) >> 16;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 13)) << (29 - 13);+ out = out.offset(1);++ *out = (*in_buf) >> 13;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 10)) << (29 - 10);+ out = out.offset(1);++ *out = (*in_buf) >> 10;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 7)) << (29 - 7);+ out = out.offset(1);++ *out = (*in_buf) >> 7;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (29 - 4);+ out = out.offset(1);++ *out = (*in_buf) >> 4;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 1)) << (29 - 1);+ out = out.offset(1);++ *out = ((*in_buf) >> 1) % (1u32 << 29);+ out = out.offset(1);+ *out = (*in_buf) >> 30;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 27)) << (29 - 27);+ out = out.offset(1);++ *out = (*in_buf) >> 27;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 24)) << (29 - 24);+ out = out.offset(1);++ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 21)) << (29 - 21);+ out = out.offset(1);++ *out = (*in_buf) >> 21;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 18)) << (29 - 18);+ out = out.offset(1);++ *out = (*in_buf) >> 18;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 15)) << (29 - 15);+ out = out.offset(1);++ *out = (*in_buf) >> 15;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 12)) << (29 - 12);+ out = out.offset(1);++ *out = (*in_buf) >> 12;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 9)) << (29 - 9);+ out = out.offset(1);++ *out = (*in_buf) >> 9;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 6)) << (29 - 6);+ out = out.offset(1);++ *out = (*in_buf) >> 6;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 3)) << (29 - 3);+ out = out.offset(1);++ *out = (*in_buf) >> 3;++ in_buf.offset(1)+}++unsafe fn unpack30_32(mut in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ *out = ((*in_buf) >> 0) % (1u32 << 30);+ out = out.offset(1);+ *out = (*in_buf) >> 30;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 28)) << (30 - 28);+ out = out.offset(1);++ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 26)) << (30 - 26);+ out = out.offset(1);++ *out = (*in_buf) >> 26;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 24)) << (30 - 24);+ out = out.offset(1);++ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 22)) << (30 - 22);+ out = out.offset(1);++ *out = (*in_buf) >> 22;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 20)) << (30 - 20);+ out = out.offset(1);++ *out = (*in_buf) >> 20;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 18)) << (30 - 18);+ out = out.offset(1);++ *out = (*in_buf) >> 18;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 16)) << (30 - 16);+ out = out.offset(1);++ *out = (*in_buf) >> 16;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 14)) << (30 - 14);+ out = out.offset(1);++ *out = (*in_buf) >> 14;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 12)) << (30 - 12);+ out = out.offset(1);++ *out = (*in_buf) >> 12;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 10)) << (30 - 10);+ out = out.offset(1);++ *out = (*in_buf) >> 10;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (30 - 8);+ out = out.offset(1);++ *out = (*in_buf) >> 8;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 6)) << (30 - 6);+ out = out.offset(1);++ *out = (*in_buf) >> 6;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (30 - 4);+ out = out.offset(1);++ *out = (*in_buf) >> 4;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 2)) << (30 - 2);+ out = out.offset(1);++ *out = (*in_buf) >> 2;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = ((*in_buf) >> 0) % (1u32 << 30);+ out = out.offset(1);+ *out = (*in_buf) >> 30;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 28)) << (30 - 28);+ out = out.offset(1);++ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 26)) << (30 - 26);+ out = out.offset(1);++ *out = (*in_buf) >> 26;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 24)) << (30 - 24);+ out = out.offset(1);++ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 22)) << (30 - 22);+ out = out.offset(1);++ *out = (*in_buf) >> 22;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 20)) << (30 - 20);+ out = out.offset(1);++ *out = (*in_buf) >> 20;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 18)) << (30 - 18);+ out = out.offset(1);++ *out = (*in_buf) >> 18;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 16)) << (30 - 16);+ out = out.offset(1);++ *out = (*in_buf) >> 16;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 14)) << (30 - 14);+ out = out.offset(1);++ *out = (*in_buf) >> 14;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 12)) << (30 - 12);+ out = out.offset(1);++ *out = (*in_buf) >> 12;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 10)) << (30 - 10);+ out = out.offset(1);++ *out = (*in_buf) >> 10;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (30 - 8);+ out = out.offset(1);++ *out = (*in_buf) >> 8;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 6)) << (30 - 6);+ out = out.offset(1);++ *out = (*in_buf) >> 6;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (30 - 4);+ out = out.offset(1);++ *out = (*in_buf) >> 4;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 2)) << (30 - 2);+ out = out.offset(1);++ *out = (*in_buf) >> 2;++ in_buf.offset(1)+}++unsafe fn unpack31_32(mut in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ *out = ((*in_buf) >> 0) % (1u32 << 31);+ out = out.offset(1);+ *out = (*in_buf) >> 31;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 30)) << (31 - 30);+ out = out.offset(1);++ *out = (*in_buf) >> 30;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 29)) << (31 - 29);+ out = out.offset(1);++ *out = (*in_buf) >> 29;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 28)) << (31 - 28);+ out = out.offset(1);++ *out = (*in_buf) >> 28;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 27)) << (31 - 27);+ out = out.offset(1);++ *out = (*in_buf) >> 27;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 26)) << (31 - 26);+ out = out.offset(1);++ *out = (*in_buf) >> 26;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 25)) << (31 - 25);+ out = out.offset(1);++ *out = (*in_buf) >> 25;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 24)) << (31 - 24);+ out = out.offset(1);++ *out = (*in_buf) >> 24;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 23)) << (31 - 23);+ out = out.offset(1);++ *out = (*in_buf) >> 23;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 22)) << (31 - 22);+ out = out.offset(1);++ *out = (*in_buf) >> 22;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 21)) << (31 - 21);+ out = out.offset(1);++ *out = (*in_buf) >> 21;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 20)) << (31 - 20);+ out = out.offset(1);++ *out = (*in_buf) >> 20;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 19)) << (31 - 19);+ out = out.offset(1);++ *out = (*in_buf) >> 19;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 18)) << (31 - 18);+ out = out.offset(1);++ *out = (*in_buf) >> 18;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 17)) << (31 - 17);+ out = out.offset(1);++ *out = (*in_buf) >> 17;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 16)) << (31 - 16);+ out = out.offset(1);++ *out = (*in_buf) >> 16;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 15)) << (31 - 15);+ out = out.offset(1);++ *out = (*in_buf) >> 15;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 14)) << (31 - 14);+ out = out.offset(1);++ *out = (*in_buf) >> 14;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 13)) << (31 - 13);+ out = out.offset(1);++ *out = (*in_buf) >> 13;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 12)) << (31 - 12);+ out = out.offset(1);++ *out = (*in_buf) >> 12;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 11)) << (31 - 11);+ out = out.offset(1);++ *out = (*in_buf) >> 11;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 10)) << (31 - 10);+ out = out.offset(1);++ *out = (*in_buf) >> 10;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 9)) << (31 - 9);+ out = out.offset(1);++ *out = (*in_buf) >> 9;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 8)) << (31 - 8);+ out = out.offset(1);++ *out = (*in_buf) >> 8;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 7)) << (31 - 7);+ out = out.offset(1);++ *out = (*in_buf) >> 7;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 6)) << (31 - 6);+ out = out.offset(1);++ *out = (*in_buf) >> 6;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 5)) << (31 - 5);+ out = out.offset(1);++ *out = (*in_buf) >> 5;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 4)) << (31 - 4);+ out = out.offset(1);++ *out = (*in_buf) >> 4;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 3)) << (31 - 3);+ out = out.offset(1);++ *out = (*in_buf) >> 3;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 2)) << (31 - 2);+ out = out.offset(1);++ *out = (*in_buf) >> 2;+ in_buf = in_buf.offset(1);+ *out |= ((*in_buf) % (1u32 << 1)) << (31 - 1);+ out = out.offset(1);++ *out = (*in_buf) >> 1;++ in_buf.offset(1)+}++unsafe fn unpack32_32(mut in_buf: *const u32, mut out: *mut u32) -> *const u32 {+ *out = (*in_buf) >> 0;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = (*in_buf) >> 0;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = (*in_buf) >> 0;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = (*in_buf) >> 0;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = (*in_buf) >> 0;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = (*in_buf) >> 0;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = (*in_buf) >> 0;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = (*in_buf) >> 0;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = (*in_buf) >> 0;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = (*in_buf) >> 0;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = (*in_buf) >> 0;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = (*in_buf) >> 0;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = (*in_buf) >> 0;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = (*in_buf) >> 0;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = (*in_buf) >> 0;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = (*in_buf) >> 0;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = (*in_buf) >> 0;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = (*in_buf) >> 0;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = (*in_buf) >> 0;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = (*in_buf) >> 0;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = (*in_buf) >> 0;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = (*in_buf) >> 0;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = (*in_buf) >> 0;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = (*in_buf) >> 0;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = (*in_buf) >> 0;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = (*in_buf) >> 0;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = (*in_buf) >> 0;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = (*in_buf) >> 0;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = (*in_buf) >> 0;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = (*in_buf) >> 0;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = (*in_buf) >> 0;+ in_buf = in_buf.offset(1);+ out = out.offset(1);++ *out = (*in_buf) >> 0;++ in_buf.offset(1)+}diff --git a/rust/src/parquet/util/bit_util.rs b/rust/src/parquet/util/bit_util.rsnew file mode 100644index 0000000000..9dbb9a3233--- /dev/null+++ b/rust/src/parquet/util/bit_util.rs@@ -0,0 +1,1058 @@+// 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,+ mem::{size_of, transmute_copy},+};++use crate::parquet::errors::{ParquetError, Result};+use crate::parquet::util::{bit_packing::unpack32, memory::ByteBufferPtr};++/// Reads `$size` of bytes from `$src`, and reinterprets them as type `$ty`, in+/// little-endian order. `$ty` must implement the `Default` trait. Otherwise this won't+/// compile.+/// This is copied and modified from byteorder crate.+macro_rules! read_num_bytes {+ ($ty:ty, $size:expr, $src:expr) => {{+ assert!($size <= $src.len());+ let mut data: $ty = Default::default();+ unsafe {+ ::std::ptr::copy_nonoverlapping($src.as_ptr(), &mut data as *mut $ty as *mut u8, $size);+ }+ data+ }};+}++/// Converts value `val` of type `T` to a byte vector, by reading `num_bytes` from `val`.+/// NOTE: if `val` is less than the size of `T` then it can be truncated.+#[inline]+pub fn convert_to_bytes<T>(val: &T, num_bytes: usize) -> Vec<u8> {+ let mut bytes: Vec<u8> = vec![0; num_bytes];+ memcpy_value(val, num_bytes, &mut bytes);+ bytes+}++#[inline]+pub fn memcpy(source: &[u8], target: &mut [u8]) {+ assert!(target.len() >= source.len());+ unsafe { ::std::ptr::copy_nonoverlapping(source.as_ptr(), target.as_mut_ptr(), source.len()) }+}++#[inline]+pub fn memcpy_value<T>(source: &T, num_bytes: usize, target: &mut [u8]) {+ assert!(+ target.len() >= num_bytes,+ "Not enough space. Only had {} bytes but need to put {} bytes",+ target.len(),+ num_bytes+ );+ unsafe {+ ::std::ptr::copy_nonoverlapping(+ source as *const T as *const u8,+ target.as_mut_ptr(),+ num_bytes,+ )+ }+}++/// Returns the ceil of value/divisor+#[inline]+pub fn ceil(value: i64, divisor: i64) -> i64 {+ let mut result = value / divisor;+ if value % divisor != 0 {+ result += 1+ };+ result+}++/// Returns ceil(log2(x))+#[inline]+pub fn log2(mut x: u64) -> i32 {+ if x == 1 {+ return 0;+ }+ x -= 1;+ let mut result = 0;+ while x > 0 {+ x >>= 1;+ result += 1;+ }+ result+}++/// Returns the `num_bits` least-significant bits of `v`+#[inline]+pub fn trailing_bits(v: u64, num_bits: usize) -> u64 {+ if num_bits == 0 {+ return 0;+ }+ if num_bits >= 64 {+ return v;+ }+ let n = 64 - num_bits;+ (v << n) >> n+}++#[inline]+pub fn set_array_bit(bits: &mut [u8], i: usize) {+ bits[i / 8] |= 1 << (i % 8);+}++#[inline]+pub fn unset_array_bit(bits: &mut [u8], i: usize) {+ bits[i / 8] &= !(1 << (i % 8));+}++/// Returns the minimum number of bits needed to represent the value 'x'+#[inline]+pub fn num_required_bits(x: u64) -> usize {+ for i in (0..64).rev() {+ if x & (1u64 << i) != 0 {+ return i + 1;+ }+ }+ 0+}++/// Utility class for writing bit/byte streams. This class can write data in either+/// bit packed or byte aligned fashion.+pub struct BitWriter {+ buffer: Vec<u8>,+ max_bytes: usize,+ buffered_values: u64,+ byte_offset: usize,+ bit_offset: usize,+ start: usize,+}++impl BitWriter {+ pub fn new(max_bytes: usize) -> Self {+ Self {+ buffer: vec![0; max_bytes],+ max_bytes,+ buffered_values: 0,+ byte_offset: 0,+ bit_offset: 0,+ start: 0,+ }+ }++ /// Initializes the writer from the existing buffer `buffer` and starting+ /// offset `start`.+ pub fn new_from_buf(buffer: Vec<u8>, start: usize) -> Self {+ assert!(start < buffer.len());+ let len = buffer.len();+ Self {+ buffer,+ max_bytes: len,+ buffered_values: 0,+ byte_offset: start,+ bit_offset: 0,+ start,+ }+ }++ /// Consumes and returns the current buffer.+ #[inline]+ pub fn consume(mut self) -> Vec<u8> {+ self.flush();+ self.buffer.truncate(self.byte_offset);+ self.buffer+ }++ /// Flushes the internal buffered bits and returns the buffer's content.+ /// This is a borrow equivalent of `consume` method.+ #[inline]+ pub fn flush_buffer(&mut self) -> &[u8] {+ self.flush();+ &self.buffer()[0..self.byte_offset]+ }++ /// Clears the internal state so the buffer can be reused.+ #[inline]+ pub fn clear(&mut self) {+ self.buffered_values = 0;+ self.byte_offset = self.start;+ self.bit_offset = 0;+ }++ /// Flushes the internal buffered bits and the align the buffer to the next byte.+ #[inline]+ pub fn flush(&mut self) {+ let num_bytes = ceil(self.bit_offset as i64, 8) as usize;+ assert!(self.byte_offset + num_bytes <= self.max_bytes);+ memcpy_value(+ &self.buffered_values,+ num_bytes,+ &mut self.buffer[self.byte_offset..],+ );+ self.buffered_values = 0;+ self.bit_offset = 0;+ self.byte_offset += num_bytes;+ }++ /// Advances the current offset by skipping `num_bytes`, flushing the internal bit+ /// buffer first.+ /// This is useful when you want to jump over `num_bytes` bytes and come back later+ /// to fill these bytes.+ ///+ /// Returns error if `num_bytes` is beyond the boundary of the internal buffer.+ /// Otherwise, returns the old offset.+ #[inline]+ pub fn skip(&mut self, num_bytes: usize) -> Result<usize> {+ self.flush();+ assert!(self.byte_offset <= self.max_bytes);+ if self.byte_offset + num_bytes > self.max_bytes {+ return Err(general_err!(+ "Not enough bytes left in BitWriter. Need {} but only have {}",+ self.byte_offset + num_bytes,+ self.max_bytes+ ));+ }+ let result = self.byte_offset;+ self.byte_offset += num_bytes;+ Ok(result)+ }++ /// Returns a slice containing the next `num_bytes` bytes starting from the current+ /// offset, and advances the underlying buffer by `num_bytes`.+ /// This is useful when you want to jump over `num_bytes` bytes and come back later+ /// to fill these bytes.+ #[inline]+ pub fn get_next_byte_ptr(&mut self, num_bytes: usize) -> Result<&mut [u8]> {+ let offset = self.skip(num_bytes)?;+ Ok(&mut self.buffer[offset..offset + num_bytes])+ }++ #[inline]+ pub fn bytes_written(&self) -> usize {+ self.byte_offset - self.start + ceil(self.bit_offset as i64, 8) as usize+ }++ #[inline]+ pub fn buffer(&self) -> &[u8] {+ &self.buffer[self.start..]+ }++ #[inline]+ pub fn byte_offset(&self) -> usize {+ self.byte_offset+ }++ /// Returns the internal buffer length. This is the maximum number of bytes that this+ /// writer can write. User needs to call `consume` to consume the current buffer before+ /// more data can be written.+ #[inline]+ pub fn buffer_len(&self) -> usize {+ self.max_bytes+ }++ /// Writes the `num_bits` LSB of value `v` to the internal buffer of this writer.+ /// The `num_bits` must not be greater than 64. This is bit packed.+ ///+ /// Returns false if there's not enough room left. True otherwise.+ #[inline]+ pub fn put_value(&mut self, v: u64, num_bits: usize) -> bool {+ assert!(num_bits <= 64);+ assert_eq!(v.checked_shr(num_bits as u32).unwrap_or(0), 0); // covers case v >> 64++ if self.byte_offset * 8 + self.bit_offset + num_bits > self.max_bytes as usize * 8 {+ return false;+ }++ self.buffered_values |= v << self.bit_offset;+ self.bit_offset += num_bits;+ if self.bit_offset >= 64 {+ memcpy_value(+ &self.buffered_values,+ 8,+ &mut self.buffer[self.byte_offset..],+ );+ self.byte_offset += 8;+ self.bit_offset -= 64;+ self.buffered_values = 0;+ // Perform checked right shift: v >> offset, where offset < 64, otherwise we shift+ // all bits+ self.buffered_values = v+ .checked_shr((num_bits - self.bit_offset) as u32)+ .unwrap_or(0);+ }+ assert!(self.bit_offset < 64);+ true+ }++ /// Writes `val` of `num_bytes` bytes to the next aligned byte. If size of `T` is+ /// larger than `num_bytes`, extra higher ordered bytes will be ignored.+ ///+ /// Returns false if there's not enough room left. True otherwise.+ #[inline]+ pub fn put_aligned<T: Copy>(&mut self, val: T, num_bytes: usize) -> bool {+ let result = self.get_next_byte_ptr(num_bytes);+ if result.is_err() {+ // TODO: should we return `Result` for this func?+ return false;+ }+ let mut ptr = result.unwrap();+ memcpy_value(&val, num_bytes, &mut ptr);+ true+ }++ /// Writes `val` of `num_bytes` bytes at the designated `offset`. The `offset` is the+ /// offset starting from the beginning of the internal buffer that this writer+ /// maintains. Note that this will overwrite any existing data between `offset` and+ /// `offset + num_bytes`. Also that if size of `T` is larger than `num_bytes`, extra+ /// higher ordered bytes will be ignored.+ ///+ /// Returns false if there's not enough room left, or the `pos` is not valid.+ /// True otherwise.+ #[inline]+ pub fn put_aligned_offset<T: Copy>(&mut self, val: T, num_bytes: usize, offset: usize) -> bool {+ if num_bytes + offset > self.max_bytes {+ return false;+ }+ memcpy_value(+ &val,+ num_bytes,+ &mut self.buffer[offset..offset + num_bytes],+ );+ true+ }++ /// Writes a VLQ encoded integer `v` to this buffer. The value is byte aligned.+ ///+ /// Returns false if there's not enough room left. True otherwise.+ #[inline]+ pub fn put_vlq_int(&mut self, mut v: u64) -> bool {+ let mut result = true;+ while v & 0xFFFFFFFFFFFFFF80 != 0 {+ result &= self.put_aligned::<u8>(((v & 0x7F) | 0x80) as u8, 1);+ v >>= 7;+ }+ result &= self.put_aligned::<u8>((v & 0x7F) as u8, 1);+ result+ }++ /// Writes a zigzag-VLQ encoded (in little endian order) int `v` to this buffer.+ /// Zigzag-VLQ is a variant of VLQ encoding where negative and positive+ /// numbers are encoded in a zigzag fashion.+ /// See: https://developers.google.com/protocol-buffers/docs/encoding+ ///+ /// Returns false if there's not enough room left. True otherwise.+ #[inline]+ pub fn put_zigzag_vlq_int(&mut self, v: i64) -> bool {+ let u: u64 = ((v << 1) ^ (v >> 63)) as u64;+ self.put_vlq_int(u)+ }+}++/// Maximum byte length for a VLQ encoded integer+/// MAX_VLQ_BYTE_LEN = 5 for i32, and MAX_VLQ_BYTE_LEN = 10 for i64+pub const MAX_VLQ_BYTE_LEN: usize = 10;++pub struct BitReader {+ // The byte buffer to read from, passed in by client+ buffer: ByteBufferPtr,++ // Bytes are memcpy'd from `buffer` and values are read from this variable.+ // This is faster than reading values byte by byte directly from `buffer`+ buffered_values: u64,++ //+ // End Start+ // |............|B|B|B|B|B|B|B|B|..............|+ // ^ ^+ // bit_offset byte_offset+ //+ // Current byte offset in `buffer`+ byte_offset: usize,++ // Current bit offset in `buffered_values`+ bit_offset: usize,++ // Total number of bytes in `buffer`+ total_bytes: usize,+}++/// Utility class to read bit/byte stream. This class can read bits or bytes that are+/// either byte aligned or not.+impl BitReader {+ pub fn new(buffer: ByteBufferPtr) -> Self {+ let total_bytes = buffer.len();+ let num_bytes = cmp::min(8, total_bytes);+ let buffered_values = read_num_bytes!(u64, num_bytes, buffer.as_ref());+ BitReader {+ buffer,+ buffered_values,+ byte_offset: 0,+ bit_offset: 0,+ total_bytes,+ }+ }++ #[inline]+ pub fn reset(&mut self, buffer: ByteBufferPtr) {+ self.buffer = buffer;+ self.total_bytes = self.buffer.len();+ let num_bytes = cmp::min(8, self.total_bytes);+ self.buffered_values = read_num_bytes!(u64, num_bytes, self.buffer.as_ref());+ self.byte_offset = 0;+ self.bit_offset = 0;+ }++ /// Gets the current byte offset+ #[inline]+ pub fn get_byte_offset(&self) -> usize {+ self.byte_offset + ceil(self.bit_offset as i64, 8) as usize+ }++ /// Reads a value of type `T` and of size `num_bits`.+ ///+ /// Returns `None` if there's not enough data available. `Some` otherwise.+ #[inline]+ pub fn get_value<T: Default>(&mut self, num_bits: usize) -> Option<T> {+ assert!(num_bits <= 64);+ assert!(num_bits <= size_of::<T>() * 8);++ if self.byte_offset * 8 + self.bit_offset + num_bits > self.total_bytes * 8 {+ return None;+ }++ let mut v =+ trailing_bits(self.buffered_values, self.bit_offset + num_bits) >> self.bit_offset;+ self.bit_offset += num_bits;++ if self.bit_offset >= 64 {+ self.byte_offset += 8;+ self.bit_offset -= 64;++ self.reload_buffer_values();+ v |= trailing_bits(self.buffered_values, self.bit_offset)+ .wrapping_shl((num_bits - self.bit_offset) as u32);+ }++ // TODO: better to avoid copying here+ let result: T = unsafe { transmute_copy::<u64, T>(&v) };+ Some(result)+ }++ #[inline]+ pub fn get_batch<T: Default>(&mut self, batch: &mut [T], num_bits: usize) -> usize {+ assert!(num_bits <= 32);+ assert!(num_bits <= size_of::<T>() * 8);++ let mut values_to_read = batch.len();+ let needed_bits = num_bits * values_to_read;+ let remaining_bits = (self.total_bytes - self.byte_offset) * 8 - self.bit_offset;+ if remaining_bits < needed_bits {+ values_to_read = remaining_bits / num_bits;+ }++ let mut i = 0;++ // First align bit offset to byte offset+ if self.bit_offset != 0 {+ while i < values_to_read && self.bit_offset != 0 {+ batch[i] = self+ .get_value(num_bits)+ .expect("expected to have more data");+ i += 1;+ }+ }++ unsafe {+ let in_buf = &self.buffer.data()[self.byte_offset..];+ let mut in_ptr = in_buf as *const [u8] as *const u8 as *const u32;+ if size_of::<T>() == 4 {+ while values_to_read - i >= 32 {+ let out_ptr = &mut batch[i..] as *mut [T] as *mut T as *mut u32;+ in_ptr = unpack32(in_ptr, out_ptr, num_bits);+ self.byte_offset += 4 * num_bits;+ i += 32;+ }+ } else {+ let mut out_buf = [0u32; 32];+ let out_ptr = &mut out_buf as &mut [u32] as *mut [u32] as *mut u32;+ while values_to_read - i >= 32 {+ in_ptr = unpack32(in_ptr, out_ptr, num_bits);+ self.byte_offset += 4 * num_bits;+ for n in 0..32 {+ // We need to copy from smaller size to bigger size to avoid overwritting+ // other memory regions.+ if size_of::<T>() > size_of::<u32>() {+ ::std::ptr::copy_nonoverlapping(+ out_buf[n..].as_ptr() as *const u32,+ &mut batch[i] as *mut T as *mut u32,+ 1,+ );+ } else {+ ::std::ptr::copy_nonoverlapping(+ out_buf[n..].as_ptr() as *const T,+ &mut batch[i] as *mut T,+ 1,+ );+ }+ i += 1;+ }+ }+ }+ }++ assert!(values_to_read - i < 32);++ self.reload_buffer_values();+ while i < values_to_read {+ batch[i] = self+ .get_value(num_bits)+ .expect("expected to have more data");+ i += 1;+ }++ values_to_read+ }++ /// Reads a `num_bytes`-sized value from this buffer and return it.+ /// `T` needs to be a little-endian native type. The value is assumed to be byte+ /// aligned so the bit reader will be advanced to the start of the next byte before+ /// reading the value.++ /// Returns `Some` if there's enough bytes left to form a value of `T`.+ /// Otherwise `None`.+ #[inline]+ pub fn get_aligned<T: Default>(&mut self, num_bytes: usize) -> Option<T> {+ let bytes_read = ceil(self.bit_offset as i64, 8) as usize;+ if self.byte_offset + bytes_read + num_bytes > self.total_bytes {+ return None;+ }++ // Advance byte_offset to next unread byte and read num_bytes+ self.byte_offset += bytes_read;+ let v = read_num_bytes!(+ T,+ num_bytes,+ self.buffer.start_from(self.byte_offset).as_ref()+ );+ self.byte_offset += num_bytes;++ // Reset buffered_values+ self.bit_offset = 0;+ self.reload_buffer_values();+ Some(v)+ }++ /// Reads a VLQ encoded (in little endian order) int from the stream.+ /// The encoded int must start at the beginning of a byte.+ ///+ /// Returns `None` if there's not enough bytes in the stream. `Some` otherwise.+ #[inline]+ pub fn get_vlq_int(&mut self) -> Option<i64> {+ let mut shift = 0;+ let mut v: i64 = 0;+ while let Some(byte) = self.get_aligned::<u8>(1) {+ v |= ((byte & 0x7F) as i64) << shift;+ shift += 7;+ assert!(+ shift <= MAX_VLQ_BYTE_LEN * 7,+ "Num of bytes exceed MAX_VLQ_BYTE_LEN ({})",+ MAX_VLQ_BYTE_LEN+ );+ if byte & 0x80 == 0 {+ return Some(v);+ }+ }+ None+ }++ /// Reads a zigzag-VLQ encoded (in little endian order) int from the stream+ /// Zigzag-VLQ is a variant of VLQ encoding where negative and positive numbers are+ /// encoded in a zigzag fashion.+ /// See: https://developers.google.com/protocol-buffers/docs/encoding+ ///+ /// Note: the encoded int must start at the beginning of a byte.+ ///+ /// Returns `None` if the number of bytes there's not enough bytes in the stream.+ /// `Some` otherwise.+ #[inline]+ pub fn get_zigzag_vlq_int(&mut self) -> Option<i64> {+ self.get_vlq_int().map(|v| {+ let u = v as u64;+ ((u >> 1) as i64 ^ -((u & 1) as i64))+ })+ }++ #[inline]+ fn reload_buffer_values(&mut self) {+ let bytes_to_read = cmp::min(self.total_bytes - self.byte_offset, 8);+ self.buffered_values = read_num_bytes!(+ u64,+ bytes_to_read,+ self.buffer.start_from(self.byte_offset).as_ref()+ );+ }+}++impl From<Vec<u8>> for BitReader {+ #[inline]+ fn from(buffer: Vec<u8>) -> Self {+ BitReader::new(ByteBufferPtr::new(buffer))+ }+}++#[cfg(test)]+mod tests {+ use super::super::test_common::*;+ use super::*;++ use rand::distributions::{Distribution, Standard};+ use std::fmt::Debug;++ #[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);+ }++ #[test]+ fn test_bit_reader_get_byte_offset() {+ let buffer = vec![255; 10];+ let mut bit_reader = BitReader::from(buffer);+ assert_eq!(bit_reader.get_byte_offset(), 0); // offset (0 bytes, 0 bits)+ bit_reader.get_value::<i32>(6);+ assert_eq!(bit_reader.get_byte_offset(), 1); // offset (0 bytes, 6 bits)+ bit_reader.get_value::<i32>(10);+ assert_eq!(bit_reader.get_byte_offset(), 2); // offset (0 bytes, 16 bits)+ bit_reader.get_value::<i32>(20);+ assert_eq!(bit_reader.get_byte_offset(), 5); // offset (0 bytes, 36 bits)+ bit_reader.get_value::<i32>(30);+ assert_eq!(bit_reader.get_byte_offset(), 9); // offset (8 bytes, 2 bits)+ }++ #[test]+ fn test_bit_reader_get_value() {+ let buffer = vec![255, 0];+ let mut bit_reader = BitReader::from(buffer);+ assert_eq!(bit_reader.get_value::<i32>(1), Some(1));+ assert_eq!(bit_reader.get_value::<i32>(2), Some(3));+ assert_eq!(bit_reader.get_value::<i32>(3), Some(7));+ assert_eq!(bit_reader.get_value::<i32>(4), Some(3));+ }++ #[test]+ fn test_bit_reader_get_value_boundary() {+ let buffer = vec![10, 0, 0, 0, 20, 0, 30, 0, 0, 0, 40, 0];+ let mut bit_reader = BitReader::from(buffer);+ assert_eq!(bit_reader.get_value::<i64>(32), Some(10));+ assert_eq!(bit_reader.get_value::<i64>(16), Some(20));+ assert_eq!(bit_reader.get_value::<i64>(32), Some(30));+ assert_eq!(bit_reader.get_value::<i64>(16), Some(40));+ }++ #[test]+ fn test_bit_reader_get_aligned() {+ // 01110101 11001011+ let buffer = ByteBufferPtr::new(vec![0x75, 0xCB]);+ let mut bit_reader = BitReader::new(buffer.all());+ assert_eq!(bit_reader.get_value::<i32>(3), Some(5));+ assert_eq!(bit_reader.get_aligned::<i32>(1), Some(203));+ assert_eq!(bit_reader.get_value::<i32>(1), None);+ bit_reader.reset(buffer.all());+ assert_eq!(bit_reader.get_aligned::<i32>(3), None);+ }++ #[test]+ fn test_bit_reader_get_vlq_int() {+ // 10001001 00000001 11110010 10110101 00000110+ let buffer: Vec<u8> = vec![0x89, 0x01, 0xF2, 0xB5, 0x06];+ let mut bit_reader = BitReader::from(buffer);+ assert_eq!(bit_reader.get_vlq_int(), Some(137));+ assert_eq!(bit_reader.get_vlq_int(), Some(105202));+ }++ #[test]+ fn test_bit_reader_get_zigzag_vlq_int() {+ let buffer: Vec<u8> = vec![0, 1, 2, 3];+ let mut bit_reader = BitReader::from(buffer);+ assert_eq!(bit_reader.get_zigzag_vlq_int(), Some(0));+ assert_eq!(bit_reader.get_zigzag_vlq_int(), Some(-1));+ assert_eq!(bit_reader.get_zigzag_vlq_int(), Some(1));+ assert_eq!(bit_reader.get_zigzag_vlq_int(), Some(-2));+ }++ #[test]+ fn test_set_array_bit() {+ let mut buffer = vec![0, 0, 0];+ set_array_bit(&mut buffer[..], 1);+ assert_eq!(buffer, vec![2, 0, 0]);+ set_array_bit(&mut buffer[..], 4);+ assert_eq!(buffer, vec![18, 0, 0]);+ unset_array_bit(&mut buffer[..], 1);+ assert_eq!(buffer, vec![16, 0, 0]);+ set_array_bit(&mut buffer[..], 10);+ assert_eq!(buffer, vec![16, 4, 0]);+ set_array_bit(&mut buffer[..], 10);+ assert_eq!(buffer, vec![16, 4, 0]);+ set_array_bit(&mut buffer[..], 11);+ assert_eq!(buffer, vec![16, 12, 0]);+ unset_array_bit(&mut buffer[..], 10);+ assert_eq!(buffer, vec![16, 8, 0]);+ }++ #[test]+ fn test_num_required_bits() {+ assert_eq!(num_required_bits(0), 0);+ assert_eq!(num_required_bits(1), 1);+ assert_eq!(num_required_bits(2), 2);+ assert_eq!(num_required_bits(4), 3);+ assert_eq!(num_required_bits(8), 4);+ assert_eq!(num_required_bits(10), 4);+ assert_eq!(num_required_bits(12), 4);+ assert_eq!(num_required_bits(16), 5);+ }++ #[test]+ fn test_log2() {+ assert_eq!(log2(1), 0);+ assert_eq!(log2(2), 1);+ assert_eq!(log2(3), 2);+ assert_eq!(log2(4), 2);+ assert_eq!(log2(5), 3);+ assert_eq!(log2(5), 3);+ assert_eq!(log2(6), 3);+ assert_eq!(log2(7), 3);+ assert_eq!(log2(8), 3);+ assert_eq!(log2(9), 4);+ }++ #[test]+ fn test_skip() {+ let mut writer = BitWriter::new(5);+ let old_offset = writer.skip(1).expect("skip() should return OK");+ writer.put_aligned(42, 4);+ writer.put_aligned_offset(0x10, 1, old_offset);+ let result = writer.consume();+ assert_eq!(result.as_ref(), [0x10, 42, 0, 0, 0]);++ writer = BitWriter::new(4);+ let result = writer.skip(5);+ assert!(result.is_err());+ }++ #[test]+ fn test_get_next_byte_ptr() {+ let mut writer = BitWriter::new(5);+ {+ let first_byte = writer+ .get_next_byte_ptr(1)+ .expect("get_next_byte_ptr() should return OK");+ first_byte[0] = 0x10;+ }+ writer.put_aligned(42, 4);+ let result = writer.consume();+ assert_eq!(result.as_ref(), [0x10, 42, 0, 0, 0]);+ }++ #[test]+ fn test_consume_flush_buffer() {+ let mut writer1 = BitWriter::new(3);+ let mut writer2 = BitWriter::new(3);+ for i in 1..10 {+ writer1.put_value(i, 4);+ writer2.put_value(i, 4);+ }+ let res1 = writer1.flush_buffer();+ let res2 = writer2.consume();+ assert_eq!(res1, &res2[..]);+ }++ #[test]+ fn test_put_get_bool() {+ let len = 8;+ let mut writer = BitWriter::new(len);++ for i in 0..8 {+ let result = writer.put_value(i % 2, 1);+ assert!(result);+ }++ writer.flush();+ {+ let buffer = writer.buffer();+ assert_eq!(buffer[0], 0b10101010);+ }++ // Write 00110011+ for i in 0..8 {+ let result = match i {+ 0 | 1 | 4 | 5 => writer.put_value(false as u64, 1),+ _ => writer.put_value(true as u64, 1),+ };+ assert!(result);+ }+ writer.flush();+ {+ let buffer = writer.buffer();+ assert_eq!(buffer[0], 0b10101010);+ assert_eq!(buffer[1], 0b11001100);+ }++ let mut reader = BitReader::from(writer.consume());++ for i in 0..8 {+ let val = reader+ .get_value::<u8>(1)+ .expect("get_value() should return OK");+ assert_eq!(val, i % 2);+ }++ for i in 0..8 {+ let val = reader+ .get_value::<bool>(1)+ .expect("get_value() should return OK");+ match i {+ 0 | 1 | 4 | 5 => assert_eq!(val, false),+ _ => assert_eq!(val, true),+ }+ }+ }++ #[test]+ fn test_put_value_roundtrip() {+ test_put_value_rand_numbers(32, 2);+ test_put_value_rand_numbers(32, 3);+ test_put_value_rand_numbers(32, 4);+ test_put_value_rand_numbers(32, 5);+ test_put_value_rand_numbers(32, 6);+ test_put_value_rand_numbers(32, 7);+ test_put_value_rand_numbers(32, 8);+ test_put_value_rand_numbers(64, 16);+ test_put_value_rand_numbers(64, 24);+ test_put_value_rand_numbers(64, 32);+ }++ fn test_put_value_rand_numbers(total: usize, num_bits: usize) {+ assert!(num_bits < 64);+ let num_bytes = ceil(num_bits as i64, 8);+ let mut writer = BitWriter::new(num_bytes as usize * total);+ let values: Vec<u64> = random_numbers::<u64>(total)+ .iter()+ .map(|v| v & ((1 << num_bits) - 1))+ .collect();+ for i in 0..total {+ assert!(+ writer.put_value(values[i] as u64, num_bits),+ "[{}]: put_value() failed",+ i+ );+ }++ let mut reader = BitReader::from(writer.consume());+ for i in 0..total {+ let v = reader+ .get_value::<u64>(num_bits)+ .expect("get_value() should return OK");+ assert_eq!(+ v, values[i],+ "[{}]: expected {} but got {}",+ i, values[i], v+ );+ }+ }++ #[test]+ fn test_get_batch() {+ const SIZE: &[usize] = &[1, 31, 32, 33, 128, 129];+ for s in SIZE {+ for i in 0..33 {+ match i {+ 0...8 => test_get_batch_helper::<u8>(*s, i),+ 9...16 => test_get_batch_helper::<u16>(*s, i),+ _ => test_get_batch_helper::<u32>(*s, i),+ }+ }+ }+ }++ fn test_get_batch_helper<T>(total: usize, num_bits: usize)+ where+ T: Default + Clone + Debug + Eq,+ {+ assert!(num_bits <= 32);+ let num_bytes = ceil(num_bits as i64, 8);+ let mut writer = BitWriter::new(num_bytes as usize * total);++ let values: Vec<u32> = random_numbers::<u32>(total)+ .iter()+ .map(|v| v & ((1u64 << num_bits) - 1) as u32)+ .collect();++ // Generic values used to check against actual values read from `get_batch`.+ let expected_values: Vec<T> = values+ .iter()+ .map(|v| unsafe { transmute_copy::<u32, T>(&v) })+ .collect();++ for i in 0..total {+ assert!(writer.put_value(values[i] as u64, num_bits));+ }++ let buf = writer.consume();+ let mut reader = BitReader::from(buf);+ let mut batch = vec![T::default(); values.len()];+ let values_read = reader.get_batch::<T>(&mut batch, num_bits);+ assert_eq!(values_read, values.len());+ for i in 0..batch.len() {+ assert_eq!(+ batch[i], expected_values[i],+ "num_bits = {}, index = {}",+ num_bits, i+ );+ }+ }++ #[test]+ fn test_put_aligned_roundtrip() {+ test_put_aligned_rand_numbers::<u8>(4, 3);+ test_put_aligned_rand_numbers::<u8>(16, 5);+ test_put_aligned_rand_numbers::<i16>(32, 7);+ test_put_aligned_rand_numbers::<i16>(32, 9);+ test_put_aligned_rand_numbers::<i32>(32, 11);+ test_put_aligned_rand_numbers::<i32>(32, 13);+ test_put_aligned_rand_numbers::<i64>(32, 17);+ test_put_aligned_rand_numbers::<i64>(32, 23);+ }++ fn test_put_aligned_rand_numbers<T>(total: usize, num_bits: usize)+ where+ T: Copy + Default + Debug + PartialEq,+ Standard: Distribution<T>,+ {+ assert!(num_bits <= 32);+ assert!(total % 2 == 0);++ let aligned_value_byte_width = ::std::mem::size_of::<T>();+ let value_byte_width = ceil(num_bits as i64, 8) as usize;+ let mut writer =+ BitWriter::new((total / 2) * (aligned_value_byte_width + value_byte_width));+ let values: Vec<u32> = random_numbers::<u32>(total / 2)+ .iter()+ .map(|v| v & ((1 << num_bits) - 1))+ .collect();+ let aligned_values = random_numbers::<T>(total / 2);++ for i in 0..total {+ let j = i / 2;+ if i % 2 == 0 {+ assert!(+ writer.put_value(values[j] as u64, num_bits),+ "[{}]: put_value() failed",+ i+ );+ } else {+ assert!(+ writer.put_aligned::<T>(aligned_values[j], aligned_value_byte_width),+ "[{}]: put_aligned() failed",+ i+ );+ }+ }++ let mut reader = BitReader::from(writer.consume());+ for i in 0..total {+ let j = i / 2;+ if i % 2 == 0 {+ let v = reader+ .get_value::<u64>(num_bits)+ .expect("get_value() should return OK");+ assert_eq!(+ v, values[j] as u64,+ "[{}]: expected {} but got {}",+ i, values[j], v+ );+ } else {+ let v = reader+ .get_aligned::<T>(aligned_value_byte_width)+ .expect("get_aligned() should return OK");+ assert_eq!(+ v, aligned_values[j],+ "[{}]: expected {:?} but got {:?}",+ i, aligned_values[j], v+ );+ }+ }+ }++ #[test]+ fn test_put_vlq_int() {+ let total = 64;+ let mut writer = BitWriter::new(total * 32);+ let values = random_numbers::<u32>(total);+ for i in 0..total {+ assert!(+ writer.put_vlq_int(values[i] as u64),+ "[{}]; put_vlq_int() failed",+ i+ );+ }++ let mut reader = BitReader::from(writer.consume());+ for i in 0..total {+ let v = reader+ .get_vlq_int()+ .expect("get_vlq_int() should return OK");+ assert_eq!(+ v as u32, values[i],+ "[{}]: expected {} but got {}",+ i, values[i], v+ );+ }+ }++ #[test]+ fn test_put_zigzag_vlq_int() {+ let total = 64;+ let mut writer = BitWriter::new(total * 32);+ let values = random_numbers::<i32>(total);+ for i in 0..total {+ assert!(+ writer.put_zigzag_vlq_int(values[i] as i64),+ "[{}]; put_zigzag_vlq_int() failed",+ i+ );+ }++ let mut reader = BitReader::from(writer.consume());+ for i in 0..total {+ let v = reader+ .get_zigzag_vlq_int()+ .expect("get_zigzag_vlq_int() should return OK");+ assert_eq!(+ v as i32, values[i],+ "[{}]: expected {} but got {}",+ i, values[i], v+ );+ }+ }+}diff --git a/rust/src/parquet/util/hash_util.rs b/rust/src/parquet/util/hash_util.rsnew file mode 100644index 0000000000..c7bffef8bb--- /dev/null+++ b/rust/src/parquet/util/hash_util.rs@@ -0,0 +1,160 @@+// Licensed to the Apache Software Foundation (ASF) under one+// or more contributor license agreements. See the NOTICE file+// distributed with this work for additional information+// regarding copyright ownership. The ASF licenses this file+// to you under the Apache License, Version 2.0 (the+// "License"); you may not use this file except in compliance+// with the License. You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing,+// software distributed under the License is distributed on an+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+// KIND, either express or implied. See the License for the+// specific language governing permissions and limitations+// under the License.++use crate::parquet::data_type::AsBytes;++/// Computes hash value for `data`, with a seed value `seed`.+/// The data type `T` must implement the `AsBytes` trait.+pub fn hash<T: AsBytes>(data: &T, seed: u32) -> u32 {+ #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]+ {+ if is_x86_feature_detected!("sse4.2") {+ unsafe { crc32_hash(data, seed) }+ } else {+ murmur_hash2_64a(data, seed as u64) as u32+ }+ }+}++const MURMUR_PRIME: u64 = 0xc6a4a7935bd1e995;+const MURMUR_R: i32 = 47;++/// Rust implementation of MurmurHash2, 64-bit version for 64-bit platforms+fn murmur_hash2_64a<T: AsBytes>(data: &T, seed: u64) -> u64 {+ let data_bytes = data.as_bytes();+ let len = data_bytes.len();+ let len_64 = (len / 8) * 8;+ let data_bytes_64 = unsafe {+ ::std::slice::from_raw_parts(&data_bytes[0..len_64] as *const [u8] as *const u64, len / 8)+ };++ let mut h = seed ^ (MURMUR_PRIME.wrapping_mul(data_bytes.len() as u64));+ for v in data_bytes_64 {+ let mut k = *v;+ k = k.wrapping_mul(MURMUR_PRIME);+ k ^= k >> MURMUR_R;+ k = k.wrapping_mul(MURMUR_PRIME);+ h ^= k;+ h = h.wrapping_mul(MURMUR_PRIME);+ }++ let data2 = &data_bytes[len_64..];++ let v = len & 7;+ if v == 7 {+ h ^= (data2[6] as u64) << 48;+ }+ if v >= 6 {+ h ^= (data2[5] as u64) << 40;+ }+ if v >= 5 {+ h ^= (data2[4] as u64) << 32;+ }+ if v >= 4 {+ h ^= (data2[3] as u64) << 24;+ }+ if v >= 3 {+ h ^= (data2[2] as u64) << 16;+ }+ if v >= 2 {+ h ^= (data2[1] as u64) << 8;+ }+ if v >= 1 {+ h ^= data2[0] as u64;+ }+ if v > 0 {+ h = h.wrapping_mul(MURMUR_PRIME);+ }++ h ^= h >> MURMUR_R;+ h = h.wrapping_mul(MURMUR_PRIME);+ h ^= h >> MURMUR_R;+ h+}++/// CRC32 hash implementation using SSE4 instructions. Borrowed from Impala.+#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]+#[target_feature(enable = "sse4.2")]+unsafe fn crc32_hash<T: AsBytes>(data: &T, seed: u32) -> u32 {+ #[cfg(target_arch = "x86")]+ use std::arch::x86::*;+ #[cfg(target_arch = "x86_64")]+ use std::arch::x86_64::*;++ let bytes: &[u8] = data.as_bytes();+ let u32_num_bytes = ::std::mem::size_of::<u32>();+ let mut num_bytes = bytes.len();+ let num_words = num_bytes / u32_num_bytes;+ num_bytes %= u32_num_bytes;++ let bytes_u32: &[u32] = ::std::slice::from_raw_parts(+ &bytes[0..num_words * u32_num_bytes] as *const [u8] as *const u32,+ num_words,+ );++ let mut offset = 0;+ let mut hash = seed;+ while offset < num_words {+ hash = _mm_crc32_u32(hash, bytes_u32[offset]);+ offset += 1;+ }++ offset = num_words * u32_num_bytes;+ while offset < num_bytes {+ hash = _mm_crc32_u8(hash, bytes[offset]);+ offset += 1;+ }++ // The lower half of the CRC hash has poor uniformity, so swap the halves+ // for anyone who only uses the first several bits of the hash.+ hash = (hash << 16) | (hash >> 16);+ hash+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_murmur2_64a() {+ let result = murmur_hash2_64a(&"hello", 123);+ assert_eq!(result, 2597646618390559622);++ let result = murmur_hash2_64a(&"helloworld", 123);+ assert_eq!(result, 4934371746140206573);++ let result = murmur_hash2_64a(&"helloworldparquet", 123);+ assert_eq!(result, 2392198230801491746);+ }++ #[test]+ #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]+ fn test_crc32() {+ if is_x86_feature_detected!("sse4.2") {+ unsafe {+ let result = crc32_hash(&"hello", 123);+ assert_eq!(result, 2927487359);++ let result = crc32_hash(&"helloworld", 123);+ assert_eq!(result, 314229527);++ let result = crc32_hash(&"helloworldparquet", 123);+ assert_eq!(result, 667078870);+ }+ }+ }+}diff --git a/rust/src/parquet/util/io.rs b/rust/src/parquet/util/io.rsnew file mode 100644index 0000000000..8724e67c2d--- /dev/null+++ b/rust/src/parquet/util/io.rs@@ -0,0 +1,220 @@+// 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, fs::File, io::*, sync::Mutex};++use crate::parquet::file::reader::ParquetReader;++// ----------------------------------------------------------------------+// Read/Write wrappers for `File`.++/// Position trait returns the current position in the stream.+/// Should be viewed as a lighter version of `Seek` that does not allow seek operations,+/// and does not require mutable reference for the current position.+pub trait Position {+ /// Returns position in the stream.+ fn pos(&self) -> u64;+}++/// Struct that represents a slice of a file data with independent start position and+/// length. Internally clones provided file handle, wraps with BufReader and resets+/// position before any read.+///+/// This is workaround and alternative for `file.try_clone()` method. It clones `File`+/// while preserving independent position, which is not available with `try_clone()`.+///+/// Designed after `arrow::io::RandomAccessFile`.+pub struct FileSource<R: ParquetReader> {+ reader: Mutex<BufReader<R>>,+ start: u64, // start position in a file+ end: u64, // end position in a file+}++impl<R: ParquetReader> FileSource<R> {+ /// Creates new file reader with start and length from a file handle+ pub fn new(fd: &R, start: u64, length: usize) -> Self {+ Self {+ reader: Mutex::new(BufReader::new(fd.try_clone().unwrap())),+ start,+ end: start + length as u64,+ }+ }+}++impl<R: ParquetReader> Read for FileSource<R> {+ fn read(&mut self, buf: &mut [u8]) -> Result<usize> {+ let mut reader = self+ .reader+ .lock()+ .map_err(|err| Error::new(ErrorKind::Other, err.to_string()))?;++ let bytes_to_read = cmp::min(buf.len(), (self.end - self.start) as usize);+ let buf = &mut buf[0..bytes_to_read];++ reader.seek(SeekFrom::Start(self.start as u64))?;+ let res = reader.read(buf);+ if let Ok(bytes_read) = res {+ self.start += bytes_read as u64;+ }++ res+ }+}++impl<R: ParquetReader> Position for FileSource<R> {+ fn pos(&self) -> u64 {+ self.start+ }+}++/// Struct that represents `File` output stream with position tracking.+/// Used as a sink in file writer.+pub struct FileSink {+ buf: BufWriter<File>,+ // This is not necessarily position in the underlying file,+ // but rather current position in the sink.+ pos: u64,+}++impl FileSink {+ /// Creates new file sink.+ /// Position is set to whatever position file has.+ pub fn new(file: &File) -> Self {+ let mut owned_file = file.try_clone().unwrap();+ let pos = owned_file.seek(SeekFrom::Current(0)).unwrap();+ Self {+ buf: BufWriter::new(owned_file),+ pos,+ }+ }+}++impl Write for FileSink {+ fn write(&mut self, buf: &[u8]) -> Result<usize> {+ let num_bytes = self.buf.write(buf)?;+ self.pos += num_bytes as u64;+ Ok(num_bytes)+ }++ fn flush(&mut self) -> Result<()> {+ self.buf.flush()+ }+}++impl Position for FileSink {+ fn pos(&self) -> u64 {+ self.pos+ }+}++// Position implementation for Cursor to use in various tests.+impl<'a> Position for Cursor<&'a mut Vec<u8>> {+ fn pos(&self) -> u64 {+ self.position()+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ use crate::parquet::util::test_common::{get_temp_file, get_test_file};++ #[test]+ fn test_io_read_fully() {+ let mut buf = vec![0; 8];+ let mut src = FileSource::new(&get_test_file("alltypes_plain.parquet"), 0, 4);++ let bytes_read = src.read(&mut buf[..]).unwrap();+ assert_eq!(bytes_read, 4);+ assert_eq!(buf, vec![b'P', b'A', b'R', b'1', 0, 0, 0, 0]);+ }++ #[test]+ fn test_io_read_in_chunks() {+ let mut buf = vec![0; 4];+ let mut src = FileSource::new(&get_test_file("alltypes_plain.parquet"), 0, 4);++ let bytes_read = src.read(&mut buf[0..2]).unwrap();+ assert_eq!(bytes_read, 2);+ let bytes_read = src.read(&mut buf[2..]).unwrap();+ assert_eq!(bytes_read, 2);+ assert_eq!(buf, vec![b'P', b'A', b'R', b'1']);+ }++ #[test]+ fn test_io_read_pos() {+ let mut src = FileSource::new(&get_test_file("alltypes_plain.parquet"), 0, 4);++ src.read(&mut vec![0; 1]).unwrap();+ assert_eq!(src.pos(), 1);++ src.read(&mut vec![0; 4]).unwrap();+ assert_eq!(src.pos(), 4);+ }++ #[test]+ fn test_io_read_over_limit() {+ let mut src = FileSource::new(&get_test_file("alltypes_plain.parquet"), 0, 4);++ // Read all bytes from source+ src.read(&mut vec![0; 128]).unwrap();+ assert_eq!(src.pos(), 4);++ // Try reading again, should return 0 bytes.+ let bytes_read = src.read(&mut vec![0; 128]).unwrap();+ assert_eq!(bytes_read, 0);+ assert_eq!(src.pos(), 4);+ }++ #[test]+ fn test_io_seek_switch() {+ let mut buf = vec![0; 4];+ let mut file = get_test_file("alltypes_plain.parquet");+ let mut src = FileSource::new(&file, 0, 4);++ file.seek(SeekFrom::Start(5 as u64))+ .expect("File seek to a position");++ let bytes_read = src.read(&mut buf[..]).unwrap();+ assert_eq!(bytes_read, 4);+ assert_eq!(buf, vec![b'P', b'A', b'R', b'1']);+ }++ #[test]+ fn test_io_write_with_pos() {+ let mut file = get_temp_file("file_sink_test", &[b'a', b'b', b'c']);+ file.seek(SeekFrom::Current(3)).unwrap();++ // Write into sink+ let mut sink = FileSink::new(&file);+ assert_eq!(sink.pos(), 3);++ sink.write(&[b'd', b'e', b'f', b'g']).unwrap();+ assert_eq!(sink.pos(), 7);++ sink.flush().unwrap();+ assert_eq!(sink.pos(), file.seek(SeekFrom::Current(0)).unwrap());++ // Read data using file chunk+ let mut res = vec![0u8; 7];+ let mut chunk = FileSource::new(&file, 0, file.metadata().unwrap().len() as usize);+ chunk.read(&mut res[..]).unwrap();++ assert_eq!(res, vec![b'a', b'b', b'c', b'd', b'e', b'f', b'g']);+ }+}diff --git a/rust/src/parquet/util/memory.rs b/rust/src/parquet/util/memory.rsnew file mode 100644index 0000000000..69a389e50f--- /dev/null+++ b/rust/src/parquet/util/memory.rs@@ -0,0 +1,524 @@+// 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.++//! Utility methods and structs for working with memory.++use std::{+ cell::Cell,+ fmt::{Debug, Display, Formatter, Result as FmtResult},+ io::{Result as IoResult, Write},+ mem,+ ops::{Index, IndexMut},+ rc::{Rc, Weak},+};++// ----------------------------------------------------------------------+// Memory Tracker classes++/// Reference counted pointer for [`MemTracker`].+pub type MemTrackerPtr = Rc<MemTracker>;+/// Non-owning reference for [`MemTracker`].+pub type WeakMemTrackerPtr = Weak<MemTracker>;++/// Struct to track memory usage information.+#[derive(Debug)]+pub struct MemTracker {+ // In the tuple, the first element is the current memory allocated (in bytes),+ // and the second element is the maximum memory allocated so far (in bytes).+ memory_usage: Cell<(i64, i64)>,+}++impl MemTracker {+ /// Creates new memory tracker.+ #[inline]+ pub fn new() -> MemTracker {+ MemTracker {+ memory_usage: Cell::new((0, 0)),+ }+ }++ /// Returns the current memory consumption, in bytes.+ pub fn memory_usage(&self) -> i64 {+ self.memory_usage.get().0+ }++ /// Returns the maximum memory consumption so far, in bytes.+ pub fn max_memory_usage(&self) -> i64 {+ self.memory_usage.get().1+ }++ /// Adds `num_bytes` to the memory consumption tracked by this memory tracker.+ #[inline]+ pub fn alloc(&self, num_bytes: i64) {+ let (current, mut maximum) = self.memory_usage.get();+ let new_current = current + num_bytes;+ if new_current > maximum {+ maximum = new_current+ }+ self.memory_usage.set((new_current, maximum));+ }+}++// ----------------------------------------------------------------------+// Buffer classes++/// Type alias for [`Buffer`].+pub type ByteBuffer = Buffer<u8>;+/// Type alias for [`BufferPtr`].+pub type ByteBufferPtr = BufferPtr<u8>;++/// A resize-able buffer class with generic member, with optional memory tracker.+///+/// Note that a buffer has two attributes:+/// `capacity` and `size`: the former is the total number of space reserved for+/// the buffer, while the latter is the actual number of elements.+/// Invariant: `capacity` >= `size`.+/// The total allocated bytes for a buffer equals to `capacity * sizeof<T>()`.+pub struct Buffer<T: Clone> {+ data: Vec<T>,+ mem_tracker: Option<MemTrackerPtr>,+ type_length: usize,+}++impl<T: Clone> Buffer<T> {+ /// Creates new empty buffer.+ pub fn new() -> Self {+ Buffer {+ data: vec![],+ mem_tracker: None,+ type_length: ::std::mem::size_of::<T>(),+ }+ }++ /// Adds [`MemTracker`] for this buffer.+ #[inline]+ pub fn with_mem_tracker(mut self, mc: MemTrackerPtr) -> Self {+ mc.alloc((self.data.capacity() * self.type_length) as i64);+ self.mem_tracker = Some(mc);+ self+ }++ /// Returns slice of data in this buffer.+ #[inline]+ pub fn data(&self) -> &[T] {+ self.data.as_slice()+ }++ /// Sets data for this buffer.+ #[inline]+ pub fn set_data(&mut self, new_data: Vec<T>) {+ if let Some(ref mc) = self.mem_tracker {+ let capacity_diff = new_data.capacity() as i64 - self.data.capacity() as i64;+ mc.alloc(capacity_diff * self.type_length as i64);+ }+ self.data = new_data;+ }++ /// Resizes underlying data in place to a new length `new_size`.+ ///+ /// If `new_size` is less than current length, data is truncated, otherwise, it is+ /// extended to `new_size` with provided default value `init_value`.+ ///+ /// Memory tracker is also updated, if available.+ #[inline]+ pub fn resize(&mut self, new_size: usize, init_value: T) {+ let old_capacity = self.data.capacity();+ self.data.resize(new_size, init_value);+ if let Some(ref mc) = self.mem_tracker {+ let capacity_diff = self.data.capacity() as i64 - old_capacity as i64;+ mc.alloc(capacity_diff * self.type_length as i64);+ }+ }++ /// Clears underlying data.+ #[inline]+ pub fn clear(&mut self) {+ self.data.clear()+ }++ /// Reserves capacity `additional_capacity` for underlying data vector.+ ///+ /// Memory tracker is also updated, if available.+ #[inline]+ pub fn reserve(&mut self, additional_capacity: usize) {+ let old_capacity = self.data.capacity();+ self.data.reserve(additional_capacity);+ if self.data.capacity() > old_capacity {+ if let Some(ref mc) = self.mem_tracker {+ let capacity_diff = self.data.capacity() as i64 - old_capacity as i64;+ mc.alloc(capacity_diff * self.type_length as i64);+ }+ }+ }++ /// Returns [`BufferPtr`] with buffer data.+ /// Buffer data is reset.+ #[inline]+ pub fn consume(&mut self) -> BufferPtr<T> {+ let old_data = mem::replace(&mut self.data, vec![]);+ let mut result = BufferPtr::new(old_data);+ if let Some(ref mc) = self.mem_tracker {+ result = result.with_mem_tracker(mc.clone());+ }+ result+ }++ /// Adds `value` to the buffer.+ #[inline]+ pub fn push(&mut self, value: T) {+ self.data.push(value)+ }++ /// Returns current capacity for the buffer.+ #[inline]+ pub fn capacity(&self) -> usize {+ self.data.capacity()+ }++ /// Returns current size for the buffer.+ #[inline]+ pub fn size(&self) -> usize {+ self.data.len()+ }++ /// Returns `true` if memory tracker is added to buffer, `false` otherwise.+ #[inline]+ pub fn is_mem_tracked(&self) -> bool {+ self.mem_tracker.is_some()+ }++ /// Returns memory tracker associated with this buffer.+ /// This may panic, if memory tracker is not set, use method above to check if+ /// memory tracker is available.+ #[inline]+ pub fn mem_tracker(&self) -> &MemTrackerPtr {+ self.mem_tracker.as_ref().unwrap()+ }+}++impl<T: Sized + Clone> Index<usize> for Buffer<T> {+ type Output = T;++ fn index(&self, index: usize) -> &T {+ &self.data[index]+ }+}++impl<T: Sized + Clone> IndexMut<usize> for Buffer<T> {+ fn index_mut(&mut self, index: usize) -> &mut T {+ &mut self.data[index]+ }+}++// TODO: implement this for other types+impl Write for Buffer<u8> {+ #[inline]+ fn write(&mut self, buf: &[u8]) -> IoResult<usize> {+ let old_capacity = self.data.capacity();+ let bytes_written = self.data.write(buf)?;+ if let Some(ref mc) = self.mem_tracker {+ if self.data.capacity() - old_capacity > 0 {+ mc.alloc((self.data.capacity() - old_capacity) as i64)+ }+ }+ Ok(bytes_written)+ }++ fn flush(&mut self) -> IoResult<()> {+ // No-op+ self.data.flush()+ }+}++impl AsRef<[u8]> for Buffer<u8> {+ fn as_ref(&self) -> &[u8] {+ self.data.as_slice()+ }+}++impl<T: Clone> Drop for Buffer<T> {+ #[inline]+ fn drop(&mut self) {+ if let Some(ref mc) = self.mem_tracker {+ mc.alloc(-((self.data.capacity() * self.type_length) as i64));+ }+ }+}++// ----------------------------------------------------------------------+// Immutable Buffer (BufferPtr) classes++/// An representation of a slice on a reference-counting and read-only byte array.+/// Sub-slices can be further created from this. The byte array will be released+/// when all slices are dropped.+#[derive(Clone, Debug)]+pub struct BufferPtr<T> {+ data: Rc<Vec<T>>,+ start: usize,+ len: usize,+ // TODO: will this create too many references? rethink about this.+ mem_tracker: Option<MemTrackerPtr>,+}++impl<T> BufferPtr<T> {+ /// Creates new buffer from a vector.+ pub fn new(v: Vec<T>) -> Self {+ let len = v.len();+ Self {+ data: Rc::new(v),+ start: 0,+ len,+ mem_tracker: None,+ }+ }++ /// Returns slice of data in this buffer.+ pub fn data(&self) -> &[T] {+ &self.data[self.start..self.start + self.len]+ }++ /// Updates this buffer with new `start` position and length `len`.+ ///+ /// Range should be within current start position and length.+ pub fn with_range(mut self, start: usize, len: usize) -> Self {+ assert!(start <= self.len);+ assert!(start + len <= self.len);+ self.start = start;+ self.len = len;+ self+ }++ /// Adds memory tracker to this buffer.+ pub fn with_mem_tracker(mut self, mc: MemTrackerPtr) -> Self {+ self.mem_tracker = Some(mc);+ self+ }++ /// Returns start position of this buffer.+ pub fn start(&self) -> usize {+ self.start+ }++ /// Returns length of this buffer+ pub fn len(&self) -> usize {+ self.len+ }++ /// Returns `true` if this buffer has memory tracker, `false` otherwise.+ pub fn is_mem_tracked(&self) -> bool {+ self.mem_tracker.is_some()+ }++ /// Returns a shallow copy of the buffer.+ /// Reference counted pointer to the data is copied.+ pub fn all(&self) -> BufferPtr<T> {+ BufferPtr {+ data: self.data.clone(),+ start: self.start,+ len: self.len,+ mem_tracker: self.mem_tracker.as_ref().map(|p| p.clone()),+ }+ }++ /// Returns a shallow copy of the buffer that starts with `start` position.+ pub fn start_from(&self, start: usize) -> BufferPtr<T> {+ assert!(start <= self.len);+ BufferPtr {+ data: self.data.clone(),+ start: self.start + start,+ len: self.len - start,+ mem_tracker: self.mem_tracker.as_ref().map(|p| p.clone()),+ }+ }++ /// Returns a shallow copy that is a range slice within this buffer.+ pub fn range(&self, start: usize, len: usize) -> BufferPtr<T> {+ assert!(start + len <= self.len);+ BufferPtr {+ data: self.data.clone(),+ start: self.start + start,+ len,+ mem_tracker: self.mem_tracker.as_ref().map(|p| p.clone()),+ }+ }+}++impl<T: Sized> Index<usize> for BufferPtr<T> {+ type Output = T;++ fn index(&self, index: usize) -> &T {+ assert!(index < self.len);+ &self.data[self.start + index]+ }+}++impl<T: Debug> Display for BufferPtr<T> {+ fn fmt(&self, f: &mut Formatter) -> FmtResult {+ write!(f, "{:?}", self.data)+ }+}++impl<T> Drop for BufferPtr<T> {+ fn drop(&mut self) {+ if self.is_mem_tracked()+ && Rc::strong_count(&self.data) == 1+ && Rc::weak_count(&self.data) == 0+ {+ let mc = self.mem_tracker.as_ref().unwrap();+ mc.alloc(-(self.data.capacity() as i64));+ }+ }+}++impl AsRef<[u8]> for BufferPtr<u8> {+ fn as_ref(&self) -> &[u8] {+ &self.data[self.start..self.start + self.len]+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_byte_buffer_mem_tracker() {+ let mem_tracker = Rc::new(MemTracker::new());++ let mut buffer = ByteBuffer::new().with_mem_tracker(mem_tracker.clone());+ buffer.set_data(vec![0; 10]);+ assert_eq!(mem_tracker.memory_usage(), buffer.capacity() as i64);+ buffer.set_data(vec![0; 20]);+ let capacity = buffer.capacity() as i64;+ assert_eq!(mem_tracker.memory_usage(), capacity);++ let max_capacity = {+ let mut buffer2 = ByteBuffer::new().with_mem_tracker(mem_tracker.clone());+ buffer2.reserve(30);+ assert_eq!(+ mem_tracker.memory_usage(),+ buffer2.capacity() as i64 + capacity+ );+ buffer2.set_data(vec![0; 100]);+ assert_eq!(+ mem_tracker.memory_usage(),+ buffer2.capacity() as i64 + capacity+ );+ buffer2.capacity() as i64 + capacity+ };++ assert_eq!(mem_tracker.memory_usage(), capacity);+ assert_eq!(mem_tracker.max_memory_usage(), max_capacity);++ buffer.reserve(40);+ assert_eq!(mem_tracker.memory_usage(), buffer.capacity() as i64);++ buffer.consume();+ assert_eq!(mem_tracker.memory_usage(), buffer.capacity() as i64);+ }++ #[test]+ fn test_byte_ptr_mem_tracker() {+ let mem_tracker = Rc::new(MemTracker::new());++ let mut buffer = ByteBuffer::new().with_mem_tracker(mem_tracker.clone());+ buffer.set_data(vec![0; 60]);++ {+ let buffer_capacity = buffer.capacity() as i64;+ let buf_ptr = buffer.consume();+ assert_eq!(mem_tracker.memory_usage(), buffer_capacity);+ {+ let buf_ptr1 = buf_ptr.all();+ {+ let _ = buf_ptr.start_from(20);+ assert_eq!(mem_tracker.memory_usage(), buffer_capacity);+ }+ assert_eq!(mem_tracker.memory_usage(), buffer_capacity);+ let _ = buf_ptr1.range(30, 20);+ assert_eq!(mem_tracker.memory_usage(), buffer_capacity);+ }+ assert_eq!(mem_tracker.memory_usage(), buffer_capacity);+ }+ assert_eq!(mem_tracker.memory_usage(), buffer.capacity() as i64);+ }++ #[test]+ fn test_byte_buffer() {+ let mut buffer = ByteBuffer::new();+ assert_eq!(buffer.size(), 0);+ assert_eq!(buffer.capacity(), 0);++ let mut buffer2 = ByteBuffer::new();+ buffer2.reserve(40);+ assert_eq!(buffer2.size(), 0);+ assert_eq!(buffer2.capacity(), 40);++ buffer.set_data((0..5).collect());+ assert_eq!(buffer.size(), 5);+ assert_eq!(buffer[4], 4);++ buffer.set_data((0..20).collect());+ assert_eq!(buffer.size(), 20);+ assert_eq!(buffer[10], 10);++ let expected: Vec<u8> = (0..20).collect();+ {+ let data = buffer.data();+ assert_eq!(data, expected.as_slice());+ }++ buffer.reserve(40);+ assert!(buffer.capacity() >= 40);++ let byte_ptr = buffer.consume();+ assert_eq!(buffer.size(), 0);+ assert_eq!(byte_ptr.as_ref(), expected.as_slice());++ let values: Vec<u8> = (0..30).collect();+ let _ = buffer.write(values.as_slice());+ let _ = buffer.flush();++ assert_eq!(buffer.data(), values.as_slice());+ }++ #[test]+ fn test_byte_ptr() {+ let values = (0..50).collect();+ let ptr = ByteBufferPtr::new(values);+ assert_eq!(ptr.len(), 50);+ assert_eq!(ptr.start(), 0);+ assert_eq!(ptr[40], 40);++ let ptr2 = ptr.all();+ assert_eq!(ptr2.len(), 50);+ assert_eq!(ptr2.start(), 0);+ assert_eq!(ptr2[40], 40);++ let ptr3 = ptr.start_from(20);+ assert_eq!(ptr3.len(), 30);+ assert_eq!(ptr3.start(), 20);+ assert_eq!(ptr3[0], 20);++ let ptr4 = ptr3.range(10, 10);+ assert_eq!(ptr4.len(), 10);+ assert_eq!(ptr4.start(), 30);+ assert_eq!(ptr4[0], 30);++ let expected: Vec<u8> = (30..40).collect();+ assert_eq!(ptr4.as_ref(), expected.as_slice());+ }+}diff --git a/rust/src/parquet/util/mod.rs b/rust/src/parquet/util/mod.rsnew file mode 100644index 0000000000..669cc3c0a4--- /dev/null+++ b/rust/src/parquet/util/mod.rs@@ -0,0 +1,26 @@+// 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 io;+pub mod memory;+#[macro_use]+pub mod bit_util;+mod bit_packing;+pub mod hash_util;++#[cfg(test)]+pub mod test_common;diff --git a/rust/src/parquet/util/test_common.rs b/rust/src/parquet/util/test_common.rsnew file mode 100644index 0000000000..f9b1af4a5c--- /dev/null+++ b/rust/src/parquet/util/test_common.rs@@ -0,0 +1,190 @@+// 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::{+ distributions::{range::SampleRange, Distribution, Standard},+ thread_rng, Rng,+};+use std::{env, fs, io::Write, path::PathBuf, str::FromStr};++use crate::parquet::data_type::*;+use crate::parquet::util::memory::ByteBufferPtr;++/// Random generator of data type `T` values and sequences.+pub trait RandGen<T: DataType> {+ fn gen(len: i32) -> T::T;++ fn gen_vec(len: i32, total: usize) -> Vec<T::T> {+ let mut result = vec![];+ for _ in 0..total {+ result.push(Self::gen(len))+ }+ result+ }+}++impl<T: DataType> RandGen<T> for T {+ default fn gen(_: i32) -> T::T {+ panic!("Unsupported data type");+ }+}++impl RandGen<BoolType> for BoolType {+ fn gen(_: i32) -> bool {+ thread_rng().gen::<bool>()+ }+}++impl RandGen<Int32Type> for Int32Type {+ fn gen(_: i32) -> i32 {+ thread_rng().gen::<i32>()+ }+}++impl RandGen<Int64Type> for Int64Type {+ fn gen(_: i32) -> i64 {+ thread_rng().gen::<i64>()+ }+}++impl RandGen<Int96Type> for Int96Type {+ fn gen(_: i32) -> Int96 {+ let mut rng = thread_rng();+ let mut result = Int96::new();+ result.set_data(rng.gen::<u32>(), rng.gen::<u32>(), rng.gen::<u32>());+ result+ }+}++impl RandGen<FloatType> for FloatType {+ fn gen(_: i32) -> f32 {+ thread_rng().gen::<f32>()+ }+}++impl RandGen<DoubleType> for DoubleType {+ fn gen(_: i32) -> f64 {+ thread_rng().gen::<f64>()+ }+}++impl RandGen<ByteArrayType> for ByteArrayType {+ fn gen(_: i32) -> ByteArray {+ let mut rng = thread_rng();+ let mut result = ByteArray::new();+ let mut value = vec![];+ let len = rng.gen_range::<usize>(0, 128);+ for _ in 0..len {+ value.push(rng.gen_range(0, 255) & 0xFF);+ }+ result.set_data(ByteBufferPtr::new(value));+ result+ }+}++impl RandGen<FixedLenByteArrayType> for FixedLenByteArrayType {+ fn gen(len: i32) -> ByteArray {+ let mut rng = thread_rng();+ let value_len = if len < 0 {+ rng.gen_range::<usize>(0, 128)+ } else {+ len as usize+ };+ let value = random_bytes(value_len);+ ByteArray::from(value)+ }+}++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+}++pub fn random_bools(n: usize) -> Vec<bool> {+ let mut result = vec![];+ let mut rng = thread_rng();+ for _ in 0..n {+ result.push(rng.gen::<bool>());+ }+ result+}++pub fn random_numbers<T>(n: usize) -> Vec<T>+where+ Standard: Distribution<T>,+{+ let mut rng = thread_rng();+ Standard.sample_iter(&mut rng).take(n).collect()+}++pub fn random_numbers_range<T>(n: usize, low: T, high: T, result: &mut Vec<T>)+where+ T: PartialOrd + SampleRange + Copy,+{+ let mut rng = thread_rng();+ for _ in 0..n {+ result.push(rng.gen_range(low, high));+ }+}++/// Returns path to the test parquet file in 'data' directory+pub fn get_test_path(file_name: &str) -> PathBuf {+ let result = env::var("PARQUET_TEST_DATA");+ if result.is_err() {+ panic!("Please point PARQUET_TEST_DATA environment variable to the test data directory");+ }+ let mut pathbuf = PathBuf::from_str(result.unwrap().as_str()).unwrap();+ pathbuf.push(file_name);+ pathbuf+}++/// Returns file handle for a test parquet file from 'data' directory+pub fn get_test_file(file_name: &str) -> fs::File {+ let file = fs::File::open(get_test_path(file_name).as_path());+ if file.is_err() {+ panic!("Test file {} not found", file_name)+ }+ file.unwrap()+}++/// Returns file handle for a temp file in 'target' directory with a provided content+pub fn get_temp_file(file_name: &str, content: &[u8]) -> fs::File {+ // build tmp path to a file in "target/debug/testdata"+ let mut path_buf = env::current_dir().unwrap();+ path_buf.push("target");+ path_buf.push("debug");+ path_buf.push("testdata");+ fs::create_dir_all(&path_buf).unwrap();+ path_buf.push(file_name);++ // write file content+ let mut tmp_file = fs::File::create(path_buf.as_path()).unwrap();+ tmp_file.write_all(content).unwrap();+ tmp_file.sync_all().unwrap();++ // return file handle for both read and write+ let file = fs::OpenOptions::new()+ .read(true)+ .write(true)+ .open(path_buf.as_path());+ assert!(file.is_ok());+ file.unwrap()+}diff --git a/rust/src/record_batch.rs b/rust/src/record_batch.rsindex 2666770460..e6a8e79500 100644--- a/rust/src/record_batch.rs+++ b/rust/src/record_batch.rs@@ -15,9 +15,10 @@// specific language governing permissions and limitations// under the License.+use std::sync::Arc;+use crate::array::*;use crate::datatypes::*;-use std::sync::Arc;/// A batch of column-oriented datapub struct RecordBatch {@@ -67,6 +68,7 @@ unsafe impl Sync for RecordBatch {}#[cfg(test)]mod tests {use super::*;+use crate::array_data::*;use crate::buffer::*;diff --git a/rust/src/tensor.rs b/rust/src/tensor.rsindex 175b68d81f..7272a2cf14 100644--- a/rust/src/tensor.rs+++ b/rust/src/tensor.rs@@ -216,6 +216,7 @@ impl<'a, T: ArrowPrimitiveType> Tensor<'a, T> {#[cfg(test)]mod tests {use super::*;+use crate::buffer::Buffer;use crate::builder::*;