arrow_json/reader/
run_end_array.rs1use std::marker::PhantomData;
19use std::ops::Range;
20use std::slice::from_ref;
21use std::sync::Arc;
22
23use arrow_array::types::RunEndIndexType;
24use arrow_array::{ArrayRef, RunArray, UInt32Array, new_empty_array};
25use arrow_buffer::{ArrowNativeType, RunEndBuffer, ScalarBuffer};
26use arrow_ord::partition::partition;
27use arrow_schema::{ArrowError, DataType};
28use arrow_select::take::take;
29
30use crate::reader::tape::Tape;
31use crate::reader::{ArrayDecoder, DecoderContext};
32
33pub struct RunEndEncodedArrayDecoder<R> {
34 data_type: DataType,
35 decoder: Box<dyn ArrayDecoder>,
36 values_nullable: bool,
37 phantom: PhantomData<R>,
38}
39
40impl<R: RunEndIndexType> RunEndEncodedArrayDecoder<R> {
41 pub fn new(
42 ctx: &DecoderContext,
43 data_type: &DataType,
44 is_nullable: bool,
45 ) -> Result<Self, ArrowError> {
46 let DataType::RunEndEncoded(_, values_field) = data_type else {
47 unreachable!()
48 };
49 let values_nullable = values_field.is_nullable() && is_nullable;
50 let decoder = ctx.make_decoder(values_field, values_nullable)?;
51
52 Ok(Self {
53 data_type: data_type.clone(),
54 decoder,
55 values_nullable,
56 phantom: Default::default(),
57 })
58 }
59}
60
61impl<R: RunEndIndexType + Send> ArrayDecoder for RunEndEncodedArrayDecoder<R> {
62 fn decode(&mut self, tape: &Tape<'_>, pos: &[u32]) -> Result<ArrayRef, ArrowError> {
63 let len = pos.len();
64 if len == 0 {
65 return Ok(new_empty_array(&self.data_type));
66 }
67
68 let flat_array = self.decoder.decode(tape, pos)?;
69 if !self.values_nullable && flat_array.logical_null_count() != 0 {
70 return Err(ArrowError::JsonError(
71 "Encountered nulls in non-nullable values of RunEndEncoded".to_string(),
72 ));
73 }
74
75 let partitions = partition(from_ref(&flat_array))?;
76 let size = partitions.len();
77 let mut run_ends = Vec::with_capacity(size);
78 let mut indices = Vec::with_capacity(size);
79
80 for Range { start, end } in partitions.ranges() {
81 let run_end = R::Native::from_usize(end).ok_or_else(|| {
82 ArrowError::JsonError(format!(
83 "Run end value {end} exceeds {:?} range",
84 R::DATA_TYPE
85 ))
86 })?;
87 run_ends.push(run_end);
88 indices.push(start);
89 }
90
91 let indices = UInt32Array::from_iter_values(indices.into_iter().map(|i| i as u32));
92 let values = take(flat_array.as_ref(), &indices, None)?;
93
94 let run_ends = unsafe { RunEndBuffer::new_unchecked(ScalarBuffer::from(run_ends), 0, len) };
96
97 let array =
99 unsafe { RunArray::<R>::new_unchecked(self.data_type.clone(), run_ends, values) };
100 Ok(Arc::new(array))
101 }
102}