Skip to main content

vortex_array/arrays/runend/
compress.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use vortex_buffer::BitBuffer;
5use vortex_buffer::BitBufferMut;
6use vortex_buffer::Buffer;
7use vortex_buffer::BufferAllocatorRef;
8use vortex_buffer::BufferMut;
9use vortex_buffer::buffer;
10use vortex_compute::lane_kernels::for_each_mask_word;
11use vortex_compute::lane_kernels::low_bits_mask;
12use vortex_error::VortexExpect;
13use vortex_error::VortexResult;
14use vortex_error::vortex_bail;
15use vortex_mask::Mask;
16
17use crate::ArrayRef;
18use crate::ArrayView;
19use crate::ExecutionCtx;
20use crate::IntoArray;
21use crate::arrays::Bool;
22use crate::arrays::BoolArray;
23use crate::arrays::ConstantArray;
24use crate::arrays::DecimalArray;
25use crate::arrays::Primitive;
26use crate::arrays::PrimitiveArray;
27use crate::arrays::VarBinViewArray;
28use crate::arrays::bool::BoolArrayExt;
29use crate::arrays::decimal::DecimalArrayExt;
30use crate::arrays::primitive::PrimitiveArrayExt;
31use crate::arrays::runend::iter::slice_relative_ends;
32use crate::buffer::BufferHandle;
33use crate::dtype::NativePType;
34use crate::dtype::Nullability;
35use crate::match_each_decimal_value_type;
36use crate::match_each_native_ptype;
37use crate::match_each_unsigned_integer_ptype;
38use crate::scalar::Scalar;
39use crate::stats::Precision;
40use crate::stats::Stat;
41use crate::validity::Validity;
42
43/// Run-end encode a `PrimitiveArray`, returning a tuple of `(ends, values)`.
44pub fn runend_encode(
45    array: ArrayView<Primitive>,
46    ctx: &mut ExecutionCtx,
47) -> (PrimitiveArray, ArrayRef) {
48    let validity = match array
49        .validity()
50        .vortex_expect("run-end validity should be derivable")
51    {
52        Validity::NonNullable => None,
53        Validity::AllValid => None,
54        Validity::AllInvalid => {
55            // We can trivially return an all-null REE array
56            let ends = PrimitiveArray::new(buffer![array.len() as u64], Validity::NonNullable);
57            ends.statistics()
58                .set(Stat::IsStrictSorted, Precision::Exact(true.into()));
59            return (
60                ends,
61                ConstantArray::new(Scalar::null(array.dtype().clone()), 1).into_array(),
62            );
63        }
64        Validity::Array(a) => {
65            let bool_array = a
66                .execute::<BoolArray>(ctx)
67                .vortex_expect("validity array must be convertible to bool");
68            Some(bool_array.to_bit_buffer())
69        }
70    };
71
72    let (ends, values) = match validity {
73        None => {
74            match_each_native_ptype!(array.ptype(), |P| {
75                let (ends, values) = runend_encode_primitive(array.as_slice::<P>());
76                (
77                    PrimitiveArray::new(ends, Validity::NonNullable),
78                    PrimitiveArray::new(values, array.dtype().nullability().into()).into_array(),
79                )
80            })
81        }
82        Some(validity) => {
83            match_each_native_ptype!(array.ptype(), |P| {
84                let (ends, values) =
85                    runend_encode_nullable_primitive(array.as_slice::<P>(), validity);
86                (
87                    PrimitiveArray::new(ends, Validity::NonNullable),
88                    values.into_array(),
89                )
90            })
91        }
92    };
93
94    let ends = ends
95        .narrow(ctx)
96        .vortex_expect("Ends must succeed downcasting");
97
98    ends.statistics()
99        .set(Stat::IsStrictSorted, Precision::Exact(true.into()));
100
101    (ends, values)
102}
103
104fn runend_encode_primitive<T: NativePType>(elements: &[T]) -> (Buffer<u64>, Buffer<T>) {
105    let mut ends = BufferMut::empty();
106    let mut values = BufferMut::empty();
107
108    if elements.is_empty() {
109        return (ends.freeze(), values.freeze());
110    }
111
112    // Run-end encode the values
113    let mut prev = elements[0];
114    let mut end = 1;
115    for &e in elements.iter().skip(1) {
116        if e != prev {
117            ends.push(end);
118            values.push(prev);
119        }
120        prev = e;
121        end += 1;
122    }
123    ends.push(end);
124    values.push(prev);
125
126    (ends.freeze(), values.freeze())
127}
128
129fn runend_encode_nullable_primitive<T: NativePType>(
130    elements: &[T],
131    element_validity: BitBuffer,
132) -> (Buffer<u64>, PrimitiveArray) {
133    let mut ends = BufferMut::empty();
134    let mut values = BufferMut::empty();
135    let mut validity = BitBufferMut::with_capacity(values.capacity());
136
137    if elements.is_empty() {
138        return (
139            ends.freeze(),
140            PrimitiveArray::new(
141                values,
142                Validity::Array(BoolArray::from(validity.freeze()).into_array()),
143            ),
144        );
145    }
146
147    // Run-end encode the values
148    let mut prev = element_validity.value(0).then(|| elements[0]);
149    let mut end = 1;
150    for e in elements
151        .iter()
152        .zip(element_validity.iter())
153        .map(|(&e, is_valid)| is_valid.then_some(e))
154        .skip(1)
155    {
156        if e != prev {
157            ends.push(end);
158            match prev {
159                None => {
160                    validity.append(false);
161                    values.push(T::default());
162                }
163                Some(p) => {
164                    validity.append(true);
165                    values.push(p);
166                }
167            }
168        }
169        prev = e;
170        end += 1;
171    }
172    ends.push(end);
173
174    match prev {
175        None => {
176            validity.append(false);
177            values.push(T::default());
178        }
179        Some(p) => {
180            validity.append(true);
181            values.push(p);
182        }
183    }
184
185    (
186        ends.freeze(),
187        PrimitiveArray::new(values, Validity::from(validity.freeze())),
188    )
189}
190
191/// Run-end encode a `BoolArray` without nulls, returning a tuple of `(ends, values)`.
192///
193/// The values child keeps the input's nullability.
194///
195/// # Errors
196///
197/// Returns an error if the array contains nulls.
198pub fn runend_encode_bool(
199    array: ArrayView<Bool>,
200    ctx: &mut ExecutionCtx,
201) -> VortexResult<(PrimitiveArray, ArrayRef)> {
202    let has_nulls = match array.validity()? {
203        Validity::NonNullable | Validity::AllValid => false,
204        Validity::AllInvalid => !array.is_empty(),
205        Validity::Array(validity) => {
206            validity
207                .execute::<BoolArray>(ctx)?
208                .to_bit_buffer()
209                .true_count()
210                != array.len()
211        }
212    };
213    if has_nulls {
214        vortex_bail!("run-end encoding of booleans with nulls is not supported");
215    }
216
217    let bits = array.to_bit_buffer();
218
219    let mut ends = BufferMut::<u64>::empty();
220    for_each_transition_word(&bits, |base, mut transitions| {
221        while transitions != 0 {
222            ends.push((base + transitions.trailing_zeros() as usize) as u64);
223            transitions &= transitions - 1;
224        }
225    });
226    if !bits.is_empty() {
227        ends.push(bits.len() as u64);
228    }
229
230    // Runs alternate between `true` and `false`, so the first bit gives all of the values.
231    let first = !bits.is_empty() && bits.value(0);
232    let values = BitBuffer::collect_bool(ends.len(), |run| first ^ (run % 2 == 1));
233
234    let ends = PrimitiveArray::new(ends.freeze(), Validity::NonNullable).narrow(ctx)?;
235    ends.statistics()
236        .set(Stat::IsStrictSorted, Precision::Exact(true.into()));
237    let values = BoolArray::new(values, array.dtype().nullability().into()).into_array();
238    Ok((ends, values))
239}
240
241/// Count the runs of equal values in a bitmap, a word at a time.
242pub fn bool_run_count(bits: &BitBuffer) -> usize {
243    if bits.is_empty() {
244        return 0;
245    }
246
247    let mut transitions = 0;
248    for_each_transition_word(bits, |_, word| transitions += word.count_ones() as usize);
249    transitions + 1
250}
251
252/// Calls `f(base, transitions)` for each word of `bits`, of at most 64 bits, where bit `j` of
253/// `transitions` is set when bit `base + j` differs from bit `base + j - 1`.
254///
255/// Bit 0 of the bitmap never counts as a transition.
256fn for_each_transition_word(bits: &BitBuffer, mut f: impl FnMut(usize, u64)) {
257    if bits.is_empty() {
258        return;
259    }
260
261    // Seed the carry with the first bit, so that bit 0 compares equal to its predecessor.
262    let mut carry = u64::from(bits.value(0));
263
264    for_each_mask_word(bits, |word, base, len| {
265        // The shift moves the last bit of a full word out, so only a short word needs the mask.
266        f(base, (word ^ ((word << 1) | carry)) & low_bits_mask(len));
267        carry = word >> (len - 1);
268    });
269}
270
271pub fn runend_decode_primitive(
272    ends: PrimitiveArray,
273    values: PrimitiveArray,
274    offset: usize,
275    length: usize,
276    ctx: &mut ExecutionCtx,
277) -> VortexResult<ArrayRef> {
278    let validity_mask = values
279        .as_ref()
280        .validity()?
281        .execute_mask(values.as_ref().len(), ctx)?;
282    if matches!(validity_mask, Mask::AllFalse(_)) {
283        return Ok(
284            ConstantArray::new(Scalar::null(values.dtype().as_nullable()), length).into_array(),
285        );
286    }
287    Ok(match_each_native_ptype!(values.ptype(), |P| {
288        match_each_unsigned_integer_ptype!(ends.ptype(), |E| {
289            runend_decode_typed_primitive(
290                slice_relative_ends(ends.as_slice::<E>(), offset, length),
291                values.as_slice::<P>(),
292                validity_mask,
293                values.dtype().nullability(),
294                length,
295                ctx.allocator(),
296            )
297            .into_array()
298        })
299    }))
300}
301
302/// Decode a run-end encoded slice of values into a flat `Buffer<T>` and `Validity`.
303///
304/// This is the core decode loop shared by primitive and varbinview run-end decoding.
305fn runend_decode_slice<T: Copy + Default>(
306    run_ends: impl ExactSizeIterator<Item = usize>,
307    values: &[T],
308    values_validity: Mask,
309    values_nullability: Nullability,
310    length: usize,
311    allocator: &BufferAllocatorRef,
312) -> (Buffer<T>, Validity) {
313    // Checked once here so the loops can use `zip`, which unlike `zip_eq` compiles to a single
314    // counted loop over the slices instead of checking both iterators for their end on every run.
315    assert_eq!(
316        run_ends.len(),
317        values.len(),
318        "run ends and values must have the same length"
319    );
320    match values_validity {
321        Mask::AllTrue(_) => {
322            let mut decoded = RunWriter::new(length, allocator);
323            for (end, &value) in run_ends.zip(values) {
324                decoded.write_run(value, end);
325            }
326            (decoded.finish(), values_nullability.into())
327        }
328        Mask::AllFalse(_) => (Buffer::<T>::zeroed(length), Validity::AllInvalid),
329        Mask::Values(mask) => {
330            // Nulls are usually rare and clustered, so start from all-valid and clear each
331            // maximal streak of null runs once, rather than appending validity per run.
332            let mut decoded = RunWriter::new(length, allocator);
333            let mut decoded_validity = BitBufferMut::full(true, length);
334            let mut null_start = None;
335            for (end, (&value, is_valid)) in
336                run_ends.zip(values.iter().zip(mask.bit_buffer().iter()))
337            {
338                let start = decoded.len();
339                decoded.write_run(if is_valid { value } else { T::default() }, end);
340                match (is_valid, null_start) {
341                    (false, None) => null_start = Some(start),
342                    (true, Some(null_from)) => {
343                        // SAFETY: null_from <= start <= length == decoded_validity.len()
344                        unsafe { decoded_validity.fill_range_unchecked(null_from, start, false) };
345                        null_start = None;
346                    }
347                    _ => {}
348                }
349            }
350            let decoded = decoded.finish();
351            if let Some(null_from) = null_start {
352                // SAFETY: null_from <= decoded.len() <= length == decoded_validity.len()
353                unsafe { decoded_validity.fill_range_unchecked(null_from, decoded.len(), false) };
354            }
355            decoded_validity.truncate(decoded.len());
356            (decoded, Validity::from(decoded_validity.freeze()))
357        }
358    }
359}
360
361/// Minimum bytes in a [`RunWriter`] block.
362const BLOCK_BYTES: usize = 32;
363
364/// Writes runs of values into a buffer of up to `length` elements.
365///
366/// Runs are usually short, and filling each one with a loop sized to its length costs more than
367/// the fill itself. Instead a run that fits in a fixed block writes the whole block, which the
368/// compiler lowers to a few vector stores, and the next run overwrites whatever went past its
369/// end. Longer runs are filled exactly. The buffer has a block of spare capacity so that the last
370/// run's block stays in bounds.
371struct RunWriter<T> {
372    buffer: BufferMut<T>,
373    len: usize,
374    length: usize,
375}
376
377impl<T: Copy> RunWriter<T> {
378    /// Elements in a block: enough to cover most short runs, at least 8 elements and 32 bytes.
379    const BLOCK: usize = if size_of::<T>() == 0 || size_of::<T>() >= BLOCK_BYTES / 8 {
380        8
381    } else {
382        BLOCK_BYTES / size_of::<T>()
383    };
384
385    fn new(length: usize, allocator: &BufferAllocatorRef) -> Self {
386        Self {
387            buffer: BufferMut::with_capacity_in(length + Self::BLOCK, allocator.clone()),
388            len: 0,
389            length,
390        }
391    }
392
393    fn len(&self) -> usize {
394        self.len
395    }
396
397    /// Fill `self.len()..end` with `value`.
398    #[inline]
399    fn write_run(&mut self, value: T, end: usize) {
400        assert!(
401            end >= self.len,
402            "Runend ends must be monotonic, got {end} after {}",
403            self.len
404        );
405        assert!(
406            end <= self.length,
407            "Runend end must be less than overall length"
408        );
409        // SAFETY: `self.len <= end <= length`, and the buffer holds `length + BLOCK` elements, so
410        // both the block and the remainder of the run are in bounds.
411        unsafe {
412            let dst = self.buffer.as_mut_ptr().add(self.len);
413            let run_len = end - self.len;
414            if run_len <= Self::BLOCK {
415                for i in 0..Self::BLOCK {
416                    dst.add(i).write(value);
417                }
418            } else {
419                for i in 0..run_len {
420                    dst.add(i).write(value);
421                }
422            }
423        }
424        self.len = end;
425    }
426
427    fn finish(mut self) -> Buffer<T> {
428        // SAFETY: every element below `self.len` was written by a run.
429        unsafe { self.buffer.set_len(self.len) };
430        self.buffer.freeze()
431    }
432}
433
434pub fn runend_decode_typed_primitive<T: NativePType>(
435    run_ends: impl ExactSizeIterator<Item = usize>,
436    values: &[T],
437    values_validity: Mask,
438    values_nullability: Nullability,
439    length: usize,
440    allocator: &BufferAllocatorRef,
441) -> PrimitiveArray {
442    let (decoded, validity) = runend_decode_slice(
443        run_ends,
444        values,
445        values_validity,
446        values_nullability,
447        length,
448        allocator,
449    );
450    PrimitiveArray::new(decoded, validity)
451}
452
453/// Decode a run-end encoded decimal array by expanding its native values.
454pub fn runend_decode_decimal(
455    ends: PrimitiveArray,
456    values: DecimalArray,
457    offset: usize,
458    length: usize,
459    ctx: &mut ExecutionCtx,
460) -> VortexResult<ArrayRef> {
461    let validity_mask = values
462        .as_ref()
463        .validity()?
464        .execute_mask(values.as_ref().len(), ctx)?;
465    if matches!(validity_mask, Mask::AllFalse(_)) {
466        return Ok(
467            ConstantArray::new(Scalar::null(values.dtype().as_nullable()), length).into_array(),
468        );
469    }
470
471    Ok(match_each_decimal_value_type!(values.values_type(), |D| {
472        let (decoded, validity) = match_each_unsigned_integer_ptype!(ends.ptype(), |E| {
473            runend_decode_slice(
474                slice_relative_ends(ends.as_slice::<E>(), offset, length),
475                values.buffer::<D>().as_slice(),
476                validity_mask,
477                values.dtype().nullability(),
478                length,
479                ctx.allocator(),
480            )
481        });
482        // SAFETY: Decoding repeats each value and its validity for the same run length.
483        unsafe { DecimalArray::new_unchecked(decoded, values.decimal_dtype(), validity) }
484            .into_array()
485    }))
486}
487
488/// Decode a run-end encoded VarBinView array by expanding views directly.
489pub fn runend_decode_varbinview(
490    ends: PrimitiveArray,
491    values: VarBinViewArray,
492    offset: usize,
493    length: usize,
494    ctx: &mut ExecutionCtx,
495) -> VortexResult<ArrayRef> {
496    let validity_mask = values
497        .as_ref()
498        .validity()?
499        .execute_mask(values.as_ref().len(), ctx)?;
500    if matches!(validity_mask, Mask::AllFalse(_)) {
501        return Ok(
502            ConstantArray::new(Scalar::null(values.dtype().as_nullable()), length).into_array(),
503        );
504    }
505    let views = values.views();
506
507    let (decoded_views, validity) = match_each_unsigned_integer_ptype!(ends.ptype(), |E| {
508        runend_decode_slice(
509            slice_relative_ends(ends.as_slice::<E>(), offset, length),
510            views,
511            validity_mask,
512            values.dtype().nullability(),
513            length,
514            ctx.allocator(),
515        )
516    });
517
518    let parts = values.into_data_parts();
519    let view_handle = BufferHandle::new_host(decoded_views.into_byte_buffer());
520
521    // SAFETY: we are expanding views from a valid VarBinViewArray with the same
522    // buffers, so all buffer indices and offsets remain valid.
523    Ok(unsafe {
524        VarBinViewArray::new_handle_unchecked(view_handle, parts.buffers, parts.dtype, validity)
525    }
526    .into_array())
527}
528
529#[cfg(test)]
530mod tests {
531    use std::sync::LazyLock;
532
533    use rstest::rstest;
534    use vortex_buffer::BitBuffer;
535    use vortex_buffer::buffer;
536    use vortex_error::VortexResult;
537    use vortex_mask::Mask;
538    use vortex_session::VortexSession;
539
540    use crate::IntoArray;
541    use crate::VortexSessionExecute;
542    use crate::arrays::BoolArray;
543    use crate::arrays::PrimitiveArray;
544    use crate::arrays::RunEnd;
545    use crate::arrays::bool::BoolArrayExt;
546    use crate::arrays::runend::compress::bool_run_count;
547    use crate::arrays::runend::compress::runend_decode_primitive;
548    use crate::arrays::runend::compress::runend_decode_typed_primitive;
549    use crate::arrays::runend::compress::runend_encode;
550    use crate::assert_arrays_eq;
551    use crate::dtype::Nullability;
552    use crate::validity::Validity;
553
554    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
555
556    /// Bits alternate in runs of `run`, with lengths on 64-bit word boundaries. `valid` adds a
557    /// validity bitmap that is all valid (`true`) or has one null (`false`).
558    #[rstest]
559    #[case(0, 1, None)]
560    #[case(1, 1, None)]
561    #[case(63, 62, None)]
562    #[case(64, 63, None)]
563    #[case(65, 64, None)]
564    #[case(130, 1, None)]
565    #[case(300, 61, Some(true))]
566    #[case(300, 61, Some(false))]
567    fn encode_bool(
568        #[case] len: usize,
569        #[case] run: usize,
570        #[case] valid: Option<bool>,
571    ) -> VortexResult<()> {
572        let mut ctx = SESSION.create_execution_ctx();
573        let bits: Vec<bool> = (0..len).map(|i| (i / run) % 2 == 1).collect();
574        // Array-backed even when all valid, which `Validity::from(BitBuffer)` would collapse.
575        let validity = valid.map_or(Validity::NonNullable, |v| {
576            Validity::Array(BoolArray::from_iter((0..len).map(|i| v || i != 1)).into_array())
577        });
578        let arr = BoolArray::new(BitBuffer::from(bits.clone()), validity);
579        let runs = |b: &[bool]| b.len().min(1) + b.windows(2).filter(|w| w[0] != w[1]).count();
580        for offset in [0, 1].into_iter().filter(|&o| o <= len) {
581            let sliced = arr.to_bit_buffer().slice(offset..);
582            assert_eq!(bool_run_count(&sliced), runs(&bits[offset..]));
583
584            let sliced = BoolArray::new(sliced, Validity::NonNullable);
585            let encoded = RunEnd::encode(sliced.clone().into_array(), &mut ctx)?;
586            assert_arrays_eq!(encoded, sliced, &mut ctx);
587        }
588
589        let encoded = RunEnd::encode(arr.clone().into_array(), &mut ctx);
590        if valid == Some(false) {
591            assert!(encoded.is_err());
592        } else {
593            assert_arrays_eq!(encoded?, arr, &mut ctx);
594        }
595        Ok(())
596    }
597
598    #[test]
599    fn encode() -> VortexResult<()> {
600        let mut ctx = SESSION.create_execution_ctx();
601        let arr = PrimitiveArray::from_iter([1i32, 1, 2, 2, 2, 3, 3, 3, 3, 3]);
602        let (ends, values) = runend_encode(arr.as_view(), &mut ctx);
603
604        let expected_ends = PrimitiveArray::from_iter(vec![2u8, 5, 10]);
605        assert_arrays_eq!(ends, expected_ends, &mut ctx);
606        let expected_values = PrimitiveArray::from_iter(vec![1i32, 2, 3]);
607        assert_arrays_eq!(values, expected_values, &mut ctx);
608        Ok(())
609    }
610
611    #[test]
612    fn encode_nullable() -> VortexResult<()> {
613        let mut ctx = SESSION.create_execution_ctx();
614        let arr = PrimitiveArray::new(
615            buffer![1i32, 1, 2, 2, 2, 3, 3, 3, 3, 3],
616            Validity::from(BitBuffer::from(vec![
617                true, true, false, false, true, true, true, true, false, false,
618            ])),
619        );
620        let (ends, values) = runend_encode(arr.as_view(), &mut ctx);
621
622        let expected_ends = PrimitiveArray::from_iter(vec![2u8, 4, 5, 8, 10]);
623        assert_arrays_eq!(ends, expected_ends, &mut ctx);
624        let expected_values =
625            PrimitiveArray::from_option_iter(vec![Some(1i32), None, Some(2), Some(3), None]);
626        assert_arrays_eq!(values, expected_values, &mut ctx);
627        Ok(())
628    }
629
630    #[test]
631    fn encode_all_null() -> VortexResult<()> {
632        let mut ctx = SESSION.create_execution_ctx();
633        let arr = PrimitiveArray::new(
634            buffer![0, 0, 0, 0, 0],
635            Validity::from(BitBuffer::new_unset(5)),
636        );
637        let (ends, values) = runend_encode(arr.as_view(), &mut ctx);
638
639        let expected_ends = PrimitiveArray::from_iter(vec![5u64]);
640        assert_arrays_eq!(ends, expected_ends, &mut ctx);
641        let expected_values = PrimitiveArray::from_option_iter(vec![Option::<i32>::None]);
642        assert_arrays_eq!(values, expected_values, &mut ctx);
643        Ok(())
644    }
645
646    #[test]
647    fn decode() -> VortexResult<()> {
648        let mut ctx = SESSION.create_execution_ctx();
649        let ends = PrimitiveArray::from_iter([2u32, 5, 10]);
650        let values = PrimitiveArray::from_iter([1i32, 2, 3]);
651        let decoded = runend_decode_primitive(ends, values, 0, 10, &mut ctx)?;
652
653        let expected = PrimitiveArray::from_iter(vec![1i32, 1, 2, 2, 2, 3, 3, 3, 3, 3]);
654        assert_arrays_eq!(decoded, expected, &mut ctx);
655        Ok(())
656    }
657
658    #[rstest]
659    #[case::middle_nulls(&[Some(1), None, None, Some(2)], 0, 10)]
660    #[case::leading_and_trailing_nulls(&[None, Some(1), Some(2), None], 0, 10)]
661    #[case::all_null(&[None, None, None, None], 0, 10)]
662    #[case::offset_and_trailing_null(&[None, Some(1), Some(2), None], 1, 8)]
663    fn decode_nullable(
664        #[case] values: &[Option<i32>],
665        #[case] offset: usize,
666        #[case] length: usize,
667    ) -> VortexResult<()> {
668        let mut ctx = SESSION.create_execution_ctx();
669        let ends = [2u32, 5, 7, 10];
670        let expected = PrimitiveArray::from_option_iter(
671            (offset..offset + length)
672                .map(|row| values[ends.iter().position(|&end| row < end as usize).unwrap_or(0)]),
673        );
674        let decoded = runend_decode_primitive(
675            PrimitiveArray::from_iter(ends),
676            PrimitiveArray::from_option_iter(values.iter().copied()),
677            offset,
678            length,
679            &mut ctx,
680        )?;
681        assert_arrays_eq!(decoded, expected, &mut ctx);
682        Ok(())
683    }
684
685    #[test]
686    #[should_panic(expected = "run ends and values must have the same length")]
687    fn typed_primitive_rejects_mismatched_run_ends() {
688        let ctx = SESSION.create_execution_ctx();
689        runend_decode_typed_primitive(
690            [1, 3, 4].into_iter(),
691            &[1i32, 2],
692            Mask::AllTrue(2),
693            Nullability::NonNullable,
694            4,
695            ctx.allocator(),
696        );
697    }
698}