alamb commented on code in PR #5318: URL: https://github.com/apache/arrow-rs/pull/5318#discussion_r1465334902
########## arrow-json/src/writer/encoder.rs: ########## @@ -0,0 +1,436 @@ +// 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 arrow_array::cast::AsArray; +use arrow_array::types::*; +use arrow_array::*; +use arrow_buffer::{ArrowNativeType, NullBuffer, OffsetBuffer, ScalarBuffer}; +use arrow_cast::display::{ArrayFormatter, FormatOptions}; +use arrow_schema::{ArrowError, DataType, FieldRef}; +use half::f16; +use lexical_core::FormattedSize; +use serde::Serializer; +use std::io::Write; + +#[derive(Debug, Clone, Default)] +pub struct EncoderOptions { + pub explicit_nulls: bool, +} + +pub trait Encoder { + fn encode(&mut self, idx: usize, out: &mut Vec<u8>); +} + +pub fn make_encoder<'a>( + array: &'a dyn Array, + options: &EncoderOptions, +) -> Result<Box<dyn Encoder + 'a>, ArrowError> { + let (encoder, nulls) = make_encoder_impl(array, options)?; + assert!(nulls.is_none(), "root cannot be nullable"); Review Comment: I don't understand this -- isn't it possible to try to encode a `BooleanArray` as the root with null values? ########## arrow-json/src/writer/encoder.rs: ########## @@ -0,0 +1,436 @@ +// 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 arrow_array::cast::AsArray; +use arrow_array::types::*; +use arrow_array::*; +use arrow_buffer::{ArrowNativeType, NullBuffer, OffsetBuffer, ScalarBuffer}; +use arrow_cast::display::{ArrayFormatter, FormatOptions}; +use arrow_schema::{ArrowError, DataType, FieldRef}; +use half::f16; +use lexical_core::FormattedSize; +use serde::Serializer; +use std::io::Write; + +#[derive(Debug, Clone, Default)] +pub struct EncoderOptions { + pub explicit_nulls: bool, +} + +pub trait Encoder { + fn encode(&mut self, idx: usize, out: &mut Vec<u8>); +} + +pub fn make_encoder<'a>( + array: &'a dyn Array, + options: &EncoderOptions, +) -> Result<Box<dyn Encoder + 'a>, ArrowError> { + let (encoder, nulls) = make_encoder_impl(array, options)?; + assert!(nulls.is_none(), "root cannot be nullable"); + Ok(encoder) +} + +fn make_encoder_impl<'a>( + array: &'a dyn Array, + options: &EncoderOptions, +) -> Result<(Box<dyn Encoder + 'a>, Option<NullBuffer>), ArrowError> { + macro_rules! primitive_helper { + ($t:ty) => {{ + let array = array.as_primitive::<$t>(); + let nulls = array.nulls().cloned(); + (Box::new(PrimitiveEncoder::new(array)) as _, nulls) + }}; + } + + Ok(downcast_integer! { + array.data_type() => (primitive_helper), + DataType::Float16 => primitive_helper!(Float16Type), + DataType::Float32 => primitive_helper!(Float32Type), + DataType::Float64 => primitive_helper!(Float64Type), + DataType::Boolean => { + let array = array.as_boolean(); + (Box::new(BooleanEncoder(array.clone())), array.nulls().cloned()) + } + DataType::Null => (Box::new(NullEncoder), array.logical_nulls()), + DataType::Utf8 => { + let array = array.as_string::<i32>(); + (Box::new(StringEncoder(array.clone())) as _, array.nulls().cloned()) + } + DataType::LargeUtf8 => { + let array = array.as_string::<i64>(); + (Box::new(StringEncoder(array.clone())) as _, array.nulls().cloned()) + } + DataType::List(_) => { + let array = array.as_list::<i32>(); + (Box::new(ListEncoder::try_new(array, options)?) as _, array.nulls().cloned()) + } + DataType::LargeList(_) => { + let array = array.as_list::<i64>(); + (Box::new(ListEncoder::try_new(array, options)?) as _, array.nulls().cloned()) + } + + DataType::Dictionary(_, _) => downcast_dictionary_array! { + array => (Box::new(DictionaryEncoder::try_new(array, options)?) as _, array.logical_nulls()), + _ => unreachable!() + } + + DataType::Map(_, _) => { + let array = array.as_map(); + (Box::new(MapEncoder::try_new(array, options)?) as _, array.nulls().cloned()) + } + + DataType::Struct(fields) => { + let array = array.as_struct(); + let encoders = fields.iter().zip(array.columns()).map(|(field, array)| { + let (encoder, nulls) = make_encoder_impl(array, options)?; + Ok(FieldEncoder{ + field: field.clone(), + encoder, nulls + }) + }).collect::<Result<Vec<_>, ArrowError>>()?; + + let encoder = StructArrayEncoder{ + encoders, + explicit_nulls: options.explicit_nulls, + }; + (Box::new(encoder) as _, array.nulls().cloned()) + } + d => match d.is_temporal() { + true => { + // Note: the implementation of Encoder for ArrayFormatter assumes it does not produce + // characters that would need to be escaped within a JSON string, e.g. `'"'`. + // If support for user-provided format specifications is added, this assumption + // may need to be revisited + let options = FormatOptions::new().with_display_error(true); + let formatter = ArrayFormatter::try_new(array, &options)?; + (Box::new(formatter) as _, array.nulls().cloned()) + } + false => return Err(ArrowError::InvalidArgumentError(format!("JSON Writer does not support data type: {d}"))), + } + }) +} + +fn encode_string(s: &str, out: &mut Vec<u8>) { + let mut serializer = serde_json::Serializer::new(out); + serializer.serialize_str(s).unwrap(); +} + +struct FieldEncoder<'a> { + field: FieldRef, + encoder: Box<dyn Encoder + 'a>, + nulls: Option<NullBuffer>, +} + +struct StructArrayEncoder<'a> { + encoders: Vec<FieldEncoder<'a>>, + explicit_nulls: bool, +} + +impl<'a> Encoder for StructArrayEncoder<'a> { + fn encode(&mut self, idx: usize, out: &mut Vec<u8>) { + out.push(b'{'); + let mut is_first = true; + for field_encoder in &mut self.encoders { + let is_null = field_encoder.nulls.as_ref().is_some_and(|n| n.is_null(idx)); + if is_null && !self.explicit_nulls { + continue; + } + + if !is_first { + out.push(b','); + } + is_first = false; + + encode_string(field_encoder.field.name(), out); + out.push(b':'); + + match is_null { + true => out.extend_from_slice(b"null"), + false => field_encoder.encoder.encode(idx, out), + } + } + out.push(b'}'); + } +} + +trait PrimitiveEncode: ArrowNativeType { + type Buffer; + + // Workaround https://github.com/rust-lang/rust/issues/61415 + fn init_buffer() -> Self::Buffer; + + fn encode(self, buf: &mut Self::Buffer) -> &[u8]; +} + +macro_rules! integer_encode { + ($($t:ty),*) => { + $( + impl PrimitiveEncode for $t { + type Buffer = [u8; Self::FORMATTED_SIZE]; + + fn init_buffer() -> Self::Buffer { + [0; Self::FORMATTED_SIZE] + } + + fn encode(self, buf: &mut Self::Buffer) -> &[u8] { + lexical_core::write(self, buf) + } + } + )* + }; +} +integer_encode!(i8, i16, i32, i64, u8, u16, u32, u64); + +macro_rules! float_encode { + ($($t:ty),*) => { + $( + impl PrimitiveEncode for $t { + type Buffer = [u8; Self::FORMATTED_SIZE]; + + fn init_buffer() -> Self::Buffer { + [0; Self::FORMATTED_SIZE] + } + + fn encode(self, buf: &mut Self::Buffer) -> &[u8] { + if self.is_infinite() || self.is_nan() { + b"null" + } else { + lexical_core::write(self, buf) + } + } + } + )* + }; +} +float_encode!(f32, f64); + +impl PrimitiveEncode for f16 { + type Buffer = <f64 as PrimitiveEncode>::Buffer; Review Comment: why can't we just use the `PrimitiveEncode` directly for `f16`? I doubt the performance of f16 encoding is particular critical but I am curious ########## arrow-json/src/writer.rs: ########## @@ -20,28 +20,6 @@ //! This JSON writer converts Arrow [`RecordBatch`]es into arrays of //! JSON objects or JSON formatted byte streams. //! -//! ## Writing JSON Objects Review Comment: > but it is deprecated as I can't think of any reasonable use-cases for this. Looks like @houqp added it in https://github.com/apache/arrow-rs/commit/d868cff11d667e1c3fb6269628680cfe38734471 many 🌔 's ago - perhaps he has some additional context. I agree I can't really think of why this would be useful - it seems like it may be similar to wanting to convert RecordBatches into actual Rust `struct`s via serde but I can't remember how far we got with that Given I am not familiar with `serde_json's raw value mechanism` I suspect others may not be either Perhaps you can add a note here about writing JSON objects using serde and leave a link for readers to follow ########## arrow-json/src/writer/encoder.rs: ########## @@ -0,0 +1,435 @@ +// 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 arrow_array::cast::AsArray; +use arrow_array::types::*; +use arrow_array::*; +use arrow_buffer::{ArrowNativeType, NullBuffer, OffsetBuffer, ScalarBuffer}; +use arrow_cast::display::{ArrayFormatter, FormatOptions}; +use arrow_schema::{ArrowError, DataType, FieldRef}; +use half::f16; +use lexical_core::FormattedSize; +use serde::Serializer; +use std::io::Write; + +#[derive(Debug, Clone, Default)] +pub struct EncoderOptions { + pub explicit_nulls: bool, +} + +pub trait Encoder { + fn encode(&mut self, idx: usize, out: &mut Vec<u8>); +} + +pub fn make_encoder<'a>( + array: &'a dyn Array, + options: &EncoderOptions, +) -> Result<Box<dyn Encoder + 'a>, ArrowError> { + let (encoder, nulls) = make_encoder_impl(array, options)?; + assert!(nulls.is_none(), "root cannot be nullable"); + Ok(encoder) +} + +fn make_encoder_impl<'a>( + array: &'a dyn Array, + options: &EncoderOptions, +) -> Result<(Box<dyn Encoder + 'a>, Option<NullBuffer>), ArrowError> { + macro_rules! primitive_helper { + ($t:ty) => {{ + let array = array.as_primitive::<$t>(); + let nulls = array.nulls().cloned(); + (Box::new(PrimitiveEncoder::new(array)) as _, nulls) + }}; + } + + Ok(downcast_integer! { + array.data_type() => (primitive_helper), + DataType::Float16 => primitive_helper!(Float16Type), + DataType::Float32 => primitive_helper!(Float32Type), + DataType::Float64 => primitive_helper!(Float64Type), + DataType::Boolean => { + let array = array.as_boolean(); + (Box::new(BooleanEncoder(array.clone())), array.nulls().cloned()) + } + DataType::Null => (Box::new(NullEncoder), array.logical_nulls()), + DataType::Utf8 => { + let array = array.as_string::<i32>(); + (Box::new(StringEncoder(array.clone())) as _, array.nulls().cloned()) + } + DataType::LargeUtf8 => { + let array = array.as_string::<i64>(); + (Box::new(StringEncoder(array.clone())) as _, array.nulls().cloned()) + } + DataType::List(_) => { + let array = array.as_list::<i32>(); + (Box::new(ListEncoder::try_new(array, options)?) as _, array.nulls().cloned()) + } + DataType::LargeList(_) => { + let array = array.as_list::<i64>(); + (Box::new(ListEncoder::try_new(array, options)?) as _, array.nulls().cloned()) + } + + DataType::Dictionary(_, _) => downcast_dictionary_array! { + array => (Box::new(DictionaryEncoder::try_new(array, options)?) as _, array.logical_nulls()), + _ => unreachable!() + } + + DataType::Map(_, _) => { + let array = array.as_map(); + (Box::new(MapEncoder::try_new(array, options)?) as _, array.nulls().cloned()) + } + + DataType::Struct(fields) => { + let array = array.as_struct(); + let encoders = fields.iter().zip(array.columns()).map(|(field, array)| { + let (encoder, nulls) = make_encoder_impl(array, options)?; + Ok(FieldEncoder{ + field: field.clone(), + encoder, nulls + }) + }).collect::<Result<Vec<_>, ArrowError>>()?; + + let encoder = StructArrayEncoder{ + encoders, + explicit_nulls: options.explicit_nulls, + }; + (Box::new(encoder) as _, array.nulls().cloned()) + } + d => match d.is_temporal() { + true => { + // Note: the implementation assumes that escaping is not necessary + // If this is extended to support user-provided format specifications + // this assumption may need to be revisited + let options = FormatOptions::new().with_display_error(true); + let formatter = ArrayFormatter::try_new(array, &options)?; + (Box::new(formatter) as _, array.nulls().cloned()) + } + false => return Err(ArrowError::InvalidArgumentError(format!("JSON Writer does not support data type: {d}"))), + } + }) +} + +fn encode_string(s: &str, out: &mut Vec<u8>) { + let mut serializer = serde_json::Serializer::new(out); + serializer.serialize_str(s).unwrap(); +} + +struct FieldEncoder<'a> { + field: FieldRef, + encoder: Box<dyn Encoder + 'a>, + nulls: Option<NullBuffer>, +} + +struct StructArrayEncoder<'a> { + encoders: Vec<FieldEncoder<'a>>, + explicit_nulls: bool, +} + +impl<'a> Encoder for StructArrayEncoder<'a> { + fn encode(&mut self, idx: usize, out: &mut Vec<u8>) { + out.push(b'{'); + let mut is_first = true; + for field_encoder in &mut self.encoders { + let is_null = field_encoder.nulls.as_ref().is_some_and(|n| n.is_null(idx)); + if is_null && !self.explicit_nulls { + continue; + } + + if !is_first { + out.push(b','); + } + is_first = false; + + encode_string(field_encoder.field.name(), out); + out.push(b':'); + + match is_null { + true => out.extend_from_slice(b"null"), + false => field_encoder.encoder.encode(idx, out), + } + } + out.push(b'}'); + } +} + +trait PrimitiveEncode: ArrowNativeType { + type Buffer; + + // Workaround https://github.com/rust-lang/rust/issues/61415 + fn init_buffer() -> Self::Buffer; + + fn encode(self, buf: &mut Self::Buffer) -> &[u8]; +} + +macro_rules! integer_encode { + ($($t:ty),*) => { + $( + impl PrimitiveEncode for $t { + type Buffer = [u8; Self::FORMATTED_SIZE]; + + fn init_buffer() -> Self::Buffer { + [0; Self::FORMATTED_SIZE] + } + + fn encode(self, buf: &mut Self::Buffer) -> &[u8] { + lexical_core::write(self, buf) + } + } + )* + }; +} +integer_encode!(i8, i16, i32, i64, u8, u16, u32, u64); + +macro_rules! float_encode { + ($($t:ty),*) => { + $( + impl PrimitiveEncode for $t { + type Buffer = [u8; Self::FORMATTED_SIZE]; + + fn init_buffer() -> Self::Buffer { + [0; Self::FORMATTED_SIZE] + } + + fn encode(self, buf: &mut Self::Buffer) -> &[u8] { + if self.is_infinite() || self.is_nan() { + b"null" + } else { + lexical_core::write(self, buf) + } + } + } + )* + }; +} +float_encode!(f32, f64); + +impl PrimitiveEncode for f16 { + type Buffer = <f64 as PrimitiveEncode>::Buffer; + + fn init_buffer() -> Self::Buffer { + f64::init_buffer() + } + + fn encode(self, buf: &mut Self::Buffer) -> &[u8] { + self.to_f64().encode(buf) + } +} + +struct PrimitiveEncoder<N: PrimitiveEncode> { + values: ScalarBuffer<N>, + buffer: N::Buffer, +} + +impl<N: PrimitiveEncode> PrimitiveEncoder<N> { + fn new<P: ArrowPrimitiveType<Native = N>>(array: &PrimitiveArray<P>) -> Self { + Self { + values: array.values().clone(), + buffer: N::init_buffer(), + } + } +} + +impl<N: PrimitiveEncode> Encoder for PrimitiveEncoder<N> { + fn encode(&mut self, idx: usize, out: &mut Vec<u8>) { + out.extend_from_slice(self.values[idx].encode(&mut self.buffer)); + } +} + +struct BooleanEncoder(BooleanArray); + +impl Encoder for BooleanEncoder { + fn encode(&mut self, idx: usize, out: &mut Vec<u8>) { + match self.0.value(idx) { + true => out.extend_from_slice(b"true"), + false => out.extend_from_slice(b"false"), + } + } +} + +struct StringEncoder<O: OffsetSizeTrait>(GenericStringArray<O>); + +impl<O: OffsetSizeTrait> Encoder for StringEncoder<O> { + fn encode(&mut self, idx: usize, out: &mut Vec<u8>) { + encode_string(self.0.value(idx), out); + } +} + +struct ListEncoder<'a, O: OffsetSizeTrait> { + offsets: OffsetBuffer<O>, + nulls: Option<NullBuffer>, + encoder: Box<dyn Encoder + 'a>, +} + +impl<'a, O: OffsetSizeTrait> ListEncoder<'a, O> { + fn try_new( + array: &'a GenericListArray<O>, + options: &EncoderOptions, + ) -> Result<Self, ArrowError> { + let (encoder, nulls) = make_encoder_impl(array.values().as_ref(), options)?; + Ok(Self { + offsets: array.offsets().clone(), + encoder, + nulls, + }) + } +} + +impl<'a, O: OffsetSizeTrait> Encoder for ListEncoder<'a, O> { + fn encode(&mut self, idx: usize, out: &mut Vec<u8>) { + let end = self.offsets[idx + 1].as_usize(); + let start = self.offsets[idx].as_usize(); + out.push(b'['); + match self.nulls.as_ref() { + Some(n) => (start..end).for_each(|idx| { + if idx != start { + out.push(b',') + } + match n.is_null(idx) { + true => out.extend_from_slice(b"null"), + false => self.encoder.encode(idx, out), + } + }), + None => (start..end).for_each(|idx| { + if idx != start { + out.push(b',') + } + self.encoder.encode(idx, out); + }), + } + out.push(b']'); + } +} + +struct DictionaryEncoder<'a, K: ArrowDictionaryKeyType> { + keys: ScalarBuffer<K::Native>, + encoder: Box<dyn Encoder + 'a>, +} + +impl<'a, K: ArrowDictionaryKeyType> DictionaryEncoder<'a, K> { + fn try_new( + array: &'a DictionaryArray<K>, + options: &EncoderOptions, + ) -> Result<Self, ArrowError> { + let encoder = make_encoder(array.values().as_ref(), options)?; + + Ok(Self { + keys: array.keys().values().clone(), + encoder, + }) + } +} + +impl<'a, K: ArrowDictionaryKeyType> Encoder for DictionaryEncoder<'a, K> { + fn encode(&mut self, idx: usize, out: &mut Vec<u8>) { + self.encoder.encode(self.keys[idx].as_usize(), out) + } +} + +impl<'a> Encoder for ArrayFormatter<'a> { + fn encode(&mut self, idx: usize, out: &mut Vec<u8>) { + out.push(b'"'); + // Should be infallible + // Note: We are making an assumption that the formatter does not produce characters that require escaping Review Comment: I saw some comments to this effect elsewhere. I wonder if it is possible to add a test that would fail if the invariant was broken in the future. I suspect the answer is no given it is not possible to specify format specifiers now 🤔 ########## arrow-json/src/writer.rs: ########## @@ -481,6 +463,7 @@ fn set_column_for_json_rows( /// Converts an arrow [`RecordBatch`] into a `Vec` of Serde JSON /// [`JsonMap`]s (objects) +#[deprecated(note = "Use Writer")] Review Comment: I can't figure out if the deprecation is needed for the new json writer, or did you just include it in the same PR for convenience? ########## arrow-json/src/writer/encoder.rs: ########## @@ -0,0 +1,436 @@ +// 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 arrow_array::cast::AsArray; +use arrow_array::types::*; +use arrow_array::*; +use arrow_buffer::{ArrowNativeType, NullBuffer, OffsetBuffer, ScalarBuffer}; +use arrow_cast::display::{ArrayFormatter, FormatOptions}; +use arrow_schema::{ArrowError, DataType, FieldRef}; +use half::f16; +use lexical_core::FormattedSize; +use serde::Serializer; +use std::io::Write; + +#[derive(Debug, Clone, Default)] +pub struct EncoderOptions { + pub explicit_nulls: bool, +} + +pub trait Encoder { + fn encode(&mut self, idx: usize, out: &mut Vec<u8>); +} + +pub fn make_encoder<'a>( + array: &'a dyn Array, + options: &EncoderOptions, +) -> Result<Box<dyn Encoder + 'a>, ArrowError> { + let (encoder, nulls) = make_encoder_impl(array, options)?; + assert!(nulls.is_none(), "root cannot be nullable"); + Ok(encoder) +} + +fn make_encoder_impl<'a>( + array: &'a dyn Array, + options: &EncoderOptions, +) -> Result<(Box<dyn Encoder + 'a>, Option<NullBuffer>), ArrowError> { + macro_rules! primitive_helper { + ($t:ty) => {{ + let array = array.as_primitive::<$t>(); + let nulls = array.nulls().cloned(); + (Box::new(PrimitiveEncoder::new(array)) as _, nulls) + }}; + } + + Ok(downcast_integer! { + array.data_type() => (primitive_helper), + DataType::Float16 => primitive_helper!(Float16Type), + DataType::Float32 => primitive_helper!(Float32Type), + DataType::Float64 => primitive_helper!(Float64Type), + DataType::Boolean => { + let array = array.as_boolean(); + (Box::new(BooleanEncoder(array.clone())), array.nulls().cloned()) + } + DataType::Null => (Box::new(NullEncoder), array.logical_nulls()), + DataType::Utf8 => { + let array = array.as_string::<i32>(); + (Box::new(StringEncoder(array.clone())) as _, array.nulls().cloned()) + } + DataType::LargeUtf8 => { + let array = array.as_string::<i64>(); + (Box::new(StringEncoder(array.clone())) as _, array.nulls().cloned()) + } + DataType::List(_) => { + let array = array.as_list::<i32>(); + (Box::new(ListEncoder::try_new(array, options)?) as _, array.nulls().cloned()) + } + DataType::LargeList(_) => { + let array = array.as_list::<i64>(); + (Box::new(ListEncoder::try_new(array, options)?) as _, array.nulls().cloned()) + } + + DataType::Dictionary(_, _) => downcast_dictionary_array! { + array => (Box::new(DictionaryEncoder::try_new(array, options)?) as _, array.logical_nulls()), + _ => unreachable!() + } + + DataType::Map(_, _) => { + let array = array.as_map(); + (Box::new(MapEncoder::try_new(array, options)?) as _, array.nulls().cloned()) + } + + DataType::Struct(fields) => { + let array = array.as_struct(); + let encoders = fields.iter().zip(array.columns()).map(|(field, array)| { + let (encoder, nulls) = make_encoder_impl(array, options)?; + Ok(FieldEncoder{ + field: field.clone(), + encoder, nulls + }) + }).collect::<Result<Vec<_>, ArrowError>>()?; + + let encoder = StructArrayEncoder{ + encoders, + explicit_nulls: options.explicit_nulls, + }; + (Box::new(encoder) as _, array.nulls().cloned()) + } + d => match d.is_temporal() { + true => { + // Note: the implementation of Encoder for ArrayFormatter assumes it does not produce + // characters that would need to be escaped within a JSON string, e.g. `'"'`. + // If support for user-provided format specifications is added, this assumption + // may need to be revisited + let options = FormatOptions::new().with_display_error(true); + let formatter = ArrayFormatter::try_new(array, &options)?; + (Box::new(formatter) as _, array.nulls().cloned()) + } + false => return Err(ArrowError::InvalidArgumentError(format!("JSON Writer does not support data type: {d}"))), + } + }) +} + +fn encode_string(s: &str, out: &mut Vec<u8>) { + let mut serializer = serde_json::Serializer::new(out); + serializer.serialize_str(s).unwrap(); +} + +struct FieldEncoder<'a> { + field: FieldRef, + encoder: Box<dyn Encoder + 'a>, + nulls: Option<NullBuffer>, +} + +struct StructArrayEncoder<'a> { + encoders: Vec<FieldEncoder<'a>>, + explicit_nulls: bool, +} + +impl<'a> Encoder for StructArrayEncoder<'a> { + fn encode(&mut self, idx: usize, out: &mut Vec<u8>) { + out.push(b'{'); + let mut is_first = true; + for field_encoder in &mut self.encoders { + let is_null = field_encoder.nulls.as_ref().is_some_and(|n| n.is_null(idx)); + if is_null && !self.explicit_nulls { + continue; + } + + if !is_first { + out.push(b','); + } + is_first = false; + + encode_string(field_encoder.field.name(), out); + out.push(b':'); + + match is_null { + true => out.extend_from_slice(b"null"), + false => field_encoder.encoder.encode(idx, out), + } + } + out.push(b'}'); + } +} + +trait PrimitiveEncode: ArrowNativeType { + type Buffer; + + // Workaround https://github.com/rust-lang/rust/issues/61415 + fn init_buffer() -> Self::Buffer; + + fn encode(self, buf: &mut Self::Buffer) -> &[u8]; Review Comment: I think it would help to document what encode does here ```suggestion /// Encode the primitive value as bytes, returning a reference to that slice. /// `buf` is temporary space that may be used fn encode(self, buf: &mut Self::Buffer) -> &[u8]; ``` ########## arrow-json/src/writer/encoder.rs: ########## @@ -0,0 +1,436 @@ +// 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 arrow_array::cast::AsArray; +use arrow_array::types::*; +use arrow_array::*; +use arrow_buffer::{ArrowNativeType, NullBuffer, OffsetBuffer, ScalarBuffer}; +use arrow_cast::display::{ArrayFormatter, FormatOptions}; +use arrow_schema::{ArrowError, DataType, FieldRef}; +use half::f16; +use lexical_core::FormattedSize; +use serde::Serializer; +use std::io::Write; + +#[derive(Debug, Clone, Default)] +pub struct EncoderOptions { + pub explicit_nulls: bool, +} + +pub trait Encoder { + fn encode(&mut self, idx: usize, out: &mut Vec<u8>); +} + +pub fn make_encoder<'a>( + array: &'a dyn Array, + options: &EncoderOptions, +) -> Result<Box<dyn Encoder + 'a>, ArrowError> { + let (encoder, nulls) = make_encoder_impl(array, options)?; + assert!(nulls.is_none(), "root cannot be nullable"); + Ok(encoder) +} + +fn make_encoder_impl<'a>( + array: &'a dyn Array, + options: &EncoderOptions, +) -> Result<(Box<dyn Encoder + 'a>, Option<NullBuffer>), ArrowError> { + macro_rules! primitive_helper { + ($t:ty) => {{ + let array = array.as_primitive::<$t>(); + let nulls = array.nulls().cloned(); + (Box::new(PrimitiveEncoder::new(array)) as _, nulls) + }}; + } + + Ok(downcast_integer! { + array.data_type() => (primitive_helper), + DataType::Float16 => primitive_helper!(Float16Type), + DataType::Float32 => primitive_helper!(Float32Type), + DataType::Float64 => primitive_helper!(Float64Type), + DataType::Boolean => { + let array = array.as_boolean(); + (Box::new(BooleanEncoder(array.clone())), array.nulls().cloned()) + } + DataType::Null => (Box::new(NullEncoder), array.logical_nulls()), + DataType::Utf8 => { + let array = array.as_string::<i32>(); + (Box::new(StringEncoder(array.clone())) as _, array.nulls().cloned()) + } + DataType::LargeUtf8 => { + let array = array.as_string::<i64>(); + (Box::new(StringEncoder(array.clone())) as _, array.nulls().cloned()) + } + DataType::List(_) => { + let array = array.as_list::<i32>(); + (Box::new(ListEncoder::try_new(array, options)?) as _, array.nulls().cloned()) + } + DataType::LargeList(_) => { + let array = array.as_list::<i64>(); + (Box::new(ListEncoder::try_new(array, options)?) as _, array.nulls().cloned()) + } + + DataType::Dictionary(_, _) => downcast_dictionary_array! { + array => (Box::new(DictionaryEncoder::try_new(array, options)?) as _, array.logical_nulls()), + _ => unreachable!() + } + + DataType::Map(_, _) => { + let array = array.as_map(); + (Box::new(MapEncoder::try_new(array, options)?) as _, array.nulls().cloned()) + } + + DataType::Struct(fields) => { + let array = array.as_struct(); + let encoders = fields.iter().zip(array.columns()).map(|(field, array)| { + let (encoder, nulls) = make_encoder_impl(array, options)?; + Ok(FieldEncoder{ + field: field.clone(), + encoder, nulls + }) + }).collect::<Result<Vec<_>, ArrowError>>()?; + + let encoder = StructArrayEncoder{ + encoders, + explicit_nulls: options.explicit_nulls, + }; + (Box::new(encoder) as _, array.nulls().cloned()) + } + d => match d.is_temporal() { + true => { + // Note: the implementation of Encoder for ArrayFormatter assumes it does not produce + // characters that would need to be escaped within a JSON string, e.g. `'"'`. + // If support for user-provided format specifications is added, this assumption + // may need to be revisited + let options = FormatOptions::new().with_display_error(true); + let formatter = ArrayFormatter::try_new(array, &options)?; + (Box::new(formatter) as _, array.nulls().cloned()) + } + false => return Err(ArrowError::InvalidArgumentError(format!("JSON Writer does not support data type: {d}"))), + } + }) +} + +fn encode_string(s: &str, out: &mut Vec<u8>) { + let mut serializer = serde_json::Serializer::new(out); + serializer.serialize_str(s).unwrap(); +} + +struct FieldEncoder<'a> { + field: FieldRef, + encoder: Box<dyn Encoder + 'a>, + nulls: Option<NullBuffer>, +} + +struct StructArrayEncoder<'a> { + encoders: Vec<FieldEncoder<'a>>, + explicit_nulls: bool, +} + +impl<'a> Encoder for StructArrayEncoder<'a> { + fn encode(&mut self, idx: usize, out: &mut Vec<u8>) { + out.push(b'{'); + let mut is_first = true; + for field_encoder in &mut self.encoders { + let is_null = field_encoder.nulls.as_ref().is_some_and(|n| n.is_null(idx)); + if is_null && !self.explicit_nulls { + continue; + } + + if !is_first { + out.push(b','); + } + is_first = false; + + encode_string(field_encoder.field.name(), out); + out.push(b':'); + + match is_null { + true => out.extend_from_slice(b"null"), + false => field_encoder.encoder.encode(idx, out), + } + } + out.push(b'}'); + } +} + +trait PrimitiveEncode: ArrowNativeType { + type Buffer; + + // Workaround https://github.com/rust-lang/rust/issues/61415 + fn init_buffer() -> Self::Buffer; + + fn encode(self, buf: &mut Self::Buffer) -> &[u8]; +} + +macro_rules! integer_encode { + ($($t:ty),*) => { + $( + impl PrimitiveEncode for $t { + type Buffer = [u8; Self::FORMATTED_SIZE]; + + fn init_buffer() -> Self::Buffer { + [0; Self::FORMATTED_SIZE] + } + + fn encode(self, buf: &mut Self::Buffer) -> &[u8] { + lexical_core::write(self, buf) + } + } + )* + }; +} +integer_encode!(i8, i16, i32, i64, u8, u16, u32, u64); + +macro_rules! float_encode { + ($($t:ty),*) => { + $( + impl PrimitiveEncode for $t { + type Buffer = [u8; Self::FORMATTED_SIZE]; + + fn init_buffer() -> Self::Buffer { + [0; Self::FORMATTED_SIZE] + } + + fn encode(self, buf: &mut Self::Buffer) -> &[u8] { + if self.is_infinite() || self.is_nan() { + b"null" + } else { + lexical_core::write(self, buf) + } + } + } + )* + }; +} +float_encode!(f32, f64); + +impl PrimitiveEncode for f16 { + type Buffer = <f64 as PrimitiveEncode>::Buffer; + + fn init_buffer() -> Self::Buffer { + f64::init_buffer() + } + + fn encode(self, buf: &mut Self::Buffer) -> &[u8] { + self.to_f64().encode(buf) + } +} + +struct PrimitiveEncoder<N: PrimitiveEncode> { + values: ScalarBuffer<N>, + buffer: N::Buffer, +} + +impl<N: PrimitiveEncode> PrimitiveEncoder<N> { + fn new<P: ArrowPrimitiveType<Native = N>>(array: &PrimitiveArray<P>) -> Self { + Self { + values: array.values().clone(), + buffer: N::init_buffer(), + } + } +} + +impl<N: PrimitiveEncode> Encoder for PrimitiveEncoder<N> { + fn encode(&mut self, idx: usize, out: &mut Vec<u8>) { + out.extend_from_slice(self.values[idx].encode(&mut self.buffer)); + } +} + +struct BooleanEncoder(BooleanArray); + +impl Encoder for BooleanEncoder { + fn encode(&mut self, idx: usize, out: &mut Vec<u8>) { + match self.0.value(idx) { Review Comment: I was pretty confused at first trying to figure out why this doesn't check for null, but then I saw the null check is handled in the outer loop ########## arrow-json/src/writer/encoder.rs: ########## @@ -0,0 +1,436 @@ +// 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 arrow_array::cast::AsArray; +use arrow_array::types::*; +use arrow_array::*; +use arrow_buffer::{ArrowNativeType, NullBuffer, OffsetBuffer, ScalarBuffer}; +use arrow_cast::display::{ArrayFormatter, FormatOptions}; +use arrow_schema::{ArrowError, DataType, FieldRef}; +use half::f16; +use lexical_core::FormattedSize; +use serde::Serializer; +use std::io::Write; + +#[derive(Debug, Clone, Default)] +pub struct EncoderOptions { + pub explicit_nulls: bool, +} + +pub trait Encoder { Review Comment: Could you please document the expectations on nullability here? Specifically, it seems like this code assumes that this is invoked with `idx` for non-null entries, which was not clear to me on my first read of this code -- 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]
