tustvold commented on code in PR #2221: URL: https://github.com/apache/arrow-rs/pull/2221#discussion_r933395801
########## parquet/src/arrow/arrow_writer/byte_array.rs: ########## @@ -0,0 +1,557 @@ +// 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::arrow::arrow_writer::levels::LevelInfo; +use crate::arrow::arrow_writer::ArrayWriter; +use crate::basic::Encoding; +use crate::column::page::PageWriter; +use crate::column::writer::encoder::{ + ColumnValueEncoder, DataPageValues, DictionaryPage, +}; +use crate::column::writer::GenericColumnWriter; +use crate::data_type::{AsBytes, ByteArray, Int32Type}; +use crate::encodings::encoding::{DeltaBitPackEncoder, Encoder}; +use crate::encodings::rle::RleEncoder; +use crate::errors::{ParquetError, Result}; +use crate::file::properties::{WriterProperties, WriterPropertiesPtr, WriterVersion}; +use crate::file::writer::OnCloseColumnChunk; +use crate::schema::types::ColumnDescPtr; +use crate::util::bit_util::num_required_bits; +use crate::util::interner::{Interner, Storage}; +use arrow::array::{ + Array, ArrayAccessor, ArrayRef, BinaryArray, LargeBinaryArray, LargeStringArray, + StringArray, +}; +use arrow::datatypes::DataType; + +macro_rules! downcast_op { + ($data_type:expr, $array:ident, $op:expr $(, $arg:expr)*) => { + match $data_type { + DataType::Utf8 => $op($array.as_any().downcast_ref::<StringArray>().unwrap()$(, $arg)*), + DataType::LargeUtf8 => { + $op($array.as_any().downcast_ref::<LargeStringArray>().unwrap()$(, $arg)*) + } + DataType::Binary => { + $op($array.as_any().downcast_ref::<BinaryArray>().unwrap()$(, $arg)*) + } + DataType::LargeBinary => { + $op($array.as_any().downcast_ref::<LargeBinaryArray>().unwrap()$(, $arg)*) + } + d => unreachable!("cannot downcast {} to byte array", d) + } + }; +} + +/// Returns an [`ArrayWriter`] for byte or string arrays +pub(super) fn make_byte_array_writer<'a>( + descr: ColumnDescPtr, + data_type: DataType, + props: WriterPropertiesPtr, + page_writer: Box<dyn PageWriter + 'a>, + on_close: OnCloseColumnChunk<'a>, +) -> Box<dyn ArrayWriter + 'a> { + Box::new(ByteArrayWriter { + writer: Some(GenericColumnWriter::new(descr, props, page_writer)), + on_close: Some(on_close), + data_type, + }) +} + +/// An [`ArrayWriter`] for [`ByteArray`] +struct ByteArrayWriter<'a> { + writer: Option<GenericColumnWriter<'a, ByteArrayEncoder>>, + on_close: Option<OnCloseColumnChunk<'a>>, + data_type: DataType, +} + +impl<'a> ArrayWriter for ByteArrayWriter<'a> { + fn write(&mut self, array: &ArrayRef, levels: LevelInfo) -> Result<()> { + self.writer.as_mut().unwrap().write_batch_internal( + array, + Some(levels.non_null_indices()), + levels.def_levels(), + levels.rep_levels(), + None, + None, + None, + )?; + Ok(()) + } + + fn close(&mut self) -> Result<()> { + let (bytes_written, rows_written, metadata, column_index, offset_index) = + self.writer.take().unwrap().close()?; + + if let Some(on_close) = self.on_close.take() { + on_close( + bytes_written, + rows_written, + metadata, + column_index, + offset_index, + )?; + } + Ok(()) + } +} + +/// A fallback encoder, i.e. non-dictionary, for [`ByteArray`] +struct FallbackEncoder { + encoder: FallbackEncoderImpl, + num_values: usize, +} + +/// The fallback encoder in use +/// +/// Note: DeltaBitPackEncoder is boxed as it is rather large +enum FallbackEncoderImpl { + Plain { + buffer: Vec<u8>, + }, + DeltaLength { + buffer: Vec<u8>, + lengths: Box<DeltaBitPackEncoder<Int32Type>>, + }, + Delta { + buffer: Vec<u8>, + last_value: Vec<u8>, + prefix_lengths: Box<DeltaBitPackEncoder<Int32Type>>, + suffix_lengths: Box<DeltaBitPackEncoder<Int32Type>>, + }, +} + +impl FallbackEncoder { + /// Create the fallback encoder for the given [`ColumnDescPtr`] and [`WriterProperties`] + fn new(descr: &ColumnDescPtr, props: &WriterProperties) -> Result<Self> { + // Set either main encoder or fallback encoder. + let encoding = props.encoding(descr.path()).unwrap_or_else(|| { + match props.writer_version() { + WriterVersion::PARQUET_1_0 => Encoding::PLAIN, + WriterVersion::PARQUET_2_0 => Encoding::DELTA_BYTE_ARRAY, + } + }); + + let encoder = match encoding { + Encoding::PLAIN => FallbackEncoderImpl::Plain { buffer: vec![] }, + Encoding::DELTA_LENGTH_BYTE_ARRAY => FallbackEncoderImpl::DeltaLength { + buffer: vec![], + lengths: Box::new(DeltaBitPackEncoder::new()), + }, + Encoding::DELTA_BYTE_ARRAY => FallbackEncoderImpl::Delta { + buffer: vec![], + last_value: vec![], + prefix_lengths: Box::new(DeltaBitPackEncoder::new()), + suffix_lengths: Box::new(DeltaBitPackEncoder::new()), + }, + _ => { + return Err(general_err!( + "unsupported encoding {} for byte array", + encoding + )) + } + }; + + Ok(Self { + encoder, + num_values: 0, + }) + } + + /// Encode `values` to the in-progress page + fn encode<T>(&mut self, values: T, indices: &[usize]) + where + T: ArrayAccessor + Copy, + T::Item: AsRef<[u8]>, + { + self.num_values += indices.len(); + match &mut self.encoder { Review Comment: See https://github.com/apache/parquet-format/blob/master/Encodings.md for what the various encodings are. They are all relatively self-explantory -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
