Skip to main content

vortex_array/builders/
listview.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! ListView Builder Implementation.
5//!
6//! A builder for [`ListViewArray`] that tracks both offsets and sizes.
7//!
8//! Unlike [`ListArray`] which only tracks offsets, [`ListViewArray`] stores both offsets and sizes
9//! in separate arrays for better compression.
10//!
11//! [`ListArray`]: crate::arrays::ListArray
12
13use std::sync::Arc;
14
15use num_traits::ToPrimitive;
16use vortex_buffer::BufferAllocatorRef;
17use vortex_error::VortexExpect;
18use vortex_error::VortexResult;
19use vortex_error::vortex_ensure;
20use vortex_error::vortex_ensure_eq;
21use vortex_error::vortex_panic;
22
23use crate::ArrayRef;
24use crate::Canonical;
25use crate::ExecutionCtx;
26use crate::array::ArrayView;
27use crate::array::IntoArray;
28use crate::arrays::List;
29use crate::arrays::ListView;
30use crate::arrays::ListViewArray;
31use crate::arrays::PrimitiveArray;
32use crate::arrays::list::ListArraySlotsExt;
33use crate::arrays::listview::ListViewArrayExt;
34use crate::arrays::listview::ListViewArraySlotsExt;
35use crate::builders::ArrayBuilder;
36use crate::builders::ChildBuilder;
37use crate::builders::DEFAULT_BUILDER_CAPACITY;
38use crate::builders::PrimitiveBuilder;
39use crate::builders::UninitRange;
40use crate::builders::ValidityBuilder;
41use crate::dtype::DType;
42use crate::dtype::IntegerPType;
43use crate::dtype::Nullability;
44use crate::dtype::OffsetBuilderPType;
45use crate::match_each_integer_ptype;
46use crate::scalar::ListScalar;
47use crate::scalar::Scalar;
48
49/// A builder for creating [`ListViewArray`] instances, parameterized by the [`OffsetBuilderPType`]
50/// of the `offsets` and the `sizes` builders.
51///
52/// This builder tracks both offsets and sizes using potentially different integer types for memory
53/// efficiency. For example, you might use `u64` for offsets but only `u8` for sizes if your lists
54/// are small.
55///
56/// Any combination of [`OffsetBuilderPType`] types is valid, as long as the type of `sizes` can fit
57/// into the type of `offsets`.
58pub struct ListViewBuilder<O: OffsetBuilderPType, S: OffsetBuilderPType> {
59    /// The [`DType`] of the [`ListViewArray`]. This **must** be a [`DType::List`].
60    dtype: DType,
61
62    /// The builder for the underlying elements of the [`ListArray`](crate::arrays::ListArray).
63    elements_builder: ChildBuilder,
64
65    /// The builder for the `offsets` into the `elements` array.
66    offsets_builder: PrimitiveBuilder<O>,
67
68    /// The builder for the `sizes` of each list view.
69    sizes_builder: PrimitiveBuilder<S>,
70
71    /// The null map builder of the [`ListViewArray`].
72    nulls: ValidityBuilder,
73
74    /// Whether the appends so far leave the result zero-copyable to a [`ListArray`].
75    ///
76    /// Only [`append_listview_array`](Self::append_listview_array) can clear this; every other
77    /// append writes its lists back to back.
78    ///
79    /// [`ListArray`]: crate::arrays::ListArray
80    zero_copy_to_list: bool,
81}
82
83impl<O: OffsetBuilderPType, S: OffsetBuilderPType> ListViewBuilder<O, S> {
84    /// Creates a new `ListViewBuilder` with a capacity of [`DEFAULT_BUILDER_CAPACITY`].
85    #[deprecated(note = "use `new_in` with an explicit allocator")]
86    pub fn new(element_dtype: Arc<DType>, nullability: Nullability) -> Self {
87        Self::new_in(element_dtype, nullability, BufferAllocatorRef::static_ref())
88    }
89
90    /// Creates a new `ListViewBuilder` with the default capacity using `allocator`.
91    pub fn new_in(
92        element_dtype: Arc<DType>,
93        nullability: Nullability,
94        allocator: &BufferAllocatorRef,
95    ) -> Self {
96        Self::with_capacity_in(
97            element_dtype,
98            nullability,
99            DEFAULT_BUILDER_CAPACITY,
100            allocator,
101        )
102    }
103
104    /// Create a new [`ListViewArray`] builder with the given `capacity`.
105    ///
106    /// # Panics
107    ///
108    /// Panics if the size type `S` cannot fit within the offset type `O`.
109    #[deprecated(note = "use `with_capacity_in` with an explicit allocator")]
110    pub fn with_capacity(
111        element_dtype: Arc<DType>,
112        nullability: Nullability,
113        _elements_capacity: usize,
114        capacity: usize,
115    ) -> Self {
116        Self::with_capacity_in(
117            element_dtype,
118            nullability,
119            capacity,
120            BufferAllocatorRef::static_ref(),
121        )
122    }
123
124    /// Creates a list-view builder with the given capacity using `allocator`.
125    ///
126    /// # Panics
127    ///
128    /// Panics if the size type `S` cannot fit within the offset type `O`.
129    pub fn with_capacity_in(
130        element_dtype: Arc<DType>,
131        nullability: Nullability,
132        capacity: usize,
133        allocator: &BufferAllocatorRef,
134    ) -> Self {
135        let elements_builder = ChildBuilder::with_capacity(&element_dtype, 2 * capacity, allocator);
136
137        let offsets_builder =
138            PrimitiveBuilder::<O>::with_capacity_in(Nullability::NonNullable, capacity, allocator);
139        let sizes_builder =
140            PrimitiveBuilder::<S>::with_capacity_in(Nullability::NonNullable, capacity, allocator);
141
142        let nulls = ValidityBuilder::new(capacity, allocator);
143
144        Self {
145            dtype: DType::List(element_dtype, nullability),
146            elements_builder,
147            offsets_builder,
148            sizes_builder,
149            nulls,
150            zero_copy_to_list: true,
151        }
152    }
153
154    /// Appends an array as a single non-null list entry to the builder.
155    ///
156    /// The input `array` must have the same dtype as the element dtype of this list builder.
157    ///
158    /// Note that the list entry will be non-null but the elements themselves are allowed to be null
159    /// (only if the elements [`DType`] is nullable, of course).
160    pub fn append_array_as_list(
161        &mut self,
162        array: &ArrayRef,
163        ctx: &mut ExecutionCtx,
164    ) -> VortexResult<()> {
165        vortex_ensure_eq!(array.dtype(), self.element_dtype());
166
167        let curr_offset = self.elements_builder.len();
168        let num_elements = array.len();
169
170        // We must assert this even in release mode to ensure that the safety comment in
171        // `finish_into_listview` is correct.
172        assert!(
173            ((curr_offset + num_elements) as u64) < O::max_value_as_u64(),
174            "appending this list would cause an offset overflow"
175        );
176
177        self.elements_builder.append_array(array, ctx)?;
178        self.nulls.append_non_null();
179
180        self.offsets_builder.append_value(
181            O::from_usize(curr_offset).vortex_expect("Failed to convert from usize to `O`"),
182        );
183        self.sizes_builder.append_value(
184            S::from_usize(num_elements).vortex_expect("Failed to convert from usize to `S`"),
185        );
186
187        Ok(())
188    }
189
190    /// Append a list of values to the builder.
191    ///
192    /// This method extends the value builder with the provided values and records
193    /// the offset and size of the new list.
194    pub fn append_value(&mut self, value: ListScalar) -> VortexResult<()> {
195        let Some(elements) = value.elements() else {
196            // If `elements` is `None`, then the `value` is a null value.
197            vortex_ensure!(
198                self.dtype.is_nullable(),
199                "Cannot append null value to non-nullable list builder"
200            );
201            self.append_null();
202            return Ok(());
203        };
204
205        let curr_offset = self.elements_builder.len();
206        let num_elements = elements.len();
207
208        // We must assert this even in release mode to ensure that the safety comment in
209        // `finish_into_listview` is correct.
210        assert!(
211            ((curr_offset + num_elements) as u64) < O::max_value_as_u64(),
212            "appending this list would cause an offset overflow"
213        );
214
215        for scalar in elements {
216            self.elements_builder.append_scalar(&scalar)?;
217        }
218        self.nulls.append_non_null();
219
220        self.offsets_builder.append_value(
221            O::from_usize(curr_offset).vortex_expect("Failed to convert from usize to `O`"),
222        );
223        self.sizes_builder.append_value(
224            S::from_usize(num_elements).vortex_expect("Failed to convert from usize to `S`"),
225        );
226
227        Ok(())
228    }
229
230    /// Appends `array` as `n` identical non-null lists, storing its elements once.
231    ///
232    /// A `ListViewArray` can point many views at one range of elements, so a repeated list costs
233    /// its elements once however many rows it covers. The elements go in as one appended array, so
234    /// a caller that hands over the same `array` on every call - a sparse array filling the gaps
235    /// between its patches, say - stores those elements once for the whole result.
236    ///
237    /// The views share their elements, so the result is no longer zero-copyable to a
238    /// [`ListArray`](crate::arrays::ListArray) unless it covers a single row or empty lists.
239    pub fn append_array_as_repeated_list(
240        &mut self,
241        array: &ArrayRef,
242        n: usize,
243        ctx: &mut ExecutionCtx,
244    ) -> VortexResult<()> {
245        vortex_ensure_eq!(array.dtype(), self.element_dtype());
246
247        if n == 0 {
248            return Ok(());
249        }
250
251        let curr_offset = self.elements_builder.len();
252        let num_elements = array.len();
253
254        // We must assert this even in release mode to ensure that the safety comment in
255        // `finish_into_listview` is correct.
256        assert!(
257            ((curr_offset + num_elements) as u64) < O::max_value_as_u64(),
258            "appending this list would cause an offset overflow"
259        );
260
261        self.elements_builder.append_array(array, ctx)?;
262
263        let offset =
264            O::from_usize(curr_offset).vortex_expect("Failed to convert from usize to `O`");
265        let size = S::from_usize(num_elements).vortex_expect("Failed to convert from usize to `S`");
266        self.offsets_builder.append_n_values(offset, n);
267        self.sizes_builder.append_n_values(size, n);
268        self.nulls.append_n_non_nulls(n);
269
270        if n > 1 && num_elements > 0 {
271            self.zero_copy_to_list = false;
272        }
273
274        Ok(())
275    }
276
277    /// Finishes the builder directly into a [`ListViewArray`].
278    pub fn finish_into_listview(&mut self) -> ListViewArray {
279        debug_assert_eq!(self.offsets_builder.len(), self.sizes_builder.len());
280        debug_assert_eq!(self.offsets_builder.len(), self.nulls.len());
281
282        let elements = self.elements_builder.finish();
283        let offsets = self.offsets_builder.finish();
284        let sizes = self.sizes_builder.finish();
285        let validity = self.nulls.finish_with_nullability(self.dtype.nullability());
286
287        let zero_copy_to_list = std::mem::replace(&mut self.zero_copy_to_list, true);
288
289        // SAFETY:
290        // - Both the offsets and the sizes are non-nullable.
291        // - The offsets, sizes, and validity have the same length since we always appended the same
292        //   amount.
293        // - We checked on construction that the sizes type fits into the offsets.
294        // - In every method that adds values to this builder (`append_value`, `append_scalar`,
295        //   `append_list_array`, and `append_listview_array`), we checked that `offset + size`
296        //   does not overflow. `append_listview_array` rebases the offsets it was handed onto
297        //   exactly the elements it appended, so the source's bound carries over.
298        // - Every append writes its lists back to back, so the result is zero-copyable to a
299        //   `ListArray` unless `zero_copy_to_list` recorded an appended layout we left alone.
300        unsafe {
301            ListViewArray::new_unchecked(elements, offsets, sizes, validity)
302                .with_zero_copy_to_list(zero_copy_to_list)
303        }
304    }
305
306    /// The [`DType`] of the inner elements. Note that this is **not** the same as the [`DType`] of
307    /// the outer `FixedSizeList`.
308    pub fn element_dtype(&self) -> &DType {
309        let DType::List(element_dtype, ..) = &self.dtype else {
310            vortex_panic!("`ListViewBuilder` has an incorrect dtype: {}", self.dtype);
311        };
312
313        element_dtype
314    }
315
316    /// Appends the values of a [`List`]-encoded `array` to this builder.
317    ///
318    /// List encodings dispatch here through
319    /// [`match_each_list_builder!`](crate::match_each_list_builder) because the concrete list
320    /// builders are generic over their offset/size integer types, which cannot be named through a
321    /// `dyn ArrayBuilder`.
322    pub fn append_list_array(
323        &mut self,
324        array: ArrayView<'_, List>,
325        ctx: &mut ExecutionCtx,
326    ) -> VortexResult<()> {
327        if array.is_empty() {
328            return Ok(());
329        }
330
331        self.nulls.append_validity(array.validity()?, array.len());
332
333        let offsets = array.offsets().clone().execute::<PrimitiveArray>(ctx)?;
334        match_each_integer_ptype!(offsets.ptype(), |OffsetType| {
335            extend_from_list(
336                self,
337                array.elements(),
338                offsets.as_slice::<OffsetType>(),
339                ctx,
340            )?
341        });
342        Ok(())
343    }
344
345    /// Appends the values of a [`ListView`]-encoded `array` to this builder.
346    ///
347    /// See [`append_list_array`](Self::append_list_array); this is the same hook for the canonical
348    /// [`ListViewArray`] encoding.
349    ///
350    /// The views keep the layout they arrived in, so overlapping sources keep sharing their
351    /// elements and the finished array reports [`is_zero_copy_to_list`] as `false`. Callers that
352    /// need an exact layout should [`rebuild`](ListViewArray::rebuild) it.
353    ///
354    /// [`is_zero_copy_to_list`]: crate::arrays::listview::ListViewData::is_zero_copy_to_list
355    pub fn append_listview_array(
356        &mut self,
357        array: ArrayView<'_, ListView>,
358        ctx: &mut ExecutionCtx,
359    ) -> VortexResult<()> {
360        if array.is_empty() {
361            return Ok(());
362        }
363
364        let len = array.len();
365
366        // Materialize the metadata once and do the trimming and the rebase by hand. Going through
367        // `rebuild(ListViewRebuildMode::TrimElements)` would subtract the window start from every
368        // offset with a compute kernel, only for the rebase below to add this builder's elements
369        // base straight back on - two passes, one of them through the compute stack, for one
370        // addition per offset. Casting the sizes to the builder's type is another kernel for what
371        // is a copy.
372        let offsets = array.offsets().clone().execute::<PrimitiveArray>(ctx)?;
373        let sizes = array.sizes().clone().execute::<PrimitiveArray>(ctx)?;
374
375        // The window of `elements` that the views actually reference. Everything outside it is
376        // unreachable and must not be appended. An exact source covers its window back to back and
377        // in order, so the first and last view bound it; any other layout has to be searched.
378        let (start, end) = if array.is_zero_copy_to_list() {
379            let last = len - 1;
380            (
381                metadata_at(&offsets, 0),
382                metadata_at(&offsets, last) + metadata_at(&sizes, last),
383            )
384        } else {
385            array.into_owned().referenced_element_bounds(ctx)?
386        };
387
388        // An exact source references every element it carries, back to back, so it lands flush
389        // against the elements already in the builder. Any other layout does not.
390        self.zero_copy_to_list &= array.is_zero_copy_to_list();
391
392        self.nulls.append_validity(array.validity()?, len);
393
394        // Bulk append the referenced elements; the offsets are rebased onto them below.
395        let elements_base = self.elements_builder.len();
396
397        // We must assert this even in release mode to ensure that the safety comment in
398        // `finish_into_listview` is correct.
399        assert!(
400            ((elements_base + (end - start)) as u64) < O::max_value_as_u64(),
401            "appending this list would cause an offset overflow"
402        );
403
404        if end > start {
405            self.elements_builder
406                .append_array(&array.elements().slice(start..end)?, ctx)?;
407        }
408
409        // Every view lies inside `start..end`, so rebasing it onto `elements_base` keeps it inside
410        // the elements this builder now holds - which is what lets `finish_into_listview` build the
411        // array unchecked.
412        assert_eq!(
413            self.elements_builder.len(),
414            elements_base + (end - start),
415            "appending the referenced elements did not extend the child by the window's length"
416        );
417
418        self.offsets_builder.reserve_exact(len);
419        let offsets_range = self.offsets_builder.uninit_range(len);
420        match_each_integer_ptype!(offsets.ptype(), |A| {
421            extend_rebased_offsets::<O, A>(
422                offsets_range,
423                offsets.as_slice::<A>(),
424                start,
425                elements_base,
426            );
427        });
428
429        self.sizes_builder.reserve_exact(len);
430        let mut sizes_range = self.sizes_builder.uninit_range(len);
431        if sizes.ptype() == S::PTYPE {
432            // The sizes already have the builder's type, so there is nothing to convert.
433            sizes_range.copy_from_slice(0, sizes.as_slice::<S>());
434            // SAFETY: `copy_from_slice` initialized all `len` values, and the sizes builder is
435            // non-nullable.
436            unsafe { sizes_range.finish() };
437        } else {
438            match_each_integer_ptype!(sizes.ptype(), |A| {
439                extend_converted_sizes::<S, A>(sizes_range, sizes.as_slice::<A>());
440            });
441        }
442
443        Ok(())
444    }
445}
446
447impl<O: OffsetBuilderPType, S: OffsetBuilderPType> ArrayBuilder for ListViewBuilder<O, S> {
448    fn as_any(&self) -> &dyn std::any::Any {
449        self
450    }
451
452    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
453        self
454    }
455
456    fn dtype(&self) -> &DType {
457        &self.dtype
458    }
459
460    fn len(&self) -> usize {
461        self.offsets_builder.len()
462    }
463
464    fn append_zeros(&mut self, n: usize) {
465        debug_assert_eq!(self.offsets_builder.len(), self.sizes_builder.len());
466        debug_assert_eq!(self.offsets_builder.len(), self.nulls.len());
467
468        // Get the current position in the elements array.
469        let curr_offset = self.elements_builder.len();
470
471        // Since we consider the "zero" element of a list an empty list, we simply update the
472        // `offsets` and `sizes` metadata to add an empty list.
473        self.offsets_builder.append_n_values(
474            O::from_usize(curr_offset).vortex_expect("Failed to convert from usize to `O`"),
475            n,
476        );
477        self.sizes_builder.append_n_values(S::zero(), n);
478
479        self.nulls.append_n_non_nulls(n);
480    }
481
482    unsafe fn append_nulls_unchecked(&mut self, n: usize) {
483        debug_assert_eq!(self.offsets_builder.len(), self.sizes_builder.len());
484        debug_assert_eq!(self.offsets_builder.len(), self.nulls.len());
485
486        // Get the current position in the elements array.
487        let curr_offset = self.elements_builder.len();
488
489        // A null list can have any representation, but we choose to use the zero representation.
490        self.offsets_builder.append_n_values(
491            O::from_usize(curr_offset).vortex_expect("Failed to convert from usize to `O`"),
492            n,
493        );
494        self.sizes_builder.append_n_values(S::zero(), n);
495
496        // This is the only difference from `append_zeros`.
497        self.nulls.append_n_nulls(n);
498    }
499
500    fn append_scalar(&mut self, scalar: &Scalar) -> VortexResult<()> {
501        vortex_ensure_eq!(
502            scalar.dtype(),
503            self.dtype(),
504            "ListViewBuilder received a scalar with the wrong dtype"
505        );
506
507        let list_scalar = scalar.as_list();
508        self.append_value(list_scalar)
509    }
510
511    fn reserve_chunks(&mut self, additional: usize) {
512        self.elements_builder.reserve_chunks(additional);
513        self.nulls.reserve_runs(additional);
514    }
515
516    fn reserve_exact(&mut self, capacity: usize) {
517        self.elements_builder.reserve_exact(capacity * 2);
518        self.offsets_builder.reserve_exact(capacity);
519        self.sizes_builder.reserve_exact(capacity);
520        self.nulls.reserve_exact(capacity);
521    }
522
523    fn finish(&mut self) -> ArrayRef {
524        self.finish_into_listview().into_array()
525    }
526
527    fn finish_into_canonical(&mut self, _ctx: &mut ExecutionCtx) -> Canonical {
528        Canonical::List(self.finish_into_listview())
529    }
530}
531
532/// Appends `ListArray`-layout lists (`n + 1` cumulative offsets) into a [`ListViewBuilder`].
533///
534/// Lists in a `ListArray` are contiguous, so the referenced elements can be appended in bulk,
535/// with the offsets rebased onto the builder's elements and the sizes taken from consecutive
536/// offset differences.
537fn extend_from_list<O, S, OffsetType>(
538    builder: &mut ListViewBuilder<O, S>,
539    elements: &ArrayRef,
540    offsets: &[OffsetType],
541    ctx: &mut ExecutionCtx,
542) -> VortexResult<()>
543where
544    O: OffsetBuilderPType,
545    S: OffsetBuilderPType,
546    OffsetType: IntegerPType,
547{
548    let num_lists = offsets.len() - 1;
549    let first: usize = offsets[0].as_();
550    let last: usize = offsets[num_lists].as_();
551
552    let elements_base = builder.elements_builder.len();
553
554    // We must assert this even in release mode to ensure that the safety comment in
555    // `finish_into_listview` is correct.
556    assert!(
557        ((elements_base + (last - first)) as u64) < O::max_value_as_u64(),
558        "appending this list would cause an offset overflow"
559    );
560
561    if last > first {
562        builder
563            .elements_builder
564            .append_array(&elements.slice(first..last)?, ctx)?;
565    }
566
567    builder.offsets_builder.reserve_exact(num_lists);
568    builder.sizes_builder.reserve_exact(num_lists);
569    let mut offsets_range = builder.offsets_builder.uninit_range(num_lists);
570    let mut sizes_range = builder.sizes_builder.uninit_range(num_lists);
571    for i in 0..num_lists {
572        let start: usize = offsets[i].as_();
573        let end: usize = offsets[i + 1].as_();
574        offsets_range.set_value(
575            i,
576            O::from_usize(start - first + elements_base)
577                .vortex_expect("Failed to convert from usize to `O`"),
578        );
579        sizes_range.set_value(
580            i,
581            S::from_usize(end - start).vortex_expect("Failed to convert from usize to `S`"),
582        );
583    }
584    // SAFETY: We have initialized all `num_lists` values in both ranges, and both the `offsets`
585    // and the `sizes` builders are non-nullable.
586    unsafe { offsets_range.finish() };
587    unsafe { sizes_range.finish() };
588    Ok(())
589}
590
591/// Reads one non-nullable integer value of list view metadata as a `usize`.
592fn metadata_at(metadata: &PrimitiveArray, index: usize) -> usize {
593    match_each_integer_ptype!(metadata.ptype(), |A| {
594        metadata.as_slice::<A>()[index]
595            .to_usize()
596            .vortex_expect("list view metadata must fit in a usize")
597    })
598}
599
600/// Writes `offsets` into `range`, moved off the source's element window and onto the elements the
601/// builder already holds.
602///
603/// `window_start` is the first element the source's views reference, so every offset is at least
604/// `window_start` and the subtraction cannot underflow.
605fn extend_rebased_offsets<O: OffsetBuilderPType, A: IntegerPType>(
606    mut range: UninitRange<O>,
607    offsets: &[A],
608    window_start: usize,
609    elements_base: usize,
610) {
611    debug_assert_eq!(range.len(), offsets.len());
612
613    for (i, &offset) in offsets.iter().enumerate() {
614        let offset = offset
615            .to_usize()
616            .vortex_expect("offsets must always fit in usize");
617        debug_assert!(
618            offset >= window_start,
619            "offset {offset} precedes the referenced window at {window_start}"
620        );
621        let rebased = O::from_usize(offset - window_start + elements_base)
622            .vortex_expect("rebased offset did not fit into the builder's offset type");
623        range.set_value(i, rebased);
624    }
625
626    // SAFETY: We have set all the values in the range, and since `offsets` are non-nullable, we are
627    // done.
628    unsafe { range.finish() };
629}
630
631/// Writes `sizes` into `range`, converting them to the builder's size type.
632///
633/// Sizes that already have the builder's type are copied in bulk by the caller instead.
634fn extend_converted_sizes<S: OffsetBuilderPType, A: IntegerPType>(
635    mut range: UninitRange<S>,
636    sizes: &[A],
637) {
638    debug_assert_eq!(range.len(), sizes.len());
639
640    for (i, &size) in sizes.iter().enumerate() {
641        let size = S::from_usize(
642            size.to_usize()
643                .vortex_expect("sizes must always fit in usize"),
644        )
645        .vortex_expect("size did not fit into the builder's size type");
646        range.set_value(i, size);
647    }
648
649    // SAFETY: We have set all the values in the range, and since `sizes` are non-nullable, we are
650    // done.
651    unsafe { range.finish() };
652}
653
654#[cfg(test)]
655mod tests {
656    use std::sync::Arc;
657    use std::sync::LazyLock;
658
659    use rstest::rstest;
660    use vortex_buffer::BufferAllocatorRef;
661    use vortex_buffer::buffer;
662    use vortex_error::VortexExpect;
663    use vortex_error::VortexResult;
664    use vortex_session::VortexSession;
665
666    use super::ListViewBuilder;
667    use crate::IntoArray;
668    use crate::VortexSessionExecute;
669    use crate::arrays::ConstantArray;
670    use crate::arrays::ListArray;
671    use crate::arrays::ListViewArray;
672    use crate::arrays::listview::ListViewArrayExt;
673    use crate::arrays::listview::ListViewArraySlotsExt;
674    use crate::assert_arrays_eq;
675    use crate::builders::ArrayBuilder;
676    use crate::builders::listview::PrimitiveArray;
677    use crate::dtype::DType;
678    use crate::dtype::Nullability::NonNullable;
679    use crate::dtype::Nullability::Nullable;
680    use crate::dtype::PType::I32;
681    use crate::scalar::Scalar;
682    use crate::validity::Validity;
683
684    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
685
686    #[test]
687    fn test_empty() {
688        let mut builder = ListViewBuilder::<u32, u32>::with_capacity_in(
689            Arc::new(I32.into()),
690            NonNullable,
691            0,
692            BufferAllocatorRef::static_ref(),
693        );
694
695        let listview = builder.finish();
696        assert_eq!(listview.len(), 0);
697        assert_eq!(
698            listview.dtype(),
699            &DType::List(Arc::new(I32.into()), NonNullable)
700        );
701    }
702
703    #[test]
704    fn test_basic_append_and_nulls() {
705        let mut ctx = SESSION.create_execution_ctx();
706        let dtype: Arc<DType> = Arc::new(I32.into());
707        let mut builder = ListViewBuilder::<u32, u32>::with_capacity_in(
708            Arc::clone(&dtype),
709            Nullable,
710            0,
711            BufferAllocatorRef::static_ref(),
712        );
713
714        // Append a regular list.
715        builder
716            .append_value(
717                Scalar::list(
718                    Arc::clone(&dtype),
719                    vec![1i32.into(), 2i32.into(), 3i32.into()],
720                    NonNullable,
721                )
722                .as_list(),
723            )
724            .unwrap();
725
726        // Append an empty list.
727        builder
728            .append_value(Scalar::list_empty(Arc::clone(&dtype), NonNullable).as_list())
729            .unwrap();
730
731        // Append a null list.
732        builder.append_null();
733
734        // Append another regular list.
735        builder
736            .append_value(
737                Scalar::list(dtype, vec![4i32.into(), 5i32.into()], NonNullable).as_list(),
738            )
739            .unwrap();
740
741        let listview = builder.finish_into_listview();
742        assert_eq!(listview.len(), 4);
743
744        // Check first list: [1, 2, 3].
745        assert_arrays_eq!(
746            listview.list_elements_at(0, &mut ctx).unwrap(),
747            PrimitiveArray::from_iter([1i32, 2, 3]),
748            &mut ctx
749        );
750
751        // Check empty list.
752        assert_eq!(listview.list_elements_at(1, &mut ctx).unwrap().len(), 0);
753
754        // Check null list.
755        assert!(
756            !listview
757                .validity()
758                .vortex_expect("listview validity should be derivable")
759                .execute_is_valid(2, &mut ctx)
760                .unwrap()
761        );
762
763        // Check last list: [4, 5].
764        assert_arrays_eq!(
765            listview.list_elements_at(3, &mut ctx).unwrap(),
766            PrimitiveArray::from_iter([4i32, 5]),
767            &mut ctx
768        );
769        let expected = ListArray::new(
770            buffer![1i32, 2, 3, 4, 5].into_array(),
771            buffer![0u32, 3, 3, 3, 5].into_array(),
772            Validity::from_iter([true, true, false, true]),
773            &mut ctx,
774        );
775        assert_arrays_eq!(listview, expected, &mut ctx);
776    }
777
778    #[test]
779    fn test_different_offset_size_types() {
780        let mut ctx = SESSION.create_execution_ctx();
781        // Test u64 offsets with u32 sizes.
782        let dtype: Arc<DType> = Arc::new(I32.into());
783        let mut builder = ListViewBuilder::<u64, u32>::with_capacity_in(
784            Arc::clone(&dtype),
785            NonNullable,
786            0,
787            BufferAllocatorRef::static_ref(),
788        );
789
790        builder
791            .append_value(
792                Scalar::list(
793                    Arc::clone(&dtype),
794                    vec![1i32.into(), 2i32.into()],
795                    NonNullable,
796                )
797                .as_list(),
798            )
799            .unwrap();
800
801        builder
802            .append_value(
803                Scalar::list(
804                    dtype,
805                    vec![3i32.into(), 4i32.into(), 5i32.into()],
806                    NonNullable,
807                )
808                .as_list(),
809            )
810            .unwrap();
811
812        let listview = builder.finish_into_listview();
813        assert_eq!(listview.len(), 2);
814
815        // Verify first list: [1, 2].
816        assert_arrays_eq!(
817            listview.list_elements_at(0, &mut ctx).unwrap(),
818            PrimitiveArray::from_iter([1i32, 2]),
819            &mut ctx
820        );
821
822        // Verify second list: [3, 4, 5].
823        assert_arrays_eq!(
824            listview.list_elements_at(1, &mut ctx).unwrap(),
825            PrimitiveArray::from_iter([3i32, 4, 5]),
826            &mut ctx
827        );
828
829        // Test i64 offsets with i32 sizes.
830        let dtype2: Arc<DType> = Arc::new(I32.into());
831        let mut builder2 = ListViewBuilder::<i64, i32>::with_capacity_in(
832            Arc::clone(&dtype2),
833            NonNullable,
834            0,
835            BufferAllocatorRef::static_ref(),
836        );
837
838        for i in 0..5 {
839            builder2
840                .append_value(
841                    Scalar::list(Arc::clone(&dtype2), vec![(i * 10).into()], NonNullable).as_list(),
842                )
843                .unwrap();
844        }
845
846        let listview2 = builder2.finish_into_listview();
847        assert_eq!(listview2.len(), 5);
848
849        // Verify the values: [0], [10], [20], [30], [40].
850        for i in 0..5i32 {
851            assert_arrays_eq!(
852                listview2.list_elements_at(i as usize, &mut ctx).unwrap(),
853                PrimitiveArray::from_iter([i * 10]),
854                &mut ctx
855            );
856        }
857    }
858
859    /// Empty lists are appended in bulk rather than one offset/size pair at a time, so a large
860    /// `n` has to land exactly as a per-row loop would: `n` empty lists, all sharing the current
861    /// end of `elements`, with validity taken from which method was called.
862    #[rstest]
863    #[case::zeros(false)]
864    #[case::nulls(true)]
865    fn test_bulk_empty_lists(#[case] null: bool) -> VortexResult<()> {
866        let mut ctx = SESSION.create_execution_ctx();
867        let dtype: Arc<DType> = Arc::new(I32.into());
868        let mut builder = ListViewBuilder::<u32, u32>::with_capacity_in(
869            Arc::clone(&dtype),
870            Nullable,
871            0,
872            BufferAllocatorRef::static_ref(),
873        );
874
875        // Put something in `elements` first, so the empty lists have a non-zero offset to share.
876        builder.append_array_as_list(&buffer![1i32, 2].into_array(), &mut ctx)?;
877
878        const N: usize = 5;
879        if null {
880            builder.append_nulls(N);
881        } else {
882            builder.append_zeros(N);
883        }
884
885        let listview = builder.finish_into_listview();
886        assert_eq!(listview.len(), N + 1);
887        for i in 1..=N {
888            assert_eq!(listview.size_at(i, &mut ctx), 0);
889            assert_eq!(listview.offset_at(i, &mut ctx), 2);
890            assert_eq!(listview.validity()?.execute_is_valid(i, &mut ctx)?, !null);
891        }
892
893        Ok(())
894    }
895
896    #[test]
897    fn test_builder_trait_methods() {
898        let mut ctx = SESSION.create_execution_ctx();
899        let dtype: Arc<DType> = Arc::new(I32.into());
900        let mut builder = ListViewBuilder::<u32, u32>::with_capacity_in(
901            Arc::clone(&dtype),
902            Nullable,
903            0,
904            BufferAllocatorRef::static_ref(),
905        );
906
907        // Test append_zeros (creates empty lists).
908        builder.append_zeros(2);
909        assert_eq!(builder.len(), 2);
910
911        // Test append_nulls.
912        unsafe {
913            builder.append_nulls_unchecked(2);
914        }
915        assert_eq!(builder.len(), 4);
916
917        // Test append_scalar.
918        let list_scalar = Scalar::list(dtype, vec![10i32.into(), 20i32.into()], Nullable);
919        builder.append_scalar(&list_scalar).unwrap();
920        assert_eq!(builder.len(), 5);
921
922        let listview = builder.finish_into_listview();
923        assert_eq!(listview.len(), 5);
924
925        // First two are empty lists (from append_zeros).
926        assert_eq!(listview.list_elements_at(0, &mut ctx).unwrap().len(), 0);
927        assert_eq!(listview.list_elements_at(1, &mut ctx).unwrap().len(), 0);
928
929        // Next two are nulls.
930        assert!(
931            !listview
932                .validity()
933                .vortex_expect("listview validity should be derivable")
934                .execute_is_valid(2, &mut ctx)
935                .unwrap()
936        );
937        assert!(
938            !listview
939                .validity()
940                .vortex_expect("listview validity should be derivable")
941                .execute_is_valid(3, &mut ctx)
942                .unwrap()
943        );
944
945        // Last is the regular list: [10, 20].
946        assert_arrays_eq!(
947            listview.list_elements_at(4, &mut ctx).unwrap(),
948            PrimitiveArray::from_iter([10i32, 20]),
949            &mut ctx
950        );
951        let expected = ListArray::new(
952            buffer![10i32, 20].into_array(),
953            buffer![0u32, 0, 0, 0, 0, 2].into_array(),
954            Validity::from_iter([true, true, false, false, true]),
955            &mut ctx,
956        );
957        assert_arrays_eq!(listview, expected, &mut ctx);
958    }
959
960    #[test]
961    fn test_extend_from_array() {
962        let mut ctx = SESSION.create_execution_ctx();
963        let dtype: Arc<DType> = Arc::new(I32.into());
964
965        // Create a source ListArray.
966        let source = ListArray::from_iter_opt_slow::<u32, _, Vec<i32>>(
967            [Some(vec![1, 2, 3]), None, Some(vec![4, 5])],
968            Arc::new(I32.into()),
969        )
970        .unwrap();
971
972        let mut builder = ListViewBuilder::<u32, u32>::with_capacity_in(
973            Arc::clone(&dtype),
974            Nullable,
975            0,
976            BufferAllocatorRef::static_ref(),
977        );
978
979        // Add initial data.
980        builder
981            .append_value(Scalar::list(dtype, vec![0i32.into()], NonNullable).as_list())
982            .unwrap();
983
984        // Extend from the ListArray.
985        let source = source
986            .into_array()
987            .execute::<ListViewArray>(&mut ctx)
988            .unwrap();
989        builder
990            .append_listview_array(source.as_view(), &mut ctx)
991            .unwrap();
992
993        // Extend from empty array (should be no-op).
994        let empty_source = ListArray::from_iter_opt_slow::<u32, _, Vec<i32>>(
995            std::iter::empty::<Option<Vec<i32>>>(),
996            Arc::new(I32.into()),
997        )
998        .unwrap();
999        let empty_source = empty_source
1000            .into_array()
1001            .execute::<ListViewArray>(&mut ctx)
1002            .unwrap();
1003        builder
1004            .append_listview_array(empty_source.as_view(), &mut ctx)
1005            .unwrap();
1006
1007        let listview = builder.finish_into_listview();
1008        assert_eq!(listview.len(), 4);
1009
1010        // Check the extended data.
1011        // First list: [0] (initial data).
1012        assert_arrays_eq!(
1013            listview.list_elements_at(0, &mut ctx).unwrap(),
1014            PrimitiveArray::from_iter([0i32]),
1015            &mut ctx
1016        );
1017
1018        // Second list: [1, 2, 3] (from source).
1019        assert_arrays_eq!(
1020            listview.list_elements_at(1, &mut ctx).unwrap(),
1021            PrimitiveArray::from_iter([1i32, 2, 3]),
1022            &mut ctx
1023        );
1024
1025        // Third list: null (from source).
1026        assert!(
1027            !listview
1028                .validity()
1029                .vortex_expect("listview validity should be derivable")
1030                .execute_is_valid(2, &mut ctx)
1031                .unwrap()
1032        );
1033
1034        // Fourth list: [4, 5] (from source).
1035        assert_arrays_eq!(
1036            listview.list_elements_at(3, &mut ctx).unwrap(),
1037            PrimitiveArray::from_iter([4i32, 5]),
1038            &mut ctx
1039        );
1040        let expected = ListArray::new(
1041            buffer![0i32, 1, 2, 3, 4, 5].into_array(),
1042            buffer![0u32, 1, 4, 4, 6].into_array(),
1043            Validity::from_iter([true, true, false, true]),
1044            &mut ctx,
1045        );
1046        assert_arrays_eq!(listview, expected, &mut ctx);
1047    }
1048
1049    #[test]
1050    fn test_append_list_array_grows_builder() -> VortexResult<()> {
1051        let mut ctx = SESSION.create_execution_ctx();
1052        let dtype: Arc<DType> = Arc::new(I32.into());
1053
1054        // Enough lists to exceed the offsets/sizes capacity of a zero-capacity builder, so
1055        // appending must grow the builder rather than panic in `uninit_range`.
1056        let lists: Vec<Option<Vec<i32>>> =
1057            (0..100).map(|i| (i % 10 != 0).then(|| vec![i])).collect();
1058        let source = ListArray::from_iter_opt_slow::<u32, _, _>(lists.clone(), Arc::clone(&dtype))?;
1059
1060        let mut builder = ListViewBuilder::<u32, u32>::with_capacity_in(
1061            Arc::clone(&dtype),
1062            Nullable,
1063            0,
1064            BufferAllocatorRef::static_ref(),
1065        );
1066        builder.append_list_array(source.as_view(), &mut ctx)?;
1067        // Append a second time to check growth from a non-empty builder and offset rebasing.
1068        builder.append_list_array(source.as_view(), &mut ctx)?;
1069
1070        let listview = builder.finish_into_listview();
1071        assert!(listview.is_zero_copy_to_list());
1072
1073        let expected = ListArray::from_iter_opt_slow::<u32, _, _>(
1074            lists.iter().cloned().chain(lists.iter().cloned()),
1075            dtype,
1076        )?;
1077        assert_arrays_eq!(listview, expected, &mut ctx);
1078
1079        Ok(())
1080    }
1081
1082    /// A constant list array points every view at a single copy of the value; flattening it in the
1083    /// builder would materialize a copy per row.
1084    #[test]
1085    fn test_constant_list_append_keeps_one_copy_of_the_value() -> VortexResult<()> {
1086        let mut ctx = SESSION.create_execution_ctx();
1087        let element_dtype: Arc<DType> = Arc::new(I32.into());
1088
1089        const ROWS: usize = 10_000;
1090        let fill = Scalar::list(
1091            Arc::clone(&element_dtype),
1092            vec![1i32.into(), 2i32.into(), 3i32.into()],
1093            NonNullable,
1094        );
1095        let constant = ConstantArray::new(fill, ROWS).into_array();
1096
1097        let mut builder = ListViewBuilder::<u64, u64>::with_capacity_in(
1098            element_dtype,
1099            NonNullable,
1100            0,
1101            BufferAllocatorRef::static_ref(),
1102        );
1103        constant.append_to_builder(&mut builder, &mut ctx)?;
1104        let listview = builder.finish_into_listview();
1105
1106        assert_eq!(listview.len(), ROWS);
1107        assert_eq!(
1108            listview.elements().len(),
1109            3,
1110            "the fill value should be stored once, not once per row",
1111        );
1112        assert!(!listview.is_zero_copy_to_list());
1113        assert_arrays_eq!(&listview.into_array(), &constant, &mut ctx);
1114
1115        Ok(())
1116    }
1117
1118    /// Only the elements the views reference land in the builder: appending a slice out of the
1119    /// middle of a list array leaves the elements on either side of it behind.
1120    #[test]
1121    fn test_append_listview_array_trims_unreferenced_elements() -> VortexResult<()> {
1122        let mut ctx = SESSION.create_execution_ctx();
1123        let dtype: Arc<DType> = Arc::new(I32.into());
1124
1125        // Five lists of two elements each, of which we append only the middle three.
1126        let source = ListArray::from_iter_slow::<u32, _>(
1127            (0..5).map(|i| vec![2 * i, 2 * i + 1]),
1128            Arc::clone(&dtype),
1129        )?
1130        .into_array()
1131        .execute::<ListViewArray>(&mut ctx)?;
1132        let middle = source.slice(1..4)?.execute::<ListViewArray>(&mut ctx)?;
1133
1134        let mut builder = ListViewBuilder::<u32, u32>::with_capacity_in(
1135            Arc::clone(&dtype),
1136            NonNullable,
1137            0,
1138            BufferAllocatorRef::static_ref(),
1139        );
1140        builder.append_listview_array(middle.as_view(), &mut ctx)?;
1141        // A second append has to rebase onto the elements already in the builder.
1142        builder.append_listview_array(middle.as_view(), &mut ctx)?;
1143        let listview = builder.finish_into_listview();
1144
1145        assert_eq!(
1146            listview.elements().len(),
1147            12,
1148            "only the six referenced elements of each append should have landed",
1149        );
1150        assert!(
1151            listview.is_zero_copy_to_list(),
1152            "trimming an exact source keeps the result exact",
1153        );
1154
1155        let expected = ListArray::from_iter_slow::<u32, _>(
1156            (1..4).chain(1..4).map(|i| vec![2 * i, 2 * i + 1]),
1157            dtype,
1158        )?;
1159        assert_arrays_eq!(listview, expected, &mut ctx);
1160
1161        Ok(())
1162    }
1163
1164    #[test]
1165    fn test_extend_from_array_overlapping_listview() {
1166        let mut ctx = SESSION.create_execution_ctx();
1167        let dtype: Arc<DType> = Arc::new(I32.into());
1168
1169        // Non-ZCTL source:
1170        // - List 0: [10, 20]
1171        // - List 1: null (size is intentionally non-zero in source metadata)
1172        // - List 2: [10]
1173        let source = unsafe {
1174            ListViewArray::new_unchecked(
1175                buffer![10i32, 20, 30].into_array(),
1176                buffer![0u32, 1, 0].into_array(),
1177                buffer![2u8, 2, 1].into_array(),
1178                Validity::from_iter([true, false, true]),
1179            )
1180        };
1181        assert!(!source.is_zero_copy_to_list());
1182
1183        let mut builder = ListViewBuilder::<u32, u32>::with_capacity_in(
1184            Arc::clone(&dtype),
1185            Nullable,
1186            0,
1187            BufferAllocatorRef::static_ref(),
1188        );
1189        builder
1190            .append_listview_array(source.as_view(), &mut ctx)
1191            .unwrap();
1192
1193        let listview = builder.finish_into_listview();
1194        assert_eq!(listview.len(), 3);
1195        // The builder kept the source's overlapping layout.
1196        assert!(!listview.is_zero_copy_to_list());
1197
1198        assert_arrays_eq!(
1199            listview.list_elements_at(0, &mut ctx).unwrap(),
1200            PrimitiveArray::from_iter([10i32, 20]),
1201            &mut ctx
1202        );
1203        assert!(
1204            !listview
1205                .validity()
1206                .vortex_expect("listview validity should be derivable")
1207                .execute_is_valid(1, &mut ctx)
1208                .unwrap()
1209        );
1210        // List 1 is null, so the builder no longer rewrites its size to zero.
1211        assert_eq!(listview.size_at(1, &mut ctx), source.size_at(1, &mut ctx));
1212        assert_arrays_eq!(
1213            listview.list_elements_at(2, &mut ctx).unwrap(),
1214            PrimitiveArray::from_iter([10i32]),
1215            &mut ctx
1216        );
1217        let expected = ListArray::new(
1218            buffer![10i32, 20, 10].into_array(),
1219            buffer![0u32, 2, 2, 3].into_array(),
1220            Validity::from_iter([true, false, true]),
1221            &mut ctx,
1222        );
1223        assert_arrays_eq!(listview, expected, &mut ctx);
1224    }
1225
1226    #[test]
1227    fn test_error_append_null_to_non_nullable() {
1228        let dtype: Arc<DType> = Arc::new(I32.into());
1229        let mut builder = ListViewBuilder::<u32, u32>::with_capacity_in(
1230            Arc::clone(&dtype),
1231            NonNullable,
1232            0,
1233            BufferAllocatorRef::static_ref(),
1234        );
1235
1236        // Create a null list with nullable type (since Scalar::null requires nullable type).
1237        let null_scalar = Scalar::null(DType::List(dtype, Nullable));
1238        let null_list = null_scalar.as_list();
1239
1240        // This should fail because we're trying to append a null to a non-nullable builder.
1241        let result = builder.append_value(null_list);
1242        assert!(result.is_err());
1243        assert!(
1244            result
1245                .unwrap_err()
1246                .to_string()
1247                .contains("null value to non-nullable")
1248        );
1249    }
1250
1251    #[test]
1252    fn test_append_array_as_list() {
1253        let dtype: Arc<DType> = Arc::new(I32.into());
1254        let mut ctx = SESSION.create_execution_ctx();
1255        let mut builder = ListViewBuilder::<u32, u32>::with_capacity_in(
1256            Arc::clone(&dtype),
1257            NonNullable,
1258            10,
1259            BufferAllocatorRef::static_ref(),
1260        );
1261
1262        // Append a primitive array as a single list entry.
1263        let arr1 = buffer![1i32, 2, 3].into_array();
1264        builder.append_array_as_list(&arr1, &mut ctx).unwrap();
1265
1266        // Interleave with a list scalar.
1267        builder
1268            .append_value(
1269                Scalar::list(
1270                    Arc::clone(&dtype),
1271                    vec![10i32.into(), 11i32.into()],
1272                    NonNullable,
1273                )
1274                .as_list(),
1275            )
1276            .unwrap();
1277
1278        // Append another primitive array as a single list entry.
1279        let arr2 = buffer![4i32, 5].into_array();
1280        builder.append_array_as_list(&arr2, &mut ctx).unwrap();
1281
1282        // Append an empty array as a single list entry (empty list).
1283        let arr3 = buffer![0i32; 0].into_array();
1284        builder.append_array_as_list(&arr3, &mut ctx).unwrap();
1285
1286        // Interleave with another list scalar.
1287        builder
1288            .append_value(Scalar::list_empty(Arc::clone(&dtype), NonNullable).as_list())
1289            .unwrap();
1290
1291        let listview = builder.finish_into_listview();
1292        assert_eq!(listview.len(), 5);
1293
1294        // Verify elements array: [1, 2, 3, 10, 11, 4, 5].
1295        assert_arrays_eq!(
1296            listview.elements(),
1297            PrimitiveArray::from_iter([1i32, 2, 3, 10, 11, 4, 5]),
1298            &mut ctx
1299        );
1300
1301        // Verify offsets array.
1302        assert_arrays_eq!(
1303            listview.offsets(),
1304            PrimitiveArray::from_iter([0u32, 3, 5, 7, 7]),
1305            &mut ctx
1306        );
1307
1308        // Verify sizes array.
1309        assert_arrays_eq!(
1310            listview.sizes(),
1311            PrimitiveArray::from_iter([3u32, 2, 2, 0, 0]),
1312            &mut ctx
1313        );
1314
1315        // Test dtype mismatch error.
1316        let mut builder = ListViewBuilder::<u32, u32>::with_capacity_in(
1317            dtype,
1318            NonNullable,
1319            10,
1320            BufferAllocatorRef::static_ref(),
1321        );
1322        let wrong_dtype_arr = buffer![1i64, 2, 3].into_array();
1323        assert!(
1324            builder
1325                .append_array_as_list(&wrong_dtype_arr, &mut ctx)
1326                .is_err()
1327        );
1328    }
1329}