Skip to main content

vortex_array/arrays/listview/
array.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt::Display;
5use std::fmt::Formatter;
6use std::sync::Arc;
7
8use num_traits::AsPrimitive;
9use vortex_buffer::BitBufferMut;
10use vortex_error::VortexExpect;
11use vortex_error::VortexResult;
12use vortex_error::vortex_ensure;
13use vortex_error::vortex_ensure_eq;
14use vortex_error::vortex_err;
15use vortex_mask::Mask;
16
17use crate::ArrayRef;
18use crate::ArraySlots;
19use crate::ExecutionCtx;
20use crate::aggregate_fn::NumericalAggregateOpts;
21use crate::aggregate_fn::fns::min_max::min_max;
22use crate::array::Array;
23use crate::array::ArrayParts;
24use crate::array::TypedArrayRef;
25use crate::array::child_to_validity;
26use crate::array::validity_to_child;
27use crate::array_slots;
28use crate::arrays::ListView;
29use crate::arrays::Primitive;
30use crate::arrays::PrimitiveArray;
31use crate::arrays::bool;
32use crate::arrays::primitive::PrimitiveArrayExt;
33use crate::builtins::ArrayBuiltins;
34use crate::dtype::DType;
35use crate::dtype::IntegerPType;
36use crate::dtype::PType;
37use crate::match_each_integer_ptype;
38use crate::match_each_unsigned_integer_ptype;
39use crate::optimizer::ArrayOptimizer;
40use crate::scalar::NumericOperator;
41use crate::stats::Stat;
42use crate::validity::Validity;
43
44#[array_slots(ListView)]
45pub struct ListViewSlots {
46    /// The `elements` data array, where each list scalar is a _slice_ of the `elements` array,
47    /// and each inner list element is a _scalar_ of the `elements` array.
48    #[slot(0)]
49    pub elements: ArrayRef,
50    /// The `offsets` array indicating the start position of each list in elements.
51    ///
52    /// Since we also store `sizes`, this `offsets` field is allowed to be stored out-of-order
53    /// (which is different from [`ListArray`](crate::arrays::ListArray)).
54    #[slot(1)]
55    pub offsets: ArrayRef,
56    /// The `sizes` array indicating the length of each list.
57    ///
58    /// This field is intended to be paired with a corresponding offset to determine the list
59    /// scalar we want to access.
60    #[slot(2)]
61    pub sizes: ArrayRef,
62    /// The validity bitmap indicating which list elements are non-null.
63    #[slot(3)]
64    pub validity_child: Option<ArrayRef>,
65}
66
67/// The canonical encoding for variable-length list arrays.
68///
69/// The `ListViewArray` encoding differs from [`ListArray`] in that it stores a child `sizes` array
70/// in addition to a child `offsets` array (which is the _only_ child in [`ListArray`]).
71///
72/// In the past, we used [`ListArray`] as the canonical encoding for [`DType::List`], but we have
73/// since migrated to `ListViewArray` for a few reasons:
74///
75/// - Enables better SIMD vectorization (no sequential dependency when reading `offsets`)
76/// - Allows out-of-order offsets for better compression (we can shuffle the buffers)
77/// - Supports different integer types for offsets vs sizes
78///
79/// It is worth mentioning that this encoding mirrors Apache Arrow's `ListView` array type, but does
80/// not exactly mirror the similar type found in DuckDB and Velox, which stores the pair of offset
81/// and size in a row-major fashion rather than column-major. More specifically, the row-major
82/// layout has a single child array with alternating offset and size next to each other.
83///
84/// We choose the column-major layout as it allows better compressability, as well as using
85/// different (logical) integer widths for our `offsets` and `sizes` buffers (note that the
86/// compressor will likely compress to a different bit-packed width, but this is speaking strictly
87/// about flexibility in the logcial type).
88///
89/// # Examples
90///
91/// ```
92/// # fn main() -> vortex_error::VortexResult<()> {
93/// # use vortex_array::arrays::{ListViewArray, PrimitiveArray};
94/// # use vortex_array::arrays::listview::ListViewArrayExt;
95/// # use vortex_array::validity::Validity;
96/// # use vortex_session::VortexSession;
97/// # use vortex_array::{IntoArray, VortexSessionExecute};
98/// # use vortex_buffer::buffer;
99/// # use std::sync::Arc;
100/// #
101/// // Create a list view array representing [[3, 4], [1], [2, 3]].
102/// // Note: Unlike `ListArray`, offsets don't need to be monotonic.
103///
104/// let elements = buffer![1i32, 2, 3, 4, 5].into_array();
105/// let offsets = buffer![2u32, 0, 1].into_array();  // Out-of-order offsets
106/// let sizes = buffer![2u32, 1, 2].into_array();  // The sizes cause overlaps
107///
108/// let mut ctx = VortexSession::empty().create_execution_ctx();
109/// let list_view = ListViewArray::new(
110///     elements.into_array(),
111///     offsets.into_array(),
112///     sizes.into_array(),
113///     Validity::NonNullable,
114///     &mut ctx,
115/// );
116///
117/// assert_eq!(list_view.len(), 3);
118///
119/// // Access individual lists
120/// let first_list = list_view.list_elements_at(0, &mut ctx)?;
121/// assert_eq!(first_list.len(), 2);
122/// // First list contains elements[2..4] = [3, 4]
123///
124/// let first_offset = list_view.offset_at(0, &mut ctx);
125/// let first_size = list_view.size_at(0, &mut ctx);
126/// assert_eq!(first_offset, 2);
127/// assert_eq!(first_size, 2);
128/// # Ok(())
129/// # }
130/// ```
131///
132/// [`ListArray`]: crate::arrays::ListArray
133#[derive(Clone, Debug)]
134pub struct ListViewData {
135    // TODO(connor)[ListView]: Add the n+1 memory allocation optimization.
136    /// A flag denoting if the array is zero-copyable* to a [`ListArray`](crate::arrays::ListArray).
137    ///
138    /// We use this information to help us more efficiently rebuild / compact our data.
139    ///
140    /// When this flag is true (indicating sorted offsets with no gaps and no overlaps and all
141    /// `offsets[i] + sizes[i]` are in order), conversions can bypass the very expensive rebuild
142    /// process which must rebuild the array from scratch.
143    is_zero_copy_to_list: bool,
144}
145
146impl Display for ListViewData {
147    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
148        write!(f, "is_zero_copy_to_list: {}", self.is_zero_copy_to_list)
149    }
150}
151
152pub struct ListViewDataParts {
153    pub elements_dtype: Arc<DType>,
154
155    /// See `ListViewArray::elements`
156    pub elements: ArrayRef,
157
158    /// See `ListViewArray::offsets`
159    pub offsets: ArrayRef,
160
161    /// See `ListViewArray::sizes`
162    pub sizes: ArrayRef,
163
164    /// See `ListViewArray::validity`
165    pub validity: Validity,
166}
167
168impl ListViewData {
169    pub(crate) fn make_slots(
170        elements: &ArrayRef,
171        offsets: &ArrayRef,
172        sizes: &ArrayRef,
173        validity: &Validity,
174        len: usize,
175    ) -> ArraySlots {
176        ListViewSlots {
177            elements: elements.clone(),
178            offsets: offsets.clone(),
179            sizes: sizes.clone(),
180            validity_child: validity_to_child(validity, len),
181        }
182        .into_slots()
183    }
184
185    /// Creates a new `ListViewArray`.
186    ///
187    /// # Panics
188    ///
189    /// Panics if the provided components do not satisfy the invariants documented
190    /// in `ListViewArray::new_unchecked`.
191    pub fn new() -> Self {
192        Self {
193            is_zero_copy_to_list: false,
194        }
195    }
196
197    /// Constructs a new `ListViewArray`.
198    ///
199    /// # Errors
200    ///
201    /// Returns an error if the provided components do not satisfy the invariants documented
202    /// in `ListViewArray::new_unchecked`.
203    pub fn try_new() -> VortexResult<Self> {
204        Ok(Self::new())
205    }
206
207    /// Creates a new `ListViewArray` without validation.
208    ///
209    /// This unsafe function does not check the validity of the data. Prefer calling [`new()`] or
210    /// [`try_new()`] over this function, as they will check the validity of the data.
211    ///
212    /// [`ListArray`]: crate::arrays::ListArray
213    /// [`new()`]: Self::new
214    /// [`try_new()`]: Self::try_new
215    ///
216    /// # Safety
217    ///
218    /// The caller must ensure all of the following invariants are satisfied:
219    ///
220    /// - `offsets` and `sizes` must be non-nullable integer arrays.
221    /// - `offsets` and `sizes` must have the same length.
222    /// - Size integer width must be smaller than or equal to offset type (to prevent overflow).
223    /// - For each `i`, `offsets[i] + sizes[i]` must not overflow and must be `<= elements.len()`
224    ///   (even if the corresponding view is defined as null by the validity array).
225    /// - If validity is an array, its length must equal `offsets.len()`.
226    pub unsafe fn new_unchecked() -> Self {
227        Self::new()
228    }
229
230    /// Validates the components that would be used to create a `ListViewArray`.
231    pub fn validate(
232        elements: &ArrayRef,
233        offsets: &ArrayRef,
234        sizes: &ArrayRef,
235        validity: &Validity,
236        ctx: &mut ExecutionCtx,
237    ) -> VortexResult<()> {
238        // Check that offsets and sizes are integer arrays and non-nullable.
239        vortex_ensure!(
240            offsets.dtype().is_int() && !offsets.dtype().is_nullable(),
241            "offsets must be non-nullable integer array, got {}",
242            offsets.dtype()
243        );
244        vortex_ensure!(
245            sizes.dtype().is_int() && !sizes.dtype().is_nullable(),
246            "sizes must be non-nullable integer array, got {}",
247            sizes.dtype()
248        );
249
250        // Check that they have the same length.
251        vortex_ensure_eq!(
252            offsets.len(),
253            sizes.len(),
254            "offsets and sizes must have the same length",
255        );
256
257        // If a validity array is present, it must be the same length as the `ListViewArray`.
258        if let Some(validity_len) = validity.maybe_len() {
259            vortex_ensure_eq!(
260                validity_len,
261                offsets.len(),
262                "validity length does not match array size",
263            );
264        }
265
266        // Skip host-only validation when offsets/sizes are not host-resident.
267        if offsets.is_host() && sizes.is_host() {
268            let offsets_primitive = offsets.clone().execute::<PrimitiveArray>(ctx)?;
269            let sizes_primitive = sizes.clone().execute::<PrimitiveArray>(ctx)?;
270            // Offsets and sizes are non-negative; reinterpret to unsigned to dispatch over 4 widths
271            // each (4x4 instead of 8x8). This is a read-only validation, so result types are moot.
272            let offsets_primitive =
273                offsets_primitive.reinterpret_cast(offsets_primitive.ptype().to_unsigned());
274            let sizes_primitive =
275                sizes_primitive.reinterpret_cast(sizes_primitive.ptype().to_unsigned());
276
277            // Validate the `offsets` and `sizes` arrays.
278            match_each_unsigned_integer_ptype!(offsets_primitive.ptype(), |O| {
279                match_each_unsigned_integer_ptype!(sizes_primitive.ptype(), |S| {
280                    let offsets_slice = offsets_primitive.as_slice::<O>();
281                    let sizes_slice = sizes_primitive.as_slice::<S>();
282
283                    validate_offsets_and_sizes::<O, S>(
284                        offsets_slice,
285                        sizes_slice,
286                        elements.len() as u64,
287                    )?;
288                })
289            });
290        }
291
292        Ok(())
293    }
294
295    /// Sets whether this `ListViewArray` is zero-copyable to a [`ListArray`].
296    ///
297    /// This is an optimization flag that enables more efficient conversion to [`ListArray`] without
298    /// needing to copy or reorganize the data.
299    ///
300    /// [`ListArray`]: crate::arrays::ListArray
301    ///
302    /// # Safety
303    ///
304    /// When setting `is_zctl` to `true`, the caller must ensure that the `ListViewArray` is
305    /// actually zero-copyable to a [`ListArray`]. This means:
306    ///
307    /// - Offsets must be sorted (but not strictly sorted, zero-length lists are allowed).
308    /// - `offsets[i] + sizes[i] == offsets[i + 1]` for all `i`.
309    /// - No gaps in elements between first and last referenced elements.
310    /// - No overlapping list views (each element referenced at most once).
311    ///
312    /// Note that leading and trailing unreferenced elements **ARE** allowed.
313    pub unsafe fn with_zero_copy_to_list(mut self, is_zctl: bool) -> Self {
314        self.is_zero_copy_to_list = is_zctl;
315        self
316    }
317
318    /// Returns true if the `ListViewArray` is zero-copyable to a
319    /// [`ListArray`](crate::arrays::ListArray).
320    pub fn is_zero_copy_to_list(&self) -> bool {
321        self.is_zero_copy_to_list
322    }
323}
324
325impl Default for ListViewData {
326    fn default() -> Self {
327        Self::new()
328    }
329}
330
331/// Walks parallel `(offset, size)` slices and sets each range `[offset, offset + size]` in `buf`.
332///
333/// **Preconditions**
334///
335/// `offsets` and `sizes` must be the same length (which is always the case in valid `ListViewArray`s).
336fn fill_referenced_mask<O: IntegerPType, S: IntegerPType>(
337    buf: &mut BitBufferMut,
338    offsets: &[O],
339    sizes: &[S],
340) {
341    let len = offsets.len();
342
343    assert_eq!(
344        len,
345        sizes.len(),
346        "offsets and sizes must be the same length"
347    );
348
349    for i in 0..len {
350        let start: usize = offsets[i].as_();
351        let size: usize = sizes[i].as_();
352        buf.fill_range(start, start + size, true);
353    }
354}
355
356pub trait ListViewArrayExt: TypedArrayRef<ListView> {
357    fn nullability(&self) -> crate::dtype::Nullability {
358        match self.dtype() {
359            DType::List(_, nullability) => *nullability,
360            _ => unreachable!("ListViewArrayExt requires a list dtype"),
361        }
362    }
363
364    fn listview_validity(&self) -> Validity {
365        child_to_validity(self.validity_child(), self.nullability())
366    }
367
368    fn offset_at(&self, index: usize, ctx: &mut ExecutionCtx) -> usize {
369        assert!(
370            index < self.len(),
371            "Index {index} out of bounds 0..{}",
372            self.len()
373        );
374        self.offsets()
375            .as_opt::<Primitive>()
376            .map(|p| match_each_integer_ptype!(p.ptype(), |P| { p.as_slice::<P>()[index].as_() }))
377            .unwrap_or_else(|| {
378                self.offsets()
379                    .execute_scalar(index, ctx)
380                    .vortex_expect("offsets must support execute_scalar")
381                    .as_primitive()
382                    .as_::<usize>()
383                    .vortex_expect("offset must fit in usize")
384            })
385    }
386
387    fn size_at(&self, index: usize, ctx: &mut ExecutionCtx) -> usize {
388        assert!(
389            index < self.len(),
390            "Index {} out of bounds 0..{}",
391            index,
392            self.len()
393        );
394        self.sizes()
395            .as_opt::<Primitive>()
396            .map(|p| match_each_integer_ptype!(p.ptype(), |P| { p.as_slice::<P>()[index].as_() }))
397            .unwrap_or_else(|| {
398                self.sizes()
399                    .execute_scalar(index, ctx)
400                    .vortex_expect("sizes must support execute_scalar")
401                    .as_primitive()
402                    .as_::<usize>()
403                    .vortex_expect("size must fit in usize")
404            })
405    }
406
407    fn list_elements_at(&self, index: usize, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
408        let offset = self.offset_at(index, ctx);
409        let size = self.size_at(index, ctx);
410        self.elements()
411            .slice(offset..offset + size)?
412            .optimize_ctx(ctx)
413    }
414
415    /// Returns a [`Mask`] of length `elements.len()` where each bit is set iff that
416    /// position in `elements` is referenced by at least one view. Caller must ensure `elements`
417    /// is non-empty.
418    ///
419    /// Walks every `(offset, size)` pair, canonicalizes both `offsets` and `sizes`,
420    /// and allocates a `BitBuffer` of length `elements.len()`, so it is extremely costly.
421    ///
422    /// **Preconditions**
423    ///
424    /// `self.elements()` must be non-empty.
425    fn compute_referenced_elements_mask(&self, ctx: &mut ExecutionCtx) -> VortexResult<Mask> {
426        assert!(!self.elements().is_empty());
427        let len = self.elements().len();
428
429        let offsets_primitive = self.offsets().clone().execute::<PrimitiveArray>(ctx)?;
430        let sizes_primitive = self.sizes().clone().execute::<PrimitiveArray>(ctx)?;
431
432        let mut buf = BitBufferMut::new_unset(len);
433
434        // Offsets/sizes are non-negative; reinterpret to unsigned (4x4 instead of 8x8).
435        let offsets_primitive =
436            offsets_primitive.reinterpret_cast(offsets_primitive.ptype().to_unsigned());
437        let sizes_primitive =
438            sizes_primitive.reinterpret_cast(sizes_primitive.ptype().to_unsigned());
439        match_each_unsigned_integer_ptype!(offsets_primitive.ptype(), |O| {
440            match_each_unsigned_integer_ptype!(sizes_primitive.ptype(), |S| {
441                fill_referenced_mask::<O, S>(
442                    &mut buf,
443                    offsets_primitive.as_slice::<O>(),
444                    sizes_primitive.as_slice::<S>(),
445                );
446            })
447        });
448
449        Ok(Mask::from_buffer(buf.freeze()))
450    }
451
452    /// Exact fraction of `elements` referenced by some view, in `[0.0, 1.0]`. Extremely costly.
453    ///
454    /// Returns `Ok(1.0)` when `elements` is empty instead of dividing by 0.
455    fn compute_density(&self, ctx: &mut ExecutionCtx) -> VortexResult<f32> {
456        if self.elements().is_empty() {
457            return Ok(1.0);
458        }
459
460        if self.sizes().is_empty() {
461            return Ok(0.0);
462        }
463
464        let density = match self.compute_referenced_elements_mask(ctx)? {
465            Mask::AllTrue(_) => 1.0,
466            Mask::AllFalse(_) => 0.0,
467            Mask::Values(values) => values.true_count() as f32 / self.elements().len() as f32,
468        };
469
470        Ok(density)
471    }
472
473    /// Upper-bound estimate of [`compute_density`](Self::compute_density) via
474    /// `sum(sizes) / elements.len()`, clamped to `[0.0, 1.0]`.
475    ///
476    /// Exact for non-overlapping views, but overcounts when multiple views share the same elements.
477    ///
478    /// Returns `Ok(1.0)` when `elements` is empty instead of dividing by 0.
479    fn upper_bound_density(&self, ctx: &mut ExecutionCtx) -> VortexResult<f32> {
480        let n_elts = self.elements().len();
481        if n_elts == 0 {
482            return Ok(1.0);
483        }
484
485        let sizes = self.sizes();
486        if sizes.is_empty() {
487            return Ok(0.0);
488        }
489
490        // compute_stat short-circuits on a cached exact Sum and otherwise computes
491        let sizes_sum = sizes
492            .statistics()
493            .compute_stat(Stat::Sum, ctx)?
494            .vortex_expect("sizes array has integer ptype elements")
495            .as_primitive()
496            .as_::<u64>()
497            .vortex_expect("integer ptypes can be upcast to u64");
498
499        // if the same elements are referenced more than once the estimate may be
500        // greater than 1.0, so clamp
501        let estimate = (sizes_sum as f32 / n_elts as f32).min(1.0);
502
503        debug_assert!(estimate >= 0.0);
504
505        Ok(estimate)
506    }
507
508    /// Returns the half-open range `[start, end)` of `elements` indices referenced by any view:
509    /// the minimum offset and the maximum `offset + size`. Elements outside this range are
510    /// unreferenced leading or trailing slack that a
511    /// [`TrimElements`](super::ListViewRebuildMode::TrimElements) rebuild would reclaim.
512    ///
513    /// For **zero-copy-to-list** arrays this is `O(1)`: views are sorted and non-overlapping with
514    /// no interior gaps, so the bounds are exactly `[first_offset, last_offset + last_size)`.
515    /// Otherwise it computes min/max statistics over `offsets` and `offsets + sizes`.
516    ///
517    /// # Preconditions
518    ///
519    /// The array must contain at least one list (`len() > 0`).
520    fn referenced_element_bounds(&self, ctx: &mut ExecutionCtx) -> VortexResult<(usize, usize)> {
521        let n_lists = self.len();
522        vortex_ensure!(
523            n_lists > 0,
524            "referenced_element_bounds requires a non-empty array"
525        );
526
527        if self.is_zero_copy_to_list() {
528            let start = self.offset_at(0, ctx);
529            let end = self.offset_at(n_lists - 1, ctx) + self.size_at(n_lists - 1, ctx);
530            return Ok((start, end));
531        }
532
533        let start = self
534            .offsets()
535            .statistics()
536            .compute_min::<usize>(ctx)
537            .vortex_expect("offsets must report a usize min statistic");
538
539        // Cast offsets and sizes to the widest integer type so that `offset + size` cannot overflow
540        // the narrower input width.
541        let wide_dtype = DType::from(if self.offsets().dtype().as_ptype().is_unsigned_int() {
542            PType::U64
543        } else {
544            PType::I64
545        });
546        let offsets = self.offsets().cast(wide_dtype.clone())?;
547        let sizes = self.sizes().cast(wide_dtype)?;
548        let end = min_max(
549            &offsets.numeric(sizes, NumericOperator::Add)?,
550            ctx,
551            NumericalAggregateOpts::default(),
552        )?
553        .vortex_expect("non-empty array must report a min/max")
554        .max
555        .as_primitive()
556        .as_::<usize>()
557        .vortex_expect("max `offset + size` must fit in a usize");
558
559        Ok((start, end))
560    }
561}
562impl<T: TypedArrayRef<ListView>> ListViewArrayExt for T {}
563
564impl Array<ListView> {
565    /// Creates a new `ListViewArray`.
566    pub fn new(
567        elements: ArrayRef,
568        offsets: ArrayRef,
569        sizes: ArrayRef,
570        validity: Validity,
571        ctx: &mut ExecutionCtx,
572    ) -> Self {
573        let dtype = DType::List(Arc::new(elements.dtype().clone()), validity.nullability());
574        let len = offsets.len();
575        let slots = ListViewData::make_slots(&elements, &offsets, &sizes, &validity, len);
576        ListViewData::validate(&elements, &offsets, &sizes, &validity, ctx)
577            .vortex_expect("`ListViewArray` construction failed");
578        let data = ListViewData::new();
579        unsafe { Array::from_parts_unchecked(ArrayParts::new(ListView, dtype, len, data, slots)) }
580    }
581
582    /// Constructs a new `ListViewArray`.
583    pub fn try_new(
584        elements: ArrayRef,
585        offsets: ArrayRef,
586        sizes: ArrayRef,
587        validity: Validity,
588        ctx: &mut ExecutionCtx,
589    ) -> VortexResult<Self> {
590        let dtype = DType::List(Arc::new(elements.dtype().clone()), validity.nullability());
591        let len = offsets.len();
592        let slots = ListViewData::make_slots(&elements, &offsets, &sizes, &validity, len);
593        ListViewData::validate(&elements, &offsets, &sizes, &validity, ctx)?;
594        let data = ListViewData::try_new()?;
595        Ok(unsafe {
596            Array::from_parts_unchecked(ArrayParts::new(ListView, dtype, len, data, slots))
597        })
598    }
599
600    /// Creates a new `ListViewArray` without validation.
601    ///
602    /// # Safety
603    ///
604    /// See [`ListViewData::new_unchecked`].
605    pub unsafe fn new_unchecked(
606        elements: ArrayRef,
607        offsets: ArrayRef,
608        sizes: ArrayRef,
609        validity: Validity,
610    ) -> Self {
611        let dtype = DType::List(Arc::new(elements.dtype().clone()), validity.nullability());
612        let len = offsets.len();
613        let slots = ListViewData::make_slots(&elements, &offsets, &sizes, &validity, len);
614        let data = unsafe { ListViewData::new_unchecked() };
615        unsafe { Array::from_parts_unchecked(ArrayParts::new(ListView, dtype, len, data, slots)) }
616    }
617
618    /// Mark whether this list view can be zero-copy converted to a list.
619    ///
620    /// # Safety
621    ///
622    /// See [`ListViewData::with_zero_copy_to_list`].
623    pub unsafe fn with_zero_copy_to_list(self, is_zctl: bool) -> Self {
624        // The flag is only checked when the offsets and sizes are canonical and host-resident,
625        // since validation never executes them.
626        if cfg!(debug_assertions)
627            && is_zctl
628            && self.offsets().is_host()
629            && self.sizes().is_host()
630            && let Some(offsets_primitive) = self.offsets().as_opt::<Primitive>()
631            && let Some(sizes_primitive) = self.sizes().as_opt::<Primitive>()
632        {
633            validate_zctl(
634                self.elements(),
635                offsets_primitive.into_owned(),
636                sizes_primitive.into_owned(),
637            )
638            .vortex_expect("Failed to validate zero-copy to list flag");
639        }
640        let dtype = self.dtype().clone();
641        let len = self.len();
642        let slots: ArraySlots = self.slots().iter().cloned().collect();
643        let data = unsafe { self.into_data().with_zero_copy_to_list(is_zctl) };
644        unsafe { Array::from_parts_unchecked(ArrayParts::new(ListView, dtype, len, data, slots)) }
645    }
646
647    pub fn into_data_parts(self) -> ListViewDataParts {
648        let elements = self.elements().clone();
649        let offsets = self.offsets().clone();
650        let sizes = self.sizes().clone();
651        let validity = self.listview_validity();
652        ListViewDataParts {
653            elements_dtype: Arc::new(elements.dtype().clone()),
654            elements,
655            offsets,
656            sizes,
657            validity,
658        }
659    }
660}
661
662/// Helper function to validate `offsets` and `sizes` with specific types.
663fn validate_offsets_and_sizes<O, S>(
664    offsets_slice: &[O],
665    sizes_slice: &[S],
666    elements_len: u64,
667) -> VortexResult<()>
668where
669    O: IntegerPType,
670    S: IntegerPType,
671{
672    debug_assert_eq!(offsets_slice.len(), sizes_slice.len());
673
674    #[allow(clippy::absurd_extreme_comparisons, unused_comparisons)]
675    for i in 0..offsets_slice.len() {
676        let offset = offsets_slice[i];
677        let size = sizes_slice[i];
678
679        vortex_ensure!(offset >= O::zero(), "cannot have negative offsets");
680        vortex_ensure!(size >= S::zero(), "cannot have negative size");
681
682        let offset_u64 = offset
683            .to_u64()
684            .ok_or_else(|| vortex_err!("offset[{i}] = {offset:?} cannot be converted to u64"))?;
685
686        let size_u64 = size
687            .to_u64()
688            .ok_or_else(|| vortex_err!("size[{i}] = {size:?} cannot be converted to u64"))?;
689
690        // Check for overflow when adding offset + size.
691        let end = offset_u64.checked_add(size_u64).ok_or_else(|| {
692            vortex_err!("offset[{i}] ({offset_u64}) + size[{i}] ({size_u64}) would overflow u64")
693        })?;
694
695        if offset_u64 == elements_len {
696            vortex_ensure_eq!(
697                size_u64,
698                0,
699                "views to the end of the elements array (length {elements_len}) must have size 0",
700            );
701        }
702
703        vortex_ensure!(
704            end <= elements_len,
705            "offset[{i}] + size[{i}] = {offset_u64} + {size_u64} = {end} \
706            exceeds elements length {elements_len}",
707        );
708    }
709
710    Ok(())
711}
712
713/// Helper function to validate if the `ListViewArray` components are actually zero-copyable to
714/// [`ListArray`](crate::arrays::ListArray).
715fn validate_zctl(
716    elements: &ArrayRef,
717    offsets_primitive: PrimitiveArray,
718    sizes_primitive: PrimitiveArray,
719) -> VortexResult<()> {
720    // Offsets must be sorted (but not strictly sorted, zero-length lists are allowed), even
721    // if there are null views.
722    let offsets_sorted = match_each_integer_ptype!(offsets_primitive.ptype(), |P| {
723        offsets_primitive.as_slice::<P>().is_sorted()
724    });
725    vortex_ensure!(offsets_sorted, "offsets must be sorted");
726
727    // Validate that offset[i] + size[i] <= offset[i+1] for all items
728    // This ensures views are non-overlapping and properly ordered for zero-copy-to-list
729    fn validate_monotonic_ends<O: IntegerPType, S: IntegerPType>(
730        offsets_slice: &[O],
731        sizes_slice: &[S],
732        len: usize,
733    ) -> VortexResult<()> {
734        let mut max_end = 0usize;
735
736        for i in 0..len {
737            let offset = offsets_slice[i].to_usize().unwrap_or(usize::MAX);
738            let size = sizes_slice[i].to_usize().unwrap_or(usize::MAX);
739
740            // Check that this view starts at or after the previous view ended
741            vortex_ensure!(
742                offset >= max_end,
743                "Zero-copy-to-list requires views to be non-overlapping and ordered: \
744                 view[{}] starts at {} but previous views extend to {}",
745                i,
746                offset,
747                max_end
748            );
749
750            // Update max_end for the next iteration
751            let end = offset.saturating_add(size);
752            max_end = max_end.max(end);
753        }
754
755        Ok(())
756    }
757
758    let offsets_dtype = offsets_primitive.dtype();
759    let sizes_dtype = sizes_primitive.dtype();
760    let len = offsets_primitive.len();
761
762    // Offsets/sizes are non-negative; reinterpret to unsigned (4x4 instead of 8x8).
763    let offsets_unsigned =
764        offsets_primitive.reinterpret_cast(offsets_dtype.as_ptype().to_unsigned());
765    let sizes_unsigned = sizes_primitive.reinterpret_cast(sizes_dtype.as_ptype().to_unsigned());
766
767    // Check that offset + size values are monotonic (no overlaps)
768    match_each_unsigned_integer_ptype!(offsets_unsigned.ptype(), |O| {
769        match_each_unsigned_integer_ptype!(sizes_unsigned.ptype(), |S| {
770            let offsets_slice = offsets_unsigned.as_slice::<O>();
771            let sizes_slice = sizes_unsigned.as_slice::<S>();
772
773            validate_monotonic_ends(offsets_slice, sizes_slice, len)?;
774        })
775    });
776
777    // TODO(connor)[ListView]: Making this allocation is expensive, but the more efficient
778    // implementation would be even more complicated than this. We could use a bit buffer denoting
779    // if positions in `elements` are used, and then additionally store a separate flag that tells
780    // us if a position is used more than once.
781    let mut element_references = vec![0u8; elements.len()];
782
783    fn count_references<O: IntegerPType, S: IntegerPType>(
784        element_references: &mut [u8],
785        offsets_primitive: PrimitiveArray,
786        sizes_primitive: PrimitiveArray,
787    ) {
788        let offsets_slice = offsets_primitive.as_slice::<O>();
789        let sizes_slice = sizes_primitive.as_slice::<S>();
790
791        // Note that we ignore nulls here, as the "null" view metadata must still maintain the same
792        // invariants as non-null views, even for a `bool` information.
793        for i in 0..offsets_slice.len() {
794            let offset: usize = offsets_slice[i].as_();
795            let size: usize = sizes_slice[i].as_();
796            for j in offset..offset + size {
797                element_references[j] = element_references[j].saturating_add(1);
798            }
799        }
800    }
801
802    match_each_unsigned_integer_ptype!(offsets_unsigned.ptype(), |O| {
803        match_each_unsigned_integer_ptype!(sizes_unsigned.ptype(), |S| {
804            count_references::<O, S>(&mut element_references, offsets_unsigned, sizes_unsigned);
805        })
806    });
807
808    // Allow leading and trailing unreferenced elements, but not gaps in the middle.
809    let leftmost_used = element_references
810        .iter()
811        .position(|&references| references != 0);
812    let rightmost_used = element_references
813        .iter()
814        .rposition(|&references| references != 0);
815
816    if let (Some(first_ref), Some(last_ref)) = (leftmost_used, rightmost_used) {
817        vortex_ensure!(
818            element_references[first_ref..=last_ref]
819                .iter()
820                .all(|&references| references != 0),
821            "found gap in elements array between first and last referenced elements"
822        );
823    }
824
825    vortex_ensure!(element_references.iter().all(|&references| references <= 1));
826
827    Ok(())
828}