arrow_array/array/
list_view_array.rs

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