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