Jefffrey commented on code in PR #9379:
URL: https://github.com/apache/arrow-rs/pull/9379#discussion_r2787539036
##########
arrow-json/src/reader/mod.rs:
##########
@@ -2857,4 +2860,187 @@ mod tests {
"Json error: whilst decoding field 'a': failed to parse \"a\" as
Int32".to_owned()
);
}
+
+ #[test]
+ fn test_read_run_end_encoded() {
+ let buf = r#"
+ {"a": "x"}
+ {"a": "x"}
+ {"a": "y"}
+ {"a": "y"}
+ {"a": "y"}
+ "#;
+
+ let ree_type = DataType::RunEndEncoded(
+ Arc::new(Field::new("run_ends", DataType::Int32, false)),
+ Arc::new(Field::new("values", DataType::Utf8, true)),
+ );
+ let schema = Arc::new(Schema::new(vec![Field::new("a", ree_type,
true)]));
+ let batches = do_read(buf, 1024, false, false, schema);
+ assert_eq!(batches.len(), 1);
+
+ let col = batches[0].column(0);
+ let run_array = col
+ .as_any()
+
.downcast_ref::<arrow_array::RunArray<arrow_array::types::Int32Type>>()
+ .unwrap();
+
+ // 5 logical values compressed into 2 runs
+ assert_eq!(run_array.len(), 5);
+ assert_eq!(run_array.run_ends().values(), &[2, 5]);
+
+ let values = run_array
Review Comment:
and `as_string` here
##########
arrow-json/src/reader/mod.rs:
##########
@@ -2857,4 +2860,187 @@ mod tests {
"Json error: whilst decoding field 'a': failed to parse \"a\" as
Int32".to_owned()
);
}
+
+ #[test]
+ fn test_read_run_end_encoded() {
+ let buf = r#"
+ {"a": "x"}
+ {"a": "x"}
+ {"a": "y"}
+ {"a": "y"}
+ {"a": "y"}
+ "#;
+
+ let ree_type = DataType::RunEndEncoded(
+ Arc::new(Field::new("run_ends", DataType::Int32, false)),
+ Arc::new(Field::new("values", DataType::Utf8, true)),
+ );
+ let schema = Arc::new(Schema::new(vec![Field::new("a", ree_type,
true)]));
+ let batches = do_read(buf, 1024, false, false, schema);
+ assert_eq!(batches.len(), 1);
+
+ let col = batches[0].column(0);
+ let run_array = col
+ .as_any()
+
.downcast_ref::<arrow_array::RunArray<arrow_array::types::Int32Type>>()
+ .unwrap();
+
+ // 5 logical values compressed into 2 runs
+ assert_eq!(run_array.len(), 5);
+ assert_eq!(run_array.run_ends().values(), &[2, 5]);
+
+ let values = run_array
+ .values()
+ .as_any()
+ .downcast_ref::<StringArray>()
+ .unwrap();
+ assert_eq!(values.len(), 2);
+ assert_eq!(values.value(0), "x");
+ assert_eq!(values.value(1), "y");
+ }
+
+ #[test]
+ fn test_run_end_encoded_roundtrip() {
+ let run_ends = arrow_array::Int32Array::from(vec![3, 5, 7]);
+ let values = StringArray::from(vec![Some("a"), None, Some("b")]);
+ let ree =
+
arrow_array::RunArray::<arrow_array::types::Int32Type>::try_new(&run_ends,
&values)
+ .unwrap();
+
+ let schema = Arc::new(Schema::new(vec![Field::new(
+ "c",
+ ree.data_type().clone(),
+ true,
+ )]));
+ let batch = RecordBatch::try_new(schema.clone(),
vec![Arc::new(ree)]).unwrap();
+
+ // Write to JSON
+ let mut buf = Vec::new();
+ {
+ let mut writer = crate::writer::LineDelimitedWriter::new(&mut buf);
+ writer.write_batches(&[&batch]).unwrap();
Review Comment:
it feels like this test best belongs in the write module since it uses write
functionality 🤔
##########
arrow-json/src/reader/run_end_array.rs:
##########
@@ -0,0 +1,150 @@
+// 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::reader::tape::Tape;
+use crate::reader::{ArrayDecoder, DecoderContext};
+use arrow_array::Array;
+use arrow_data::transform::MutableArrayData;
+use arrow_data::{ArrayData, ArrayDataBuilder};
+use arrow_schema::{ArrowError, DataType};
+
+pub struct RunEndEncodedArrayDecoder {
+ data_type: DataType,
+ decoder: Box<dyn ArrayDecoder>,
+}
+
+impl RunEndEncodedArrayDecoder {
+ pub fn new(
+ ctx: &DecoderContext,
+ data_type: &DataType,
+ is_nullable: bool,
+ ) -> Result<Self, ArrowError> {
+ let values_field = match data_type {
+ DataType::RunEndEncoded(_, v) => v,
+ _ => unreachable!(),
+ };
+ let decoder = ctx.make_decoder(
+ values_field.data_type(),
+ values_field.is_nullable() || is_nullable,
+ )?;
+
+ Ok(Self {
+ data_type: data_type.clone(),
+ decoder,
+ })
+ }
+}
+
+impl ArrayDecoder for RunEndEncodedArrayDecoder {
+ fn decode(&mut self, tape: &Tape<'_>, pos: &[u32]) -> Result<ArrayData,
ArrowError> {
+ let run_ends_type = match &self.data_type {
+ DataType::RunEndEncoded(r, _) => r.data_type(),
+ _ => unreachable!(),
+ };
+
+ let len = pos.len();
+ if len == 0 {
+ let empty_run_ends = new_empty_run_ends(run_ends_type);
+ let empty_values = self.decoder.decode(tape, &[])?;
+ let data = ArrayDataBuilder::new(self.data_type.clone())
+ .len(0)
+ .add_child_data(empty_run_ends)
+ .add_child_data(empty_values);
+ // Safety:
+ // Valid by construction
+ return Ok(unsafe { data.build_unchecked() });
+ }
+
+ let flat_data = self.decoder.decode(tape, pos)?;
+
+ let mut run_ends: Vec<i64> = Vec::new();
+ let mut mutable = MutableArrayData::new(vec![&flat_data], false, len);
+
+ let mut run_start = 0;
+ for i in 1..len {
+ if !same_run(&flat_data, run_start, i) {
+ run_ends.push(i as i64);
+ mutable.extend(0, run_start, run_start + 1);
+ run_start = i;
+ }
+ }
+ run_ends.push(len as i64);
+ mutable.extend(0, run_start, run_start + 1);
+
+ let values_data = mutable.freeze();
+ let run_ends_data = build_run_ends_array(run_ends_type, run_ends)?;
+
+ let data = ArrayDataBuilder::new(self.data_type.clone())
+ .len(len)
+ .add_child_data(run_ends_data)
+ .add_child_data(values_data);
+
+ // Safety:
+ // Valid by construction
Review Comment:
What does valid by construction mean?
##########
arrow-json/src/reader/mod.rs:
##########
@@ -2857,4 +2860,187 @@ mod tests {
"Json error: whilst decoding field 'a': failed to parse \"a\" as
Int32".to_owned()
);
}
+
+ #[test]
+ fn test_read_run_end_encoded() {
+ let buf = r#"
+ {"a": "x"}
+ {"a": "x"}
+ {"a": "y"}
+ {"a": "y"}
+ {"a": "y"}
+ "#;
+
+ let ree_type = DataType::RunEndEncoded(
+ Arc::new(Field::new("run_ends", DataType::Int32, false)),
+ Arc::new(Field::new("values", DataType::Utf8, true)),
+ );
+ let schema = Arc::new(Schema::new(vec![Field::new("a", ree_type,
true)]));
+ let batches = do_read(buf, 1024, false, false, schema);
+ assert_eq!(batches.len(), 1);
+
+ let col = batches[0].column(0);
+ let run_array = col
Review Comment:
use `as_run` for more ergonomic downcasting
##########
arrow-json/src/reader/run_end_array.rs:
##########
@@ -0,0 +1,150 @@
+// 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::reader::tape::Tape;
+use crate::reader::{ArrayDecoder, DecoderContext};
+use arrow_array::Array;
+use arrow_data::transform::MutableArrayData;
+use arrow_data::{ArrayData, ArrayDataBuilder};
+use arrow_schema::{ArrowError, DataType};
+
+pub struct RunEndEncodedArrayDecoder {
+ data_type: DataType,
+ decoder: Box<dyn ArrayDecoder>,
+}
+
+impl RunEndEncodedArrayDecoder {
+ pub fn new(
+ ctx: &DecoderContext,
+ data_type: &DataType,
+ is_nullable: bool,
+ ) -> Result<Self, ArrowError> {
+ let values_field = match data_type {
+ DataType::RunEndEncoded(_, v) => v,
+ _ => unreachable!(),
+ };
+ let decoder = ctx.make_decoder(
+ values_field.data_type(),
+ values_field.is_nullable() || is_nullable,
+ )?;
+
+ Ok(Self {
+ data_type: data_type.clone(),
+ decoder,
+ })
+ }
+}
+
+impl ArrayDecoder for RunEndEncodedArrayDecoder {
+ fn decode(&mut self, tape: &Tape<'_>, pos: &[u32]) -> Result<ArrayData,
ArrowError> {
+ let run_ends_type = match &self.data_type {
+ DataType::RunEndEncoded(r, _) => r.data_type(),
+ _ => unreachable!(),
+ };
+
+ let len = pos.len();
+ if len == 0 {
+ let empty_run_ends = new_empty_run_ends(run_ends_type);
+ let empty_values = self.decoder.decode(tape, &[])?;
+ let data = ArrayDataBuilder::new(self.data_type.clone())
+ .len(0)
+ .add_child_data(empty_run_ends)
+ .add_child_data(empty_values);
+ // Safety:
+ // Valid by construction
+ return Ok(unsafe { data.build_unchecked() });
+ }
+
+ let flat_data = self.decoder.decode(tape, pos)?;
+
+ let mut run_ends: Vec<i64> = Vec::new();
+ let mut mutable = MutableArrayData::new(vec![&flat_data], false, len);
+
+ let mut run_start = 0;
+ for i in 1..len {
+ if !same_run(&flat_data, run_start, i) {
+ run_ends.push(i as i64);
+ mutable.extend(0, run_start, run_start + 1);
+ run_start = i;
+ }
+ }
+ run_ends.push(len as i64);
+ mutable.extend(0, run_start, run_start + 1);
+
+ let values_data = mutable.freeze();
+ let run_ends_data = build_run_ends_array(run_ends_type, run_ends)?;
+
+ let data = ArrayDataBuilder::new(self.data_type.clone())
+ .len(len)
+ .add_child_data(run_ends_data)
+ .add_child_data(values_data);
+
+ // Safety:
+ // Valid by construction
+ Ok(unsafe { data.build_unchecked() })
+ }
+}
+
+fn same_run(data: &ArrayData, i: usize, j: usize) -> bool {
+ let null_i = data.is_null(i);
+ let null_j = data.is_null(j);
+ if null_i != null_j {
+ return false;
+ }
+ if null_i {
+ return true;
+ }
+ data.slice(i, 1) == data.slice(j, 1)
+}
+
+fn build_run_ends_array(dt: &DataType, run_ends: Vec<i64>) ->
Result<ArrayData, ArrowError> {
Review Comment:
We could probably inline this if we make `RunEndEncodedArrayDecoder` generic
over its index type, instead of defaulting to `i64` and then trying to convert
after the fact
##########
arrow-json/src/reader/run_end_array.rs:
##########
@@ -0,0 +1,150 @@
+// 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::reader::tape::Tape;
+use crate::reader::{ArrayDecoder, DecoderContext};
+use arrow_array::Array;
+use arrow_data::transform::MutableArrayData;
+use arrow_data::{ArrayData, ArrayDataBuilder};
+use arrow_schema::{ArrowError, DataType};
+
+pub struct RunEndEncodedArrayDecoder {
+ data_type: DataType,
+ decoder: Box<dyn ArrayDecoder>,
+}
+
+impl RunEndEncodedArrayDecoder {
+ pub fn new(
+ ctx: &DecoderContext,
+ data_type: &DataType,
+ is_nullable: bool,
+ ) -> Result<Self, ArrowError> {
+ let values_field = match data_type {
+ DataType::RunEndEncoded(_, v) => v,
+ _ => unreachable!(),
+ };
+ let decoder = ctx.make_decoder(
+ values_field.data_type(),
+ values_field.is_nullable() || is_nullable,
+ )?;
+
+ Ok(Self {
+ data_type: data_type.clone(),
+ decoder,
+ })
+ }
+}
+
+impl ArrayDecoder for RunEndEncodedArrayDecoder {
+ fn decode(&mut self, tape: &Tape<'_>, pos: &[u32]) -> Result<ArrayData,
ArrowError> {
+ let run_ends_type = match &self.data_type {
+ DataType::RunEndEncoded(r, _) => r.data_type(),
+ _ => unreachable!(),
+ };
+
+ let len = pos.len();
+ if len == 0 {
+ let empty_run_ends = new_empty_run_ends(run_ends_type);
Review Comment:
We can use
[`new_empty_array`](https://docs.rs/arrow/latest/arrow/array/fn.new_empty_array.html)
Also not sure about calling decode here if len is zero; does that achieve
anything?
--
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]