Skip to main content

vortex_array/builders/
list.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::any::Any;
5use std::sync::Arc;
6
7use num_traits::AsPrimitive;
8use vortex_buffer::BufferAllocatorRef;
9use vortex_error::VortexExpect;
10use vortex_error::VortexResult;
11use vortex_error::vortex_bail;
12use vortex_error::vortex_ensure_eq;
13use vortex_error::vortex_panic;
14
15use crate::ArrayRef;
16use crate::Canonical;
17use crate::ExecutionCtx;
18use crate::IntoArray;
19use crate::array::ArrayView;
20use crate::arrays::List;
21use crate::arrays::ListArray;
22use crate::arrays::ListView;
23use crate::arrays::ListViewArray;
24use crate::arrays::PrimitiveArray;
25use crate::arrays::list::ListArraySlotsExt;
26use crate::arrays::listview::ListViewArraySlotsExt;
27use crate::arrays::listview::ListViewRebuildMode;
28use crate::builders::ArrayBuilder;
29use crate::builders::ChildBuilder;
30use crate::builders::DEFAULT_BUILDER_CAPACITY;
31use crate::builders::PrimitiveBuilder;
32use crate::builders::ValidityBuilder;
33use crate::dtype::DType;
34use crate::dtype::IntegerPType;
35use crate::dtype::Nullability;
36use crate::dtype::Nullability::NonNullable;
37use crate::dtype::OffsetBuilderPType;
38use crate::match_each_integer_ptype;
39use crate::scalar::ListScalar;
40use crate::scalar::Scalar;
41
42/// The builder for building a [`ListArray`], parametrized by the [`OffsetBuilderPType`] of the
43/// `offsets` builder.
44pub struct ListBuilder<O: OffsetBuilderPType> {
45    /// The [`DType`] of the [`ListArray`]. This **must** be a [`DType::List`].
46    dtype: DType,
47
48    /// The builder for the underlying elements of the [`ListArray`].
49    elements_builder: ChildBuilder,
50
51    /// The builder for the `offsets` into the `elements` array.
52    offsets_builder: PrimitiveBuilder<O>,
53
54    /// The null map builder of the [`ListArray`].
55    nulls: ValidityBuilder,
56}
57
58impl<O: OffsetBuilderPType> ListBuilder<O> {
59    /// Creates a new `ListBuilder` with a capacity of [`DEFAULT_BUILDER_CAPACITY`].
60    #[deprecated(note = "use `new_in` with an explicit allocator")]
61    pub fn new(value_dtype: Arc<DType>, nullability: Nullability) -> Self {
62        Self::new_in(value_dtype, nullability, BufferAllocatorRef::static_ref())
63    }
64
65    /// Creates a new `ListBuilder` with the default capacity using `allocator`.
66    pub fn new_in(
67        value_dtype: Arc<DType>,
68        nullability: Nullability,
69        allocator: &BufferAllocatorRef,
70    ) -> Self {
71        Self::with_capacity_in(
72            value_dtype,
73            nullability,
74            DEFAULT_BUILDER_CAPACITY,
75            allocator,
76        )
77    }
78
79    /// Create a new [`ListArray`] builder with the given `capacity`.
80    ///
81    /// # Notes
82    ///
83    /// The number of offsets is one more than the length (# of list scalars) in the array.
84    #[deprecated(note = "use `with_capacity_in` with an explicit allocator")]
85    pub fn with_capacity(
86        value_dtype: Arc<DType>,
87        nullability: Nullability,
88        _elements_capacity: usize,
89        capacity: usize,
90    ) -> Self {
91        Self::with_capacity_in(
92            value_dtype,
93            nullability,
94            capacity,
95            BufferAllocatorRef::static_ref(),
96        )
97    }
98
99    /// Creates a list builder with the given capacity using `allocator`.
100    pub fn with_capacity_in(
101        value_dtype: Arc<DType>,
102        nullability: Nullability,
103        capacity: usize,
104        allocator: &BufferAllocatorRef,
105    ) -> Self {
106        let elements_builder =
107            ChildBuilder::with_capacity(value_dtype.as_ref(), 2 * capacity, allocator);
108        let mut offsets_builder =
109            PrimitiveBuilder::<O>::with_capacity_in(NonNullable, capacity + 1, allocator);
110
111        // The first offset is always 0 and represents an empty list.
112        offsets_builder.append_zero();
113
114        Self {
115            elements_builder,
116            offsets_builder,
117            nulls: ValidityBuilder::new(capacity, allocator),
118            dtype: DType::List(value_dtype, nullability),
119        }
120    }
121
122    /// Appends an array as a single non-null list entry to the builder.
123    ///
124    /// The input `array` must have the same dtype as the element dtype of this list builder.
125    ///
126    /// Note that the list entry will be non-null but the elements themselves are allowed to be null
127    /// (only if the elements [`DType`] in nullable, of course).
128    pub fn append_array_as_list(
129        &mut self,
130        array: &ArrayRef,
131        ctx: &mut ExecutionCtx,
132    ) -> VortexResult<()> {
133        vortex_ensure_eq!(array.dtype(), self.element_dtype());
134
135        self.elements_builder.append_array(array, ctx)?;
136        self.nulls.append_non_null();
137        self.offsets_builder.append_value(
138            O::from_usize(self.elements_builder.len())
139                .vortex_expect("Failed to convert from usize to O"),
140        );
141
142        Ok(())
143    }
144
145    /// Appends a list `value` to the builder.
146    pub fn append_value(&mut self, value: ListScalar) -> VortexResult<()> {
147        match value.elements() {
148            None => {
149                if self.dtype.nullability() == NonNullable {
150                    vortex_bail!("Cannot append null value to non-nullable list");
151                }
152                self.append_null();
153            }
154            Some(elements) => {
155                for scalar in elements {
156                    // TODO(connor): This is slow, we should be able to append multiple values at
157                    // once, or the list scalar should hold an Array
158                    self.elements_builder.append_scalar(&scalar)?;
159                }
160
161                self.nulls.append_non_null();
162                self.offsets_builder.append_value(
163                    O::from_usize(self.elements_builder.len())
164                        .vortex_expect("Failed to convert from usize to O"),
165                );
166            }
167        }
168
169        Ok(())
170    }
171
172    /// Finishes the builder directly into a [`ListArray`].
173    pub fn finish_into_list(&mut self) -> ListArray {
174        assert_eq!(
175            self.offsets_builder.len(),
176            self.nulls.len() + 1,
177            "offsets length must be one more than nulls length."
178        );
179
180        let elements = self.elements_builder.finish();
181        let offsets = self.offsets_builder.finish();
182        let validity = self.nulls.finish_with_nullability(self.dtype.nullability());
183
184        // Re-seed the retained offsets builder with the leading 0 for the next batch.
185        self.offsets_builder.append_zero();
186
187        // SAFETY:
188        // - The offsets come from a non-nullable integer builder seeded with a leading zero, so
189        //   they are a non-nullable integer array of at least one non-negative value.
190        // - Every append records `elements_builder.len()` after appending its elements, so the
191        //   offsets increase monotonically and the last one is exactly the elements length.
192        // - The assert above pairs one validity entry with each list.
193        unsafe { ListArray::new_unchecked(elements, offsets, validity) }
194    }
195
196    /// The [`DType`] of the inner elements. Note that this is **not** the same as the [`DType`] of
197    /// the outer `List`.
198    pub fn element_dtype(&self) -> &DType {
199        let DType::List(element_dtype, _) = &self.dtype else {
200            vortex_panic!("`ListBuilder` has an incorrect dtype: {}", self.dtype);
201        };
202
203        element_dtype
204    }
205
206    /// Appends the values of a [`List`]-encoded `array` to this builder.
207    ///
208    /// List encodings dispatch here through
209    /// [`match_each_list_builder!`](crate::match_each_list_builder) because the concrete list
210    /// builders are generic over their offset integer type, which cannot be named through a
211    /// `dyn ArrayBuilder`.
212    pub fn append_list_array(
213        &mut self,
214        array: ArrayView<'_, List>,
215        ctx: &mut ExecutionCtx,
216    ) -> VortexResult<()> {
217        if array.is_empty() {
218            return Ok(());
219        }
220
221        self.nulls.append_validity(array.validity()?, array.len());
222
223        let num_lists = array.len();
224        let offsets = array.offsets().clone().execute::<PrimitiveArray>(ctx)?;
225        match_each_integer_ptype!(offsets.ptype(), |OffsetType| {
226            let offsets = offsets.as_slice::<OffsetType>();
227            let first: usize = offsets[0].as_();
228            let last: usize = offsets[num_lists].as_();
229
230            // Lists in a `ListArray` are contiguous, so the referenced elements can be appended
231            // in bulk and the offsets rebased onto this builder's elements.
232            let elements_base = self.elements_builder.len();
233            if last > first {
234                self.elements_builder
235                    .append_array(&array.elements().slice(first..last)?, ctx)?;
236            }
237
238            self.offsets_builder.reserve_exact(num_lists);
239            let mut offsets_range = self.offsets_builder.uninit_range(num_lists);
240            for i in 0..num_lists {
241                let end: usize = offsets[i + 1].as_();
242                offsets_range.set_value(
243                    i,
244                    O::from_usize(end - first + elements_base)
245                        .vortex_expect("Failed to convert offset"),
246                );
247            }
248            // SAFETY: We have initialized all `num_lists` values, and since the `offsets` array is
249            // non-nullable, we are done.
250            unsafe { offsets_range.finish() };
251        });
252        Ok(())
253    }
254
255    /// Appends the values of a [`ListView`]-encoded `array` to this builder.
256    ///
257    /// See [`append_list_array`](Self::append_list_array); this is the same hook for the canonical
258    /// [`ListViewArray`] encoding.
259    ///
260    /// A `ListArray`'s offsets can only describe contiguous, in-order lists, so views laid out any
261    /// other way (overlapping, out of order, or with interior gaps) are flattened first.
262    pub fn append_listview_array(
263        &mut self,
264        array: ArrayView<'_, ListView>,
265        ctx: &mut ExecutionCtx,
266    ) -> VortexResult<()> {
267        if array.is_empty() {
268            return Ok(());
269        }
270
271        self.nulls.append_validity(array.validity()?, array.len());
272
273        // Flatten the views into the only layout `ListArray` offsets can express. This is a cheap
274        // clone when they already are laid out that way, and the flattened result keeps the
275        // original validity, so the null map appended above still describes it.
276        let array = array
277            .into_owned()
278            .rebuild(ListViewRebuildMode::MakeZeroCopyToList, ctx)?;
279        debug_assert!(array.is_zero_copy_to_list());
280
281        // Note that `ListViewArray` has `n` offsets and sizes, not `n+1` offsets like `ListArray`.
282        let elements = array.elements();
283        let offsets = array.offsets().clone().execute::<PrimitiveArray>(ctx)?;
284        let sizes = array.sizes().clone().execute::<PrimitiveArray>(ctx)?;
285
286        match_each_integer_ptype!(offsets.ptype(), |OffsetType| {
287            match_each_integer_ptype!(sizes.ptype(), |SizeType| {
288                extend_from_listview(
289                    self,
290                    elements,
291                    offsets.as_slice::<OffsetType>(),
292                    sizes.as_slice::<SizeType>(),
293                    ctx,
294                )?
295            })
296        });
297        Ok(())
298    }
299}
300
301/// Appends the lists of a zero-copy-to-list [`ListViewArray`] (`n` offsets and sizes) into a
302/// [`ListBuilder`], converting into the `ListArray` (`n + 1` offsets) layout.
303///
304/// The caller must have made `new_offsets` and `new_sizes` zero-copyable to a `ListArray`, so the
305/// lists they describe are contiguous and in order — which is the only layout `ListArray` offsets
306/// can express. That lets the referenced elements be appended in bulk, with the offsets rebased
307/// onto this builder's elements, instead of appending a slice per list.
308fn extend_from_listview<O, OffsetType, SizeType>(
309    builder: &mut ListBuilder<O>,
310    new_elements: &ArrayRef,
311    new_offsets: &[OffsetType],
312    new_sizes: &[SizeType],
313    ctx: &mut ExecutionCtx,
314) -> VortexResult<()>
315where
316    O: OffsetBuilderPType,
317    OffsetType: IntegerPType,
318    SizeType: IntegerPType,
319{
320    let num_lists = new_offsets.len();
321    debug_assert_eq!(num_lists, new_sizes.len());
322
323    // Leading and trailing unreferenced elements are allowed even in a zero-copy-to-list layout,
324    // so the referenced range is bounded by the first list's start and the last list's end.
325    let first: usize = new_offsets[0].as_();
326    let last: usize = new_offsets[num_lists - 1].as_() + new_sizes[num_lists - 1].as_();
327
328    let elements_base = builder.elements_builder.len();
329    if last > first {
330        builder
331            .elements_builder
332            .append_array(&new_elements.slice(first..last)?, ctx)?;
333    }
334
335    builder.offsets_builder.reserve_exact(num_lists);
336    let mut offsets_range = builder.offsets_builder.uninit_range(num_lists);
337    for i in 0..num_lists {
338        let end: usize = new_offsets[i].as_() + new_sizes[i].as_();
339        offsets_range.set_value(
340            i,
341            O::from_usize(end - first + elements_base).vortex_expect("Failed to convert offset"),
342        );
343    }
344
345    // SAFETY: We have initialized all `num_lists` values, and since the `offsets` array is
346    // non-nullable, we are done.
347    unsafe { offsets_range.finish() };
348    Ok(())
349}
350
351impl<O: OffsetBuilderPType> ArrayBuilder for ListBuilder<O> {
352    fn as_any(&self) -> &dyn Any {
353        self
354    }
355
356    fn as_any_mut(&mut self) -> &mut dyn Any {
357        self
358    }
359
360    fn dtype(&self) -> &DType {
361        &self.dtype
362    }
363
364    fn len(&self) -> usize {
365        self.nulls.len()
366    }
367
368    fn append_zeros(&mut self, n: usize) {
369        let curr_len = self.elements_builder.len();
370        self.offsets_builder.append_n_values(
371            O::from_usize(curr_len).vortex_expect("Failed to convert from usize to <O>"),
372            n,
373        );
374        self.nulls.append_n_non_nulls(n);
375    }
376
377    unsafe fn append_nulls_unchecked(&mut self, n: usize) {
378        let curr_len = self.elements_builder.len();
379        // A list with a null element can be a list with a zero-span offset and a cleared validity
380        // bit.
381        self.offsets_builder.append_n_values(
382            O::from_usize(curr_len).vortex_expect("Failed to convert from usize to <O>"),
383            n,
384        );
385        self.nulls.append_n_nulls(n);
386    }
387
388    fn append_scalar(&mut self, scalar: &Scalar) -> VortexResult<()> {
389        vortex_ensure_eq!(
390            scalar.dtype(),
391            self.dtype(),
392            "ListBuilder received a scalar with the wrong dtype"
393        );
394
395        self.append_value(scalar.as_list())
396    }
397
398    fn reserve_chunks(&mut self, additional: usize) {
399        self.elements_builder.reserve_chunks(additional);
400        self.nulls.reserve_runs(additional);
401    }
402
403    fn reserve_exact(&mut self, additional: usize) {
404        self.elements_builder.reserve_exact(additional);
405        self.offsets_builder.reserve_exact(additional);
406        self.nulls.reserve_exact(additional);
407    }
408
409    fn finish(&mut self) -> ArrayRef {
410        self.finish_into_list().into_array()
411    }
412
413    fn finish_into_canonical(&mut self, ctx: &mut ExecutionCtx) -> Canonical {
414        let listview = self
415            .finish()
416            .execute::<ListViewArray>(ctx)
417            .vortex_expect("list builder should canonicalize to listview");
418        Canonical::List(listview)
419    }
420}
421
422#[cfg(test)]
423mod tests {
424    use std::sync::Arc;
425    use std::sync::LazyLock;
426
427    use Nullability::NonNullable;
428    use Nullability::Nullable;
429    use rstest::rstest;
430    use vortex_buffer::BufferAllocatorRef;
431    use vortex_buffer::buffer;
432    use vortex_error::VortexExpect;
433    use vortex_error::VortexResult;
434    use vortex_session::VortexSession;
435
436    use crate::IntoArray;
437    use crate::arrays::ChunkedArray;
438    use crate::arrays::ListViewArray;
439    use crate::arrays::PrimitiveArray;
440    use crate::arrays::list::ListArraySlotsExt;
441    use crate::arrays::listview::ListViewArrayExt;
442    use crate::arrays::listview::ListViewArraySlotsExt;
443    use crate::assert_arrays_eq;
444    use crate::builders::ArrayBuilder;
445    use crate::builders::ListViewBuilder;
446    use crate::builders::builder_with_capacity_in;
447    use crate::builders::list::ListArray;
448    use crate::builders::list::ListBuilder;
449    use crate::dtype::DType;
450    use crate::dtype::Nullability;
451    use crate::dtype::OffsetBuilderPType;
452    use crate::dtype::PType::I32;
453    use crate::executor::VortexSessionExecute;
454    use crate::scalar::Scalar;
455    use crate::validity::Validity;
456
457    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
458
459    /// The `ListBuilder` twin of the `ListViewBuilder` bulk empty-list case: `n` empty lists must
460    /// all land at the current end of `elements`, with validity from the method that was called.
461    #[rstest]
462    #[case::zeros(false)]
463    #[case::nulls(true)]
464    fn test_bulk_empty_lists(#[case] null: bool) -> VortexResult<()> {
465        let mut ctx = SESSION.create_execution_ctx();
466        let dtype: Arc<DType> = Arc::new(I32.into());
467        let mut builder = ListBuilder::<u64>::with_capacity_in(
468            Arc::clone(&dtype),
469            Nullable,
470            0,
471            BufferAllocatorRef::static_ref(),
472        );
473
474        builder.append_array_as_list(&buffer![1i32, 2].into_array(), &mut ctx)?;
475
476        const N: usize = 5;
477        if null {
478            builder.append_nulls(N);
479        } else {
480            builder.append_zeros(N);
481        }
482
483        let list = builder.finish_into_list();
484        assert_eq!(list.len(), N + 1);
485        let listview = list.into_array().execute::<ListViewArray>(&mut ctx)?;
486        for i in 1..=N {
487            assert_eq!(listview.size_at(i, &mut ctx), 0);
488            assert_eq!(listview.validity()?.execute_is_valid(i, &mut ctx)?, !null,);
489        }
490
491        Ok(())
492    }
493
494    #[test]
495    fn test_empty() {
496        let mut builder = ListBuilder::<u32>::with_capacity_in(
497            Arc::new(I32.into()),
498            NonNullable,
499            0,
500            BufferAllocatorRef::static_ref(),
501        );
502
503        let list = builder.finish();
504        assert_eq!(list.len(), 0);
505        assert_eq!(
506            list.dtype(),
507            &DType::List(Arc::new(I32.into()), NonNullable)
508        );
509    }
510
511    #[test]
512    fn test_values() {
513        let dtype: Arc<DType> = Arc::new(I32.into());
514        let mut builder = ListBuilder::<u32>::with_capacity_in(
515            Arc::clone(&dtype),
516            NonNullable,
517            0,
518            BufferAllocatorRef::static_ref(),
519        );
520
521        builder
522            .append_value(
523                Scalar::list(
524                    Arc::clone(&dtype),
525                    vec![1i32.into(), 2i32.into(), 3i32.into()],
526                    NonNullable,
527                )
528                .as_list(),
529            )
530            .unwrap();
531
532        builder
533            .append_value(
534                Scalar::list(
535                    dtype,
536                    vec![4i32.into(), 5i32.into(), 6i32.into()],
537                    NonNullable,
538                )
539                .as_list(),
540            )
541            .unwrap();
542
543        let list = builder.finish();
544        assert_eq!(list.len(), 2);
545
546        let mut ctx = SESSION.create_execution_ctx();
547        let list_array = list.execute::<ListViewArray>(&mut ctx).unwrap();
548
549        assert_eq!(list_array.list_elements_at(0, &mut ctx).unwrap().len(), 3);
550        assert_eq!(list_array.list_elements_at(1, &mut ctx).unwrap().len(), 3);
551        let expected = ListArray::new(
552            buffer![1i32, 2, 3, 4, 5, 6].into_array(),
553            buffer![0u32, 3, 6].into_array(),
554            Validity::NonNullable,
555            &mut ctx,
556        );
557        assert_arrays_eq!(list_array, expected, &mut ctx);
558    }
559
560    #[test]
561    fn test_append_empty_list() {
562        let mut ctx = SESSION.create_execution_ctx();
563        let dtype: Arc<DType> = Arc::new(I32.into());
564        let mut builder = ListBuilder::<u32>::with_capacity_in(
565            Arc::clone(&dtype),
566            NonNullable,
567            0,
568            BufferAllocatorRef::static_ref(),
569        );
570
571        assert!(
572            builder
573                .append_value(Scalar::list_empty(dtype, NonNullable).as_list())
574                .is_ok()
575        );
576        let expected = ListArray::new(
577            buffer![0i32; 0].into_array(),
578            buffer![0u32, 0].into_array(),
579            Validity::NonNullable,
580            &mut ctx,
581        );
582        assert_arrays_eq!(
583            builder.finish(),
584            expected,
585            &mut SESSION.create_execution_ctx()
586        );
587    }
588
589    #[test]
590    fn test_nullable_values() {
591        let dtype: Arc<DType> = Arc::new(I32.into());
592        let mut builder = ListBuilder::<u32>::with_capacity_in(
593            Arc::clone(&dtype),
594            Nullable,
595            0,
596            BufferAllocatorRef::static_ref(),
597        );
598
599        builder
600            .append_value(
601                Scalar::list(
602                    Arc::clone(&dtype),
603                    vec![1i32.into(), 2i32.into(), 3i32.into()],
604                    NonNullable,
605                )
606                .as_list(),
607            )
608            .unwrap();
609
610        builder
611            .append_value(Scalar::list_empty(Arc::clone(&dtype), NonNullable).as_list())
612            .unwrap();
613
614        builder
615            .append_value(
616                Scalar::list(
617                    dtype,
618                    vec![4i32.into(), 5i32.into(), 6i32.into()],
619                    NonNullable,
620                )
621                .as_list(),
622            )
623            .unwrap();
624
625        let list = builder.finish();
626        assert_eq!(list.len(), 3);
627
628        let mut ctx = SESSION.create_execution_ctx();
629        let list_array = list.execute::<ListViewArray>(&mut ctx).unwrap();
630
631        assert_eq!(list_array.list_elements_at(0, &mut ctx).unwrap().len(), 3);
632        assert_eq!(list_array.list_elements_at(1, &mut ctx).unwrap().len(), 0);
633        assert_eq!(list_array.list_elements_at(2, &mut ctx).unwrap().len(), 3);
634        let expected = ListArray::new(
635            buffer![1i32, 2, 3, 4, 5, 6].into_array(),
636            buffer![0u32, 3, 3, 6].into_array(),
637            Validity::AllValid,
638            &mut ctx,
639        );
640        assert_arrays_eq!(list_array, expected, &mut ctx);
641    }
642
643    fn test_extend_builder_gen<O: OffsetBuilderPType>() {
644        let list = ListArray::from_iter_opt_slow::<O, _, _>(
645            [Some(vec![0, 1, 2]), None, Some(vec![4, 5])],
646            Arc::new(I32.into()),
647        )
648        .unwrap()
649        .into_array();
650        assert_eq!(list.len(), 3);
651
652        let mut ctx = SESSION.create_execution_ctx();
653
654        let mut builder = ListBuilder::<O>::with_capacity_in(
655            Arc::new(I32.into()),
656            Nullable,
657            9,
658            BufferAllocatorRef::static_ref(),
659        );
660        list.append_to_builder(&mut builder, &mut ctx).unwrap();
661        list.append_to_builder(&mut builder, &mut ctx).unwrap();
662        list.slice(0..0)
663            .unwrap()
664            .append_to_builder(&mut builder, &mut ctx)
665            .unwrap();
666        list.slice(1..3)
667            .unwrap()
668            .append_to_builder(&mut builder, &mut ctx)
669            .unwrap();
670
671        let expected = ListArray::from_iter_opt_slow::<O, _, _>(
672            [
673                Some(vec![0, 1, 2]),
674                None,
675                Some(vec![4, 5]),
676                Some(vec![0, 1, 2]),
677                None,
678                Some(vec![4, 5]),
679                None,
680                Some(vec![4, 5]),
681            ],
682            Arc::new(DType::Primitive(I32, NonNullable)),
683        )
684        .unwrap()
685        .into_array()
686        .execute::<ListViewArray>(&mut ctx)
687        .unwrap();
688
689        let actual = builder.finish_into_canonical(&mut ctx).into_listview();
690
691        assert_arrays_eq!(actual.elements(), expected.elements(), &mut ctx);
692
693        assert_arrays_eq!(actual.offsets(), expected.offsets(), &mut ctx);
694
695        assert!(
696            actual
697                .validity()
698                .vortex_expect("list validity should be derivable")
699                .mask_eq(
700                    &expected
701                        .validity()
702                        .vortex_expect("list validity should be derivable"),
703                    actual.len(),
704                    &mut ctx,
705                )
706                .unwrap(),
707        );
708        let independent = ListArray::new(
709            buffer![0i32, 1, 2, 4, 5, 0, 1, 2, 4, 5, 4, 5].into_array(),
710            buffer![0u32, 3, 3, 5, 8, 8, 10, 10, 12].into_array(),
711            Validity::from_iter([true, false, true, true, false, true, false, true]),
712            &mut ctx,
713        );
714        assert_arrays_eq!(actual, independent, &mut ctx);
715    }
716
717    /// `append_to_builder` must handle any list builder kind without assuming the offset/size
718    /// integer types produced by `builder_with_capacity`. It appends a `List`-encoded array and a
719    /// `ListView`-encoded array into `ListViewBuilder`s and `ListBuilder`s with assorted (and
720    /// non-`u64`) offset/size types.
721    #[test]
722    fn test_append_to_builder_any_list_builder() -> VortexResult<()> {
723        let mut ctx = SESSION.create_execution_ctx();
724
725        let list = ListArray::from_iter_opt_slow::<u64, _, _>(
726            [Some(vec![0, 1, 2]), None, Some(vec![4, 5])],
727            Arc::new(I32.into()),
728        )?
729        .into_array();
730        let listview = list
731            .clone()
732            .execute::<ListViewArray>(&mut ctx)?
733            .into_array();
734        let elem_dtype = || Arc::new(I32.into());
735
736        // `builder_with_capacity` produces a `ListViewBuilder` for `DType::List`; appending the
737        // `List`-encoded array must dispatch into it instead of bailing.
738        let mut listview_builder =
739            builder_with_capacity_in(list.dtype(), list.len(), BufferAllocatorRef::static_ref());
740        list.append_to_builder(listview_builder.as_mut(), &mut ctx)?;
741        assert_arrays_eq!(listview_builder.finish(), list, &mut ctx);
742
743        // A `ListViewBuilder` with non-`u64` (including signed) offset and size types must work
744        // for both source encodings.
745        let mut lv_u64_u32 = ListViewBuilder::<u64, u32>::with_capacity_in(
746            elem_dtype(),
747            Nullable,
748            4,
749            BufferAllocatorRef::static_ref(),
750        );
751        list.append_to_builder(&mut lv_u64_u32, &mut ctx)?;
752        assert_arrays_eq!(lv_u64_u32.finish(), list, &mut ctx);
753
754        let mut lv_i64_i32 = ListViewBuilder::<i64, i32>::with_capacity_in(
755            elem_dtype(),
756            Nullable,
757            4,
758            BufferAllocatorRef::static_ref(),
759        );
760        list.append_to_builder(&mut lv_i64_i32, &mut ctx)?;
761        assert_arrays_eq!(lv_i64_i32.finish(), list, &mut ctx);
762
763        let mut lv_u32_u32 = ListViewBuilder::<u32, u32>::with_capacity_in(
764            elem_dtype(),
765            Nullable,
766            4,
767            BufferAllocatorRef::static_ref(),
768        );
769        listview.append_to_builder(&mut lv_u32_u32, &mut ctx)?;
770        assert_arrays_eq!(lv_u32_u32.finish(), list, &mut ctx);
771
772        // Both source encodings appended into `ListBuilder`s with non-`u64` (including signed)
773        // offset types.
774        let mut list_builder = ListBuilder::<u32>::with_capacity_in(
775            elem_dtype(),
776            Nullable,
777            4,
778            BufferAllocatorRef::static_ref(),
779        );
780        list.append_to_builder(&mut list_builder, &mut ctx)?;
781        assert_arrays_eq!(list_builder.finish(), list, &mut ctx);
782
783        let mut list_builder_i32 = ListBuilder::<i32>::with_capacity_in(
784            elem_dtype(),
785            Nullable,
786            4,
787            BufferAllocatorRef::static_ref(),
788        );
789        listview.append_to_builder(&mut list_builder_i32, &mut ctx)?;
790        assert_arrays_eq!(list_builder_i32.finish(), list, &mut ctx);
791
792        Ok(())
793    }
794
795    #[test]
796    fn test_append_list_arrays_grow_builder() -> VortexResult<()> {
797        let mut ctx = SESSION.create_execution_ctx();
798        let dtype: Arc<DType> = Arc::new(I32.into());
799
800        // Enough lists to exceed the offsets capacity of a zero-capacity builder, so appending
801        // must grow the builder rather than panic in `uninit_range`.
802        let lists: Vec<Option<Vec<i32>>> =
803            (0..100).map(|i| (i % 10 != 0).then(|| vec![i])).collect();
804        let source = ListArray::from_iter_opt_slow::<u32, _, _>(lists.clone(), Arc::clone(&dtype))?;
805        let expected = ListArray::from_iter_opt_slow::<u32, _, _>(
806            lists.iter().cloned().chain(lists.iter().cloned()),
807            Arc::clone(&dtype),
808        )?;
809
810        // Appending twice checks growth from a non-empty builder and offset rebasing.
811        let mut builder = ListBuilder::<u32>::with_capacity_in(
812            Arc::clone(&dtype),
813            Nullable,
814            0,
815            BufferAllocatorRef::static_ref(),
816        );
817        builder.append_list_array(source.as_view(), &mut ctx)?;
818        builder.append_list_array(source.as_view(), &mut ctx)?;
819        assert_arrays_eq!(builder.finish(), expected, &mut ctx);
820
821        let source_listview = source.into_array().execute::<ListViewArray>(&mut ctx)?;
822        let mut builder = ListBuilder::<u32>::with_capacity_in(
823            dtype,
824            Nullable,
825            0,
826            BufferAllocatorRef::static_ref(),
827        );
828        builder.append_listview_array(source_listview.as_view(), &mut ctx)?;
829        builder.append_listview_array(source_listview.as_view(), &mut ctx)?;
830        assert_arrays_eq!(builder.finish(), expected, &mut ctx);
831
832        Ok(())
833    }
834
835    /// A `ListArray`'s offsets can only describe contiguous, in-order lists, so an overlapping
836    /// source has to be flattened before its elements can be appended in bulk. A sliced source,
837    /// meanwhile, keeps the layout it has and is appended from wherever its first list starts.
838    #[test]
839    fn test_append_listview_array_flattens_overlaps_and_skips_leading_elements() -> VortexResult<()>
840    {
841        let mut ctx = SESSION.create_execution_ctx();
842        let dtype: Arc<DType> = Arc::new(I32.into());
843
844        // Overlapping source, so not zero-copyable to a list:
845        // - List 0: [10, 20]
846        // - List 1: null (size is intentionally non-zero in the source metadata)
847        // - List 2: [10], sharing the elements list 0 already referenced
848        let overlapping = unsafe {
849            ListViewArray::new_unchecked(
850                buffer![10i32, 20, 30].into_array(),
851                buffer![0u32, 1, 0].into_array(),
852                buffer![2u8, 2, 1].into_array(),
853                Validity::from_iter([true, false, true]),
854            )
855        };
856        assert!(!overlapping.is_zero_copy_to_list());
857
858        // Zero-copyable source sliced past its first list, so its elements start at offset 2.
859        let sliced = unsafe {
860            ListViewArray::new_unchecked(
861                buffer![40i32, 50, 60, 70].into_array(),
862                buffer![0u32, 2].into_array(),
863                buffer![2u32, 2].into_array(),
864                Validity::AllValid,
865            )
866            .with_zero_copy_to_list(true)
867        }
868        .into_array()
869        .slice(1..2)?
870        .execute::<ListViewArray>(&mut ctx)?;
871
872        let mut builder = ListBuilder::<u32>::with_capacity_in(
873            dtype,
874            Nullable,
875            0,
876            BufferAllocatorRef::static_ref(),
877        );
878        builder.append_listview_array(overlapping.as_view(), &mut ctx)?;
879        builder.append_listview_array(sliced.as_view(), &mut ctx)?;
880
881        let list = builder.finish_into_list();
882        assert_arrays_eq!(
883            list.elements(),
884            PrimitiveArray::from_iter([10i32, 20, 10, 60, 70]),
885            &mut ctx
886        );
887        assert_arrays_eq!(
888            list.offsets(),
889            PrimitiveArray::from_iter([0u32, 2, 2, 3, 5]),
890            &mut ctx
891        );
892
893        let expected = ListArray::new(
894            buffer![10i32, 20, 10, 60, 70].into_array(),
895            buffer![0u32, 2, 2, 3, 5].into_array(),
896            Validity::from_iter([true, false, true, true]),
897            &mut ctx,
898        );
899        assert_arrays_eq!(list, expected, &mut ctx);
900        Ok(())
901    }
902
903    #[test]
904    fn test_extend_builder() {
905        test_extend_builder_gen::<i32>();
906        test_extend_builder_gen::<i64>();
907
908        test_extend_builder_gen::<u32>();
909        test_extend_builder_gen::<u64>();
910    }
911
912    #[test]
913    pub fn test_array_with_gap() {
914        let mut ctx = SESSION.create_execution_ctx();
915        let one_trailing_unused_element = ListArray::try_new(
916            buffer![1, 2, 3, 4].into_array(),
917            buffer![0, 3].into_array(),
918            Validity::NonNullable,
919            &mut ctx,
920        )
921        .unwrap();
922
923        let second_array = ListArray::try_new(
924            buffer![5, 6].into_array(),
925            buffer![0, 2].into_array(),
926            Validity::NonNullable,
927            &mut ctx,
928        )
929        .unwrap();
930
931        let chunked_list = ChunkedArray::try_new(
932            vec![
933                one_trailing_unused_element.clone().into_array(),
934                second_array.clone().into_array(),
935            ],
936            DType::List(Arc::new(DType::Primitive(I32, NonNullable)), NonNullable),
937        );
938
939        let mut ctx = SESSION.create_execution_ctx();
940        let canon_values = chunked_list
941            .unwrap()
942            .as_array()
943            .clone()
944            .execute::<ListViewArray>(&mut ctx)
945            .unwrap();
946
947        assert_eq!(
948            one_trailing_unused_element
949                .execute_scalar(0, &mut SESSION.create_execution_ctx())
950                .unwrap(),
951            canon_values
952                .execute_scalar(0, &mut SESSION.create_execution_ctx())
953                .unwrap()
954        );
955        assert_eq!(
956            second_array
957                .execute_scalar(0, &mut SESSION.create_execution_ctx())
958                .unwrap(),
959            canon_values
960                .execute_scalar(1, &mut SESSION.create_execution_ctx())
961                .unwrap()
962        );
963    }
964
965    #[test]
966    fn test_append_scalar() {
967        let dtype: Arc<DType> = Arc::new(I32.into());
968        let mut builder = ListBuilder::<u64>::with_capacity_in(
969            Arc::clone(&dtype),
970            Nullable,
971            10,
972            BufferAllocatorRef::static_ref(),
973        );
974
975        // Test appending a valid list.
976        let list_scalar1 =
977            Scalar::list(Arc::clone(&dtype), vec![1i32.into(), 2i32.into()], Nullable);
978        builder.append_scalar(&list_scalar1).unwrap();
979
980        // Test appending another list.
981        let list_scalar2 = Scalar::list(
982            Arc::clone(&dtype),
983            vec![3i32.into(), 4i32.into(), 5i32.into()],
984            Nullable,
985        );
986        builder.append_scalar(&list_scalar2).unwrap();
987
988        // Test appending null value.
989        let null_scalar = Scalar::null(DType::List(Arc::clone(&dtype), Nullable));
990        builder.append_scalar(&null_scalar).unwrap();
991
992        let array = builder.finish_into_list();
993        assert_eq!(array.len(), 3);
994
995        let mut ctx = SESSION.create_execution_ctx();
996
997        // Check actual values using scalar_at.
998
999        let scalar0 = array.execute_scalar(0, &mut ctx).unwrap();
1000        let list0 = scalar0.as_list();
1001        assert_eq!(list0.len(), 2);
1002        if let Some(list0_items) = list0.elements() {
1003            assert_eq!(list0_items[0].as_primitive().typed_value::<i32>(), Some(1));
1004            assert_eq!(list0_items[1].as_primitive().typed_value::<i32>(), Some(2));
1005        }
1006
1007        let scalar1 = array.execute_scalar(1, &mut ctx).unwrap();
1008        let list1 = scalar1.as_list();
1009        assert_eq!(list1.len(), 3);
1010        if let Some(list1_items) = list1.elements() {
1011            assert_eq!(list1_items[0].as_primitive().typed_value::<i32>(), Some(3));
1012            assert_eq!(list1_items[1].as_primitive().typed_value::<i32>(), Some(4));
1013            assert_eq!(list1_items[2].as_primitive().typed_value::<i32>(), Some(5));
1014        }
1015
1016        let scalar2 = array.execute_scalar(2, &mut ctx).unwrap();
1017        let list2 = scalar2.as_list();
1018        assert!(list2.is_null()); // This should be null.
1019
1020        // Check validity.
1021        assert!(
1022            array
1023                .validity()
1024                .vortex_expect("list validity should be derivable")
1025                .execute_is_valid(0, &mut ctx)
1026                .unwrap()
1027        );
1028        assert!(
1029            array
1030                .validity()
1031                .vortex_expect("list validity should be derivable")
1032                .execute_is_valid(1, &mut ctx)
1033                .unwrap()
1034        );
1035        assert!(
1036            !array
1037                .validity()
1038                .vortex_expect("list validity should be derivable")
1039                .execute_is_valid(2, &mut ctx)
1040                .unwrap()
1041        );
1042
1043        // Test wrong dtype error.
1044        let mut builder = ListBuilder::<u64>::with_capacity_in(
1045            dtype,
1046            NonNullable,
1047            10,
1048            BufferAllocatorRef::static_ref(),
1049        );
1050        let wrong_scalar = Scalar::from(42i32);
1051        assert!(builder.append_scalar(&wrong_scalar).is_err());
1052    }
1053
1054    #[test]
1055    fn test_append_array_as_list() {
1056        let dtype: Arc<DType> = Arc::new(I32.into());
1057        let mut ctx = SESSION.create_execution_ctx();
1058        let mut builder = ListBuilder::<u32>::with_capacity_in(
1059            Arc::clone(&dtype),
1060            NonNullable,
1061            10,
1062            BufferAllocatorRef::static_ref(),
1063        );
1064
1065        // Append a primitive array as a single list entry.
1066        let arr1 = buffer![1i32, 2, 3].into_array();
1067        builder.append_array_as_list(&arr1, &mut ctx).unwrap();
1068
1069        // Interleave with a list scalar.
1070        builder
1071            .append_value(
1072                Scalar::list(
1073                    Arc::clone(&dtype),
1074                    vec![10i32.into(), 11i32.into()],
1075                    NonNullable,
1076                )
1077                .as_list(),
1078            )
1079            .unwrap();
1080
1081        // Append another primitive array as a single list entry.
1082        let arr2 = buffer![4i32, 5].into_array();
1083        builder.append_array_as_list(&arr2, &mut ctx).unwrap();
1084
1085        // Append an empty array as a single list entry (empty list).
1086        let arr3 = buffer![0i32; 0].into_array();
1087        builder.append_array_as_list(&arr3, &mut ctx).unwrap();
1088
1089        // Interleave with another list scalar (empty list).
1090        builder
1091            .append_value(Scalar::list_empty(Arc::clone(&dtype), NonNullable).as_list())
1092            .unwrap();
1093
1094        let list = builder.finish_into_list();
1095        assert_eq!(list.len(), 5);
1096
1097        // Verify elements array: [1, 2, 3, 10, 11, 4, 5].
1098        assert_arrays_eq!(
1099            list.elements(),
1100            PrimitiveArray::from_iter([1i32, 2, 3, 10, 11, 4, 5]),
1101            &mut ctx
1102        );
1103
1104        // Verify offsets array.
1105        assert_arrays_eq!(
1106            list.offsets(),
1107            PrimitiveArray::from_iter([0u32, 3, 5, 7, 7, 7]),
1108            &mut ctx
1109        );
1110
1111        // Test dtype mismatch error.
1112        let mut builder = ListBuilder::<u32>::with_capacity_in(
1113            dtype,
1114            NonNullable,
1115            10,
1116            BufferAllocatorRef::static_ref(),
1117        );
1118        let wrong_dtype_arr = buffer![1i64, 2, 3].into_array();
1119        assert!(
1120            builder
1121                .append_array_as_list(&wrong_dtype_arr, &mut ctx)
1122                .is_err()
1123        );
1124    }
1125
1126    #[test]
1127    fn test_reuse_finish_into_list() -> VortexResult<()> {
1128        let mut ctx = SESSION.create_execution_ctx();
1129        let dtype: Arc<DType> = Arc::new(I32.into());
1130        let mut reused = ListBuilder::<u32>::with_capacity_in(
1131            Arc::clone(&dtype),
1132            Nullable,
1133            4,
1134            BufferAllocatorRef::static_ref(),
1135        );
1136
1137        // Consecutive empty finishes must each keep a leading zero offset.
1138        for _ in 0..2 {
1139            let empty = reused.finish_into_list();
1140            assert_eq!(empty.len(), 0);
1141            assert_eq!(empty.elements().len(), 0);
1142            assert_arrays_eq!(empty.offsets(), PrimitiveArray::from_iter([0u32]), &mut ctx);
1143        }
1144
1145        // Batch 1: nonempty list, null row, empty list, nonempty list.
1146        let list_1_2 = Scalar::list(Arc::clone(&dtype), vec![1i32.into(), 2i32.into()], Nullable);
1147        let list_null = Scalar::null(DType::List(Arc::clone(&dtype), Nullable));
1148        let list_empty = Scalar::list_empty(Arc::clone(&dtype), Nullable);
1149        let list_3 = Scalar::list(Arc::clone(&dtype), vec![3i32.into()], Nullable);
1150
1151        for scalar in [&list_1_2, &list_null, &list_empty, &list_3] {
1152            reused.append_value(scalar.as_list())?;
1153        }
1154        let batch1 = reused.finish_into_list();
1155        assert_arrays_eq!(
1156            batch1.offsets(),
1157            PrimitiveArray::from_iter([0u32, 2, 2, 2, 3]),
1158            &mut ctx
1159        );
1160        assert_eq!(batch1.elements().len(), 3);
1161
1162        // Batch 2 on the reused builder: null row and nonempty list.
1163        let list_10_20_30 = Scalar::list(
1164            Arc::clone(&dtype),
1165            vec![10i32.into(), 20i32.into(), 30i32.into()],
1166            Nullable,
1167        );
1168        for scalar in [&list_null, &list_10_20_30] {
1169            reused.append_value(scalar.as_list())?;
1170        }
1171        let batch2 = reused.finish_into_list();
1172        assert_arrays_eq!(
1173            batch2.offsets(),
1174            PrimitiveArray::from_iter([0u32, 0, 3]),
1175            &mut ctx
1176        );
1177        assert_eq!(batch2.elements().len(), 3);
1178
1179        // Batch 1 remains independent of later appends to the reused builder.
1180        assert_arrays_eq!(
1181            batch1.offsets(),
1182            PrimitiveArray::from_iter([0u32, 2, 2, 2, 3]),
1183            &mut ctx
1184        );
1185        assert_arrays_eq!(
1186            batch1.elements(),
1187            PrimitiveArray::from_iter([1i32, 2, 3]),
1188            &mut ctx
1189        );
1190
1191        Ok(())
1192    }
1193}