Skip to main content

arrow_json/reader/
run_end_array.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use 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        // SAFETY: run_ends are strictly increasing with the last value equal to len
91        let run_ends = unsafe { RunEndBuffer::new_unchecked(ScalarBuffer::from(run_ends), 0, len) };
92
93        // SAFETY: run_ends are valid and values has the same length as run_ends
94        let array =
95            unsafe { RunArray::<R>::new_unchecked(self.data_type.clone(), run_ends, values) };
96        Ok(Arc::new(array))
97    }
98}