Skip to main content

arrow_array/array/
run_array.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use std::any::Any;
6use std::sync::Arc;
7
8use arrow_buffer::{ArrowNativeType, BooleanBufferBuilder, NullBuffer, RunEndBuffer, ScalarBuffer};
9use arrow_data::{ArrayData, ArrayDataBuilder};
10use arrow_schema::{ArrowError, DataType, Field, FieldRef};
11
12use crate::{
13    Array, ArrayAccessor, ArrayRef, PrimitiveArray,
14    builder::StringRunBuilder,
15    make_array,
16    run_iterator::RunArrayIter,
17    types::{Int16Type, Int32Type, Int64Type, RunEndIndexType},
18};
19
20/// Recursively applies a function to the values of a RunEndEncoded array, preserving the run structure.
21///
22/// # Example
23///
24/// ```ignore
25/// let result = ree_recurse!(array, Int32Type, my_function)?;
26/// ```
27///
28/// This macro is useful for implementing functions that should work on the logical values
29/// of a REE array while preserving the run-end encoding structure.
30#[macro_export]
31macro_rules! ree_map {
32    ($array:expr, $run_type:ty, $func:expr) => {{
33        let ree = $array.as_run_opt::<$run_type>().unwrap();
34        let inner_values = $func(ree.values().as_ref())?;
35        Ok(std::sync::Arc::new(ree.with_values(inner_values)))
36    }};
37}
38
39/// An array of [run-end encoded values].
40///
41/// This encoding is variation on [run-length encoding (RLE)] and is good for representing
42/// data containing the same values repeated consecutively.
43///
44/// A [`RunArray`] consists of a `run_ends` buffer and a `values` array of equivalent
45/// lengths. The `run_ends` buffer stores the indexes at which the run ends. The
46/// `values` array stores the corresponding value of each run. The below example
47/// illustrates how a logical array is represented by a [`RunArray`]:
48///
49/// ```text
50/// ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─┐
51///   ┌─────────────────┐  ┌─────────┐       ┌─────────────────┐
52/// │ │        A        │  │    2    │ │     │        A        │
53///   ├─────────────────┤  ├─────────┤       ├─────────────────┤
54/// │ │        D        │  │    3    │ │     │        A        │    run length of 'A' = run_ends[0] - 0 = 2
55///   ├─────────────────┤  ├─────────┤       ├─────────────────┤
56/// │ │        B        │  │    6    │ │     │        D        │    run length of 'D' = run_ends[1] - run_ends[0] = 1
57///   └─────────────────┘  └─────────┘       ├─────────────────┤
58/// │        values          run_ends  │     │        B        │
59///                                          ├─────────────────┤
60/// └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─┘     │        B        │
61///                                          ├─────────────────┤
62///                RunArray                  │        B        │    run length of 'B' = run_ends[2] - run_ends[1] = 3
63///          offset = 0, len = 6             └─────────────────┘
64///
65///                                             Logical array
66///                                                Contents
67/// ```
68///
69/// # `offset` and `len`
70///
71/// The [`Array::len`] and [`Array::offset`] for a `RunArray` refer to the
72/// **logical** length, not the `run_ends` and `values` child arrays. In the
73/// example above the `RunArray` has length `6` even though `run_ends` and
74/// `values` each contain `3` elements.
75///
76/// The values in `run_ends` represent indexes of the *unsliced* logical array.
77/// This allows zero-copy [`RunArray::slice`]: `run_ends` and `values` are left
78/// untouched and only `offset` and `len` are adjusted.
79///
80/// A [`RunArray`] must satisfy the following invariants:
81///
82/// * every run end is greater than zero and `run_ends` is strictly increasing
83/// * `run_ends` has no null values
84/// * `run_ends` and `values` have the same length
85/// * if `len > 0`, the last run end is greater than or equal to `offset + len`.
86///
87/// Note an empty `RunArray` (`len == 0`) is valid even when `run_ends` is empty
88/// or its last run end is less than `offset`. Note this is more permissive than
89/// the Arrow C++ implementation.
90///
91/// The example below shows the same array as above after calling `slice(1, 3)`
92///
93/// ```text
94/// ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─┐
95///   ┌─────────────────┐  ┌─────────┐       ┌ ─ ─ ─ ─ ─ ─ ─ ─ ┐
96/// │ │        A        │  │    2    │ │              A             logical index 0: before offset, not visible
97///   ├─────────────────┤  ├─────────┤       ┌─────────────────┐ ◄── offset = 1
98/// │ │        D        │  │    3    │ │     │        A        │    logical index 1 < run_ends[0] = 2, so 'A'
99///   ├─────────────────┤  ├─────────┤       ├─────────────────┤
100/// │ │        B        │  │    6    │ │     │        D        │    logical index 2 < run_ends[1] = 3, so 'D'
101///   └─────────────────┘  └─────────┘       ├─────────────────┤
102/// │        values          run_ends  │     │        B        │    logical index 3 < run_ends[2] = 6, so 'B'
103///                                          └─────────────────┘ ◄── offset + len = 4
104/// └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─┘              B             logical index 4: after offset + len, not visible
105///                                          ├ ─ ─ ─ ─ ─ ─ ─ ─ ┤
106///                RunArray                           B             logical index 5: after offset + len, not visible
107///          offset = 1, len = 3             └ ─ ─ ─ ─ ─ ─ ─ ─ ┘
108///
109///                                             Logical array
110///                                                Contents
111/// ```
112///
113/// # Sliced child arrays
114///
115/// [`RunArray::slice`] doesn't slice child arrays, but a `RunArray` may be
116/// built (for example from [`ArrayData`]) from child arrays that are already
117/// sliced. In that case each child's own `offset` and `len` are respected,
118/// independently of the logical `offset` and `len` of the `RunArray`:
119///
120/// * Run `i` ends at `run_ends.value(i)`, the `i`th (logical) element
121/// * The value of run `i` is `values.value(i)`, the `i`th (logical) element
122///
123/// [run-end encoded values]: https://arrow.apache.org/docs/format/Columnar.html#run-end-encoded-layout
124/// [run-length encoding (RLE)]: https://en.wikipedia.org/wiki/Run-length_encoding
125pub struct RunArray<R: RunEndIndexType> {
126    data_type: DataType,
127    run_ends: RunEndBuffer<R::Native>,
128    values: ArrayRef,
129}
130
131impl<R: RunEndIndexType> Clone for RunArray<R> {
132    fn clone(&self) -> Self {
133        Self {
134            data_type: self.data_type.clone(),
135            run_ends: self.run_ends.clone(),
136            values: self.values.clone(),
137        }
138    }
139}
140
141impl<R: RunEndIndexType> RunArray<R> {
142    /// Calculates the logical length of the array encoded by treating the `run_ends`
143    /// array as if it were a [`RunEndBuffer`].
144    pub fn logical_len(run_ends: &PrimitiveArray<R>) -> usize {
145        let len = run_ends.len();
146        if len == 0 {
147            return 0;
148        }
149        run_ends.value(len - 1).as_usize()
150    }
151
152    /// Attempts to create a [`RunArray`] using the given `run_ends` and `values`.
153    ///
154    /// The resulting array is unsliced: its logical offset is `0` and its logical
155    /// length is the last value of `run_ends` (or `0` if `run_ends` is empty).
156    ///
157    /// # Errors
158    ///
159    /// Returns an error if the [`RunArray` invariants] are not satisfied:
160    ///
161    /// - If `run_ends` and `values` have different lengths
162    /// - If `run_ends` has any null values
163    /// - If `run_ends` doesn't consist of strictly increasing positive integers
164    ///
165    /// [`RunArray` invariants]: RunArray#offset-and-len
166    pub fn try_new(run_ends: &PrimitiveArray<R>, values: &dyn Array) -> Result<Self, ArrowError> {
167        // 1. run_ends and values must have the same (physical) length.
168        if run_ends.len() != values.len() {
169            return Err(ArrowError::InvalidArgumentError(format!(
170                "The run_ends array length should be the same as values array length. Run_ends array length is {}, values array length is {}",
171                run_ends.len(),
172                values.len()
173            )));
174        }
175
176        // 2. run_ends must not contain null values.
177        if run_ends.nulls().is_some() {
178            return Err(ArrowError::InvalidArgumentError(
179                "Found null values in run_ends array. The run_ends array should not have null values."
180                    .to_string(),
181            ));
182        }
183
184        // 3. run_ends must be strictly increasing, strictly positive integers.
185        if let Some(first) = run_ends.values().first() {
186            let mut prev_value = *first;
187            if prev_value <= R::Native::usize_as(0) {
188                return Err(ArrowError::InvalidArgumentError(format!(
189                    "The values in run_ends array should be strictly positive. Found value {prev_value:?} at index 0 that does not match the criteria."
190                )));
191            }
192
193            for (ix, &run_end) in run_ends.values().iter().enumerate().skip(1) {
194                if run_end <= prev_value {
195                    return Err(ArrowError::InvalidArgumentError(format!(
196                        "The values in run_ends array should be strictly increasing. Found value {run_end:?} at index {ix} with previous value {prev_value:?} that does not match the criteria."
197                    )));
198                }
199                prev_value = run_end;
200            }
201        }
202
203        let data_type = DataType::RunEndEncoded(
204            Arc::new(Field::new(
205                Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
206                run_ends.data_type().clone(),
207                false,
208            )),
209            Arc::new(Field::new(
210                Field::REE_VALUES_FIELD_DEFAULT_NAME,
211                values.data_type().clone(),
212                true,
213            )),
214        );
215
216        let logical_len = RunArray::logical_len(run_ends);
217        // Safety: validated above that the run ends are strictly increasing, strictly
218        // positive integers, so the last value equals the logical length.
219        let run_ends_buffer =
220            unsafe { RunEndBuffer::new_unchecked(run_ends.values().clone(), 0, logical_len) };
221
222        Ok(Self {
223            data_type,
224            run_ends: run_ends_buffer,
225            values: values.to_arc(),
226        })
227    }
228
229    /// Create a new [`RunArray`] from the provided parts, without validation
230    ///
231    /// # Safety
232    ///
233    /// Safe if [`Self::try_new`] would not error, that is if `run_ends` and
234    /// `values` satisfy the [`RunArray` invariants]
235    ///
236    /// [`RunArray` invariants]: RunArray#offset-and-len
237    pub unsafe fn new_unchecked(
238        data_type: DataType,
239        run_ends: RunEndBuffer<R::Native>,
240        values: ArrayRef,
241    ) -> Self {
242        if cfg!(feature = "force_validate") {
243            match &data_type {
244                DataType::RunEndEncoded(run_ends, values_field) => {
245                    assert!(!run_ends.is_nullable(), "run_ends should not be nullable");
246                    assert_eq!(
247                        run_ends.data_type(),
248                        &R::DATA_TYPE,
249                        "Incorrect run ends type"
250                    );
251                    assert_eq!(
252                        values_field.data_type(),
253                        values.data_type(),
254                        "Incorrect values type"
255                    );
256                }
257                _ => {
258                    panic!(
259                        "Invalid data type {data_type:?} for RunArray. Should be DataType::RunEndEncoded"
260                    );
261                }
262            }
263
264            let run_array = Self {
265                data_type,
266                run_ends,
267                values,
268            };
269
270            // Safety: `validate_data` checks below
271            //    1. The given array data has exactly two child arrays.
272            //    2. The first child array (run_ends) has valid data type.
273            //    3. run_ends array does not have null values
274            //    4. run_ends array has non-zero and strictly increasing values.
275            //    5. The length of run_ends array and values array are the same.
276            run_array
277                .to_data()
278                .validate_data()
279                .expect("RunArray data should be valid");
280
281            return run_array;
282        }
283
284        Self {
285            data_type,
286            run_ends,
287            values,
288        }
289    }
290
291    /// Deconstruct this array into its constituent parts
292    pub fn into_parts(self) -> (DataType, RunEndBuffer<R::Native>, ArrayRef) {
293        (self.data_type, self.run_ends, self.values)
294    }
295
296    /// The field that describes the run ends of this array.
297    pub fn run_ends_field(&self) -> &FieldRef {
298        match &self.data_type {
299            DataType::RunEndEncoded(f, _) => f,
300            _ => unreachable!(),
301        }
302    }
303
304    /// The field that describes the values of this array.
305    pub fn values_field(&self) -> &FieldRef {
306        match &self.data_type {
307            DataType::RunEndEncoded(_, f) => f,
308            _ => unreachable!(),
309        }
310    }
311
312    /// Returns a reference to the [`RunEndBuffer`].
313    pub fn run_ends(&self) -> &RunEndBuffer<R::Native> {
314        &self.run_ends
315    }
316
317    /// Returns a reference to the values array.
318    ///
319    /// Any slicing of this [`RunArray`] array is **not** applied to the returned
320    /// values here and must be handled separately.
321    pub fn values(&self) -> &ArrayRef {
322        &self.values
323    }
324
325    /// Returns a new [`RunArray`] with the same `run_ends` and the supplied `values`.
326    ///
327    /// # Panics
328    ///
329    /// Panics if `values.len()` does not equal `self.values().len()`.
330    ///
331    /// # Example
332    ///
333    /// ```
334    /// # use std::sync::Arc;
335    /// # use arrow_array::{RunArray, Int32Array, StringArray, ArrayRef,Array};
336    /// # use arrow_array::types::Int32Type;
337    /// // A RunArray logically representing ["a", "a", "b", "c", "c"]
338    /// let run_ends = Int32Array::from(vec![2, 3, 5]);
339    /// let values: ArrayRef = Arc::new(StringArray::from(vec!["a", "b", "c"]));
340    /// let run_array = RunArray::<Int32Type>::try_new(&run_ends, &values).unwrap();
341    ///
342    /// // Swap in new values while keeping the same run pattern.
343    /// // The result logically represents ["x", "x", "y", "z", "z"].
344    /// let new_values: ArrayRef = Arc::new(StringArray::from(vec!["x", "y", "z"]));
345    /// let new_run_array = run_array.with_values(new_values);
346    ///
347    /// assert_eq!(new_run_array.len(), 5);
348    /// assert_eq!(new_run_array.run_ends().values(), &[2, 3, 5]);
349    /// ```
350    pub fn with_values(&self, values: ArrayRef) -> Self {
351        assert_eq!(values.len(), self.values.len());
352        let (run_ends_field, values_field) = match &self.data_type {
353            DataType::RunEndEncoded(r, v) => {
354                let new_v = Arc::new(Field::new(
355                    v.name(),
356                    values.data_type().clone(),
357                    v.is_nullable(),
358                ));
359                (r, new_v)
360            }
361            _ => unreachable!("RunArray should have type RunEndEncoded"),
362        };
363        let data_type = DataType::RunEndEncoded(Arc::clone(run_ends_field), values_field);
364
365        Self {
366            data_type,
367            run_ends: self.run_ends.clone(),
368            values,
369        }
370    }
371
372    /// Similar to [`values`] but accounts for logical slicing, returning only the values
373    /// that are part of the logical slice of this array.
374    ///
375    /// [`values`]: Self::values
376    pub fn values_slice(&self) -> ArrayRef {
377        if self.is_empty() {
378            return self.values.slice(0, 0);
379        }
380        let start = self.get_start_physical_index();
381        let end = self.get_end_physical_index();
382        self.values.slice(start, end - start + 1)
383    }
384
385    /// Returns the physical index at which the array slice starts.
386    ///
387    /// See [`RunEndBuffer::get_start_physical_index`].
388    pub fn get_start_physical_index(&self) -> usize {
389        self.run_ends.get_start_physical_index()
390    }
391
392    /// Returns the physical index at which the array slice ends.
393    ///
394    /// See [`RunEndBuffer::get_end_physical_index`].
395    pub fn get_end_physical_index(&self) -> usize {
396        self.run_ends.get_end_physical_index()
397    }
398
399    /// Downcast this [`RunArray`] to a [`TypedRunArray`]
400    ///
401    /// ```
402    /// use arrow_array::{Array, ArrayAccessor, RunArray, StringArray, types::Int32Type};
403    ///
404    /// let orig = [Some("a"), Some("b"), None];
405    /// let run_array = RunArray::<Int32Type>::from_iter(orig);
406    /// let typed = run_array.downcast::<StringArray>().unwrap();
407    /// assert_eq!(typed.value(0), "a");
408    /// assert_eq!(typed.value(1), "b");
409    /// assert!(typed.values().is_null(2));
410    /// ```
411    pub fn downcast<V: 'static>(&self) -> Option<TypedRunArray<'_, R, V>> {
412        let values = self.values.as_any().downcast_ref()?;
413        Some(TypedRunArray {
414            run_array: self,
415            values,
416        })
417    }
418
419    /// Calls [`RunEndBuffer::get_physical_index`].
420    ///
421    /// The result is arbitrary if `logical_index >= self.len()`
422    pub fn get_physical_index(&self, logical_index: usize) -> usize {
423        self.run_ends.get_physical_index(logical_index)
424    }
425
426    /// Returns the physical indices corresponding to the provided logical indices.
427    ///
428    /// See [`RunEndBuffer::get_physical_indices`] for more details.
429    #[inline]
430    pub fn get_physical_indices<I>(&self, logical_indices: &[I]) -> Result<Vec<usize>, ArrowError>
431    where
432        I: ArrowNativeType,
433    {
434        self.run_ends()
435            .get_physical_indices(logical_indices)
436            .map_err(|index| {
437                ArrowError::InvalidArgumentError(format!(
438                    "Logical index {} is out of bounds for RunArray of length {}",
439                    index.as_usize(),
440                    self.len()
441                ))
442            })
443    }
444
445    /// Returns a zero-copy slice of this array with the indicated offset and length.
446    ///
447    /// # Panics
448    ///
449    /// - Specified slice (`offset` + `length`) exceeds existing length
450    pub fn slice(&self, offset: usize, length: usize) -> Self {
451        Self {
452            data_type: self.data_type.clone(),
453            run_ends: self.run_ends.slice(offset, length),
454            values: self.values.clone(),
455        }
456    }
457}
458
459/// Converts an [`ArrayData`] into a [`RunArray`].
460///
461/// The `len` and `offset` of `data` become the logical length and offset of the
462/// [`RunArray`]; see the [`RunArray`] documentation for how they relate to the
463/// run ends.
464///
465/// The `offset` and `len` of the `run_ends` child are respected: only the `len`
466/// elements starting at `offset` are used as run ends. See [Sliced child
467/// arrays].
468///
469/// [Sliced child arrays]: RunArray#sliced-child-arrays
470///
471/// # Panics
472///
473/// Panics if `data` is not a [`DataType::RunEndEncoded`] array with a `run_ends`
474/// child of type `R`, or does not have exactly two children.
475impl<R: RunEndIndexType> From<ArrayData> for RunArray<R> {
476    // The method assumes the caller already validated the data using `ArrayData::validate_data()`
477    fn from(data: ArrayData) -> Self {
478        let (data_type, len, _nulls, offset, _buffers, child_data) = data.into_parts();
479
480        match &data_type {
481            DataType::RunEndEncoded(_, _) => {}
482            _ => {
483                panic!(
484                    "Invalid data type {data_type:?} for RunArray. Should be DataType::RunEndEncoded"
485                );
486            }
487        }
488
489        let [run_end_child, values_child]: [ArrayData; 2] = child_data
490            .try_into()
491            .expect("RunArray data should have exactly two child arrays");
492
493        // deconstruct the run ends child array
494        let (
495            run_end_data_type,
496            run_end_len,
497            _run_end_nulls,
498            run_end_offset,
499            run_end_buffers,
500            _run_end_child_data,
501        ) = run_end_child.into_parts();
502        assert_eq!(run_end_data_type, R::DATA_TYPE, "Incorrect run ends type");
503        let [run_end_buffer]: [arrow_buffer::Buffer; 1] = run_end_buffers
504            .try_into()
505            .expect("Run ends should have exactly one buffer");
506        let scalar = ScalarBuffer::new(run_end_buffer, run_end_offset, run_end_len);
507        let run_ends = unsafe { RunEndBuffer::new_unchecked(scalar, offset, len) };
508
509        let values = make_array(values_child);
510
511        Self {
512            data_type,
513            run_ends,
514            values,
515        }
516    }
517}
518
519impl<R: RunEndIndexType> From<RunArray<R>> for ArrayData {
520    fn from(array: RunArray<R>) -> Self {
521        let len = array.run_ends.len();
522        let offset = array.run_ends.offset();
523
524        let run_ends = ArrayDataBuilder::new(R::DATA_TYPE)
525            .len(array.run_ends.values().len())
526            .buffers(vec![array.run_ends.into_inner().into_inner()]);
527
528        let run_ends = unsafe { run_ends.build_unchecked() };
529
530        let builder = ArrayDataBuilder::new(array.data_type)
531            .len(len)
532            .offset(offset)
533            .child_data(vec![run_ends, array.values.to_data()]);
534
535        unsafe { builder.build_unchecked() }
536    }
537}
538
539/// SAFETY: Correctly implements the contract of Arrow Arrays
540unsafe impl<T: RunEndIndexType> Array for RunArray<T> {
541    fn as_any(&self) -> &dyn Any {
542        self
543    }
544
545    fn to_arc(&self) -> ArrayRef {
546        Arc::new(self.clone())
547    }
548
549    fn to_data(&self) -> ArrayData {
550        self.clone().into()
551    }
552
553    fn into_data(self) -> ArrayData {
554        self.into()
555    }
556
557    fn data_type(&self) -> &DataType {
558        &self.data_type
559    }
560
561    fn slice(&self, offset: usize, length: usize) -> ArrayRef {
562        Arc::new(self.slice(offset, length))
563    }
564
565    fn len(&self) -> usize {
566        self.run_ends.len()
567    }
568
569    fn is_empty(&self) -> bool {
570        self.run_ends.is_empty()
571    }
572
573    fn shrink_to_fit(&mut self) {
574        self.run_ends.shrink_to_fit();
575        self.values.shrink_to_fit();
576    }
577
578    fn offset(&self) -> usize {
579        self.run_ends.offset()
580    }
581
582    fn nulls(&self) -> Option<&NullBuffer> {
583        None
584    }
585
586    fn logical_nulls(&self) -> Option<NullBuffer> {
587        let len = self.len();
588        let nulls = self.values.logical_nulls()?;
589        let mut out = BooleanBufferBuilder::new(len);
590        let offset = self.run_ends.offset();
591        let mut valid_start = 0;
592        let mut last_end = 0;
593        for (idx, end) in self.run_ends.values().iter().enumerate() {
594            let end = end.as_usize();
595            if end < offset {
596                continue;
597            }
598            let end = (end - offset).min(len);
599            if nulls.is_null(idx) {
600                if valid_start < last_end {
601                    out.append_n(last_end - valid_start, true);
602                }
603                out.append_n(end - last_end, false);
604                valid_start = end;
605            }
606            last_end = end;
607            if end == len {
608                break;
609            }
610        }
611        if valid_start < len {
612            out.append_n(len - valid_start, true)
613        }
614        // Sanity check
615        assert_eq!(out.len(), len);
616        Some(out.finish().into())
617    }
618
619    fn is_nullable(&self) -> bool {
620        !self.is_empty() && self.values.is_nullable()
621    }
622
623    fn get_buffer_memory_size(&self) -> usize {
624        self.run_ends.inner().inner().capacity() + self.values.get_buffer_memory_size()
625    }
626
627    fn get_array_memory_size(&self) -> usize {
628        std::mem::size_of::<Self>()
629            + self.run_ends.inner().inner().capacity()
630            + self.values.get_array_memory_size()
631    }
632
633    #[cfg(feature = "pool")]
634    fn claim(&self, pool: &dyn arrow_buffer::MemoryPool) {
635        self.run_ends.claim(pool);
636        self.values.claim(pool);
637    }
638}
639
640impl<R: RunEndIndexType> std::fmt::Debug for RunArray<R> {
641    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
642        writeln!(
643            f,
644            "RunArray {{run_ends: {:?}, values: {:?}}}",
645            self.run_ends.values(),
646            self.values
647        )
648    }
649}
650
651/// Constructs a `RunArray` from an iterator of optional strings.
652///
653/// # Example:
654/// ```
655/// use arrow_array::{RunArray, PrimitiveArray, StringArray, types::Int16Type};
656///
657/// let test = vec!["a", "a", "b", "c", "c"];
658/// let array: RunArray<Int16Type> = test
659///     .iter()
660///     .map(|&x| if x == "b" { None } else { Some(x) })
661///     .collect();
662/// assert_eq!(
663///     "RunArray {run_ends: [2, 3, 5], values: StringArray\n[\n  \"a\",\n  null,\n  \"c\",\n]}\n",
664///     format!("{:?}", array)
665/// );
666/// ```
667impl<'a, T: RunEndIndexType> FromIterator<Option<&'a str>> for RunArray<T> {
668    fn from_iter<I: IntoIterator<Item = Option<&'a str>>>(iter: I) -> Self {
669        let it = iter.into_iter();
670        let (lower, _) = it.size_hint();
671        let mut builder = StringRunBuilder::with_capacity(lower, 256);
672        it.for_each(|i| {
673            builder.append_option(i);
674        });
675
676        builder.finish()
677    }
678}
679
680/// Constructs a `RunArray` from an iterator of strings.
681///
682/// # Example:
683///
684/// ```
685/// use arrow_array::{RunArray, PrimitiveArray, StringArray, types::Int16Type};
686///
687/// let test = vec!["a", "a", "b", "c"];
688/// let array: RunArray<Int16Type> = test.into_iter().collect();
689/// assert_eq!(
690///     "RunArray {run_ends: [2, 3, 4], values: StringArray\n[\n  \"a\",\n  \"b\",\n  \"c\",\n]}\n",
691///     format!("{:?}", array)
692/// );
693/// ```
694impl<'a, T: RunEndIndexType> FromIterator<&'a str> for RunArray<T> {
695    fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> Self {
696        let it = iter.into_iter();
697        let (lower, _) = it.size_hint();
698        let mut builder = StringRunBuilder::with_capacity(lower, 256);
699        it.for_each(|i| {
700            builder.append_value(i);
701        });
702
703        builder.finish()
704    }
705}
706
707///
708/// A [`RunArray`] with `i16` run ends
709///
710/// # Example: Using `collect`
711/// ```
712/// # use arrow_array::{Array, Int16RunArray, Int16Array, StringArray};
713/// # use std::sync::Arc;
714///
715/// let array: Int16RunArray = vec!["a", "a", "b", "c", "c"].into_iter().collect();
716/// let values: Arc<dyn Array> = Arc::new(StringArray::from(vec!["a", "b", "c"]));
717/// assert_eq!(array.run_ends().values(), &[2, 3, 5]);
718/// assert_eq!(array.values(), &values);
719/// ```
720pub type Int16RunArray = RunArray<Int16Type>;
721
722///
723/// A [`RunArray`] with `i32` run ends
724///
725/// # Example: Using `collect`
726/// ```
727/// # use arrow_array::{Array, Int32RunArray, Int32Array, StringArray};
728/// # use std::sync::Arc;
729///
730/// let array: Int32RunArray = vec!["a", "a", "b", "c", "c"].into_iter().collect();
731/// let values: Arc<dyn Array> = Arc::new(StringArray::from(vec!["a", "b", "c"]));
732/// assert_eq!(array.run_ends().values(), &[2, 3, 5]);
733/// assert_eq!(array.values(), &values);
734/// ```
735pub type Int32RunArray = RunArray<Int32Type>;
736
737///
738/// A [`RunArray`] with `i64` run ends
739///
740/// # Example: Using `collect`
741/// ```
742/// # use arrow_array::{Array, Int64RunArray, Int64Array, StringArray};
743/// # use std::sync::Arc;
744///
745/// let array: Int64RunArray = vec!["a", "a", "b", "c", "c"].into_iter().collect();
746/// let values: Arc<dyn Array> = Arc::new(StringArray::from(vec!["a", "b", "c"]));
747/// assert_eq!(array.run_ends().values(), &[2, 3, 5]);
748/// assert_eq!(array.values(), &values);
749/// ```
750pub type Int64RunArray = RunArray<Int64Type>;
751
752/// A [`RunArray`] typed on its child values array
753///
754/// Implements [`ArrayAccessor`] and [`IntoIterator`] allowing fast access to its elements
755///
756/// ```
757/// use arrow_array::{RunArray, StringArray, types::Int32Type};
758///
759/// let orig = ["a", "b", "a", "b"];
760/// let ree_array = RunArray::<Int32Type>::from_iter(orig);
761///
762/// // `TypedRunArray` allows you to access the values directly
763/// let typed = ree_array.downcast::<StringArray>().unwrap();
764///
765/// for (maybe_val, orig) in typed.into_iter().zip(orig) {
766///     assert_eq!(maybe_val.unwrap(), orig)
767/// }
768/// ```
769pub struct TypedRunArray<'a, R: RunEndIndexType, V> {
770    /// The run array
771    run_array: &'a RunArray<R>,
772
773    /// The values of the run_array
774    values: &'a V,
775}
776
777// Manually implement `Clone` to avoid `V: Clone` type constraint
778impl<R: RunEndIndexType, V> Clone for TypedRunArray<'_, R, V> {
779    fn clone(&self) -> Self {
780        *self
781    }
782}
783
784impl<R: RunEndIndexType, V> Copy for TypedRunArray<'_, R, V> {}
785
786impl<R: RunEndIndexType, V> std::fmt::Debug for TypedRunArray<'_, R, V> {
787    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
788        writeln!(f, "TypedRunArray({:?})", self.run_array)
789    }
790}
791
792impl<'a, R: RunEndIndexType, V> TypedRunArray<'a, R, V> {
793    /// Returns the run_ends of this [`TypedRunArray`]
794    pub fn run_ends(&self) -> &'a RunEndBuffer<R::Native> {
795        self.run_array.run_ends()
796    }
797
798    /// Returns the values of this [`TypedRunArray`]
799    pub fn values(&self) -> &'a V {
800        self.values
801    }
802
803    /// Returns the run array of this [`TypedRunArray`]
804    pub fn run_array(&self) -> &'a RunArray<R> {
805        self.run_array
806    }
807}
808
809/// SAFETY: Correctly implements the contract of Arrow Arrays
810unsafe impl<R: RunEndIndexType, V: Sync> Array for TypedRunArray<'_, R, V> {
811    fn as_any(&self) -> &dyn Any {
812        self.run_array
813    }
814
815    fn to_arc(&self) -> ArrayRef {
816        Arc::new(self.run_array.clone())
817    }
818
819    fn to_data(&self) -> ArrayData {
820        self.run_array.to_data()
821    }
822
823    fn into_data(self) -> ArrayData {
824        self.run_array.into_data()
825    }
826
827    fn data_type(&self) -> &DataType {
828        self.run_array.data_type()
829    }
830
831    fn slice(&self, offset: usize, length: usize) -> ArrayRef {
832        Arc::new(self.run_array.slice(offset, length))
833    }
834
835    fn len(&self) -> usize {
836        self.run_array.len()
837    }
838
839    fn is_empty(&self) -> bool {
840        self.run_array.is_empty()
841    }
842
843    fn offset(&self) -> usize {
844        self.run_array.offset()
845    }
846
847    fn nulls(&self) -> Option<&NullBuffer> {
848        self.run_array.nulls()
849    }
850
851    fn logical_nulls(&self) -> Option<NullBuffer> {
852        self.run_array.logical_nulls()
853    }
854
855    fn logical_null_count(&self) -> usize {
856        self.run_array.logical_null_count()
857    }
858
859    fn is_nullable(&self) -> bool {
860        self.run_array.is_nullable()
861    }
862
863    fn get_buffer_memory_size(&self) -> usize {
864        self.run_array.get_buffer_memory_size()
865    }
866
867    fn get_array_memory_size(&self) -> usize {
868        self.run_array.get_array_memory_size()
869    }
870
871    #[cfg(feature = "pool")]
872    fn claim(&self, pool: &dyn arrow_buffer::MemoryPool) {
873        self.run_array.claim(pool);
874    }
875}
876
877// Array accessor converts the index of logical array to the index of the physical array
878// using binary search. The time complexity is O(log N) where N is number of runs.
879impl<'a, R, V> ArrayAccessor for TypedRunArray<'a, R, V>
880where
881    R: RunEndIndexType,
882    V: Sync + Send,
883    &'a V: ArrayAccessor,
884    <&'a V as ArrayAccessor>::Item: Default,
885{
886    type Item = <&'a V as ArrayAccessor>::Item;
887
888    fn value(&self, logical_index: usize) -> Self::Item {
889        assert!(
890            logical_index < self.len(),
891            "Trying to access an element at index {} from a TypedRunArray of length {}",
892            logical_index,
893            self.len()
894        );
895        unsafe { self.value_unchecked(logical_index) }
896    }
897
898    unsafe fn value_unchecked(&self, logical_index: usize) -> Self::Item {
899        let physical_index = self.run_array.get_physical_index(logical_index);
900        unsafe { self.values().value_unchecked(physical_index) }
901    }
902}
903
904impl<'a, R, V> IntoIterator for TypedRunArray<'a, R, V>
905where
906    R: RunEndIndexType,
907    V: Sync + Send,
908    &'a V: ArrayAccessor,
909    <&'a V as ArrayAccessor>::Item: Default,
910{
911    type Item = Option<<&'a V as ArrayAccessor>::Item>;
912    type IntoIter = RunArrayIter<'a, R, V>;
913
914    fn into_iter(self) -> Self::IntoIter {
915        RunArrayIter::new(self)
916    }
917}
918/// An array that can be downcast to a [`RunArray`] of any run end type and any value type.
919///
920/// This can be used to efficiently implement kernels for all possible run end
921/// types without needing to create specialized implementations for each key type.
922pub trait AnyRunEndArray: Array {
923    /// Returns the values of this array.
924    fn values(&self) -> &Arc<dyn Array>;
925
926    /// Returns a new run-end encoded array with the given values, preserving the
927    /// existing run ends.
928    fn with_values(&self, values: ArrayRef) -> ArrayRef;
929}
930
931impl<R: RunEndIndexType> AnyRunEndArray for RunArray<R> {
932    fn values(&self) -> &Arc<dyn Array> {
933        &self.values
934    }
935
936    fn with_values(&self, values: ArrayRef) -> ArrayRef {
937        Arc::new(RunArray::<R>::with_values(self, values))
938    }
939}
940
941#[cfg(test)]
942mod tests {
943    use rand::RngExt;
944    use rand::rng;
945    use rand::seq::SliceRandom;
946
947    use super::*;
948    use crate::Float32Array;
949    use crate::Int64Array;
950    use crate::builder::PrimitiveRunBuilder;
951    use crate::cast::AsArray;
952    use crate::new_empty_array;
953    use crate::types::{Int8Type, UInt32Type};
954    use crate::{Int16Array, Int32Array, StringArray};
955
956    fn build_input_array(size: usize) -> Vec<Option<i32>> {
957        // The input array is created by shuffling and repeating
958        // the seed values random number of times.
959        let mut seed: Vec<Option<i32>> = vec![
960            None,
961            None,
962            None,
963            Some(1),
964            Some(2),
965            Some(3),
966            Some(4),
967            Some(5),
968            Some(6),
969            Some(7),
970            Some(8),
971            Some(9),
972        ];
973        let mut result: Vec<Option<i32>> = Vec::with_capacity(size);
974        let mut ix = 0;
975        let mut rng = rng();
976        // run length can go up to 8. Cap the max run length for smaller arrays to size / 2.
977        let max_run_length = 8_usize.min(1_usize.max(size / 2));
978        while result.len() < size {
979            // shuffle the seed array if all the values are iterated.
980            if ix == 0 {
981                seed.shuffle(&mut rng);
982            }
983            // repeat the items between 1 and 8 times. Cap the length for smaller sized arrays
984            let num = max_run_length.min(rng.random_range(1..=max_run_length));
985            for _ in 0..num {
986                result.push(seed[ix]);
987            }
988            ix += 1;
989            if ix == seed.len() {
990                ix = 0
991            }
992        }
993        result.resize(size, None);
994        result
995    }
996
997    // Asserts that `logical_array[logical_indices[*]] == physical_array[physical_indices[*]]`
998    fn compare_logical_and_physical_indices(
999        logical_indices: &[u32],
1000        logical_array: &[Option<i32>],
1001        physical_indices: &[usize],
1002        physical_array: &PrimitiveArray<Int32Type>,
1003    ) {
1004        assert_eq!(logical_indices.len(), physical_indices.len());
1005
1006        // check value in logical index in the logical_array matches physical index in physical_array
1007        logical_indices
1008            .iter()
1009            .map(|f| f.as_usize())
1010            .zip(physical_indices.iter())
1011            .for_each(|(logical_ix, physical_ix)| {
1012                let expected = logical_array[logical_ix];
1013                match expected {
1014                    Some(val) => {
1015                        assert!(physical_array.is_valid(*physical_ix));
1016                        let actual = physical_array.value(*physical_ix);
1017                        assert_eq!(val, actual);
1018                    }
1019                    None => {
1020                        assert!(physical_array.is_null(*physical_ix))
1021                    }
1022                }
1023            });
1024    }
1025    #[test]
1026    fn test_run_array() {
1027        // Construct a value array
1028        let value_data =
1029            PrimitiveArray::<Int8Type>::from_iter_values([10_i8, 11, 12, 13, 14, 15, 16, 17]);
1030
1031        // Construct a run_ends array:
1032        let run_ends_values = [4_i16, 6, 7, 9, 13, 18, 20, 22];
1033        let run_ends_data =
1034            PrimitiveArray::<Int16Type>::from_iter_values(run_ends_values.iter().copied());
1035
1036        // Construct a run ends encoded array from the above two
1037        let ree_array = RunArray::<Int16Type>::try_new(&run_ends_data, &value_data).unwrap();
1038
1039        assert_eq!(ree_array.len(), 22);
1040        assert_eq!(ree_array.null_count(), 0);
1041
1042        let values = ree_array.values();
1043        assert_eq!(value_data.into_data(), values.to_data());
1044        assert_eq!(&DataType::Int8, values.data_type());
1045
1046        let run_ends = ree_array.run_ends();
1047        assert_eq!(run_ends.values(), &run_ends_values);
1048    }
1049
1050    #[test]
1051    fn test_run_array_empty() {
1052        let runs = new_empty_array(&DataType::Int16);
1053        let runs = runs.as_primitive::<Int16Type>();
1054        let values = new_empty_array(&DataType::Int64);
1055        let array = RunArray::try_new(runs, &values).unwrap();
1056
1057        fn assertions(array: &RunArray<Int16Type>) {
1058            assert!(array.is_empty());
1059            assert_eq!(array.get_start_physical_index(), 0);
1060            assert_eq!(array.get_end_physical_index(), 0);
1061            assert!(array.get_physical_indices::<i16>(&[]).unwrap().is_empty());
1062            assert!(array.run_ends().is_empty());
1063            assert_eq!(array.run_ends().sliced_values().count(), 0);
1064        }
1065
1066        assertions(&array);
1067        assertions(&array.slice(0, 0));
1068    }
1069
1070    #[test]
1071    fn test_run_array_fmt_debug() {
1072        let mut builder = PrimitiveRunBuilder::<Int16Type, UInt32Type>::with_capacity(3);
1073        builder.append_value(12345678);
1074        builder.append_null();
1075        builder.append_value(22345678);
1076        let array = builder.finish();
1077        assert_eq!(
1078            "RunArray {run_ends: [1, 2, 3], values: PrimitiveArray<UInt32>\n[\n  12345678,\n  null,\n  22345678,\n]}\n",
1079            format!("{array:?}")
1080        );
1081
1082        let mut builder = PrimitiveRunBuilder::<Int16Type, UInt32Type>::with_capacity(20);
1083        for _ in 0..20 {
1084            builder.append_value(1);
1085        }
1086        let array = builder.finish();
1087
1088        assert_eq!(array.len(), 20);
1089        assert_eq!(array.null_count(), 0);
1090        assert_eq!(array.logical_null_count(), 0);
1091
1092        assert_eq!(
1093            "RunArray {run_ends: [20], values: PrimitiveArray<UInt32>\n[\n  1,\n]}\n",
1094            format!("{array:?}")
1095        );
1096    }
1097
1098    #[test]
1099    fn test_run_array_from_iter() {
1100        let test = vec!["a", "a", "b", "c"];
1101        let array: RunArray<Int16Type> = test
1102            .iter()
1103            .map(|&x| if x == "b" { None } else { Some(x) })
1104            .collect();
1105        assert_eq!(
1106            "RunArray {run_ends: [2, 3, 4], values: StringArray\n[\n  \"a\",\n  null,\n  \"c\",\n]}\n",
1107            format!("{array:?}")
1108        );
1109
1110        assert_eq!(array.len(), 4);
1111        assert_eq!(array.null_count(), 0);
1112        assert_eq!(array.logical_null_count(), 1);
1113
1114        let array: RunArray<Int16Type> = test.into_iter().collect();
1115        assert_eq!(
1116            "RunArray {run_ends: [2, 3, 4], values: StringArray\n[\n  \"a\",\n  \"b\",\n  \"c\",\n]}\n",
1117            format!("{array:?}")
1118        );
1119    }
1120
1121    #[test]
1122    fn test_run_array_run_ends_as_primitive_array() {
1123        let test = vec!["a", "b", "c", "a"];
1124        let array: RunArray<Int16Type> = test.into_iter().collect();
1125
1126        assert_eq!(array.len(), 4);
1127        assert_eq!(array.null_count(), 0);
1128        assert_eq!(array.logical_null_count(), 0);
1129
1130        let run_ends = array.run_ends();
1131        assert_eq!(&[1, 2, 3, 4], run_ends.values());
1132    }
1133
1134    #[test]
1135    fn test_run_array_as_primitive_array_with_null() {
1136        let test = vec![Some("a"), None, Some("b"), None, None, Some("a")];
1137        let array: RunArray<Int32Type> = test.into_iter().collect();
1138
1139        assert_eq!(array.len(), 6);
1140        assert_eq!(array.null_count(), 0);
1141        assert_eq!(array.logical_null_count(), 3);
1142
1143        let run_ends = array.run_ends();
1144        assert_eq!(&[1, 2, 3, 5, 6], run_ends.values());
1145
1146        let values_data = array.values();
1147        assert_eq!(2, values_data.null_count());
1148        assert_eq!(5, values_data.len());
1149    }
1150
1151    #[test]
1152    fn test_run_array_all_nulls() {
1153        let test = vec![None, None, None];
1154        let array: RunArray<Int32Type> = test.into_iter().collect();
1155
1156        assert_eq!(array.len(), 3);
1157        assert_eq!(array.null_count(), 0);
1158        assert_eq!(array.logical_null_count(), 3);
1159
1160        let run_ends = array.run_ends();
1161        assert_eq!(3, run_ends.len());
1162        assert_eq!(&[3], run_ends.values());
1163
1164        let values_data = array.values();
1165        assert_eq!(1, values_data.null_count());
1166    }
1167
1168    #[test]
1169    fn test_run_array_try_new() {
1170        let values: StringArray = [Some("foo"), Some("bar"), None, Some("baz")]
1171            .into_iter()
1172            .collect();
1173        let run_ends: Int32Array = [Some(1), Some(2), Some(3), Some(4)].into_iter().collect();
1174
1175        let array = RunArray::<Int32Type>::try_new(&run_ends, &values).unwrap();
1176        assert_eq!(array.values().data_type(), &DataType::Utf8);
1177
1178        assert_eq!(array.null_count(), 0);
1179        assert_eq!(array.logical_null_count(), 1);
1180        assert_eq!(array.len(), 4);
1181        assert_eq!(array.values().null_count(), 1);
1182
1183        assert_eq!(
1184            "RunArray {run_ends: [1, 2, 3, 4], values: StringArray\n[\n  \"foo\",\n  \"bar\",\n  null,\n  \"baz\",\n]}\n",
1185            format!("{array:?}")
1186        );
1187    }
1188
1189    #[test]
1190    fn test_run_array_int16_type_definition() {
1191        let array: Int16RunArray = vec!["a", "a", "b", "c", "c"].into_iter().collect();
1192        let values: Arc<dyn Array> = Arc::new(StringArray::from(vec!["a", "b", "c"]));
1193        assert_eq!(array.run_ends().values(), &[2, 3, 5]);
1194        assert_eq!(array.values(), &values);
1195    }
1196
1197    #[test]
1198    fn test_run_array_empty_string() {
1199        let array: Int16RunArray = vec!["a", "a", "", "", "c"].into_iter().collect();
1200        let values: Arc<dyn Array> = Arc::new(StringArray::from(vec!["a", "", "c"]));
1201        assert_eq!(array.run_ends().values(), &[2, 4, 5]);
1202        assert_eq!(array.values(), &values);
1203    }
1204
1205    #[test]
1206    fn test_run_array_length_mismatch() {
1207        let values: StringArray = [Some("foo"), Some("bar"), None, Some("baz")]
1208            .into_iter()
1209            .collect();
1210        let run_ends: Int32Array = [Some(1), Some(2), Some(3)].into_iter().collect();
1211
1212        let actual = RunArray::<Int32Type>::try_new(&run_ends, &values);
1213        let expected = ArrowError::InvalidArgumentError("The run_ends array length should be the same as values array length. Run_ends array length is 3, values array length is 4".to_string());
1214        assert_eq!(expected.to_string(), actual.err().unwrap().to_string());
1215    }
1216    #[test]
1217    fn test_run_array_with_values_changes_value_type() {
1218        let values = StringArray::from(vec!["foo", "bar", "baz"]);
1219        let run_ends: Int32Array = [Some(1), Some(2), Some(3)].into_iter().collect();
1220        let ree = RunArray::<Int32Type>::try_new(&run_ends, &values).unwrap();
1221
1222        let new_values = Int64Array::from(vec![10, 20, 30]);
1223        let result = ree.with_values(Arc::new(new_values));
1224
1225        match result.data_type() {
1226            DataType::RunEndEncoded(_, v) => {
1227                assert_eq!(v.data_type(), &DataType::Int64);
1228            }
1229            other => panic!("expected RunEndEncoded, got {other:?}"),
1230        }
1231
1232        assert_eq!(result.values().data_type(), &DataType::Int64);
1233        assert_eq!(result.values().len(), 3);
1234    }
1235
1236    #[test]
1237    fn test_run_array_run_ends_with_null() {
1238        let values: StringArray = [Some("foo"), Some("bar"), Some("baz")]
1239            .into_iter()
1240            .collect();
1241        let run_ends: Int32Array = [Some(1), None, Some(3)].into_iter().collect();
1242
1243        let actual = RunArray::<Int32Type>::try_new(&run_ends, &values);
1244        let expected = ArrowError::InvalidArgumentError(
1245            "Found null values in run_ends array. The run_ends array should not have null values."
1246                .to_string(),
1247        );
1248        assert_eq!(expected.to_string(), actual.err().unwrap().to_string());
1249    }
1250
1251    #[test]
1252    fn test_run_array_run_ends_with_zeroes() {
1253        let values: StringArray = [Some("foo"), Some("bar"), Some("baz")]
1254            .into_iter()
1255            .collect();
1256        let run_ends: Int32Array = [Some(0), Some(1), Some(3)].into_iter().collect();
1257
1258        let actual = RunArray::<Int32Type>::try_new(&run_ends, &values);
1259        let expected = ArrowError::InvalidArgumentError("The values in run_ends array should be strictly positive. Found value 0 at index 0 that does not match the criteria.".to_string());
1260        assert_eq!(expected.to_string(), actual.err().unwrap().to_string());
1261    }
1262
1263    #[test]
1264    fn test_run_array_run_ends_non_increasing() {
1265        let values: StringArray = [Some("foo"), Some("bar"), Some("baz")]
1266            .into_iter()
1267            .collect();
1268        let run_ends: Int32Array = [Some(1), Some(4), Some(4)].into_iter().collect();
1269
1270        let actual = RunArray::<Int32Type>::try_new(&run_ends, &values);
1271        let expected = ArrowError::InvalidArgumentError("The values in run_ends array should be strictly increasing. Found value 4 at index 2 with previous value 4 that does not match the criteria.".to_string());
1272        assert_eq!(expected.to_string(), actual.err().unwrap().to_string());
1273    }
1274
1275    #[test]
1276    #[should_panic(expected = "Incorrect run ends type")]
1277    fn test_run_array_run_ends_data_type_mismatch() {
1278        let a = RunArray::<Int32Type>::from_iter(["32"]);
1279        let _ = RunArray::<Int64Type>::from(a.into_data());
1280    }
1281
1282    #[test]
1283    fn test_ree_array_accessor() {
1284        let input_array = build_input_array(256);
1285
1286        // Encode the input_array to ree_array
1287        let mut builder =
1288            PrimitiveRunBuilder::<Int16Type, Int32Type>::with_capacity(input_array.len());
1289        builder.extend(input_array.iter().copied());
1290        let run_array = builder.finish();
1291        let typed = run_array.downcast::<PrimitiveArray<Int32Type>>().unwrap();
1292
1293        // Access every index and check if the value in the input array matches returned value.
1294        for (i, inp_val) in input_array.iter().enumerate() {
1295            if let Some(val) = inp_val {
1296                let actual = typed.value(i);
1297                assert_eq!(*val, actual)
1298            } else {
1299                let physical_ix = run_array.get_physical_index(i);
1300                assert!(typed.values().is_null(physical_ix));
1301            }
1302        }
1303    }
1304
1305    #[test]
1306    #[cfg_attr(miri, ignore)] // Takes too long
1307    fn test_get_physical_indices() {
1308        // Test for logical lengths starting from 10 to 250 increasing by 10
1309        for logical_len in (0..250).step_by(10) {
1310            let input_array = build_input_array(logical_len);
1311
1312            // create run array using input_array
1313            let mut builder = PrimitiveRunBuilder::<Int32Type, Int32Type>::new();
1314            builder.extend(input_array.clone());
1315
1316            let run_array = builder.finish();
1317            let physical_values_array = run_array.values().as_primitive::<Int32Type>();
1318
1319            // create an array consisting of all the indices repeated twice and shuffled.
1320            let mut logical_indices: Vec<u32> = (0_u32..(logical_len as u32)).collect();
1321            // add same indices once more
1322            logical_indices.append(&mut logical_indices.clone());
1323            let mut rng = rng();
1324            logical_indices.shuffle(&mut rng);
1325
1326            let physical_indices = run_array.get_physical_indices(&logical_indices).unwrap();
1327
1328            assert_eq!(logical_indices.len(), physical_indices.len());
1329
1330            // check value in logical index in the input_array matches physical index in typed_run_array
1331            compare_logical_and_physical_indices(
1332                &logical_indices,
1333                &input_array,
1334                &physical_indices,
1335                physical_values_array,
1336            );
1337        }
1338    }
1339
1340    #[test]
1341    #[cfg_attr(miri, ignore)] // Takes too long
1342    fn test_get_physical_indices_sliced() {
1343        let total_len = 80;
1344        let input_array = build_input_array(total_len);
1345
1346        // Encode the input_array to run array
1347        let mut builder =
1348            PrimitiveRunBuilder::<Int16Type, Int32Type>::with_capacity(input_array.len());
1349        builder.extend(input_array.iter().copied());
1350        let run_array = builder.finish();
1351        let physical_values_array = run_array.values().as_primitive::<Int32Type>();
1352
1353        // test for all slice lengths.
1354        for slice_len in 1..=total_len {
1355            // create an array consisting of all the indices repeated twice and shuffled.
1356            let mut logical_indices: Vec<u32> = (0_u32..(slice_len as u32)).collect();
1357            // add same indices once more
1358            logical_indices.append(&mut logical_indices.clone());
1359            let mut rng = rng();
1360            logical_indices.shuffle(&mut rng);
1361
1362            // test for offset = 0 and slice length = slice_len
1363            // slice the input array using which the run array was built.
1364            let sliced_input_array = &input_array[0..slice_len];
1365
1366            // slice the run array
1367            let sliced_run_array: RunArray<Int16Type> =
1368                run_array.slice(0, slice_len).into_data().into();
1369
1370            // Get physical indices.
1371            let physical_indices = sliced_run_array
1372                .get_physical_indices(&logical_indices)
1373                .unwrap();
1374
1375            compare_logical_and_physical_indices(
1376                &logical_indices,
1377                sliced_input_array,
1378                &physical_indices,
1379                physical_values_array,
1380            );
1381
1382            // test for offset = total_len - slice_len and slice length = slice_len
1383            // slice the input array using which the run array was built.
1384            let sliced_input_array = &input_array[total_len - slice_len..total_len];
1385
1386            // slice the run array
1387            let sliced_run_array: RunArray<Int16Type> = run_array
1388                .slice(total_len - slice_len, slice_len)
1389                .into_data()
1390                .into();
1391
1392            // Get physical indices
1393            let physical_indices = sliced_run_array
1394                .get_physical_indices(&logical_indices)
1395                .unwrap();
1396
1397            compare_logical_and_physical_indices(
1398                &logical_indices,
1399                sliced_input_array,
1400                &physical_indices,
1401                physical_values_array,
1402            );
1403        }
1404    }
1405
1406    #[test]
1407    fn test_logical_nulls() {
1408        let run = Int32Array::from(vec![3, 6, 9, 12]);
1409        let values = Int32Array::from(vec![Some(0), None, Some(1), None]);
1410        let array = RunArray::try_new(&run, &values).unwrap();
1411
1412        let expected = [
1413            true, true, true, false, false, false, true, true, true, false, false, false,
1414        ];
1415
1416        let n = array.logical_nulls().unwrap();
1417        assert_eq!(n.null_count(), 6);
1418
1419        let slices = [(0, 12), (0, 2), (2, 5), (3, 0), (3, 3), (3, 4), (4, 8)];
1420        for (offset, length) in slices {
1421            let a = array.slice(offset, length);
1422            let n = a.logical_nulls().unwrap();
1423            let n = n.into_iter().collect::<Vec<_>>();
1424            assert_eq!(&n, &expected[offset..offset + length], "{offset} {length}");
1425        }
1426    }
1427
1428    #[test]
1429    fn test_run_array_eq_identical() {
1430        let run_ends1 = Int32Array::from(vec![2, 4, 6]);
1431        let values1 = StringArray::from(vec!["a", "b", "c"]);
1432        let array1 = RunArray::<Int32Type>::try_new(&run_ends1, &values1).unwrap();
1433
1434        let run_ends2 = Int32Array::from(vec![2, 4, 6]);
1435        let values2 = StringArray::from(vec!["a", "b", "c"]);
1436        let array2 = RunArray::<Int32Type>::try_new(&run_ends2, &values2).unwrap();
1437
1438        assert_eq!(array1, array2);
1439    }
1440
1441    #[test]
1442    fn test_run_array_ne_different_run_ends() {
1443        let run_ends1 = Int32Array::from(vec![2, 4, 6]);
1444        let values1 = StringArray::from(vec!["a", "b", "c"]);
1445        let array1 = RunArray::<Int32Type>::try_new(&run_ends1, &values1).unwrap();
1446
1447        let run_ends2 = Int32Array::from(vec![1, 4, 6]);
1448        let values2 = StringArray::from(vec!["a", "b", "c"]);
1449        let array2 = RunArray::<Int32Type>::try_new(&run_ends2, &values2).unwrap();
1450
1451        assert_ne!(array1, array2);
1452    }
1453
1454    #[test]
1455    fn test_run_array_ne_different_values() {
1456        let run_ends1 = Int32Array::from(vec![2, 4, 6]);
1457        let values1 = StringArray::from(vec!["a", "b", "c"]);
1458        let array1 = RunArray::<Int32Type>::try_new(&run_ends1, &values1).unwrap();
1459
1460        let run_ends2 = Int32Array::from(vec![2, 4, 6]);
1461        let values2 = StringArray::from(vec!["a", "b", "d"]);
1462        let array2 = RunArray::<Int32Type>::try_new(&run_ends2, &values2).unwrap();
1463
1464        assert_ne!(array1, array2);
1465    }
1466
1467    #[test]
1468    fn test_run_array_eq_with_nulls() {
1469        let run_ends1 = Int32Array::from(vec![2, 4, 6]);
1470        let values1 = StringArray::from(vec![Some("a"), None, Some("c")]);
1471        let array1 = RunArray::<Int32Type>::try_new(&run_ends1, &values1).unwrap();
1472
1473        let run_ends2 = Int32Array::from(vec![2, 4, 6]);
1474        let values2 = StringArray::from(vec![Some("a"), None, Some("c")]);
1475        let array2 = RunArray::<Int32Type>::try_new(&run_ends2, &values2).unwrap();
1476
1477        assert_eq!(array1, array2);
1478    }
1479
1480    #[test]
1481    fn test_run_array_eq_different_run_end_types() {
1482        let run_ends_i16_1 = Int16Array::from(vec![2_i16, 4, 6]);
1483        let values_i16_1 = StringArray::from(vec!["a", "b", "c"]);
1484        let array_i16_1 = RunArray::<Int16Type>::try_new(&run_ends_i16_1, &values_i16_1).unwrap();
1485
1486        let run_ends_i16_2 = Int16Array::from(vec![2_i16, 4, 6]);
1487        let values_i16_2 = StringArray::from(vec!["a", "b", "c"]);
1488        let array_i16_2 = RunArray::<Int16Type>::try_new(&run_ends_i16_2, &values_i16_2).unwrap();
1489
1490        assert_eq!(array_i16_1, array_i16_2);
1491    }
1492
1493    #[test]
1494    fn test_run_array_values_slice() {
1495        // 0, 0, 1, 1, 1, 2...2 (15 2s)
1496        let run_ends: PrimitiveArray<Int32Type> = vec![2, 5, 20].into();
1497        let values: PrimitiveArray<Int32Type> = vec![0, 1, 2].into();
1498        let array = RunArray::<Int32Type>::try_new(&run_ends, &values).unwrap();
1499
1500        let slice = array.slice(1, 4); // 0 | 1, 1, 1 |
1501        // logical indices: 1, 2, 3, 4
1502        // physical indices: 0, 1, 1, 1
1503        // values at 0 is 0
1504        // values at 1 is 1
1505        // values slice should be [0, 1]
1506        assert_eq!(slice.get_start_physical_index(), 0);
1507        assert_eq!(slice.get_end_physical_index(), 1);
1508
1509        let values_slice = slice.values_slice();
1510        let values_slice = values_slice.as_primitive::<Int32Type>();
1511        assert_eq!(values_slice.values(), &[0, 1]);
1512
1513        let slice2 = array.slice(2, 3); // 1, 1, 1
1514        // logical indices: 2, 3, 4
1515        // physical indices: 1, 1, 1
1516        assert_eq!(slice2.get_start_physical_index(), 1);
1517        assert_eq!(slice2.get_end_physical_index(), 1);
1518
1519        let values_slice2 = slice2.values_slice();
1520        let values_slice2 = values_slice2.as_primitive::<Int32Type>();
1521        assert_eq!(values_slice2.values(), &[1]);
1522    }
1523
1524    #[test]
1525    fn test_run_array_values_slice_empty() {
1526        let run_ends = Int32Array::from(vec![2, 5, 10]);
1527        let values = StringArray::from(vec!["a", "b", "c"]);
1528        let array = RunArray::<Int32Type>::try_new(&run_ends, &values).unwrap();
1529
1530        let slice = array.slice(0, 0);
1531        assert_eq!(slice.len(), 0);
1532
1533        let values_slice = slice.values_slice();
1534        assert_eq!(values_slice.len(), 0);
1535        assert_eq!(values_slice.data_type(), &DataType::Utf8);
1536    }
1537
1538    #[test]
1539    fn test_run_array_eq_empty() {
1540        let run_ends = Int32Array::from(vec![2, 5, 10]);
1541        let values = StringArray::from(vec!["a", "b", "c"]);
1542        let array = RunArray::<Int32Type>::try_new(&run_ends, &values).unwrap();
1543
1544        let slice1 = array.slice(0, 0);
1545        let slice2 = array.slice(1, 0);
1546        let slice3 = array.slice(10, 0);
1547
1548        assert_eq!(slice1, slice2);
1549        assert_eq!(slice2, slice3);
1550
1551        let empty_array = new_empty_array(array.data_type());
1552        let empty_array = crate::cast::as_run_array::<Int32Type>(empty_array.as_ref());
1553
1554        assert_eq!(&slice1, empty_array);
1555    }
1556
1557    #[test]
1558    fn test_run_array_eq_diff_physical_same_logical() {
1559        let run_ends1 = Int32Array::from(vec![1, 3, 6]);
1560        let values1 = StringArray::from(vec!["a", "b", "c"]);
1561        let array1 = RunArray::<Int32Type>::try_new(&run_ends1, &values1).unwrap();
1562
1563        let run_ends2 = Int32Array::from(vec![1, 2, 3, 4, 5, 6]);
1564        let values2 = StringArray::from(vec!["a", "b", "b", "c", "c", "c"]);
1565        let array2 = RunArray::<Int32Type>::try_new(&run_ends2, &values2).unwrap();
1566
1567        assert_eq!(array1, array2);
1568    }
1569
1570    #[test]
1571    fn test_run_array_eq_sliced() {
1572        let run_ends1 = Int32Array::from(vec![2, 5, 10]);
1573        let values1 = StringArray::from(vec!["a", "b", "c"]);
1574        let array1 = RunArray::<Int32Type>::try_new(&run_ends1, &values1).unwrap();
1575        // Logical: a, a, b, b, b, c, c, c, c, c
1576
1577        let slice1 = array1.slice(1, 6);
1578        // Logical: a, b, b, b, c, c
1579
1580        let run_ends2 = Int32Array::from(vec![1, 4, 6]);
1581        let values2 = StringArray::from(vec!["a", "b", "c"]);
1582        let array2 = RunArray::<Int32Type>::try_new(&run_ends2, &values2).unwrap();
1583        // Logical: a, b, b, b, c, c
1584
1585        assert_eq!(slice1, array2);
1586
1587        let slice2 = array1.slice(2, 3);
1588        // Logical: b, b, b
1589        let run_ends3 = Int32Array::from(vec![3]);
1590        let values3 = StringArray::from(vec!["b"]);
1591        let array3 = RunArray::<Int32Type>::try_new(&run_ends3, &values3).unwrap();
1592        assert_eq!(slice2, array3);
1593    }
1594
1595    #[test]
1596    fn test_run_array_eq_sliced_different_offsets() {
1597        let run_ends1 = Int32Array::from(vec![2, 5, 10]);
1598        let values1 = StringArray::from(vec!["a", "b", "c"]);
1599        let array1 = RunArray::<Int32Type>::try_new(&run_ends1, &values1).unwrap();
1600        let array2 = array1.clone();
1601        assert_eq!(array1, array2);
1602
1603        let slice1 = array1.slice(1, 4); // a, b, b, b
1604        let slice2 = array1.slice(1, 4);
1605        assert_eq!(slice1, slice2);
1606
1607        let slice3 = array1.slice(0, 4); // a, a, b, b
1608        assert_ne!(slice1, slice3);
1609    }
1610
1611    #[test]
1612    #[cfg(not(feature = "force_validate"))]
1613    fn allow_to_create_invalid_array_using_new_unchecked() {
1614        let valid = RunArray::<Int32Type>::from_iter(["32"]);
1615        let (_, buffer, values) = valid.into_parts();
1616
1617        let _ = unsafe {
1618            // mismatch data type
1619            RunArray::<Int32Type>::new_unchecked(DataType::Int64, buffer, values)
1620        };
1621    }
1622
1623    #[test]
1624    #[should_panic(
1625        expected = "Invalid data type Int64 for RunArray. Should be DataType::RunEndEncoded"
1626    )]
1627    #[cfg(feature = "force_validate")]
1628    fn should_not_be_able_to_create_invalid_array_using_new_unchecked_when_force_validate_is_enabled()
1629     {
1630        let valid = RunArray::<Int32Type>::from_iter(["32"]);
1631        let (_, buffer, values) = valid.into_parts();
1632
1633        let _ = unsafe {
1634            // mismatch data type
1635            RunArray::<Int32Type>::new_unchecked(DataType::Int64, buffer, values)
1636        };
1637    }
1638
1639    #[test]
1640    fn test_run_array_roundtrip() {
1641        let run = Int32Array::from(vec![3, 6, 9, 12]);
1642        let values = Int32Array::from(vec![Some(0), None, Some(1), None]);
1643        let array = RunArray::try_new(&run, &values).unwrap();
1644
1645        let (dt, buffer, values) = array.clone().into_parts();
1646        let created_from_parts =
1647            unsafe { RunArray::<Int32Type>::new_unchecked(dt, buffer, values) };
1648        assert_eq!(array, created_from_parts);
1649    }
1650
1651    #[test]
1652    fn test_from_array_data_offset() {
1653        let dt = DataType::RunEndEncoded(
1654            Arc::new(Field::new(
1655                Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
1656                DataType::Int32,
1657                false,
1658            )),
1659            Arc::new(Field::new(
1660                Field::REE_VALUES_FIELD_DEFAULT_NAME,
1661                DataType::Float32,
1662                true,
1663            )),
1664        );
1665
1666        let runs = ArrayData::builder(DataType::Int32)
1667            .len(2)
1668            .offset(2)
1669            .add_buffer(vec![-10_i32, -20, 1_i32, 4, 0, 100].into())
1670            .build()
1671            .unwrap();
1672        let values = Float32Array::from(vec![1.5, 2.5]);
1673
1674        let data = ArrayDataBuilder::new(dt)
1675            .len(3)
1676            .child_data(vec![runs, values.to_data()])
1677            .build()
1678            .unwrap();
1679        let array = RunArray::<Int32Type>::from(data);
1680        let array = array.downcast::<Float32Array>().unwrap();
1681
1682        assert_eq!(array.value(0), 1.5);
1683        assert_eq!(array.value(1), 2.5);
1684        assert_eq!(array.value(2), 2.5);
1685    }
1686}