Skip to main content

vortex_array/arrays/runend/array/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Run-end arrays and their execution into logical values.
5//!
6//! Each end is an exclusive logical index paired with the value for its preceding run. Decoding
7//! **must** apply a slice's logical offset before expanding those values. Specialized decoders
8//! handle common storage types. The generic fallback gathers values to retain their logical dtype.
9
10use std::fmt::Debug;
11use std::fmt::Display;
12use std::fmt::Formatter;
13use std::hash::Hash;
14use std::hash::Hasher;
15use std::ops::Range;
16
17use vortex_error::VortexExpect as _;
18use vortex_error::VortexResult;
19use vortex_error::vortex_bail;
20use vortex_error::vortex_ensure;
21use vortex_error::vortex_ensure_eq;
22use vortex_error::vortex_err;
23use vortex_error::vortex_panic;
24use vortex_session::registry::CachedId;
25
26use crate::AnyCanonical;
27use crate::Array;
28use crate::ArrayEq;
29use crate::ArrayHash;
30use crate::ArrayId;
31use crate::ArrayParts;
32use crate::ArrayRef;
33use crate::ArrayView;
34use crate::EqMode;
35use crate::ExecutionCtx;
36use crate::ExecutionResult;
37use crate::IntoArray;
38use crate::TypedArrayRef;
39use crate::array_slots;
40use crate::arrays::Bool;
41use crate::arrays::Decimal;
42use crate::arrays::ListView;
43use crate::arrays::ListViewArray;
44use crate::arrays::Primitive;
45use crate::arrays::PrimitiveArray;
46use crate::arrays::VarBinView;
47use crate::arrays::listview::ListViewArraySlotsExt;
48use crate::arrays::runend::compress::runend_decode_decimal;
49use crate::arrays::runend::compress::runend_decode_primitive;
50use crate::arrays::runend::compress::runend_decode_varbinview;
51use crate::arrays::runend::compress::runend_encode;
52use crate::arrays::runend::compress::runend_encode_bool;
53use crate::arrays::runend::decompress_bool::runend_decode_bools;
54use crate::arrays::runend::ops::find_physical_index;
55use crate::arrays::runend::ops::find_physical_range;
56use crate::arrays::runend::ops::find_slice_end_index;
57use crate::buffer::BufferHandle;
58use crate::dtype::DType;
59use crate::dtype::PType;
60use crate::require_child;
61use crate::validity::Validity;
62use crate::vtable::VTable;
63use crate::vtable::ValidityVTable;
64
65mod plugin;
66mod to_dict;
67
68/// A [`RunEnd`]-encoded Vortex array.
69pub type RunEndArray = Array<RunEnd>;
70
71#[derive(Clone, prost::Message)]
72pub struct RunEndMetadata {
73    #[prost(int32, tag = "1")]
74    pub(crate) ends_ptype: i32,
75    #[prost(uint64, tag = "2")]
76    pub(crate) num_runs: u64,
77    #[prost(uint64, tag = "3")]
78    pub(crate) offset: u64,
79}
80
81impl RunEndMetadata {
82    fn get_ends_ptype(&self) -> VortexResult<PType> {
83        PType::try_from(self.ends_ptype).map_err(|_| {
84            vortex_err!(
85                "RunEndMetadata ends_ptype must be a known PType, got {}",
86                self.ends_ptype
87            )
88        })
89    }
90}
91
92impl ArrayHash for RunEndData {
93    fn array_hash<H: Hasher>(&self, state: &mut H, _accuracy: EqMode) {
94        self.offset.hash(state);
95    }
96}
97
98impl ArrayEq for RunEndData {
99    fn array_eq(&self, other: &Self, _accuracy: EqMode) -> bool {
100        self.offset == other.offset
101    }
102}
103
104impl VTable for RunEnd {
105    type TypedArrayData = RunEndData;
106
107    type OperationsVTable = Self;
108    type ValidityVTable = Self;
109
110    fn id(&self) -> ArrayId {
111        static ID: CachedId = CachedId::new("vortex.runend");
112        *ID
113    }
114
115    fn validate(
116        &self,
117        data: &Self::TypedArrayData,
118        dtype: &DType,
119        len: usize,
120        slots: &[Option<ArrayRef>],
121    ) -> VortexResult<()> {
122        let run_end_slots = RunEndSlotsView::from_slots(slots);
123        let ends = run_end_slots.ends;
124        let values = run_end_slots.values;
125        RunEndData::validate_shape(ends, values, data.offset, len)?;
126        vortex_ensure_eq!(values.dtype(), dtype);
127        Ok(())
128    }
129
130    fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
131        0
132    }
133
134    fn buffer(_array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
135        vortex_panic!("RunEndArray buffer index {idx} out of bounds")
136    }
137
138    fn buffer_name(_array: ArrayView<'_, Self>, idx: usize) -> Option<String> {
139        vortex_panic!("RunEndArray buffer_name index {idx} out of bounds")
140    }
141
142    fn with_buffers(
143        &self,
144        array: ArrayView<'_, Self>,
145        buffers: &[BufferHandle],
146    ) -> VortexResult<ArrayParts<Self>> {
147        crate::vtable::with_empty_buffers(self, array, buffers)
148    }
149
150    fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
151        RunEndSlots::NAMES[idx].to_string()
152    }
153
154    fn execute(array: Array<Self>, ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
155        let array = require_child!(array, array.ends(), RunEndSlots::ENDS => Primitive);
156        let array = require_child!(array, array.values(), RunEndSlots::VALUES => AnyCanonical);
157        run_end_canonicalize(array, ctx).map(ExecutionResult::done)
158    }
159}
160
161#[array_slots(RunEnd)]
162pub struct RunEndSlots {
163    /// The run-end positions marking where each run terminates.
164    #[slot(0)]
165    pub ends: ArrayRef,
166    /// The values for each run.
167    #[slot(1)]
168    pub values: ArrayRef,
169}
170
171#[derive(Clone, Debug)]
172pub struct RunEndData {
173    offset: usize,
174}
175
176impl Display for RunEndData {
177    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
178        write!(f, "offset: {}", self.offset)
179    }
180}
181
182pub struct RunEndDataParts {
183    pub ends: ArrayRef,
184    pub values: ArrayRef,
185    pub offset: usize,
186}
187
188pub trait RunEndArrayExt: TypedArrayRef<RunEnd> {
189    fn offset(&self) -> usize {
190        self.offset
191    }
192
193    fn dtype(&self) -> &DType {
194        self.values().dtype()
195    }
196
197    fn find_physical_index(&self, index: usize, ctx: &mut ExecutionCtx) -> VortexResult<usize> {
198        find_physical_index(self.ends(), index + self.offset(), ctx)
199    }
200
201    fn find_slice_end_index(&self, index: usize, ctx: &mut ExecutionCtx) -> VortexResult<usize> {
202        find_slice_end_index(self.ends(), index + self.offset(), ctx)
203    }
204
205    /// The physical range of runs covering the logical `range`, found with one probe of the
206    /// ends.
207    fn find_physical_range(
208        &self,
209        range: Range<usize>,
210        ctx: &mut ExecutionCtx,
211    ) -> VortexResult<Range<usize>> {
212        let offset = self.offset();
213        find_physical_range(self.ends(), range.start + offset..range.end + offset, ctx)
214    }
215}
216
217impl<T: TypedArrayRef<RunEnd>> RunEndArrayExt for T {}
218
219pub(crate) trait RunEndArrayOwnedExt {
220    /// Returns the parts of the array. Moves the children out when this handle owns the array,
221    /// and clones them otherwise.
222    fn into_parts(self) -> RunEndDataParts;
223}
224
225impl RunEndArrayOwnedExt for Array<RunEnd> {
226    fn into_parts(self) -> RunEndDataParts {
227        match self.try_into_parts() {
228            Ok(parts) => {
229                let RunEndSlots { ends, values } = RunEndSlots::from_slots(parts.slots);
230                parts.data.into_parts(ends, values)
231            }
232            Err(array) => RunEndDataParts {
233                ends: array.ends().clone(),
234                values: array.values().clone(),
235                offset: array.offset(),
236            },
237        }
238    }
239}
240
241#[derive(Clone, Debug)]
242pub struct RunEnd;
243
244impl RunEnd {
245    /// Build a new [`RunEndArray`] without validation.
246    ///
247    /// # Safety
248    /// See [`RunEndData::new_unchecked`] for preconditions.
249    pub unsafe fn new_unchecked(
250        ends: ArrayRef,
251        values: ArrayRef,
252        offset: usize,
253        length: usize,
254    ) -> RunEndArray {
255        let dtype = values.dtype().clone();
256        let slots = RunEndSlots { ends, values }.into_slots();
257        let data = unsafe { RunEndData::new_unchecked(offset) };
258        unsafe { Array::from_parts_unchecked(ArrayParts::new(RunEnd, dtype, length, data, slots)) }
259    }
260
261    /// Build a new [`RunEndArray`] from ends and values.
262    pub fn try_new(
263        ends: ArrayRef,
264        values: ArrayRef,
265        ctx: &mut ExecutionCtx,
266    ) -> VortexResult<RunEndArray> {
267        let len = RunEndData::logical_len_from_ends(&ends, ctx)?;
268        RunEndData::validate_parts(&ends, &values, 0, len, ctx)?;
269        let dtype = values.dtype().clone();
270        let slots = RunEndSlots { ends, values }.into_slots();
271        let data = RunEndData::new(0);
272        Array::try_from_parts(ArrayParts::new(RunEnd, dtype, len, data, slots))
273    }
274
275    /// Build a new [`RunEndArray`] from ends, values, offset, and length.
276    pub fn try_new_offset_length(
277        ends: ArrayRef,
278        values: ArrayRef,
279        offset: usize,
280        length: usize,
281        ctx: &mut ExecutionCtx,
282    ) -> VortexResult<RunEndArray> {
283        RunEndData::validate_parts(&ends, &values, offset, length, ctx)?;
284        let dtype = values.dtype().clone();
285        let slots = RunEndSlots { ends, values }.into_slots();
286        let data = RunEndData::new(offset);
287        Array::try_from_parts(ArrayParts::new(RunEnd, dtype, length, data, slots))
288    }
289
290    /// Build a new [`RunEndArray`] from ends and values (panics on invalid input).
291    pub fn new(ends: ArrayRef, values: ArrayRef, ctx: &mut ExecutionCtx) -> RunEndArray {
292        Self::try_new(ends, values, ctx).vortex_expect("RunEndData is always valid")
293    }
294
295    /// Run the array through run-end encoding.
296    ///
297    /// Accepts primitive arrays, and boolean arrays without nulls.
298    pub fn encode(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<RunEndArray> {
299        let encoded = if let Some(parray) = array.as_opt::<Primitive>() {
300            Some(runend_encode(parray, ctx))
301        } else if let Some(barray) = array.as_opt::<Bool>() {
302            Some(runend_encode_bool(barray, ctx)?)
303        } else {
304            None
305        };
306        if let Some((ends, values)) = encoded {
307            let ends = ends.into_array();
308            let len = array.len();
309            let dtype = values.dtype().clone();
310            let slots = RunEndSlots { ends, values }.into_slots();
311            let data = unsafe { RunEndData::new_unchecked(0) };
312            Array::try_from_parts(ArrayParts::new(RunEnd, dtype, len, data, slots))
313        } else {
314            vortex_bail!("REE can only encode primitive and boolean arrays")
315        }
316    }
317}
318
319impl RunEndData {
320    fn logical_len_from_ends(ends: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<usize> {
321        if ends.is_empty() {
322            Ok(0)
323        } else {
324            usize::try_from(&ends.execute_scalar(ends.len() - 1, ctx)?)
325        }
326    }
327
328    /// Validate that `ends` and `values` form a well-formed run-end array covering
329    /// `offset..offset + length`.
330    pub fn validate_parts(
331        ends: &ArrayRef,
332        values: &ArrayRef,
333        offset: usize,
334        length: usize,
335        ctx: &mut ExecutionCtx,
336    ) -> VortexResult<()> {
337        if !Self::validate_shape(ends, values, offset, length)? {
338            return Ok(());
339        }
340
341        #[cfg(debug_assertions)]
342        {
343            // Run ends must be strictly sorted for binary search to work correctly.
344            let pre_validation = ends.statistics().to_owned();
345
346            let is_sorted = ends
347                .statistics()
348                .compute_is_strict_sorted(ctx)
349                .unwrap_or(false);
350
351            // Preserve the original statistics since compute_is_strict_sorted may have mutated them.
352            // We don't want to run with different stats in debug mode and outside.
353            ends.statistics().inherit(pre_validation.iter());
354            debug_assert!(is_sorted);
355        }
356
357        // Skip host-only validation when ends are not host-resident.
358        if !ends.is_host() {
359            return Ok(());
360        }
361
362        let first_run_end = if offset == 0 {
363            0
364        } else {
365            usize::try_from(&ends.execute_scalar(0, ctx)?)?
366        };
367        let last_run_end = usize::try_from(&ends.execute_scalar(ends.len() - 1, ctx)?)?;
368        Self::validate_run_end_bounds(first_run_end, last_run_end, offset, length)
369    }
370
371    /// Validates the dtypes and lengths of the parts. Returns `false` when there are no runs to
372    /// check against `offset..offset + length`.
373    fn validate_shape(
374        ends: &ArrayRef,
375        values: &ArrayRef,
376        offset: usize,
377        length: usize,
378    ) -> VortexResult<bool> {
379        // DType validation
380        vortex_ensure!(
381            ends.dtype().is_unsigned_int(),
382            "run ends must be unsigned integers, was {}",
383            ends.dtype(),
384        );
385        vortex_ensure_eq!(ends.len(), values.len());
386
387        // Handle empty run-ends
388        if ends.is_empty() {
389            vortex_ensure_eq!(offset, 0, "non-zero offset provided for empty RunEndArray");
390            return Ok(false);
391        }
392
393        // Zero-length logical slices may retain run metadata from the source array.
394        Ok(length != 0)
395    }
396
397    /// Validates that the first and last run ends cover `offset..offset + length`.
398    fn validate_run_end_bounds(
399        first_run_end: usize,
400        last_run_end: usize,
401        offset: usize,
402        length: usize,
403    ) -> VortexResult<()> {
404        if first_run_end < offset {
405            vortex_bail!("First run end {first_run_end} must be >= offset {offset}");
406        }
407
408        let min_required_end = offset + length;
409        if last_run_end < min_required_end {
410            vortex_bail!("Last run end {last_run_end} must be >= offset+length {min_required_end}");
411        }
412
413        Ok(())
414    }
415}
416
417impl RunEndData {
418    /// Build a new `RunEndArray` from an array of run `ends` and an array of `values`.
419    ///
420    /// Panics if any of the validation conditions described in [`RunEnd::try_new`] is
421    /// not satisfied.
422    ///
423    /// # Examples
424    ///
425    /// ```
426    /// # use vortex_array::arrays::BoolArray;
427    /// # use vortex_array::arrays::runend::RunEnd;
428    /// # use vortex_array::IntoArray;
429    /// # use vortex_session::VortexSession;
430    /// # use vortex_array::VortexSessionExecute;
431    /// # use vortex_buffer::buffer;
432    /// # use vortex_error::VortexResult;
433    /// # fn main() -> VortexResult<()> {
434    /// let session = VortexSession::empty();
435    /// let mut ctx = session.create_execution_ctx();
436    /// let ends = buffer![2u8, 3u8].into_array();
437    /// let values = BoolArray::from_iter([false, true]).into_array();
438    /// let run_end = RunEnd::new(ends, values, &mut ctx);
439    ///
440    /// // Array encodes
441    /// assert_eq!(run_end.execute_scalar(0, &mut ctx)?, false.into());
442    /// assert_eq!(run_end.execute_scalar(1, &mut ctx)?, false.into());
443    /// assert_eq!(run_end.execute_scalar(2, &mut ctx)?, true.into());
444    /// # Ok(())
445    /// # }
446    /// ```
447    pub fn new(offset: usize) -> Self {
448        Self { offset }
449    }
450
451    /// Build a new `RunEndArray` without validation.
452    ///
453    /// # Safety
454    ///
455    /// The caller must ensure that all the validation performed in
456    /// [`RunEnd::try_new_offset_length`] is
457    /// satisfied before calling this function.
458    ///
459    /// See [`RunEnd::try_new_offset_length`] for the preconditions needed to build a new array.
460    pub unsafe fn new_unchecked(offset: usize) -> Self {
461        Self { offset }
462    }
463
464    /// Run the array through run-end encoding.
465    pub fn encode(array: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<Self> {
466        if let Some(parray) = array.as_opt::<Primitive>() {
467            let (_ends, _values) = runend_encode(parray, ctx);
468            // SAFETY: runend_encode handles this
469            unsafe { Ok(Self::new_unchecked(0)) }
470        } else {
471            vortex_bail!("REE can only encode primitive arrays")
472        }
473    }
474
475    pub fn into_parts(self, ends: ArrayRef, values: ArrayRef) -> RunEndDataParts {
476        RunEndDataParts {
477            ends,
478            values,
479            offset: self.offset,
480        }
481    }
482}
483
484impl ValidityVTable<RunEnd> for RunEnd {
485    fn validity(array: ArrayView<'_, RunEnd>) -> VortexResult<Validity> {
486        Ok(match array.values().validity()? {
487            Validity::NonNullable | Validity::AllValid => Validity::AllValid,
488            Validity::AllInvalid => Validity::AllInvalid,
489            Validity::Array(values_validity) => Validity::Array(unsafe {
490                RunEnd::new_unchecked(
491                    array.ends().clone(),
492                    values_validity,
493                    array.offset(),
494                    array.len(),
495                )
496                .into_array()
497            }),
498        })
499    }
500}
501
502/// Decodes a run-end array into its canonical form.
503///
504/// The ends must already be a primitive array, and the values must already be canonical, as
505/// `RunEnd::execute` requires.
506pub(super) fn run_end_canonicalize(
507    array: RunEndArray,
508    ctx: &mut ExecutionCtx,
509) -> VortexResult<ArrayRef> {
510    if !matches!(
511        array.dtype(),
512        DType::Bool(_)
513            | DType::Primitive(..)
514            | DType::Decimal(..)
515            | DType::Utf8(_)
516            | DType::Binary(_)
517            | DType::List(..)
518    ) {
519        return Ok(array.to_dict(ctx)?.into_array());
520    }
521
522    let len = array.len();
523    let RunEndDataParts {
524        ends,
525        values,
526        offset,
527    } = array.into_parts();
528    let pends = ends.downcast::<Primitive>();
529
530    Ok(match values.dtype() {
531        DType::Bool(_) => runend_decode_bools(pends, values.downcast::<Bool>(), offset, len, ctx)?,
532        DType::Primitive(..) => {
533            runend_decode_primitive(pends, values.downcast::<Primitive>(), offset, len, ctx)?
534        }
535        DType::Decimal(..) => {
536            runend_decode_decimal(pends, values.downcast::<Decimal>(), offset, len, ctx)?
537        }
538        DType::Utf8(_) | DType::Binary(_) => {
539            runend_decode_varbinview(pends, values.downcast::<VarBinView>(), offset, len, ctx)?
540        }
541        DType::List(..) => {
542            runend_decode_listview(pends, values.downcast::<ListView>(), offset, len)?.into_array()
543        }
544        dtype => vortex_panic!("RunEnd values of type {dtype} decode through a dictionary"),
545    })
546}
547
548fn runend_decode_listview(
549    ends: PrimitiveArray,
550    values: ListViewArray,
551    offset: usize,
552    length: usize,
553) -> VortexResult<ListViewArray> {
554    let validity = match values.validity()? {
555        Validity::NonNullable => Validity::NonNullable,
556        Validity::AllValid => Validity::AllValid,
557        Validity::AllInvalid => Validity::AllInvalid,
558        Validity::Array(validity) => Validity::Array(unsafe {
559            RunEnd::new_unchecked(ends.clone().into_array(), validity, offset, length).into_array()
560        }),
561    };
562
563    // SAFETY: the `RunEndArray`s re-express valid per-run ListView metadata over the logical output
564    // length. The original `elements` child is reused, so every view still points at a valid range.
565    Ok(unsafe {
566        ListViewArray::new_unchecked(
567            values.elements().clone(),
568            RunEnd::new_unchecked(
569                ends.clone().into_array(),
570                values.offsets().clone(),
571                offset,
572                length,
573            )
574            .into_array(),
575            RunEnd::new_unchecked(ends.into_array(), values.sizes().clone(), offset, length)
576                .into_array(),
577            validity,
578        )
579    })
580}
581
582#[cfg(test)]
583mod tests {
584    use std::sync::Arc;
585    use std::sync::LazyLock;
586
587    use prost::Message;
588    use vortex_buffer::buffer;
589    use vortex_error::VortexResult;
590    use vortex_session::VortexSession;
591
592    use super::RunEndMetadata;
593    use crate::ArrayRef;
594    use crate::IntoArray;
595    use crate::VortexSessionExecute;
596    use crate::array::ArrayDeserialization;
597    use crate::array::ArrayPlugin;
598    use crate::arrays::DecimalArray;
599    use crate::arrays::DictArray;
600    use crate::arrays::ListArray;
601    use crate::arrays::ListViewArray;
602    use crate::arrays::VarBinViewArray;
603    use crate::arrays::listview::ListViewArraySlotsExt;
604    use crate::arrays::runend::RunEnd;
605    use crate::assert_arrays_eq;
606    use crate::builders::VarBinBuilder;
607    use crate::dtype::DType;
608    use crate::dtype::DecimalDType;
609    use crate::dtype::Nullability;
610    use crate::dtype::PType;
611    use crate::dtype::i256;
612    use crate::validity::Validity;
613    use crate::vtable::VTable;
614
615    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
616
617    #[test]
618    fn test_runend_constructor() {
619        let mut ctx = SESSION.create_execution_ctx();
620        let arr = RunEnd::new(
621            buffer![2u32, 5, 10].into_array(),
622            buffer![1i32, 2, 3].into_array(),
623            &mut ctx,
624        );
625        assert_eq!(arr.len(), 10);
626        assert_eq!(
627            arr.dtype(),
628            &DType::Primitive(PType::I32, Nullability::NonNullable)
629        );
630
631        // 0, 1 => 1
632        // 2, 3, 4 => 2
633        // 5, 6, 7, 8, 9 => 3
634        let expected = buffer![1, 1, 2, 2, 2, 3, 3, 3, 3, 3].into_array();
635        assert_arrays_eq!(arr.into_array(), expected, &mut ctx);
636    }
637
638    #[test]
639    fn test_runend_utf8() {
640        let mut ctx = SESSION.create_execution_ctx();
641        let values =
642            VarBinViewArray::from_iter_nullable_str([Some("a"), None, Some("c")]).into_array();
643        let arr = RunEnd::new(buffer![2u32, 5, 10].into_array(), values, &mut ctx);
644        assert_eq!(arr.len(), 10);
645        assert_eq!(arr.dtype(), &DType::Utf8(Nullability::Nullable));
646
647        let expected = VarBinViewArray::from_iter_nullable_str([
648            Some("a"),
649            Some("a"),
650            None,
651            None,
652            None,
653            Some("c"),
654            Some("c"),
655            Some("c"),
656            Some("c"),
657            Some("c"),
658        ])
659        .into_array();
660        let mut builder = VarBinBuilder::<i32>::with_capacity_in(
661            arr.dtype().clone(),
662            arr.len(),
663            vortex_buffer::BufferAllocatorRef::static_ref(),
664        );
665        arr.append_to_builder(&mut builder, &mut ctx).unwrap();
666        assert_arrays_eq!(builder.finish_into_varbin(), expected, &mut ctx);
667        assert_arrays_eq!(arr.into_array(), expected, &mut ctx);
668    }
669
670    #[test]
671    fn test_runend_decimal() {
672        let mut ctx = SESSION.create_execution_ctx();
673        let decimal_dtype = DecimalDType::new(10, 2);
674        let values = DecimalArray::from_iter([12345i64, 67890, -12300], decimal_dtype).into_array();
675        let arr = RunEnd::new(buffer![2u32, 5, 10].into_array(), values, &mut ctx);
676        assert_eq!(arr.len(), 10);
677        assert_eq!(
678            arr.dtype(),
679            &DType::Decimal(decimal_dtype, Nullability::NonNullable)
680        );
681
682        let expected = DecimalArray::from_iter(
683            [
684                12345i64, 12345, 67890, 67890, 67890, -12300, -12300, -12300, -12300, -12300,
685            ],
686            decimal_dtype,
687        )
688        .into_array();
689        assert_arrays_eq!(arr.into_array(), expected, &mut ctx);
690    }
691
692    #[test]
693    fn test_runend_list_i64() {
694        let mut ctx = SESSION.create_execution_ctx();
695        let values = ListArray::from_iter_slow::<u32, _>(
696            vec![vec![1i64, 2], vec![3], vec![4, 5, 6]],
697            Arc::new(DType::Primitive(PType::I64, Nullability::NonNullable)),
698        )
699        .unwrap()
700        .into_array();
701        let arr = RunEnd::new(buffer![2u32, 5, 10].into_array(), values, &mut ctx);
702
703        let expected = ListArray::from_iter_slow::<u32, _>(
704            vec![
705                vec![1i64, 2],
706                vec![1, 2],
707                vec![3],
708                vec![3],
709                vec![3],
710                vec![4, 5, 6],
711                vec![4, 5, 6],
712                vec![4, 5, 6],
713                vec![4, 5, 6],
714                vec![4, 5, 6],
715            ],
716            Arc::new(DType::Primitive(PType::I64, Nullability::NonNullable)),
717        )
718        .unwrap()
719        .into_array();
720        assert_arrays_eq!(arr.into_array(), expected, &mut ctx);
721    }
722
723    #[test]
724    fn test_runend_nullable_decimal() {
725        let mut ctx = SESSION.create_execution_ctx();
726        let decimal_dtype = DecimalDType::new(10, 2);
727        let values =
728            DecimalArray::from_option_iter([Some(12345i64), None, Some(-12300)], decimal_dtype)
729                .into_array();
730        let arr = RunEnd::new(buffer![2u32, 5, 10].into_array(), values, &mut ctx);
731        assert_eq!(arr.len(), 10);
732        assert_eq!(
733            arr.dtype(),
734            &DType::Decimal(decimal_dtype, Nullability::Nullable)
735        );
736
737        let expected = DecimalArray::from_option_iter(
738            [
739                Some(12345i64),
740                Some(12345),
741                None,
742                None,
743                None,
744                Some(-12300),
745                Some(-12300),
746                Some(-12300),
747                Some(-12300),
748                Some(-12300),
749            ],
750            decimal_dtype,
751        )
752        .into_array();
753        assert_arrays_eq!(arr.into_array(), expected, &mut ctx);
754    }
755
756    #[test]
757    fn test_runend_list_bool() {
758        let mut ctx = SESSION.create_execution_ctx();
759        let values = ListArray::from_iter_slow::<u32, _>(
760            vec![vec![true, false], vec![false], vec![true, true, false]],
761            Arc::new(DType::Bool(Nullability::NonNullable)),
762        )
763        .unwrap()
764        .into_array();
765        let arr = RunEnd::new(buffer![2u32, 5, 10].into_array(), values, &mut ctx);
766
767        let expected = ListArray::from_iter_slow::<u32, _>(
768            vec![
769                vec![true, false],
770                vec![true, false],
771                vec![false],
772                vec![false],
773                vec![false],
774                vec![true, true, false],
775                vec![true, true, false],
776                vec![true, true, false],
777                vec![true, true, false],
778                vec![true, true, false],
779            ],
780            Arc::new(DType::Bool(Nullability::NonNullable)),
781        )
782        .unwrap()
783        .into_array();
784        assert_arrays_eq!(arr.into_array(), expected, &mut ctx);
785    }
786
787    #[test]
788    fn test_runend_list_utf8() {
789        let mut ctx = SESSION.create_execution_ctx();
790        let values = ListArray::try_new(
791            VarBinViewArray::from_iter_str(["a", "b", "c", "d", "e", "f"]).into_array(),
792            buffer![0u32, 2, 3, 6].into_array(),
793            Validity::NonNullable,
794            &mut ctx,
795        )
796        .unwrap()
797        .into_array();
798        let arr = RunEnd::new(buffer![2u32, 5, 10].into_array(), values, &mut ctx);
799
800        let expected = ListArray::try_new(
801            VarBinViewArray::from_iter_str([
802                "a", "b", "a", "b", "c", "c", "c", "d", "e", "f", "d", "e", "f", "d", "e", "f",
803                "d", "e", "f", "d", "e", "f",
804            ])
805            .into_array(),
806            buffer![0u32, 2, 4, 5, 6, 7, 10, 13, 16, 19, 22].into_array(),
807            Validity::NonNullable,
808            &mut ctx,
809        )
810        .unwrap()
811        .into_array();
812        assert_arrays_eq!(arr.into_array(), expected, &mut ctx);
813    }
814
815    #[test]
816    fn test_runend_list_canonicalizes_to_runend_listview_slots() -> VortexResult<()> {
817        let mut ctx = SESSION.create_execution_ctx();
818        let values = ListArray::try_new(
819            buffer![1i64, 2, 3, 4, 5, 6].into_array(),
820            buffer![0u32, 2, 3, 6].into_array(),
821            Validity::from_iter([true, false, true]),
822            &mut ctx,
823        )?
824        .into_array();
825        let arr = RunEnd::try_new(buffer![2u32, 5, 6].into_array(), values, &mut ctx)?;
826
827        let listview = arr
828            .clone()
829            .into_array()
830            .execute::<ListViewArray>(&mut ctx)?;
831        assert!(listview.offsets().is::<RunEnd>());
832        assert!(listview.sizes().is::<RunEnd>());
833        match listview.validity()? {
834            Validity::Array(validity) => assert!(validity.is::<RunEnd>()),
835            validity => panic!("expected array-backed validity, got {validity:?}"),
836        }
837
838        let expected = ListArray::try_new(
839            buffer![1i64, 2, 1, 2, 3, 3, 3, 4, 5, 6].into_array(),
840            buffer![0u32, 2, 4, 5, 6, 7, 10].into_array(),
841            Validity::from_iter([true, true, false, false, false, true]),
842            &mut ctx,
843        )?
844        .into_array();
845        assert_arrays_eq!(arr.into_array(), expected, &mut ctx);
846        Ok(())
847    }
848
849    #[test]
850    fn test_runend_dict() {
851        let mut ctx = SESSION.create_execution_ctx();
852        let dict_values = VarBinViewArray::from_iter_str(["x", "y", "z"]).into_array();
853        let dict_codes = buffer![0u32, 1, 2].into_array();
854        let dict = DictArray::try_new(dict_codes, dict_values).unwrap();
855
856        let arr = RunEnd::try_new(
857            buffer![2u32, 5, 10].into_array(),
858            dict.into_array(),
859            &mut ctx,
860        )
861        .unwrap();
862        assert_eq!(arr.len(), 10);
863
864        let expected =
865            VarBinViewArray::from_iter_str(["x", "x", "y", "y", "y", "z", "z", "z", "z", "z"])
866                .into_array();
867        assert_arrays_eq!(arr.into_array(), expected, &mut ctx);
868    }
869
870    #[test]
871    fn test_runend_decimal_i128() -> VortexResult<()> {
872        let mut ctx = SESSION.create_execution_ctx();
873        let decimal_dtype = DecimalDType::new(20, 2);
874        let values = DecimalArray::from_iter([12_345i128, -67_890, 100], decimal_dtype);
875        let arr = RunEnd::try_new(
876            buffer![2u32, 5, 6].into_array(),
877            values.into_array(),
878            &mut ctx,
879        )?;
880
881        let expected = DecimalArray::from_iter(
882            [12_345i128, 12_345, -67_890, -67_890, -67_890, 100],
883            decimal_dtype,
884        );
885        assert_arrays_eq!(arr, expected, &mut ctx);
886        Ok(())
887    }
888
889    #[test]
890    fn test_runend_decimal_nullable() -> VortexResult<()> {
891        let mut ctx = SESSION.create_execution_ctx();
892        let decimal_dtype = DecimalDType::new(20, 2);
893        let values =
894            DecimalArray::from_option_iter([Some(12_345i128), None, Some(-67_890)], decimal_dtype);
895        let arr = RunEnd::try_new(
896            buffer![2u32, 5, 7].into_array(),
897            values.into_array(),
898            &mut ctx,
899        )?;
900
901        let expected = DecimalArray::from_option_iter(
902            [
903                Some(12_345i128),
904                Some(12_345),
905                None,
906                None,
907                None,
908                Some(-67_890),
909                Some(-67_890),
910            ],
911            decimal_dtype,
912        );
913        assert_arrays_eq!(arr, expected, &mut ctx);
914        Ok(())
915    }
916
917    #[test]
918    fn test_runend_decimal_slice() -> VortexResult<()> {
919        let mut ctx = SESSION.create_execution_ctx();
920        let decimal_dtype = DecimalDType::new(20, 2);
921        let values = DecimalArray::from_iter([100i128, 200, 300], decimal_dtype);
922        let arr = RunEnd::try_new(
923            buffer![3u32, 5, 10].into_array(),
924            values.into_array(),
925            &mut ctx,
926        )?;
927
928        let sliced = arr.slice(2..8)?;
929        let expected = DecimalArray::from_iter([100i128, 200, 200, 300, 300, 300], decimal_dtype);
930        assert_arrays_eq!(sliced, expected, &mut ctx);
931        Ok(())
932    }
933
934    #[test]
935    fn test_runend_decimal_i256() -> VortexResult<()> {
936        let mut ctx = SESSION.create_execution_ctx();
937        let decimal_dtype = DecimalDType::new(40, 4);
938        let first = i256::from_i128(123_456);
939        let second = i256::from_i128(-789_012);
940        let values = DecimalArray::from_iter([first, second], decimal_dtype);
941        let arr = RunEnd::try_new(buffer![2u32, 5].into_array(), values.into_array(), &mut ctx)?;
942
943        let expected =
944            DecimalArray::from_iter([first, first, second, second, second], decimal_dtype);
945        assert_arrays_eq!(arr, expected, &mut ctx);
946        Ok(())
947    }
948
949    #[test]
950    fn test_deserialize_rejects_unknown_ends_ptype() -> VortexResult<()> {
951        let metadata = RunEndMetadata {
952            ends_ptype: 11,
953            ..Default::default()
954        }
955        .encode_to_vec();
956        let children: Vec<ArrayRef> = Vec::new();
957        let result = ArrayPlugin::deserialize(
958            &RunEnd,
959            ArrayDeserialization::new(
960                VTable::id(&RunEnd),
961                &DType::Primitive(PType::I32, Nullability::NonNullable),
962                0,
963                &metadata,
964                &[],
965                &children,
966            ),
967            &SESSION,
968        );
969        assert!(result.is_err_and(|err| {
970            err.to_string()
971                .contains("RunEndMetadata ends_ptype must be a known PType, got 11")
972        }));
973
974        let known = RunEndMetadata {
975            ends_ptype: PType::U32 as i32,
976            ..Default::default()
977        };
978        assert_eq!(known.get_ends_ptype()?, PType::U32);
979
980        Ok(())
981    }
982
983    // On 32-bit targets, a crafted num_runs / offset above usize::MAX used to panic via
984    // vortex_expect. Keep a regression that only builds where the conversion can fail.
985    #[cfg(target_pointer_width = "32")]
986    #[test]
987    fn test_deserialize_rejects_num_runs_overflow() -> VortexResult<()> {
988        let metadata = RunEndMetadata {
989            ends_ptype: PType::U32 as i32,
990            num_runs: u64::from(u32::MAX) + 1,
991            offset: 0,
992        }
993        .encode_to_vec();
994        let children: Vec<ArrayRef> = Vec::new();
995        let result = ArrayPlugin::deserialize(
996            &RunEnd,
997            ArrayDeserialization::new(
998                VTable::id(&RunEnd),
999                &DType::Primitive(PType::I32, Nullability::NonNullable),
1000                0,
1001                &metadata,
1002                &[],
1003                &children,
1004            ),
1005            &SESSION,
1006        );
1007        assert!(result.is_err_and(|err| {
1008            err.to_string().contains("RunEndMetadata num_runs")
1009                && err.to_string().contains("exceeds usize range")
1010        }));
1011        Ok(())
1012    }
1013
1014    #[cfg(target_pointer_width = "32")]
1015    #[test]
1016    fn test_deserialize_rejects_offset_overflow() -> VortexResult<()> {
1017        let metadata = RunEndMetadata {
1018            ends_ptype: PType::U32 as i32,
1019            num_runs: 0,
1020            offset: u64::from(u32::MAX) + 1,
1021        }
1022        .encode_to_vec();
1023        let children: Vec<ArrayRef> = Vec::new();
1024        let result = ArrayPlugin::deserialize(
1025            &RunEnd,
1026            ArrayDeserialization::new(
1027                VTable::id(&RunEnd),
1028                &DType::Primitive(PType::I32, Nullability::NonNullable),
1029                0,
1030                &metadata,
1031                &[],
1032                &children,
1033            ),
1034            &SESSION,
1035        );
1036        assert!(result.is_err_and(|err| {
1037            err.to_string().contains("RunEndMetadata offset")
1038                && err.to_string().contains("exceeds usize range")
1039        }));
1040        Ok(())
1041    }
1042}