Skip to main content

arrow_array/array/
list_view_array.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use arrow_buffer::{Buffer, NullBuffer, ScalarBuffer};
6use arrow_data::{ArrayData, ArrayDataBuilder};
7use arrow_schema::{ArrowError, DataType, FieldRef};
8use std::any::Any;
9use std::ops::Add;
10use std::sync::Arc;
11
12use crate::array::{make_array, print_long_array};
13use crate::builder::{GenericListViewBuilder, PrimitiveBuilder};
14use crate::iterator::GenericListViewArrayIter;
15use crate::{
16    Array, ArrayAccessor, ArrayRef, ArrowPrimitiveType, FixedSizeListArray, GenericListArray,
17    OffsetSizeTrait, new_empty_array,
18};
19
20/// A [`GenericListViewArray`] of variable size lists, storing offsets as `i32`.
21pub type ListViewArray = GenericListViewArray<i32>;
22
23/// A [`GenericListViewArray`] of variable size lists, storing offsets as `i64`.
24pub type LargeListViewArray = GenericListViewArray<i64>;
25
26/// An array of [variable length lists], specifically in the [list-view layout].
27///
28/// Differs from [`GenericListArray`] (which represents the [list layout]) in that
29/// the sizes of the child arrays are explicitly encoded in a separate buffer, instead
30/// of being derived from the difference between subsequent offsets in the offset buffer.
31///
32/// This allows the offsets (and subsequently child data) to be out of order. It also
33/// allows take / filter operations to be implemented without copying the underlying data.
34///
35/// # Representation
36///
37/// Given the same example array from [`GenericListArray`], it would be represented
38/// as such via a list-view layout array:
39///
40/// ```text
41///                                         ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
42///                                                                         ┌ ─ ─ ─ ─ ─ ─ ┐    │
43///  ┌─────────────┐  ┌───────┐             │     ┌───┐   ┌───┐   ┌───┐       ┌───┐ ┌───┐
44///  │   [A,B,C]   │  │ (0,3) │                   │ 1 │   │ 0 │   │ 3 │     │ │ 1 │ │ A │ │ 0  │
45///  ├─────────────┤  ├───────┤             │     ├───┤   ├───┤   ├───┤       ├───┤ ├───┤
46///  │      []     │  │ (3,0) │                   │ 1 │   │ 3 │   │ 0 │     │ │ 1 │ │ B │ │ 1  │
47///  ├─────────────┤  ├───────┤             │     ├───┤   ├───┤   ├───┤       ├───┤ ├───┤
48///  │    NULL     │  │ (?,?) │                   │ 0 │   │ ? │   │ ? │     │ │ 1 │ │ C │ │ 2  │
49///  ├─────────────┤  ├───────┤             │     ├───┤   ├───┤   ├───┤       ├───┤ ├───┤
50///  │     [D]     │  │ (4,1) │                   │ 1 │   │ 4 │   │ 1 │     │ │ ? │ │ ? │ │ 3  │
51///  ├─────────────┤  ├───────┤             │     ├───┤   ├───┤   ├───┤       ├───┤ ├───┤
52///  │  [NULL, F]  │  │ (5,2) │                   │ 1 │   │ 5 │   │ 2 │     │ │ 1 │ │ D │ │ 4  │
53///  └─────────────┘  └───────┘             │     └───┘   └───┘   └───┘       ├───┤ ├───┤
54///                                                                         │ │ 0 │ │ ? │ │ 5  │
55///     Logical       Logical               │  Validity  Offsets  Sizes       ├───┤ ├───┤
56///      Values       Offset                   (nulls)                      │ │ 1 │ │ F │ │ 6  │
57///                   & Size                │                                 └───┘ └───┘
58///                                                                         │    Values   │    │
59///                 (offsets[i],            │   ListViewArray                   (Array)
60///                  sizes[i])                                              └ ─ ─ ─ ─ ─ ─ ┘    │
61///                                         └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
62/// ```
63///
64/// Another way of representing the same array but taking advantage of the offsets being out of order:
65///
66/// ```text
67///                                         ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
68///                                                                         ┌ ─ ─ ─ ─ ─ ─ ┐    │
69///  ┌─────────────┐  ┌───────┐             │     ┌───┐   ┌───┐   ┌───┐       ┌───┐ ┌───┐
70///  │   [A,B,C]   │  │ (2,3) │                   │ 1 │   │ 2 │   │ 3 │     │ │ 0 │ │ ? │ │ 0  │
71///  ├─────────────┤  ├───────┤             │     ├───┤   ├───┤   ├───┤       ├───┤ ├───┤
72///  │      []     │  │ (0,0) │                   │ 1 │   │ 0 │   │ 0 │     │ │ 1 │ │ F │ │ 1  │
73///  ├─────────────┤  ├───────┤             │     ├───┤   ├───┤   ├───┤       ├───┤ ├───┤
74///  │    NULL     │  │ (?,?) │                   │ 0 │   │ ? │   │ ? │     │ │ 1 │ │ A │ │ 2  │
75///  ├─────────────┤  ├───────┤             │     ├───┤   ├───┤   ├───┤       ├───┤ ├───┤
76///  │     [D]     │  │ (5,1) │                   │ 1 │   │ 5 │   │ 1 │     │ │ 1 │ │ B │ │ 3  │
77///  ├─────────────┤  ├───────┤             │     ├───┤   ├───┤   ├───┤       ├───┤ ├───┤
78///  │  [NULL, F]  │  │ (0,2) │                   │ 1 │   │ 0 │   │ 2 │     │ │ 1 │ │ C │ │ 4  │
79///  └─────────────┘  └───────┘             │     └───┘   └───┘   └───┘       ├───┤ ├───┤
80///                                                                         │ │ 1 │ │ D │ │ 5  │
81///     Logical       Logical               │  Validity  Offsets  Sizes       └───┘ └───┘
82///      Values       Offset                   (nulls)                      │    Values   │    │
83///                   & Size                │                                   (Array)
84///                                                                         └ ─ ─ ─ ─ ─ ─ ┘    │
85///                 (offsets[i],            │   ListViewArray
86///                  sizes[i])                                                                 │
87///                                         └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
88/// ```
89///
90/// [`GenericListArray`]: crate::array::GenericListArray
91/// [variable length lists]: https://arrow.apache.org/docs/format/Columnar.html#variable-size-list-layout
92/// [list layout]: https://arrow.apache.org/docs/format/Columnar.html#list-layout
93/// [list-view layout]: https://arrow.apache.org/docs/format/Columnar.html#listview-layout
94#[derive(Clone)]
95pub struct GenericListViewArray<OffsetSize: OffsetSizeTrait> {
96    data_type: DataType,
97    nulls: Option<NullBuffer>,
98    values: ArrayRef,
99    // Unlike GenericListArray, we do not use OffsetBuffer here as offsets are not
100    // guaranteed to be monotonically increasing.
101    value_offsets: ScalarBuffer<OffsetSize>,
102    value_sizes: ScalarBuffer<OffsetSize>,
103}
104
105impl<OffsetSize: OffsetSizeTrait> GenericListViewArray<OffsetSize> {
106    /// The data type constructor of listview array.
107    /// The input is the schema of the child array and
108    /// the output is the [`DataType`], ListView or LargeListView.
109    pub const DATA_TYPE_CONSTRUCTOR: fn(FieldRef) -> DataType = if OffsetSize::IS_LARGE {
110        DataType::LargeListView
111    } else {
112        DataType::ListView
113    };
114
115    /// Create a new [`GenericListViewArray`] from the provided parts
116    ///
117    /// # Errors
118    ///
119    /// Errors if
120    ///
121    /// * `offsets.len() != sizes.len()`
122    /// * `offsets.len() != nulls.len()`
123    /// * `offsets[i] > values.len()`
124    /// * `!field.is_nullable() && values.logical_null_count() != 0`
125    /// * `field.data_type() != values.data_type()`
126    /// * `0 <= offsets[i] <= length of the child array`
127    /// * `0 <= offsets[i] + size[i] <= length of the child array`
128    pub fn try_new(
129        field: FieldRef,
130        offsets: ScalarBuffer<OffsetSize>,
131        sizes: ScalarBuffer<OffsetSize>,
132        values: ArrayRef,
133        nulls: Option<NullBuffer>,
134    ) -> Result<Self, ArrowError> {
135        let len = offsets.len();
136        if let Some(n) = nulls.as_ref()
137            && n.len() != len
138        {
139            return Err(ArrowError::InvalidArgumentError(format!(
140                "Incorrect length of null buffer for {}ListViewArray, expected {len} got {}",
141                OffsetSize::PREFIX,
142                n.len(),
143            )));
144        }
145        if len != sizes.len() {
146            return Err(ArrowError::InvalidArgumentError(format!(
147                "Length of offsets buffer and sizes buffer must be equal for {}ListViewArray, got {len} and {}",
148                OffsetSize::PREFIX,
149                sizes.len()
150            )));
151        }
152
153        for (offset, size) in offsets.iter().zip(sizes.iter()) {
154            let offset = offset.as_usize();
155            let size = size.as_usize();
156            if offset.checked_add(size).ok_or_else(|| {
157                ArrowError::InvalidArgumentError(format!(
158                    "Overflow in offset + size for {}ListViewArray",
159                    OffsetSize::PREFIX
160                ))
161            })? > values.len()
162            {
163                return Err(ArrowError::InvalidArgumentError(format!(
164                    "Offset + size for {}ListViewArray must be within the bounds of the child array, got offset: {offset}, size: {size}, child array length: {}",
165                    OffsetSize::PREFIX,
166                    values.len()
167                )));
168            }
169        }
170
171        if !field.is_nullable() && values.logical_null_count() != 0 {
172            return Err(ArrowError::InvalidArgumentError(format!(
173                "Non-nullable field of {}ListViewArray {:?} cannot contain nulls",
174                OffsetSize::PREFIX,
175                field.name()
176            )));
177        }
178
179        if field.data_type() != values.data_type() {
180            return Err(ArrowError::InvalidArgumentError(format!(
181                "{}ListViewArray expected data type {} got {} for {:?}",
182                OffsetSize::PREFIX,
183                field.data_type(),
184                values.data_type(),
185                field.name()
186            )));
187        }
188
189        Ok(Self {
190            data_type: Self::DATA_TYPE_CONSTRUCTOR(field),
191            nulls,
192            values,
193            value_offsets: offsets,
194            value_sizes: sizes,
195        })
196    }
197
198    /// Create a new [`GenericListViewArray`] from the provided parts
199    ///
200    /// # Panics
201    ///
202    /// Panics if [`Self::try_new`] returns an error
203    pub fn new(
204        field: FieldRef,
205        offsets: ScalarBuffer<OffsetSize>,
206        sizes: ScalarBuffer<OffsetSize>,
207        values: ArrayRef,
208        nulls: Option<NullBuffer>,
209    ) -> Self {
210        Self::try_new(field, offsets, sizes, values, nulls).unwrap()
211    }
212
213    /// Create a new [`GenericListViewArray`] from the provided parts without validation
214    ///
215    /// See [`Self::try_new`] for the checked version of this function, and the
216    /// documentation of that function for the invariants that must be upheld.
217    ///
218    /// # Safety
219    ///
220    /// The parts must form a valid [`ListViewArray`] or [`LargeListViewArray`] according
221    /// to the Arrow spec.
222    pub unsafe fn new_unchecked(
223        field: FieldRef,
224        offsets: ScalarBuffer<OffsetSize>,
225        sizes: ScalarBuffer<OffsetSize>,
226        values: ArrayRef,
227        nulls: Option<NullBuffer>,
228    ) -> Self {
229        if cfg!(feature = "force_validate") {
230            return Self::new(field, offsets, sizes, values, nulls);
231        }
232
233        Self {
234            data_type: Self::DATA_TYPE_CONSTRUCTOR(field),
235            nulls,
236            values,
237            value_offsets: offsets,
238            value_sizes: sizes,
239        }
240    }
241
242    /// Create a new [`GenericListViewArray`] of length `len` where all values are null
243    pub fn new_null(field: FieldRef, len: usize) -> Self {
244        let values = new_empty_array(field.data_type());
245        Self {
246            data_type: Self::DATA_TYPE_CONSTRUCTOR(field),
247            nulls: Some(NullBuffer::new_null(len)),
248            value_offsets: ScalarBuffer::from(vec![OffsetSize::usize_as(0); len]),
249            value_sizes: ScalarBuffer::from(vec![OffsetSize::usize_as(0); len]),
250            values,
251        }
252    }
253
254    /// Deconstruct this array into its constituent parts
255    pub fn into_parts(
256        self,
257    ) -> (
258        FieldRef,
259        ScalarBuffer<OffsetSize>,
260        ScalarBuffer<OffsetSize>,
261        ArrayRef,
262        Option<NullBuffer>,
263    ) {
264        let (DataType::ListView(f) | DataType::LargeListView(f)) = self.data_type else {
265            unreachable!()
266        };
267        (
268            f,
269            self.value_offsets,
270            self.value_sizes,
271            self.values,
272            self.nulls,
273        )
274    }
275
276    /// The field that describes the values of this list.
277    pub fn value_field(&self) -> &FieldRef {
278        match &self.data_type {
279            DataType::ListView(f) | DataType::LargeListView(f) => f,
280            _ => unreachable!(),
281        }
282    }
283
284    /// Returns a reference to the offsets of this list
285    ///
286    /// Unlike [`Self::value_offsets`] this returns the [`ScalarBuffer`]
287    /// allowing for zero-copy cloning
288    #[inline]
289    pub fn offsets(&self) -> &ScalarBuffer<OffsetSize> {
290        &self.value_offsets
291    }
292
293    /// Returns a reference to the values of this list
294    #[inline]
295    pub fn values(&self) -> &ArrayRef {
296        &self.values
297    }
298
299    /// Returns a reference to the sizes of this list
300    ///
301    /// Unlike [`Self::value_sizes`] this returns the [`ScalarBuffer`]
302    /// allowing for zero-copy cloning
303    #[inline]
304    pub fn sizes(&self) -> &ScalarBuffer<OffsetSize> {
305        &self.value_sizes
306    }
307
308    /// Returns a clone of the value type of this list.
309    pub fn value_type(&self) -> DataType {
310        self.values.data_type().clone()
311    }
312
313    /// Returns ith value of this list view array.
314    ///
315    /// Note: This method does not check for nulls and the value is arbitrary
316    /// if [`is_null`](Self::is_null) returns true for the index.
317    ///
318    /// # Safety
319    /// Caller must ensure that the index is within the array bounds
320    pub unsafe fn value_unchecked(&self, i: usize) -> ArrayRef {
321        let offset = unsafe { self.value_offsets().get_unchecked(i).as_usize() };
322        let length = unsafe { self.value_sizes().get_unchecked(i).as_usize() };
323        self.values.slice(offset, length)
324    }
325
326    /// Returns ith value of this list view array.
327    ///
328    /// Note: This method does not check for nulls and the value is arbitrary
329    /// (but still well-defined) if [`is_null`](Self::is_null) returns true for the index.
330    ///
331    /// # Panics
332    /// Panics if `i >= self.len()`
333    pub fn value(&self, i: usize) -> ArrayRef {
334        let offset = self.value_offsets()[i].as_usize();
335        let length = self.value_sizes()[i].as_usize();
336        self.values.slice(offset, length)
337    }
338
339    /// Returns the offset values in the offsets buffer
340    #[inline]
341    pub fn value_offsets(&self) -> &[OffsetSize] {
342        &self.value_offsets
343    }
344
345    /// Returns the sizes values in the offsets buffer
346    #[inline]
347    pub fn value_sizes(&self) -> &[OffsetSize] {
348        &self.value_sizes
349    }
350
351    /// Returns the size for value at index `i`.
352    ///
353    /// # Panics
354    /// Panics if `i >= self.len()`
355    #[inline]
356    pub fn value_size(&self, i: usize) -> OffsetSize {
357        self.value_sizes[i]
358    }
359
360    /// Returns the offset for value at index `i`.
361    ///
362    /// # Panics
363    /// Panics if `i >= self.len()`
364    pub fn value_offset(&self, i: usize) -> OffsetSize {
365        self.value_offsets[i]
366    }
367
368    /// Constructs a new iterator
369    pub fn iter(&self) -> GenericListViewArrayIter<'_, OffsetSize> {
370        GenericListViewArrayIter::<'_, OffsetSize>::new(self)
371    }
372
373    #[inline]
374    fn get_type(data_type: &DataType) -> Option<&DataType> {
375        match (OffsetSize::IS_LARGE, data_type) {
376            (true, DataType::LargeListView(child)) | (false, DataType::ListView(child)) => {
377                Some(child.data_type())
378            }
379            _ => None,
380        }
381    }
382
383    /// Returns a zero-copy slice of this array with the indicated offset and length.
384    ///
385    /// # Panics
386    /// Panics if `offset + length > self.len()`
387    pub fn slice(&self, offset: usize, length: usize) -> Self {
388        Self {
389            data_type: self.data_type.clone(),
390            nulls: self.nulls.as_ref().map(|n| n.slice(offset, length)),
391            values: self.values.clone(),
392            value_offsets: self.value_offsets.slice(offset, length),
393            value_sizes: self.value_sizes.slice(offset, length),
394        }
395    }
396
397    /// Creates a [`GenericListViewArray`] from an iterator of primitive values
398    /// # Example
399    /// ```
400    /// # use arrow_array::ListViewArray;
401    /// # use arrow_array::types::Int32Type;
402    ///
403    /// let data = vec![
404    ///    Some(vec![Some(0), Some(1), Some(2)]),
405    ///    None,
406    ///    Some(vec![Some(3), None, Some(5)]),
407    ///    Some(vec![Some(6), Some(7)]),
408    /// ];
409    /// let list_array = ListViewArray::from_iter_primitive::<Int32Type, _, _>(data);
410    /// println!("{:?}", list_array);
411    /// ```
412    pub fn from_iter_primitive<T, P, I>(iter: I) -> Self
413    where
414        T: ArrowPrimitiveType,
415        P: IntoIterator<Item = Option<<T as ArrowPrimitiveType>::Native>>,
416        I: IntoIterator<Item = Option<P>>,
417    {
418        let iter = iter.into_iter();
419        let size_hint = iter.size_hint().0;
420        let mut builder =
421            GenericListViewBuilder::with_capacity(PrimitiveBuilder::<T>::new(), size_hint);
422
423        for i in iter {
424            match i {
425                Some(p) => {
426                    for t in p {
427                        builder.values().append_option(t);
428                    }
429                    builder.append(true);
430                }
431                None => builder.append(false),
432            }
433        }
434        builder.finish()
435    }
436}
437
438impl<'a, OffsetSize: OffsetSizeTrait> IntoIterator for &'a GenericListViewArray<OffsetSize> {
439    type Item = Option<ArrayRef>;
440    type IntoIter = GenericListViewArrayIter<'a, OffsetSize>;
441
442    fn into_iter(self) -> Self::IntoIter {
443        GenericListViewArrayIter::<'a, OffsetSize>::new(self)
444    }
445}
446
447impl<OffsetSize: OffsetSizeTrait> ArrayAccessor for &GenericListViewArray<OffsetSize> {
448    type Item = ArrayRef;
449
450    fn value(&self, index: usize) -> Self::Item {
451        GenericListViewArray::value(self, index)
452    }
453
454    unsafe fn value_unchecked(&self, index: usize) -> Self::Item {
455        unsafe { GenericListViewArray::value_unchecked(self, index) }
456    }
457}
458
459/// SAFETY: Correctly implements the contract of Arrow Arrays
460unsafe impl<OffsetSize: OffsetSizeTrait> Array for GenericListViewArray<OffsetSize> {
461    fn as_any(&self) -> &dyn Any {
462        self
463    }
464
465    fn to_arc(&self) -> ArrayRef {
466        Arc::new(self.clone())
467    }
468
469    fn to_data(&self) -> ArrayData {
470        self.clone().into()
471    }
472
473    fn into_data(self) -> ArrayData {
474        self.into()
475    }
476
477    fn data_type(&self) -> &DataType {
478        &self.data_type
479    }
480
481    fn slice(&self, offset: usize, length: usize) -> ArrayRef {
482        Arc::new(self.slice(offset, length))
483    }
484
485    fn len(&self) -> usize {
486        self.sizes().len()
487    }
488
489    fn is_empty(&self) -> bool {
490        self.value_sizes.is_empty()
491    }
492
493    fn shrink_to_fit(&mut self) {
494        if let Some(nulls) = &mut self.nulls {
495            nulls.shrink_to_fit();
496        }
497        self.values.shrink_to_fit();
498        self.value_offsets.shrink_to_fit();
499        self.value_sizes.shrink_to_fit();
500    }
501
502    fn offset(&self) -> usize {
503        0
504    }
505
506    fn nulls(&self) -> Option<&NullBuffer> {
507        self.nulls.as_ref()
508    }
509
510    fn logical_null_count(&self) -> usize {
511        // More efficient that the default implementation
512        self.null_count()
513    }
514
515    fn get_buffer_memory_size(&self) -> usize {
516        let mut size = self.values.get_buffer_memory_size();
517        size += self.value_offsets.inner().capacity();
518        size += self.value_sizes.inner().capacity();
519        if let Some(n) = self.nulls.as_ref() {
520            size += n.buffer().capacity();
521        }
522        size
523    }
524
525    fn get_array_memory_size(&self) -> usize {
526        let mut size = std::mem::size_of::<Self>() + self.values.get_array_memory_size();
527        size += self.value_offsets.inner().capacity();
528        size += self.value_sizes.inner().capacity();
529        if let Some(n) = self.nulls.as_ref() {
530            size += n.buffer().capacity();
531        }
532        size
533    }
534
535    #[cfg(feature = "pool")]
536    fn claim(&self, pool: &dyn arrow_buffer::MemoryPool) {
537        self.value_offsets.claim(pool);
538        self.value_sizes.claim(pool);
539        self.values.claim(pool);
540        if let Some(nulls) = &self.nulls {
541            nulls.claim(pool);
542        }
543    }
544}
545
546impl<OffsetSize: OffsetSizeTrait> super::ListLikeArray for GenericListViewArray<OffsetSize> {
547    fn values(&self) -> &ArrayRef {
548        self.values()
549    }
550
551    fn element_range(&self, index: usize) -> std::ops::Range<usize> {
552        let offset = self.value_offsets()[index].as_usize();
553        let size = self.value_sizes()[index].as_usize();
554        offset..(offset + size)
555    }
556}
557
558impl<OffsetSize: OffsetSizeTrait> std::fmt::Debug for GenericListViewArray<OffsetSize> {
559    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
560        let prefix = OffsetSize::PREFIX;
561        write!(f, "{prefix}ListViewArray\n[\n")?;
562        print_long_array(self, f, &mut |index, f| {
563            std::fmt::Debug::fmt(&self.value(index), f)
564        })?;
565        write!(f, "]")
566    }
567}
568
569impl<OffsetSize: OffsetSizeTrait> From<GenericListArray<OffsetSize>>
570    for GenericListViewArray<OffsetSize>
571{
572    fn from(value: GenericListArray<OffsetSize>) -> Self {
573        let (field, offsets, values, nulls) = value.into_parts();
574        let len = offsets.len() - 1;
575        let mut sizes = Vec::with_capacity(len);
576        let mut view_offsets = Vec::with_capacity(len);
577        for (i, offset) in offsets.iter().enumerate().take(len) {
578            view_offsets.push(*offset);
579            sizes.push(offsets[i + 1] - offsets[i]);
580        }
581
582        Self::new(
583            field,
584            ScalarBuffer::from(view_offsets),
585            ScalarBuffer::from(sizes),
586            values,
587            nulls,
588        )
589    }
590}
591
592impl<OffsetSize: OffsetSizeTrait> From<GenericListViewArray<OffsetSize>> for ArrayData {
593    fn from(array: GenericListViewArray<OffsetSize>) -> Self {
594        let len = array.len();
595        let builder = ArrayDataBuilder::new(array.data_type)
596            .len(len)
597            .nulls(array.nulls)
598            .buffers(vec![
599                array.value_offsets.into_inner(),
600                array.value_sizes.into_inner(),
601            ])
602            .child_data(vec![array.values.to_data()]);
603
604        unsafe { builder.build_unchecked() }
605    }
606}
607
608impl<OffsetSize: OffsetSizeTrait> From<ArrayData> for GenericListViewArray<OffsetSize> {
609    fn from(data: ArrayData) -> Self {
610        Self::try_new_from_array_data(data)
611            .expect("Expected infallible creation of GenericListViewArray from ArrayDataRef failed")
612    }
613}
614
615impl<OffsetSize: OffsetSizeTrait> From<FixedSizeListArray> for GenericListViewArray<OffsetSize> {
616    fn from(value: FixedSizeListArray) -> Self {
617        let (field, size) = match value.data_type() {
618            DataType::FixedSizeList(f, size) => (f, *size as usize),
619            _ => unreachable!(),
620        };
621        let mut acc = 0_usize;
622        let iter = std::iter::repeat_n(size, value.len());
623        let mut sizes = Vec::with_capacity(iter.size_hint().0);
624        let mut offsets = Vec::with_capacity(iter.size_hint().0);
625
626        for size in iter {
627            offsets.push(OffsetSize::usize_as(acc));
628            acc = acc.add(size);
629            sizes.push(OffsetSize::usize_as(size));
630        }
631        let sizes = ScalarBuffer::from(sizes);
632        let offsets = ScalarBuffer::from(offsets);
633        Self {
634            data_type: Self::DATA_TYPE_CONSTRUCTOR(field.clone()),
635            nulls: value.nulls().cloned(),
636            values: value.values().clone(),
637            value_offsets: offsets,
638            value_sizes: sizes,
639        }
640    }
641}
642
643impl<OffsetSize: OffsetSizeTrait> GenericListViewArray<OffsetSize> {
644    fn try_new_from_array_data(data: ArrayData) -> Result<Self, ArrowError> {
645        let (data_type, len, nulls, offset, buffers, child_data) = data.into_parts();
646
647        // ArrayData is valid, and verified type above
648        // buffer[0] is offsets, buffer[1] is sizes
649        let num_buffers = buffers.len();
650        let [offsets_buffer, sizes_buffer] : [Buffer; 2] = buffers.try_into().map_err(|_| {
651             ArrowError::InvalidArgumentError(format!(
652                "ListViewArray data should contain two buffers (value offsets & value sizes), had {num_buffers}",
653            ))
654        })?;
655
656        let num_child = child_data.len();
657        let [values]: [ArrayData; 1] = child_data.try_into().map_err(|_| {
658            ArrowError::InvalidArgumentError(format!(
659                "ListViewArray should contain a single child array (values array), had {num_child}",
660            ))
661        })?;
662
663        if let Some(child_data_type) = Self::get_type(&data_type) {
664            if values.data_type() != child_data_type {
665                return Err(ArrowError::InvalidArgumentError(format!(
666                    "{}ListViewArray's child datatype {:?} does not \
667                             correspond to the List's datatype {:?}",
668                    OffsetSize::PREFIX,
669                    values.data_type(),
670                    child_data_type
671                )));
672            }
673        } else {
674            return Err(ArrowError::InvalidArgumentError(format!(
675                "{}ListViewArray's datatype must be {}ListViewArray(). It is {:?}",
676                OffsetSize::PREFIX,
677                OffsetSize::PREFIX,
678                data_type
679            )));
680        }
681
682        let values = make_array(values);
683        let value_offsets = ScalarBuffer::new(offsets_buffer, offset, len);
684        let value_sizes = ScalarBuffer::new(sizes_buffer, offset, len);
685
686        Ok(Self {
687            data_type,
688            nulls,
689            values,
690            value_offsets,
691            value_sizes,
692        })
693    }
694}
695
696#[cfg(test)]
697mod tests {
698    use arrow_buffer::{BooleanBuffer, Buffer, NullBufferBuilder, ScalarBuffer, bit_util};
699    use arrow_schema::Field;
700
701    use crate::builder::{FixedSizeListBuilder, Int32Builder};
702    use crate::cast::AsArray;
703    use crate::types::Int32Type;
704    use crate::{Int8Array, Int8DictionaryArray, Int32Array, Int64Array, StringArray};
705
706    use super::*;
707
708    #[test]
709    fn test_empty_list_view_array() {
710        // Construct an empty value array
711        let vec: Vec<i32> = vec![];
712        let field = Arc::new(Field::new_list_field(DataType::Int32, true));
713        let sizes = ScalarBuffer::from(vec![]);
714        let offsets = ScalarBuffer::from(vec![]);
715        let values = Int32Array::from(vec);
716        let list_array = LargeListViewArray::new(field, offsets, sizes, Arc::new(values), None);
717
718        assert_eq!(list_array.len(), 0)
719    }
720
721    #[test]
722    fn test_list_view_array() {
723        // Construct a value array
724        let value_data = ArrayData::builder(DataType::Int32)
725            .len(8)
726            .add_buffer(Buffer::from_slice_ref([0, 1, 2, 3, 4, 5, 6, 7]))
727            .build()
728            .unwrap();
729
730        let field = Arc::new(Field::new_list_field(DataType::Int32, true));
731        let sizes = ScalarBuffer::from(vec![3i32, 3, 2]);
732        let offsets = ScalarBuffer::from(vec![0i32, 3, 6]);
733        let values = Int32Array::from(vec![0, 1, 2, 3, 4, 5, 6, 7]);
734        let list_array = ListViewArray::new(field, offsets, sizes, Arc::new(values), None);
735
736        let values = list_array.values();
737        assert_eq!(value_data, values.to_data());
738        assert_eq!(DataType::Int32, list_array.value_type());
739        assert_eq!(3, list_array.len());
740        assert_eq!(0, list_array.null_count());
741        assert_eq!(6, list_array.value_offsets()[2]);
742        assert_eq!(2, list_array.value_sizes()[2]);
743        assert_eq!(2, list_array.value_size(2));
744        assert_eq!(0, list_array.value(0).as_primitive::<Int32Type>().value(0));
745        assert_eq!(
746            0,
747            unsafe { list_array.value_unchecked(0) }
748                .as_primitive::<Int32Type>()
749                .value(0)
750        );
751        for i in 0..3 {
752            assert!(list_array.is_valid(i));
753            assert!(!list_array.is_null(i));
754        }
755    }
756
757    #[test]
758    fn test_large_list_view_array() {
759        // Construct a value array
760        let value_data = ArrayData::builder(DataType::Int32)
761            .len(8)
762            .add_buffer(Buffer::from_slice_ref([0, 1, 2, 3, 4, 5, 6, 7]))
763            .build()
764            .unwrap();
765
766        let field = Arc::new(Field::new_list_field(DataType::Int32, true));
767        let sizes = ScalarBuffer::from(vec![3i64, 3, 2]);
768        let offsets = ScalarBuffer::from(vec![0i64, 3, 6]);
769        let values = Int32Array::from(vec![0, 1, 2, 3, 4, 5, 6, 7]);
770        let list_array = LargeListViewArray::new(field, offsets, sizes, Arc::new(values), None);
771
772        let values = list_array.values();
773        assert_eq!(value_data, values.to_data());
774        assert_eq!(DataType::Int32, list_array.value_type());
775        assert_eq!(3, list_array.len());
776        assert_eq!(0, list_array.null_count());
777        assert_eq!(6, list_array.value_offsets()[2]);
778        assert_eq!(2, list_array.value_sizes()[2]);
779        assert_eq!(2, list_array.value_size(2));
780        assert_eq!(0, list_array.value(0).as_primitive::<Int32Type>().value(0));
781        assert_eq!(
782            0,
783            unsafe { list_array.value_unchecked(0) }
784                .as_primitive::<Int32Type>()
785                .value(0)
786        );
787        for i in 0..3 {
788            assert!(list_array.is_valid(i));
789            assert!(!list_array.is_null(i));
790        }
791    }
792
793    #[test]
794    fn test_list_view_array_slice() {
795        // Construct a value array
796        let value_data = ArrayData::builder(DataType::Int32)
797            .len(10)
798            .add_buffer(Buffer::from_slice_ref([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
799            .build()
800            .unwrap();
801
802        // 01011001 00000001
803        let mut null_bits: [u8; 2] = [0; 2];
804        bit_util::set_bit(&mut null_bits, 0);
805        bit_util::set_bit(&mut null_bits, 3);
806        bit_util::set_bit(&mut null_bits, 4);
807        bit_util::set_bit(&mut null_bits, 6);
808        bit_util::set_bit(&mut null_bits, 8);
809        let buffer = BooleanBuffer::new(Buffer::from(null_bits), 0, 9);
810        let null_buffer = NullBuffer::new(buffer);
811
812        let field = Arc::new(Field::new_list_field(DataType::Int32, true));
813        let sizes = ScalarBuffer::from(vec![2, 0, 0, 2, 2, 0, 3, 0, 1]);
814        let offsets = ScalarBuffer::from(vec![0, 2, 2, 2, 4, 6, 6, 9, 9]);
815        let values = Int32Array::from(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
816        let list_array =
817            ListViewArray::new(field, offsets, sizes, Arc::new(values), Some(null_buffer));
818
819        let values = list_array.values();
820        assert_eq!(value_data, values.to_data());
821        assert_eq!(DataType::Int32, list_array.value_type());
822        assert_eq!(9, list_array.len());
823        assert_eq!(4, list_array.null_count());
824        assert_eq!(2, list_array.value_offsets()[3]);
825        assert_eq!(2, list_array.value_sizes()[3]);
826        assert_eq!(2, list_array.value_size(3));
827
828        let sliced_array = list_array.slice(1, 6);
829        assert_eq!(6, sliced_array.len());
830        assert_eq!(3, sliced_array.null_count());
831
832        for i in 0..sliced_array.len() {
833            if bit_util::get_bit(&null_bits, 1 + i) {
834                assert!(sliced_array.is_valid(i));
835            } else {
836                assert!(sliced_array.is_null(i));
837            }
838        }
839
840        // Check offset and length for each non-null value.
841        let sliced_list_array = sliced_array
842            .as_any()
843            .downcast_ref::<ListViewArray>()
844            .unwrap();
845        assert_eq!(2, sliced_list_array.value_offsets()[2]);
846        assert_eq!(2, sliced_list_array.value_sizes()[2]);
847        assert_eq!(2, sliced_list_array.value_size(2));
848
849        assert_eq!(4, sliced_list_array.value_offsets()[3]);
850        assert_eq!(2, sliced_list_array.value_sizes()[3]);
851        assert_eq!(2, sliced_list_array.value_size(3));
852
853        assert_eq!(6, sliced_list_array.value_offsets()[5]);
854        assert_eq!(3, sliced_list_array.value_sizes()[5]);
855        assert_eq!(3, sliced_list_array.value_size(5));
856    }
857
858    #[test]
859    fn test_large_list_view_array_slice() {
860        // Construct a value array
861        let value_data = ArrayData::builder(DataType::Int32)
862            .len(10)
863            .add_buffer(Buffer::from_slice_ref([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
864            .build()
865            .unwrap();
866
867        // 01011001 00000001
868        let mut null_bits: [u8; 2] = [0; 2];
869        bit_util::set_bit(&mut null_bits, 0);
870        bit_util::set_bit(&mut null_bits, 3);
871        bit_util::set_bit(&mut null_bits, 4);
872        bit_util::set_bit(&mut null_bits, 6);
873        bit_util::set_bit(&mut null_bits, 8);
874        let buffer = BooleanBuffer::new(Buffer::from(null_bits), 0, 9);
875        let null_buffer = NullBuffer::new(buffer);
876
877        // Construct a large list view array from the above two
878        let field = Arc::new(Field::new_list_field(DataType::Int32, true));
879        let sizes = ScalarBuffer::from(vec![2i64, 0, 0, 2, 2, 0, 3, 0, 1]);
880        let offsets = ScalarBuffer::from(vec![0i64, 2, 2, 2, 4, 6, 6, 9, 9]);
881        let values = Int32Array::from(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
882        let list_array =
883            LargeListViewArray::new(field, offsets, sizes, Arc::new(values), Some(null_buffer));
884
885        let values = list_array.values();
886        assert_eq!(value_data, values.to_data());
887        assert_eq!(DataType::Int32, list_array.value_type());
888        assert_eq!(9, list_array.len());
889        assert_eq!(4, list_array.null_count());
890        assert_eq!(2, list_array.value_offsets()[3]);
891        assert_eq!(2, list_array.value_sizes()[3]);
892        assert_eq!(2, list_array.value_size(3));
893
894        let sliced_array = list_array.slice(1, 6);
895        assert_eq!(6, sliced_array.len());
896        assert_eq!(3, sliced_array.null_count());
897
898        for i in 0..sliced_array.len() {
899            if bit_util::get_bit(&null_bits, 1 + i) {
900                assert!(sliced_array.is_valid(i));
901            } else {
902                assert!(sliced_array.is_null(i));
903            }
904        }
905
906        // Check offset and length for each non-null value.
907        let sliced_list_array = sliced_array
908            .as_any()
909            .downcast_ref::<LargeListViewArray>()
910            .unwrap();
911        assert_eq!(2, sliced_list_array.value_offsets()[2]);
912        assert_eq!(2, sliced_list_array.value_size(2));
913        assert_eq!(2, sliced_list_array.value_sizes()[2]);
914
915        assert_eq!(4, sliced_list_array.value_offsets()[3]);
916        assert_eq!(2, sliced_list_array.value_size(3));
917        assert_eq!(2, sliced_list_array.value_sizes()[3]);
918
919        assert_eq!(6, sliced_list_array.value_offsets()[5]);
920        assert_eq!(3, sliced_list_array.value_size(5));
921        assert_eq!(2, sliced_list_array.value_sizes()[3]);
922    }
923
924    #[test]
925    #[should_panic(expected = "index out of bounds: the len is 9 but the index is 10")]
926    fn test_list_view_array_index_out_of_bound() {
927        // 01011001 00000001
928        let mut null_bits: [u8; 2] = [0; 2];
929        bit_util::set_bit(&mut null_bits, 0);
930        bit_util::set_bit(&mut null_bits, 3);
931        bit_util::set_bit(&mut null_bits, 4);
932        bit_util::set_bit(&mut null_bits, 6);
933        bit_util::set_bit(&mut null_bits, 8);
934        let buffer = BooleanBuffer::new(Buffer::from(null_bits), 0, 9);
935        let null_buffer = NullBuffer::new(buffer);
936
937        // Construct a buffer for value offsets, for the nested array:
938        //  [[0, 1], null, null, [2, 3], [4, 5], null, [6, 7, 8], null, [9]]
939        // Construct a list array from the above two
940        let field = Arc::new(Field::new_list_field(DataType::Int32, true));
941        let sizes = ScalarBuffer::from(vec![2i32, 0, 0, 2, 2, 0, 3, 0, 1]);
942        let offsets = ScalarBuffer::from(vec![0i32, 2, 2, 2, 4, 6, 6, 9, 9]);
943        let values = Int32Array::from(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
944        let list_array =
945            ListViewArray::new(field, offsets, sizes, Arc::new(values), Some(null_buffer));
946
947        assert_eq!(9, list_array.len());
948        list_array.value(10);
949    }
950    #[test]
951    #[should_panic(
952        expected = "ListViewArray data should contain two buffers (value offsets & value sizes), had 0"
953    )]
954    #[cfg(not(feature = "force_validate"))]
955    fn test_list_view_array_invalid_buffer_len() {
956        let value_data = unsafe {
957            ArrayData::builder(DataType::Int32)
958                .len(8)
959                .add_buffer(Buffer::from_slice_ref([0, 1, 2, 3, 4, 5, 6, 7]))
960                .build_unchecked()
961        };
962        let list_data_type =
963            DataType::ListView(Arc::new(Field::new_list_field(DataType::Int32, false)));
964        let list_data = unsafe {
965            ArrayData::builder(list_data_type)
966                .len(3)
967                .add_child_data(value_data)
968                .build_unchecked()
969        };
970        drop(ListViewArray::from(list_data));
971    }
972
973    #[test]
974    #[should_panic(
975        expected = "ListViewArray data should contain two buffers (value offsets & value sizes), had 1"
976    )]
977    #[cfg(not(feature = "force_validate"))]
978    fn test_list_view_array_invalid_child_array_len() {
979        let value_offsets = Buffer::from_slice_ref([0, 2, 5, 7]);
980        let list_data_type =
981            DataType::ListView(Arc::new(Field::new_list_field(DataType::Int32, false)));
982        let list_data = unsafe {
983            ArrayData::builder(list_data_type)
984                .len(3)
985                .add_buffer(value_offsets)
986                .build_unchecked()
987        };
988        drop(ListViewArray::from(list_data));
989    }
990
991    #[test]
992    fn test_list_view_array_offsets_need_not_start_at_zero() {
993        let field = Arc::new(Field::new_list_field(DataType::Int32, true));
994        let sizes = ScalarBuffer::from(vec![0i32, 0, 3]);
995        let offsets = ScalarBuffer::from(vec![2i32, 2, 5]);
996        let values = Int32Array::from(vec![0, 1, 2, 3, 4, 5, 6, 7]);
997        let list_array = ListViewArray::new(field, offsets, sizes, Arc::new(values), None);
998
999        assert_eq!(list_array.value_size(0), 0);
1000        assert_eq!(list_array.value_size(1), 0);
1001        assert_eq!(list_array.value_size(2), 3);
1002    }
1003
1004    #[test]
1005    #[should_panic(expected = "Memory pointer is not aligned with the specified scalar type")]
1006    #[cfg(not(feature = "force_validate"))]
1007    fn test_list_view_array_alignment() {
1008        let offset_buf = Buffer::from_slice_ref([0_u64]);
1009        let offset_buf2 = offset_buf.slice(1);
1010
1011        let size_buf = Buffer::from_slice_ref([0_u64]);
1012        let size_buf2 = size_buf.slice(1);
1013
1014        let values: [i32; 8] = [0; 8];
1015        let value_data = unsafe {
1016            ArrayData::builder(DataType::Int32)
1017                .add_buffer(Buffer::from_slice_ref(values))
1018                .build_unchecked()
1019        };
1020
1021        let list_data_type =
1022            DataType::ListView(Arc::new(Field::new_list_field(DataType::Int32, false)));
1023        let list_data = unsafe {
1024            ArrayData::builder(list_data_type)
1025                .add_buffer(offset_buf2)
1026                .add_buffer(size_buf2)
1027                .add_child_data(value_data)
1028                .build_unchecked()
1029        };
1030        drop(ListViewArray::from(list_data));
1031    }
1032
1033    #[test]
1034    fn test_empty_offsets() {
1035        let f = Arc::new(Field::new("element", DataType::Int32, true));
1036        let string = ListViewArray::from(
1037            ArrayData::builder(DataType::ListView(f.clone()))
1038                .buffers(vec![Buffer::from(&[]), Buffer::from(&[])])
1039                .add_child_data(ArrayData::new_empty(&DataType::Int32))
1040                .build()
1041                .unwrap(),
1042        );
1043        assert_eq!(string.value_offsets(), &[] as &[i32; 0]);
1044        assert_eq!(string.value_sizes(), &[] as &[i32; 0]);
1045
1046        let string = LargeListViewArray::from(
1047            ArrayData::builder(DataType::LargeListView(f))
1048                .buffers(vec![Buffer::from(&[]), Buffer::from(&[])])
1049                .add_child_data(ArrayData::new_empty(&DataType::Int32))
1050                .build()
1051                .unwrap(),
1052        );
1053        assert_eq!(string.len(), 0);
1054        assert_eq!(string.value_offsets(), &[] as &[i64; 0]);
1055        assert_eq!(string.value_sizes(), &[] as &[i64; 0]);
1056    }
1057
1058    #[test]
1059    fn test_try_new() {
1060        let offsets = ScalarBuffer::from(vec![0, 1, 4, 5]);
1061        let sizes = ScalarBuffer::from(vec![1, 3, 1, 0]);
1062        let values = Int32Array::new(vec![1, 2, 3, 4, 5].into(), None);
1063        let values = Arc::new(values) as ArrayRef;
1064
1065        let field = Arc::new(Field::new("element", DataType::Int32, false));
1066        ListViewArray::new(
1067            field.clone(),
1068            offsets.clone(),
1069            sizes.clone(),
1070            values.clone(),
1071            None,
1072        );
1073
1074        let nulls = NullBuffer::new_null(4);
1075        ListViewArray::new(
1076            field.clone(),
1077            offsets,
1078            sizes.clone(),
1079            values.clone(),
1080            Some(nulls),
1081        );
1082
1083        let nulls = NullBuffer::new_null(4);
1084        let offsets = ScalarBuffer::from(vec![0, 1, 2, 3, 4]);
1085        let sizes = ScalarBuffer::from(vec![1, 1, 1, 1, 0]);
1086        let err = LargeListViewArray::try_new(
1087            field,
1088            offsets.clone(),
1089            sizes.clone(),
1090            values.clone(),
1091            Some(nulls),
1092        )
1093        .unwrap_err();
1094
1095        assert_eq!(
1096            err.to_string(),
1097            "Invalid argument error: Incorrect length of null buffer for LargeListViewArray, expected 5 got 4"
1098        );
1099
1100        let field = Arc::new(Field::new("element", DataType::Int64, false));
1101        let err = LargeListViewArray::try_new(
1102            field.clone(),
1103            offsets.clone(),
1104            sizes.clone(),
1105            values.clone(),
1106            None,
1107        )
1108        .unwrap_err();
1109
1110        assert_eq!(
1111            err.to_string(),
1112            "Invalid argument error: LargeListViewArray expected data type Int64 got Int32 for \"element\""
1113        );
1114
1115        let nulls = NullBuffer::new_null(7);
1116        let values = Int64Array::new(vec![0; 7].into(), Some(nulls));
1117        let values = Arc::new(values);
1118
1119        let err = LargeListViewArray::try_new(
1120            field,
1121            offsets.clone(),
1122            sizes.clone(),
1123            values.clone(),
1124            None,
1125        )
1126        .unwrap_err();
1127
1128        assert_eq!(
1129            err.to_string(),
1130            "Invalid argument error: Non-nullable field of LargeListViewArray \"element\" cannot contain nulls"
1131        );
1132    }
1133
1134    #[test]
1135    fn test_try_new_non_nullable_field_dictionary_values() {
1136        let keys = Int8Array::new(vec![0i8, 1].into(), Some(NullBuffer::new_valid(2)));
1137        let values = StringArray::from(vec!["x", "y"]);
1138        let dict = Int8DictionaryArray::try_new(keys, Arc::new(values)).unwrap();
1139        let field = Arc::new(Field::new("element", dict.data_type().clone(), false));
1140        ListViewArray::try_new(
1141            field,
1142            ScalarBuffer::from(vec![0]),
1143            ScalarBuffer::from(vec![2]),
1144            Arc::new(dict),
1145            None,
1146        )
1147        .unwrap();
1148
1149        let keys = Int8Array::from(vec![Some(0i8), None]);
1150        let values = StringArray::from(vec!["x", "y"]);
1151        let dict = Int8DictionaryArray::try_new(keys, Arc::new(values)).unwrap();
1152        let field = Arc::new(Field::new("element", dict.data_type().clone(), false));
1153        let err = ListViewArray::try_new(
1154            field,
1155            ScalarBuffer::from(vec![0]),
1156            ScalarBuffer::from(vec![2]),
1157            Arc::new(dict),
1158            None,
1159        )
1160        .unwrap_err();
1161
1162        assert!(err.to_string().contains("cannot contain nulls"));
1163    }
1164
1165    #[test]
1166    fn test_from_fixed_size_list() {
1167        let mut builder = FixedSizeListBuilder::new(Int32Builder::new(), 3);
1168        builder.values().append_slice(&[1, 2, 3]);
1169        builder.append(true);
1170        builder.values().append_slice(&[0, 0, 0]);
1171        builder.append(false);
1172        builder.values().append_slice(&[4, 5, 6]);
1173        builder.append(true);
1174        let list: ListViewArray = builder.finish().into();
1175        let values: Vec<_> = list
1176            .iter()
1177            .map(|x| x.map(|x| x.as_primitive::<Int32Type>().values().to_vec()))
1178            .collect();
1179        assert_eq!(values, vec![Some(vec![1, 2, 3]), None, Some(vec![4, 5, 6])]);
1180        let offsets = list.value_offsets();
1181        assert_eq!(offsets, &[0, 3, 6]);
1182        let sizes = list.value_sizes();
1183        assert_eq!(sizes, &[3, 3, 3]);
1184    }
1185
1186    #[test]
1187    fn test_list_view_array_overlap_lists() {
1188        let value_data = unsafe {
1189            ArrayData::builder(DataType::Int32)
1190                .len(8)
1191                .add_buffer(Buffer::from_slice_ref([0, 1, 2, 3, 4, 5, 6, 7]))
1192                .build_unchecked()
1193        };
1194        let list_data_type =
1195            DataType::ListView(Arc::new(Field::new_list_field(DataType::Int32, false)));
1196        let list_data = unsafe {
1197            ArrayData::builder(list_data_type)
1198                .len(2)
1199                .add_buffer(Buffer::from_slice_ref([0, 3])) // offsets
1200                .add_buffer(Buffer::from_slice_ref([5, 5])) // sizes
1201                .add_child_data(value_data)
1202                .build_unchecked()
1203        };
1204        let array = ListViewArray::from(list_data);
1205
1206        assert_eq!(array.len(), 2);
1207        assert_eq!(array.value_size(0), 5);
1208        assert_eq!(array.value_size(1), 5);
1209
1210        let values: Vec<_> = array
1211            .iter()
1212            .map(|x| x.map(|x| x.as_primitive::<Int32Type>().values().to_vec()))
1213            .collect();
1214        assert_eq!(
1215            values,
1216            vec![Some(vec![0, 1, 2, 3, 4]), Some(vec![3, 4, 5, 6, 7])]
1217        );
1218    }
1219
1220    #[test]
1221    fn test_list_view_array_incomplete_offsets() {
1222        let value_data = unsafe {
1223            ArrayData::builder(DataType::Int32)
1224                .len(50)
1225                .add_buffer(Buffer::from_slice_ref((0..50).collect::<Vec<i32>>()))
1226                .build_unchecked()
1227        };
1228        let list_data_type =
1229            DataType::ListView(Arc::new(Field::new_list_field(DataType::Int32, false)));
1230        let list_data = unsafe {
1231            ArrayData::builder(list_data_type)
1232                .len(3)
1233                .add_buffer(Buffer::from_slice_ref([0, 5, 10])) // offsets
1234                .add_buffer(Buffer::from_slice_ref([0, 5, 10])) // sizes
1235                .add_child_data(value_data)
1236                .build_unchecked()
1237        };
1238        let array = ListViewArray::from(list_data);
1239
1240        assert_eq!(array.len(), 3);
1241        assert_eq!(array.value_size(0), 0);
1242        assert_eq!(array.value_size(1), 5);
1243        assert_eq!(array.value_size(2), 10);
1244
1245        let values: Vec<_> = array
1246            .iter()
1247            .map(|x| x.map(|x| x.as_primitive::<Int32Type>().values().to_vec()))
1248            .collect();
1249        assert_eq!(
1250            values,
1251            vec![
1252                Some(vec![]),
1253                Some(vec![5, 6, 7, 8, 9]),
1254                Some(vec![10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
1255            ]
1256        );
1257    }
1258
1259    #[test]
1260    fn test_list_view_array_empty_lists() {
1261        let value_data = unsafe {
1262            ArrayData::builder(DataType::Int32)
1263                .len(0)
1264                .add_buffer(Buffer::from_slice_ref::<i32, &[_; 0]>(&[]))
1265                .build_unchecked()
1266        };
1267        let list_data_type =
1268            DataType::ListView(Arc::new(Field::new_list_field(DataType::Int32, false)));
1269        let list_data = unsafe {
1270            ArrayData::builder(list_data_type)
1271                .len(3)
1272                .add_buffer(Buffer::from_slice_ref([0, 0, 0])) // offsets
1273                .add_buffer(Buffer::from_slice_ref([0, 0, 0])) // sizes
1274                .add_child_data(value_data)
1275                .build_unchecked()
1276        };
1277        let array = ListViewArray::from(list_data);
1278
1279        assert_eq!(array.len(), 3);
1280        assert_eq!(array.value_size(0), 0);
1281        assert_eq!(array.value_size(1), 0);
1282        assert_eq!(array.value_size(2), 0);
1283
1284        let values: Vec<_> = array
1285            .iter()
1286            .map(|x| x.map(|x| x.as_primitive::<Int32Type>().values().to_vec()))
1287            .collect();
1288        assert_eq!(values, vec![Some(vec![]), Some(vec![]), Some(vec![])]);
1289    }
1290
1291    #[test]
1292    fn test_list_view_new_null_len() {
1293        let field = Arc::new(Field::new_list_field(DataType::Int32, true));
1294        let array = ListViewArray::new_null(field, 5);
1295        assert_eq!(array.len(), 5);
1296    }
1297
1298    #[test]
1299    fn test_from_iter_primitive() {
1300        let data = vec![
1301            Some(vec![Some(0), Some(1), Some(2)]),
1302            None,
1303            Some(vec![Some(3), Some(4), Some(5)]),
1304            Some(vec![Some(6), Some(7)]),
1305        ];
1306        let list_array = ListViewArray::from_iter_primitive::<Int32Type, _, _>(data);
1307
1308        //  [[0, 1, 2], NULL, [3, 4, 5], [6, 7]]
1309        let values = Int32Array::from(vec![0, 1, 2, 3, 4, 5, 6, 7]);
1310        let offsets = ScalarBuffer::from(vec![0, 3, 3, 6]);
1311        let sizes = ScalarBuffer::from(vec![3, 0, 3, 2]);
1312        let field = Arc::new(Field::new_list_field(DataType::Int32, true));
1313
1314        let mut nulls = NullBufferBuilder::new(4);
1315        nulls.append(true);
1316        nulls.append(false);
1317        nulls.append_n_non_nulls(2);
1318        let another = ListViewArray::new(field, offsets, sizes, Arc::new(values), nulls.finish());
1319
1320        assert_eq!(list_array, another)
1321    }
1322}