Skip to main content

vortex_array/arrays/listview/
conversion.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use vortex_buffer::BufferAllocatorRef;
5use vortex_error::VortexExpect;
6use vortex_error::VortexResult;
7
8use crate::ArrayRef;
9use crate::Canonical;
10use crate::ExecutionCtx;
11use crate::IntoArray;
12use crate::arrays::ExtensionArray;
13use crate::arrays::FixedSizeListArray;
14use crate::arrays::ListArray;
15use crate::arrays::ListViewArray;
16use crate::arrays::PrimitiveArray;
17use crate::arrays::StructArray;
18use crate::arrays::extension::ExtensionArrayExt;
19use crate::arrays::fixed_size_list::FixedSizeListArrayExt;
20use crate::arrays::fixed_size_list::FixedSizeListArraySlotsExt;
21use crate::arrays::list::ListArrayExt;
22use crate::arrays::list::ListArraySlotsExt;
23use crate::arrays::listview::ListViewArrayExt;
24use crate::arrays::listview::ListViewArraySlotsExt;
25use crate::arrays::listview::ListViewRebuildMode;
26use crate::arrays::struct_::StructArrayExt;
27use crate::builders::PrimitiveBuilder;
28use crate::dtype::IntegerPType;
29use crate::dtype::Nullability;
30use crate::match_each_integer_ptype;
31use crate::optimizer::ArrayOptimizer;
32
33/// Creates a `ListViewArray` from a `ListArray` by computing `sizes` from `offsets`.
34///
35/// The output `ListViewArray` will be zero-copyable back to a `ListArray`, and additionally it will
36/// not have any leading or trailing garbage data.
37pub fn list_view_from_list(list: ListArray, ctx: &mut ExecutionCtx) -> VortexResult<ListViewArray> {
38    // If the list is empty, create an empty `ListViewArray` with the same offset `DType` as the
39    // input.
40    if list.is_empty() {
41        return Ok(Canonical::empty(list.dtype()).into_listview());
42    }
43
44    // We reset the offsets here because mostly for convenience, and also because callers of this
45    // function might not expect the output `ListViewArray` to have a bunch of leading and trailing
46    // garbage data when they turn it back into a `ListArray`.
47    let list = list.reset_offsets(false, ctx)?;
48
49    // `reset_offsets` can leave a lazy subtraction in the offsets slot, which both the `sizes` below
50    // and the view's own offsets read. Execute it once here so that it does not run per reader.
51    let list_offsets = list.offsets().clone().execute::<PrimitiveArray>(ctx)?;
52
53    // Create `sizes` array by computing differences between consecutive offsets.
54    // We use the same `DType` for the sizes as the `offsets` array to ensure compatibility.
55    let sizes = match_each_integer_ptype!(list_offsets.ptype(), |O| {
56        build_sizes_from_offsets::<O>(&list_offsets, ctx.allocator())?
57    });
58
59    // We need to slice the `offsets` to remove the last element (`ListArray` has `n + 1` offsets).
60    debug_assert_eq!(list_offsets.len(), list.len() + 1);
61    let adjusted_offsets = list_offsets
62        .into_array()
63        .slice(0..list.len())?
64        .optimize_ctx(ctx)?;
65
66    // SAFETY: Since everything came from an existing valid `ListArray`, and the `sizes` were
67    // derived from valid and in-order `offsets`, we know these fields are valid.
68    // We also just came directly from a `ListArray`, so we know this is zero-copyable.
69    Ok(unsafe {
70        ListViewArray::new_unchecked(
71            list.elements().clone(),
72            adjusted_offsets,
73            sizes,
74            list.validity()?,
75        )
76        .with_zero_copy_to_list(true)
77    })
78}
79
80/// Builds a sizes array by computing differences between consecutive offsets.
81///
82/// `offsets` **must** be the `n + 1` sorted offsets of a non-empty `ListArray` of `n` rows.
83fn build_sizes_from_offsets<O: IntegerPType>(
84    offsets: &PrimitiveArray,
85    allocator: &BufferAllocatorRef,
86) -> VortexResult<ArrayRef> {
87    let offsets_slice = offsets.as_slice::<O>();
88    debug_assert!(offsets_slice.is_sorted());
89
90    let len = offsets_slice.len() - 1;
91    let mut sizes_builder =
92        PrimitiveBuilder::<O>::with_capacity_in(Nullability::NonNullable, len, allocator);
93
94    // Create `UninitRange` for direct memory access.
95    let mut sizes_range = sizes_builder.uninit_range(len);
96
97    // Compute sizes as the difference between consecutive offsets.
98    for i in 0..len {
99        let size = offsets_slice[i + 1] - offsets_slice[i];
100        sizes_range.set_value(i, size);
101    }
102
103    // SAFETY: We have initialized all values in the range.
104    unsafe {
105        sizes_range.finish();
106    }
107
108    Ok(sizes_builder.finish_into_primitive().into_array())
109}
110
111/// Creates a `ListArray` from a `ListViewArray`.
112///
113/// The resulting `ListArray` will not have any leading or trailing garbage data.
114///
115/// This operation is fast when `ListViewArray::is_zero_copy_to_list` is `true`. It is not exactly
116/// zero-copy, since it must append one final offset. Otherwise it falls back to the (very)
117/// expensive path and rebuilds the `ListArray` from scratch.
118pub fn list_from_list_view(
119    list_view: ListViewArray,
120    ctx: &mut ExecutionCtx,
121) -> VortexResult<ListArray> {
122    // Rebuild as zero-copyable to list array and also trim all leading and trailing elements.
123    let zctl_array = list_view.rebuild(ListViewRebuildMode::MakeExact, ctx)?;
124    debug_assert!(zctl_array.is_zero_copy_to_list());
125
126    let list_offsets = match_each_integer_ptype!(zctl_array.offsets().dtype().as_ptype(), |O| {
127        // SAFETY: We just made the array zero-copyable to `ListArray`, so the safety contract is
128        // upheld.
129        unsafe { build_list_offsets_from_list_view::<O>(&zctl_array, ctx) }
130    });
131
132    // SAFETY: Because the shape of the `ListViewArray` is zero-copyable to a `ListArray`, we
133    // can simply reuse all of the data (besides the offsets). We also trim all of the elements to
134    // make it easier for the caller to use the `ListArray`.
135    Ok(unsafe {
136        ListArray::new_unchecked(
137            zctl_array.elements().clone(),
138            list_offsets,
139            zctl_array.validity()?,
140        )
141    })
142}
143
144// TODO(connor)[ListView]: We can optimize this by always keeping extra memory in `ListViewArray`
145// offsets for an `n+1`th offset.
146/// Builds a `ListArray` offsets array from a `ListViewArray` by constructing `n + 1` offsets.
147///
148/// The last offset is computed as `last_offset + last_size`, and is zero for an empty array.
149///
150/// # Safety
151///
152/// The `ListViewArray` must have offsets that are sorted, and every size must be equal to the gap
153/// between `offset[i]` and `offset[i + 1]`.
154unsafe fn build_list_offsets_from_list_view<O: IntegerPType>(
155    list_view: &ListViewArray,
156    ctx: &mut ExecutionCtx,
157) -> ArrayRef {
158    let len = list_view.len();
159    let mut offsets_builder =
160        PrimitiveBuilder::<O>::with_capacity_in(Nullability::NonNullable, len + 1, ctx.allocator());
161
162    // Create uninit range for direct memory access.
163    let mut offsets_range = offsets_builder.uninit_range(len + 1);
164
165    let offsets = list_view
166        .offsets()
167        .clone()
168        .execute::<PrimitiveArray>(ctx)
169        .vortex_expect("list view offsets must be primitive after rebuild");
170    let offsets_slice = offsets.as_slice::<O>();
171    debug_assert!(offsets_slice.is_sorted());
172
173    // Copy the existing n offsets.
174    offsets_range.copy_from_slice(0, offsets_slice);
175
176    // Append the final offset (last offset + last size).
177    let final_offset = if len != 0 {
178        let last_offset = offsets_slice[len - 1];
179
180        let last_size = list_view.size_at(len - 1, ctx);
181        let last_size =
182            O::from_usize(last_size).vortex_expect("size somehow did not fit into offsets");
183
184        last_offset + last_size
185    } else {
186        O::zero()
187    };
188
189    offsets_range.set_value(len, final_offset);
190
191    // SAFETY: We have initialized all values in the range.
192    unsafe {
193        offsets_range.finish();
194    }
195
196    offsets_builder.finish_into_primitive().into_array()
197}
198
199/// Recursively converts all `ListViewArray`s to `ListArray`s in a nested array structure.
200///
201/// The conversion happens bottom-up, processing children before parents.
202pub fn recursive_list_from_list_view(
203    array: ArrayRef,
204    ctx: &mut ExecutionCtx,
205) -> VortexResult<ArrayRef> {
206    if !array.dtype().is_nested() {
207        return Ok(array);
208    }
209
210    let canonical = array.execute::<Canonical>(ctx)?;
211
212    Ok(match canonical {
213        Canonical::List(listview) => {
214            let converted_elements =
215                recursive_list_from_list_view(listview.elements().clone(), ctx)?;
216            debug_assert_eq!(converted_elements.len(), listview.elements().len());
217
218            // Avoid cloning if elements didn't change.
219            let listview_with_converted_elements =
220                if !ArrayRef::ptr_eq(&converted_elements, listview.elements()) {
221                    // SAFETY: We are effectively just replacing the child elements array, which
222                    // must have the same length, so all invariants are maintained.
223                    unsafe {
224                        ListViewArray::new_unchecked(
225                            converted_elements,
226                            listview.offsets().clone(),
227                            listview.sizes().clone(),
228                            listview.validity()?,
229                        )
230                        .with_zero_copy_to_list(listview.is_zero_copy_to_list())
231                    }
232                } else {
233                    listview
234                };
235
236            // Make the conversion to `ListArray`.
237            let list_array = list_from_list_view(listview_with_converted_elements, ctx)?;
238            list_array.into_array()
239        }
240        Canonical::FixedSizeList(fixed_size_list) => {
241            let converted_elements =
242                recursive_list_from_list_view(fixed_size_list.elements().clone(), ctx)?;
243
244            // Avoid cloning if elements didn't change.
245            if !ArrayRef::ptr_eq(&converted_elements, fixed_size_list.elements()) {
246                FixedSizeListArray::try_new(
247                    converted_elements,
248                    fixed_size_list.list_size(),
249                    fixed_size_list.validity()?,
250                    fixed_size_list.len(),
251                )
252                .vortex_expect(
253                    "FixedSizeListArray reconstruction should not fail with valid components",
254                )
255                .into_array()
256            } else {
257                fixed_size_list.into_array()
258            }
259        }
260        Canonical::Struct(struct_array) => {
261            let mut converted_fields =
262                Vec::with_capacity(struct_array.iter_unmasked_fields().len());
263            let mut any_changed = false;
264
265            for field in struct_array.iter_unmasked_fields() {
266                let converted_field = recursive_list_from_list_view(field.clone(), ctx)?;
267                // Avoid cloning if elements didn't change.
268                any_changed |= !ArrayRef::ptr_eq(&converted_field, field);
269                converted_fields.push(converted_field);
270            }
271
272            if any_changed {
273                StructArray::try_new(
274                    struct_array.names().clone(),
275                    converted_fields,
276                    struct_array.len(),
277                    struct_array.validity()?,
278                )
279                .vortex_expect("StructArray reconstruction should not fail with valid components")
280                .into_array()
281            } else {
282                struct_array.into_array()
283            }
284        }
285        Canonical::Extension(ext_array) => {
286            let converted_storage =
287                recursive_list_from_list_view(ext_array.storage_array().clone(), ctx)?;
288
289            // Avoid cloning if elements didn't change.
290            if !ArrayRef::ptr_eq(&converted_storage, ext_array.storage_array()) {
291                ExtensionArray::new(ext_array.ext_dtype().clone(), converted_storage).into_array()
292            } else {
293                ext_array.into_array()
294            }
295        }
296        _ => unreachable!(),
297    })
298}
299
300#[cfg(test)]
301mod tests {
302
303    use vortex_buffer::buffer;
304    use vortex_error::VortexExpect;
305    use vortex_error::VortexResult;
306
307    use super::super::tests::common::SESSION;
308    use super::super::tests::common::create_basic_listview;
309    use super::super::tests::common::create_empty_lists_listview;
310    use super::super::tests::common::create_nullable_listview;
311    use super::super::tests::common::create_overlapping_listview;
312    use super::recursive_list_from_list_view;
313    use crate::ArrayEq;
314    use crate::ArrayRef;
315    use crate::EqMode;
316    use crate::IntoArray;
317    use crate::VortexSessionExecute;
318    use crate::arrays::BoolArray;
319    use crate::arrays::FixedSizeList;
320    use crate::arrays::FixedSizeListArray;
321    use crate::arrays::List;
322    use crate::arrays::ListArray;
323    use crate::arrays::ListViewArray;
324    use crate::arrays::PrimitiveArray;
325    use crate::arrays::Struct;
326    use crate::arrays::StructArray;
327    use crate::arrays::VarBinViewArray;
328    use crate::arrays::fixed_size_list::FixedSizeListArraySlotsExt;
329    use crate::arrays::list::ListArrayExt;
330    use crate::arrays::list::ListArraySlotsExt;
331    use crate::arrays::listview::ListViewArraySlotsExt;
332    use crate::arrays::listview::list_from_list_view;
333    use crate::arrays::listview::list_view_from_list;
334    use crate::arrays::struct_::StructArrayExt;
335    use crate::assert_arrays_eq;
336    use crate::dtype::FieldNames;
337    use crate::validity::Validity;
338
339    #[test]
340    fn test_list_to_listview_basic() -> VortexResult<()> {
341        let mut ctx = SESSION.create_execution_ctx();
342        // Create a basic ListArray: [[0,1,2], [3,4], [5,6], [7,8,9]].
343        let elements = buffer![0i32, 1, 2, 3, 4, 5, 6, 7, 8, 9].into_array();
344        let offsets = buffer![0u32, 3, 5, 7, 10].into_array();
345        let list_array =
346            ListArray::try_new(elements.clone(), offsets, Validity::NonNullable, &mut ctx)?;
347
348        let list_view = list_view_from_list(list_array.clone(), &mut ctx)?;
349
350        // Verify structure.
351        assert_eq!(list_view.len(), 4);
352        assert_arrays_eq!(list_view.elements().clone(), elements, &mut ctx);
353
354        // Verify offsets (should be same but without last element).
355        let expected_offsets = buffer![0u32, 3, 5, 7].into_array();
356        assert_arrays_eq!(list_view.offsets().clone(), expected_offsets, &mut ctx);
357
358        // Verify sizes.
359        let expected_sizes = buffer![3u32, 2, 2, 3].into_array();
360        assert_arrays_eq!(list_view.sizes().clone(), expected_sizes, &mut ctx);
361
362        // Verify data integrity.
363        assert_arrays_eq!(list_view, list_array, &mut ctx);
364        Ok(())
365    }
366
367    #[test]
368    fn test_list_to_listview_resets_nonzero_offsets() -> VortexResult<()> {
369        let mut ctx = SESSION.create_execution_ctx();
370        let elements = buffer![0i32, 1, 2, 3, 4].into_array();
371        let offsets = buffer![2u16, 4, 5].into_array();
372        let list = ListArray::try_new(elements, offsets, Validity::NonNullable, &mut ctx)?;
373
374        let list_view = list_view_from_list(list.clone(), &mut ctx)?;
375
376        assert_arrays_eq!(
377            list_view.offsets().clone(),
378            buffer![0u16, 2].into_array(),
379            &mut ctx
380        );
381        assert_arrays_eq!(list_view, list, &mut ctx);
382        Ok(())
383    }
384
385    #[test]
386    fn test_listview_to_list_zero_copy() -> VortexResult<()> {
387        let mut ctx = SESSION.create_execution_ctx();
388        let list_view = create_basic_listview();
389        let list_array =
390            list_from_list_view(list_view.clone(), &mut SESSION.create_execution_ctx())?;
391
392        // Should have same elements.
393        assert_arrays_eq!(
394            list_array.elements().clone(),
395            list_view.elements().clone(),
396            &mut ctx
397        );
398
399        // ListArray offsets should have n+1 elements for n lists (add the final offset).
400        // Check that the first n offsets match.
401        let list_array_offsets_without_last = list_array.offsets().slice(0..list_view.len())?;
402        assert_arrays_eq!(
403            list_array_offsets_without_last,
404            list_view.offsets().clone(),
405            &mut ctx
406        );
407
408        // Verify data integrity.
409        assert_arrays_eq!(list_array, list_view, &mut ctx);
410        Ok(())
411    }
412
413    #[test]
414    fn test_empty_array_conversions() -> VortexResult<()> {
415        let mut ctx = SESSION.create_execution_ctx();
416        // Empty ListArray to ListViewArray.
417        let empty_elements = PrimitiveArray::from_iter::<[i32; 0]>([]).into_array();
418        let empty_offsets = buffer![0u32].into_array();
419        let empty_list = ListArray::try_new(
420            empty_elements,
421            empty_offsets,
422            Validity::NonNullable,
423            &mut ctx,
424        )?;
425
426        // This conversion will create an empty ListViewArray.
427        // Note: list_view_from_list handles the empty case specially.
428        let mut ctx = SESSION.create_execution_ctx();
429        let empty_list_view = list_view_from_list(empty_list.clone(), &mut ctx)?;
430        assert_eq!(empty_list_view.len(), 0);
431
432        // Convert back.
433        assert_arrays_eq!(empty_list_view, empty_list, &mut ctx);
434        let converted_back = list_from_list_view(empty_list_view, &mut ctx)?;
435        assert_eq!(converted_back.len(), 0);
436        assert_arrays_eq!(converted_back, empty_list, &mut ctx);
437        Ok(())
438    }
439
440    #[test]
441    fn test_nullable_conversions() -> VortexResult<()> {
442        let mut ctx = SESSION.create_execution_ctx();
443        // Create nullable ListArray: [[10,20], null, [50]].
444        let elements = buffer![10i32, 20, 30, 40, 50].into_array();
445        let offsets = buffer![0u32, 2, 4, 5].into_array();
446        let validity = Validity::Array(BoolArray::from_iter(vec![true, false, true]).into_array());
447        let nullable_list = ListArray::try_new(elements, offsets, validity.clone(), &mut ctx)?;
448
449        let nullable_list_view = list_view_from_list(nullable_list.clone(), &mut ctx)?;
450
451        // Verify validity is preserved.
452        assert!(
453            nullable_list_view
454                .validity()
455                .vortex_expect("listview validity should be derivable")
456                .array_eq(&validity, EqMode::Ptr)
457        );
458        assert_eq!(nullable_list_view.len(), 3);
459
460        // Round-trip conversion.
461        let converted_back = list_from_list_view(nullable_list_view, &mut ctx)?;
462        assert_arrays_eq!(converted_back, nullable_list, &mut ctx);
463        Ok(())
464    }
465
466    #[test]
467    fn test_non_zero_copy_listview_to_list() -> VortexResult<()> {
468        let mut ctx = SESSION.create_execution_ctx();
469        // Create ListViewArray with overlapping lists (not zero-copyable).
470        let list_view = create_overlapping_listview();
471        let list_array =
472            list_from_list_view(list_view.clone(), &mut SESSION.create_execution_ctx())?;
473
474        // The resulting ListArray should have monotonic offsets.
475        for i in 0..list_array.len() {
476            let start = list_array.offset_at(i, &mut ctx)?;
477            let end = list_array.offset_at(i + 1, &mut ctx)?;
478            assert!(end >= start, "Offsets should be monotonic after conversion");
479        }
480
481        // The data should still be correct even though it required a rebuild.
482        assert_arrays_eq!(list_array, list_view, &mut ctx);
483        Ok(())
484    }
485
486    #[test]
487    fn test_empty_sublists() -> VortexResult<()> {
488        let mut ctx = SESSION.create_execution_ctx();
489        let empty_lists_view = create_empty_lists_listview();
490
491        // Convert to ListArray.
492        let list_array = list_from_list_view(empty_lists_view.clone(), &mut ctx)?;
493        assert_eq!(list_array.len(), 4);
494
495        // All sublists should be empty.
496        for i in 0..list_array.len() {
497            assert_eq!(list_array.list_elements_at(i, &mut ctx)?.len(), 0);
498        }
499
500        // Round-trip.
501        let converted_back = list_view_from_list(list_array, &mut ctx)?;
502        assert_arrays_eq!(converted_back, empty_lists_view, &mut ctx);
503        Ok(())
504    }
505
506    #[test]
507    fn test_different_offset_types() -> VortexResult<()> {
508        let mut ctx = SESSION.create_execution_ctx();
509        // Test with i32 offsets.
510        let elements = buffer![1i32, 2, 3, 4, 5].into_array();
511        let i32_offsets = buffer![0i32, 2, 5].into_array();
512        let list_i32 = ListArray::try_new(
513            elements.clone(),
514            i32_offsets.clone(),
515            Validity::NonNullable,
516            &mut ctx,
517        )?;
518
519        let list_view_i32 = list_view_from_list(list_i32.clone(), &mut ctx)?;
520        assert_eq!(list_view_i32.offsets().dtype(), i32_offsets.dtype());
521        assert_eq!(list_view_i32.sizes().dtype(), i32_offsets.dtype());
522
523        // Test with i64 offsets.
524        let i64_offsets = buffer![0i64, 2, 5].into_array();
525        let list_i64 = ListArray::try_new(
526            elements,
527            i64_offsets.clone(),
528            Validity::NonNullable,
529            &mut ctx,
530        )?;
531
532        let list_view_i64 = list_view_from_list(list_i64.clone(), &mut ctx)?;
533        assert_eq!(list_view_i64.offsets().dtype(), i64_offsets.dtype());
534        assert_eq!(list_view_i64.sizes().dtype(), i64_offsets.dtype());
535
536        // Verify data integrity.
537        assert_arrays_eq!(list_view_i32, list_i32, &mut ctx);
538        assert_arrays_eq!(list_view_i64, list_i64, &mut ctx);
539        Ok(())
540    }
541
542    #[test]
543    fn test_round_trip_conversions() -> VortexResult<()> {
544        let mut ctx = SESSION.create_execution_ctx();
545
546        // Test 1: Basic round-trip.
547        let original = create_basic_listview();
548        let to_list = list_from_list_view(original.clone(), &mut ctx)?;
549        let back_to_view = list_view_from_list(to_list, &mut ctx)?;
550        assert_arrays_eq!(back_to_view, original, &mut ctx);
551
552        // Test 2: Nullable round-trip.
553        let nullable = create_nullable_listview();
554        let nullable_to_list = list_from_list_view(nullable.clone(), &mut ctx)?;
555        let nullable_back = list_view_from_list(nullable_to_list, &mut ctx)?;
556        assert_arrays_eq!(nullable_back, nullable, &mut ctx);
557
558        // Test 3: Non-zero-copyable round-trip.
559        let overlapping = create_overlapping_listview();
560
561        let overlapping_to_list = list_from_list_view(overlapping.clone(), &mut ctx)?;
562        let overlapping_back = list_view_from_list(overlapping_to_list, &mut ctx)?;
563        assert_arrays_eq!(overlapping_back, overlapping, &mut ctx);
564        Ok(())
565    }
566
567    #[test]
568    fn test_single_element_lists() -> VortexResult<()> {
569        let mut ctx = SESSION.create_execution_ctx();
570        // Create lists with single elements: [[100], [200], [300]].
571        let elements = buffer![100i32, 200, 300].into_array();
572        let offsets = buffer![0u32, 1, 2, 3].into_array();
573        let single_elem_list =
574            ListArray::try_new(elements, offsets, Validity::NonNullable, &mut ctx)?;
575
576        let list_view = list_view_from_list(single_elem_list.clone(), &mut ctx)?;
577        assert_eq!(list_view.len(), 3);
578
579        // Verify sizes are all 1.
580        let expected_sizes = buffer![1u32, 1, 1].into_array();
581        assert_arrays_eq!(list_view.sizes().clone(), expected_sizes, &mut ctx);
582
583        // Round-trip.
584        let converted_back = list_from_list_view(list_view, &mut ctx)?;
585        assert_arrays_eq!(converted_back, single_elem_list, &mut ctx);
586        Ok(())
587    }
588
589    #[test]
590    fn test_mixed_empty_and_non_empty_lists() -> VortexResult<()> {
591        let mut ctx = SESSION.create_execution_ctx();
592        // Create: [[1,2], [], [3], [], [4,5,6]].
593        let elements = buffer![1i32, 2, 3, 4, 5, 6].into_array();
594        let offsets = buffer![0u32, 2, 2, 3, 3, 6].into_array();
595        let mixed_list = ListArray::try_new(elements, offsets, Validity::NonNullable, &mut ctx)?;
596
597        let list_view = list_view_from_list(mixed_list.clone(), &mut ctx)?;
598        assert_eq!(list_view.len(), 5);
599
600        // Verify sizes.
601        let expected_sizes = buffer![2u32, 0, 1, 0, 3].into_array();
602        assert_arrays_eq!(list_view.sizes().clone(), expected_sizes, &mut ctx);
603
604        // Round-trip.
605        let converted_back = list_from_list_view(list_view, &mut ctx)?;
606        assert_arrays_eq!(converted_back, mixed_list, &mut ctx);
607        Ok(())
608    }
609
610    #[test]
611    fn test_recursive_simple_listview() -> VortexResult<()> {
612        let mut ctx = SESSION.create_execution_ctx();
613        let list_view = create_basic_listview();
614        let result = recursive_list_from_list_view(
615            list_view.clone().into_array(),
616            &mut SESSION.create_execution_ctx(),
617        )?;
618
619        assert!(result.is::<List>());
620        assert_eq!(result.len(), list_view.len());
621        assert_arrays_eq!(result, list_view.into_array(), &mut ctx);
622        Ok(())
623    }
624
625    #[test]
626    fn test_recursive_nested_listview() -> VortexResult<()> {
627        let mut ctx = SESSION.create_execution_ctx();
628        let inner_elements = buffer![1i32, 2, 3].into_array();
629        let inner_offsets = buffer![0u32, 2].into_array();
630        let inner_sizes = buffer![2u32, 1].into_array();
631        let inner_listview = unsafe {
632            ListViewArray::new_unchecked(
633                inner_elements,
634                inner_offsets,
635                inner_sizes,
636                Validity::NonNullable,
637            )
638            .with_zero_copy_to_list(true)
639        };
640
641        let outer_offsets = buffer![0u32, 1].into_array();
642        let outer_sizes = buffer![1u32, 1].into_array();
643        let outer_listview = unsafe {
644            ListViewArray::new_unchecked(
645                inner_listview.into_array(),
646                outer_offsets,
647                outer_sizes,
648                Validity::NonNullable,
649            )
650            .with_zero_copy_to_list(true)
651        };
652
653        let result = recursive_list_from_list_view(
654            outer_listview.clone().into_array(),
655            &mut SESSION.create_execution_ctx(),
656        )?;
657
658        assert!(result.as_::<List>().elements().is::<List>());
659        assert_eq!(result.len(), 2);
660        assert_arrays_eq!(result, outer_listview.into_array(), &mut ctx);
661        Ok(())
662    }
663
664    #[test]
665    fn test_recursive_struct_with_listview_fields() -> VortexResult<()> {
666        let mut ctx = SESSION.create_execution_ctx();
667        let listview_field = create_basic_listview().into_array();
668        let primitive_field = buffer![10i32, 20, 30, 40].into_array();
669
670        let struct_array = StructArray::try_new(
671            FieldNames::from(["lists", "values"]),
672            vec![listview_field, primitive_field],
673            4,
674            Validity::NonNullable,
675        )?;
676
677        let result = recursive_list_from_list_view(
678            struct_array.clone().into_array(),
679            &mut SESSION.create_execution_ctx(),
680        )?;
681
682        assert!(
683            result
684                .as_::<Struct>()
685                .unmasked_field_by_name("lists")?
686                .is::<List>()
687        );
688        assert_eq!(result.len(), 4);
689        assert_arrays_eq!(result, struct_array.into_array(), &mut ctx);
690        Ok(())
691    }
692
693    #[test]
694    fn test_recursive_fixed_size_list_with_listview_elements() -> VortexResult<()> {
695        let mut ctx = SESSION.create_execution_ctx();
696        let lv1_elements = buffer![1i32, 2].into_array();
697        let lv1_offsets = buffer![0u32].into_array();
698        let lv1_sizes = buffer![2u32].into_array();
699        let lv1 = unsafe {
700            ListViewArray::new_unchecked(
701                lv1_elements,
702                lv1_offsets,
703                lv1_sizes,
704                Validity::NonNullable,
705            )
706            .with_zero_copy_to_list(true)
707        };
708
709        let lv2_elements = buffer![3i32, 4].into_array();
710        let lv2_offsets = buffer![0u32].into_array();
711        let lv2_sizes = buffer![2u32].into_array();
712        let lv2 = unsafe {
713            ListViewArray::new_unchecked(
714                lv2_elements,
715                lv2_offsets,
716                lv2_sizes,
717                Validity::NonNullable,
718            )
719            .with_zero_copy_to_list(true)
720        };
721
722        let dtype = lv1.dtype().clone();
723        let chunked_listviews =
724            crate::arrays::ChunkedArray::try_new(vec![lv1.into_array(), lv2.into_array()], dtype)?;
725
726        let fixed_list =
727            FixedSizeListArray::new(chunked_listviews.into_array(), 1, Validity::NonNullable, 2);
728
729        let result = recursive_list_from_list_view(
730            fixed_list.clone().into_array(),
731            &mut SESSION.create_execution_ctx(),
732        )?;
733
734        assert!(result.as_::<FixedSizeList>().elements().is::<List>());
735        assert_eq!(result.len(), 2);
736        assert_arrays_eq!(result, fixed_list.into_array(), &mut ctx);
737        Ok(())
738    }
739
740    #[test]
741    fn test_recursive_deep_nesting() -> VortexResult<()> {
742        let mut ctx = SESSION.create_execution_ctx();
743        let innermost_elements = buffer![1i32, 2, 3].into_array();
744        let innermost_offsets = buffer![0u32, 2].into_array();
745        let innermost_sizes = buffer![2u32, 1].into_array();
746        let innermost_listview = unsafe {
747            ListViewArray::new_unchecked(
748                innermost_elements,
749                innermost_offsets,
750                innermost_sizes,
751                Validity::NonNullable,
752            )
753            .with_zero_copy_to_list(true)
754        };
755
756        let struct_array = StructArray::try_new(
757            FieldNames::from(["inner_lists"]),
758            vec![innermost_listview.into_array()],
759            2,
760            Validity::NonNullable,
761        )?;
762
763        let outer_offsets = buffer![0u32, 1].into_array();
764        let outer_sizes = buffer![1u32, 1].into_array();
765        let outer_listview = unsafe {
766            ListViewArray::new_unchecked(
767                struct_array.into_array(),
768                outer_offsets,
769                outer_sizes,
770                Validity::NonNullable,
771            )
772            .with_zero_copy_to_list(true)
773        };
774
775        let result = recursive_list_from_list_view(
776            outer_listview.clone().into_array(),
777            &mut SESSION.create_execution_ctx(),
778        )?;
779
780        assert!(
781            result
782                .as_::<List>()
783                .elements()
784                .as_::<Struct>()
785                .unmasked_field_by_name("inner_lists")?
786                .is::<List>()
787        );
788        assert_eq!(result.len(), 2);
789        assert_arrays_eq!(result, outer_listview.into_array(), &mut ctx);
790        Ok(())
791    }
792
793    #[test]
794    fn test_recursive_primitive_unchanged() -> VortexResult<()> {
795        let prim = buffer![1i32, 2, 3].into_array();
796        let prim_clone = prim.clone();
797        let result = recursive_list_from_list_view(prim, &mut SESSION.create_execution_ctx())?;
798
799        assert!(ArrayRef::ptr_eq(&result, &prim_clone));
800        Ok(())
801    }
802
803    #[test]
804    fn test_recursive_mixed_listview_and_list() -> VortexResult<()> {
805        let mut ctx = SESSION.create_execution_ctx();
806        let listview = create_basic_listview();
807        let list = list_from_list_view(listview.clone(), &mut ctx)?;
808
809        let struct_array = StructArray::try_new(
810            FieldNames::from(["listview_field", "list_field"]),
811            vec![listview.into_array(), list.into_array()],
812            4,
813            Validity::NonNullable,
814        )?;
815
816        let result = recursive_list_from_list_view(struct_array.clone().into_array(), &mut ctx)?;
817
818        assert!(
819            result
820                .as_::<Struct>()
821                .unmasked_field_by_name("listview_field")?
822                .is::<List>()
823        );
824        assert!(
825            result
826                .as_::<Struct>()
827                .unmasked_field_by_name("list_field")?
828                .is::<List>()
829        );
830        assert_eq!(result.len(), 4);
831        assert_arrays_eq!(result, struct_array.into_array(), &mut ctx);
832        Ok(())
833    }
834
835    /// Regression test for <https://github.com/vortex-data/vortex/issues/6882>.
836    ///
837    /// An empty `ListViewArray` constructed via `try_new` has `is_zero_copy_to_list: false`.
838    /// `list_from_list_view` should still succeed because empty arrays are trivially
839    /// zero-copyable.
840    #[test]
841    fn test_empty_listview_to_list_without_zctl_flag() -> VortexResult<()> {
842        let mut ctx = SESSION.create_execution_ctx();
843        let elements = VarBinViewArray::from_iter_str(Vec::<&str>::new()).into_array();
844        let offsets = PrimitiveArray::from_iter(Vec::<i16>::new()).into_array();
845        let sizes = PrimitiveArray::from_iter(Vec::<i16>::new()).into_array();
846        let list_view =
847            ListViewArray::try_new(elements, offsets, sizes, Validity::AllValid, &mut ctx)?;
848
849        // `try_new` sets `is_zero_copy_to_list: false`.
850        assert!(!list_view.is_zero_copy_to_list());
851
852        let list_array = list_from_list_view(list_view, &mut SESSION.create_execution_ctx())?;
853        assert_eq!(list_array.len(), 0);
854        Ok(())
855    }
856}