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