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 phantom: PhantomData<R>,
37}
38
39impl<R: RunEndIndexType> RunEndEncodedArrayDecoder<R> {
40 pub fn new(
41 ctx: &DecoderContext,
42 data_type: &DataType,
43 is_nullable: bool,
44 ) -> Result<Self, ArrowError> {
45 let values_field = match data_type {
46 DataType::RunEndEncoded(_, v) => v,
47 _ => unreachable!(),
48 };
49 let decoder = ctx.make_decoder(
50 values_field.data_type(),
51 values_field.is_nullable() || is_nullable,
52 )?;
53
54 Ok(Self {
55 data_type: data_type.clone(),
56 decoder,
57 phantom: Default::default(),
58 })
59 }
60}
61
62impl<R: RunEndIndexType + Send> ArrayDecoder for RunEndEncodedArrayDecoder<R> {
63 fn decode(&mut self, tape: &Tape<'_>, pos: &[u32]) -> Result<ArrayRef, ArrowError> {
64 let len = pos.len();
65 if len == 0 {
66 return Ok(new_empty_array(&self.data_type));
67 }
68
69 let flat_array = self.decoder.decode(tape, pos)?;
70
71 let partitions = partition(from_ref(&flat_array))?;
72 let size = partitions.len();
73 let mut run_ends = Vec::with_capacity(size);
74 let mut indices = Vec::with_capacity(size);
75
76 for Range { start, end } in partitions.ranges() {
77 let run_end = R::Native::from_usize(end).ok_or_else(|| {
78 ArrowError::JsonError(format!(
79 "Run end value {end} exceeds {:?} range",
80 R::DATA_TYPE
81 ))
82 })?;
83 run_ends.push(run_end);
84 indices.push(start);
85 }
86
87 let indices = UInt32Array::from_iter_values(indices.into_iter().map(|i| i as u32));
88 let values = take(flat_array.as_ref(), &indices, None)?;
89
90 let run_ends = unsafe { RunEndBuffer::new_unchecked(ScalarBuffer::from(run_ends), 0, len) };
92
93 let array =
95 unsafe { RunArray::<R>::new_unchecked(self.data_type.clone(), run_ends, values) };
96 Ok(Arc::new(array))
97 }
98}