Skip to main content

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
418/// SAFETY: Correctly implements the contract of Arrow Arrays
419unsafe impl<OffsetSize: OffsetSizeTrait> Array for GenericListViewArray<OffsetSize> {
420    fn as_any(&self) -> &dyn Any {
421        self
422    }
423
424    fn to_data(&self) -> ArrayData {
425        self.clone().into()
426    }
427
428    fn into_data(self) -> ArrayData {
429        self.into()
430    }
431
432    fn data_type(&self) -> &DataType {
433        &self.data_type
434    }
435
436    fn slice(&self, offset: usize, length: usize) -> ArrayRef {
437        Arc::new(self.slice(offset, length))
438    }
439
440    fn len(&self) -> usize {
441        self.sizes().len()
442    }
443
444    fn is_empty(&self) -> bool {
445        self.value_sizes.is_empty()
446    }
447
448    fn shrink_to_fit(&mut self) {
449        if let Some(nulls) = &mut self.nulls {
450            nulls.shrink_to_fit();
451        }
452        self.values.shrink_to_fit();
453        self.value_offsets.shrink_to_fit();
454        self.value_sizes.shrink_to_fit();
455    }
456
457    fn offset(&self) -> usize {
458        0
459    }
460
461    fn nulls(&self) -> Option<&NullBuffer> {
462        self.nulls.as_ref()
463    }
464
465    fn logical_null_count(&self) -> usize {
466        // More efficient that the default implementation
467        self.null_count()
468    }
469
470    fn get_buffer_memory_size(&self) -> usize {
471        let mut size = self.values.get_buffer_memory_size();
472        size += self.value_offsets.inner().capacity();
473        size += self.value_sizes.inner().capacity();
474        if let Some(n) = self.nulls.as_ref() {
475            size += n.buffer().capacity();
476        }
477        size
478    }
479
480    fn get_array_memory_size(&self) -> usize {
481        let mut size = std::mem::size_of::<Self>() + self.values.get_array_memory_size();
482        size += self.value_offsets.inner().capacity();
483        size += self.value_sizes.inner().capacity();
484        if let Some(n) = self.nulls.as_ref() {
485            size += n.buffer().capacity();
486        }
487        size
488    }
489}
490
491impl<OffsetSize: OffsetSizeTrait> std::fmt::Debug for GenericListViewArray<OffsetSize> {
492    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
493        let prefix = OffsetSize::PREFIX;
494        write!(f, "{prefix}ListViewArray\n[\n")?;
495        print_long_array(self, f, |array, index, f| {
496            std::fmt::Debug::fmt(&array.value(index), f)
497        })?;
498        write!(f, "]")
499    }
500}
501
502impl<OffsetSize: OffsetSizeTrait> From<GenericListArray<OffsetSize>>
503    for GenericListViewArray<OffsetSize>
504{
505    fn from(value: GenericListArray<OffsetSize>) -> Self {
506        let (field, offsets, values, nulls) = value.into_parts();
507        let len = offsets.len() - 1;
508        let mut sizes = Vec::with_capacity(len);
509        let mut view_offsets = Vec::with_capacity(len);
510        for (i, offset) in offsets.iter().enumerate().take(len) {
511            view_offsets.push(*offset);
512            sizes.push(offsets[i + 1] - offsets[i]);
513        }
514
515        Self::new(
516            field,
517            ScalarBuffer::from(view_offsets),
518            ScalarBuffer::from(sizes),
519            values,
520            nulls,
521        )
522    }
523}
524
525impl<OffsetSize: OffsetSizeTrait> From<GenericListViewArray<OffsetSize>> for ArrayData {
526    fn from(array: GenericListViewArray<OffsetSize>) -> Self {
527        let len = array.len();
528        let builder = ArrayDataBuilder::new(array.data_type)
529            .len(len)
530            .nulls(array.nulls)
531            .buffers(vec![
532                array.value_offsets.into_inner(),
533                array.value_sizes.into_inner(),
534            ])
535            .child_data(vec![array.values.to_data()]);
536
537        unsafe { builder.build_unchecked() }
538    }
539}
540
541impl<OffsetSize: OffsetSizeTrait> From<ArrayData> for GenericListViewArray<OffsetSize> {
542    fn from(data: ArrayData) -> Self {
543        Self::try_new_from_array_data(data)
544            .expect("Expected infallible creation of GenericListViewArray from ArrayDataRef failed")
545    }
546}
547
548impl<OffsetSize: OffsetSizeTrait> From<FixedSizeListArray> for GenericListViewArray<OffsetSize> {
549    fn from(value: FixedSizeListArray) -> Self {
550        let (field, size) = match value.data_type() {
551            DataType::FixedSizeList(f, size) => (f, *size as usize),
552            _ => unreachable!(),
553        };
554        let mut acc = 0_usize;
555        let iter = std::iter::repeat_n(size, value.len());
556        let mut sizes = Vec::with_capacity(iter.size_hint().0);
557        let mut offsets = Vec::with_capacity(iter.size_hint().0);
558
559        for size in iter {
560            offsets.push(OffsetSize::usize_as(acc));
561            acc = acc.add(size);
562            sizes.push(OffsetSize::usize_as(size));
563        }
564        let sizes = ScalarBuffer::from(sizes);
565        let offsets = ScalarBuffer::from(offsets);
566        Self {
567            data_type: Self::DATA_TYPE_CONSTRUCTOR(field.clone()),
568            nulls: value.nulls().cloned(),
569            values: value.values().clone(),
570            value_offsets: offsets,
571            value_sizes: sizes,
572        }
573    }
574}
575
576impl<OffsetSize: OffsetSizeTrait> GenericListViewArray<OffsetSize> {
577    fn try_new_from_array_data(data: ArrayData) -> Result<Self, ArrowError> {
578        if data.buffers().len() != 2 {
579            return Err(ArrowError::InvalidArgumentError(format!(
580                "ListViewArray data should contain two buffers (value offsets & value sizes), had {}",
581                data.buffers().len()
582            )));
583        }
584
585        if data.child_data().len() != 1 {
586            return Err(ArrowError::InvalidArgumentError(format!(
587                "ListViewArray should contain a single child array (values array), had {}",
588                data.child_data().len()
589            )));
590        }
591
592        let values = data.child_data()[0].clone();
593
594        if let Some(child_data_type) = Self::get_type(data.data_type()) {
595            if values.data_type() != child_data_type {
596                return Err(ArrowError::InvalidArgumentError(format!(
597                    "{}ListViewArray's child datatype {:?} does not \
598                             correspond to the List's datatype {:?}",
599                    OffsetSize::PREFIX,
600                    values.data_type(),
601                    child_data_type
602                )));
603            }
604        } else {
605            return Err(ArrowError::InvalidArgumentError(format!(
606                "{}ListViewArray's datatype must be {}ListViewArray(). It is {:?}",
607                OffsetSize::PREFIX,
608                OffsetSize::PREFIX,
609                data.data_type()
610            )));
611        }
612
613        let values = make_array(values);
614        // ArrayData is valid, and verified type above
615        let value_offsets = ScalarBuffer::new(data.buffers()[0].clone(), data.offset(), data.len());
616        let value_sizes = ScalarBuffer::new(data.buffers()[1].clone(), data.offset(), data.len());
617
618        Ok(Self {
619            data_type: data.data_type().clone(),
620            nulls: data.nulls().cloned(),
621            values,
622            value_offsets,
623            value_sizes,
624        })
625    }
626}
627
628#[cfg(test)]
629mod tests {
630    use arrow_buffer::{BooleanBuffer, Buffer, NullBufferBuilder, ScalarBuffer, bit_util};
631    use arrow_schema::Field;
632
633    use crate::builder::{FixedSizeListBuilder, Int32Builder};
634    use crate::cast::AsArray;
635    use crate::types::Int32Type;
636    use crate::{Int32Array, Int64Array};
637
638    use super::*;
639
640    #[test]
641    fn test_empty_list_view_array() {
642        // Construct an empty value array
643        let vec: Vec<i32> = vec![];
644        let field = Arc::new(Field::new_list_field(DataType::Int32, true));
645        let sizes = ScalarBuffer::from(vec![]);
646        let offsets = ScalarBuffer::from(vec![]);
647        let values = Int32Array::from(vec);
648        let list_array = LargeListViewArray::new(field, offsets, sizes, Arc::new(values), None);
649
650        assert_eq!(list_array.len(), 0)
651    }
652
653    #[test]
654    fn test_list_view_array() {
655        // Construct a value array
656        let value_data = ArrayData::builder(DataType::Int32)
657            .len(8)
658            .add_buffer(Buffer::from_slice_ref([0, 1, 2, 3, 4, 5, 6, 7]))
659            .build()
660            .unwrap();
661
662        let field = Arc::new(Field::new_list_field(DataType::Int32, true));
663        let sizes = ScalarBuffer::from(vec![3i32, 3, 2]);
664        let offsets = ScalarBuffer::from(vec![0i32, 3, 6]);
665        let values = Int32Array::from(vec![0, 1, 2, 3, 4, 5, 6, 7]);
666        let list_array = ListViewArray::new(field, offsets, sizes, Arc::new(values), None);
667
668        let values = list_array.values();
669        assert_eq!(value_data, values.to_data());
670        assert_eq!(DataType::Int32, list_array.value_type());
671        assert_eq!(3, list_array.len());
672        assert_eq!(0, list_array.null_count());
673        assert_eq!(6, list_array.value_offsets()[2]);
674        assert_eq!(2, list_array.value_sizes()[2]);
675        assert_eq!(2, list_array.value_size(2));
676        assert_eq!(0, list_array.value(0).as_primitive::<Int32Type>().value(0));
677        assert_eq!(
678            0,
679            unsafe { list_array.value_unchecked(0) }
680                .as_primitive::<Int32Type>()
681                .value(0)
682        );
683        for i in 0..3 {
684            assert!(list_array.is_valid(i));
685            assert!(!list_array.is_null(i));
686        }
687    }
688
689    #[test]
690    fn test_large_list_view_array() {
691        // Construct a value array
692        let value_data = ArrayData::builder(DataType::Int32)
693            .len(8)
694            .add_buffer(Buffer::from_slice_ref([0, 1, 2, 3, 4, 5, 6, 7]))
695            .build()
696            .unwrap();
697
698        let field = Arc::new(Field::new_list_field(DataType::Int32, true));
699        let sizes = ScalarBuffer::from(vec![3i64, 3, 2]);
700        let offsets = ScalarBuffer::from(vec![0i64, 3, 6]);
701        let values = Int32Array::from(vec![0, 1, 2, 3, 4, 5, 6, 7]);
702        let list_array = LargeListViewArray::new(field, offsets, sizes, Arc::new(values), None);
703
704        let values = list_array.values();
705        assert_eq!(value_data, values.to_data());
706        assert_eq!(DataType::Int32, list_array.value_type());
707        assert_eq!(3, list_array.len());
708        assert_eq!(0, list_array.null_count());
709        assert_eq!(6, list_array.value_offsets()[2]);
710        assert_eq!(2, list_array.value_sizes()[2]);
711        assert_eq!(2, list_array.value_size(2));
712        assert_eq!(0, list_array.value(0).as_primitive::<Int32Type>().value(0));
713        assert_eq!(
714            0,
715            unsafe { list_array.value_unchecked(0) }
716                .as_primitive::<Int32Type>()
717                .value(0)
718        );
719        for i in 0..3 {
720            assert!(list_array.is_valid(i));
721            assert!(!list_array.is_null(i));
722        }
723    }
724
725    #[test]
726    fn test_list_view_array_slice() {
727        // Construct a value array
728        let value_data = ArrayData::builder(DataType::Int32)
729            .len(10)
730            .add_buffer(Buffer::from_slice_ref([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
731            .build()
732            .unwrap();
733
734        // 01011001 00000001
735        let mut null_bits: [u8; 2] = [0; 2];
736        bit_util::set_bit(&mut null_bits, 0);
737        bit_util::set_bit(&mut null_bits, 3);
738        bit_util::set_bit(&mut null_bits, 4);
739        bit_util::set_bit(&mut null_bits, 6);
740        bit_util::set_bit(&mut null_bits, 8);
741        let buffer = BooleanBuffer::new(Buffer::from(null_bits), 0, 9);
742        let null_buffer = NullBuffer::new(buffer);
743
744        let field = Arc::new(Field::new_list_field(DataType::Int32, true));
745        let sizes = ScalarBuffer::from(vec![2, 0, 0, 2, 2, 0, 3, 0, 1]);
746        let offsets = ScalarBuffer::from(vec![0, 2, 2, 2, 4, 6, 6, 9, 9]);
747        let values = Int32Array::from(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
748        let list_array =
749            ListViewArray::new(field, offsets, sizes, Arc::new(values), Some(null_buffer));
750
751        let values = list_array.values();
752        assert_eq!(value_data, values.to_data());
753        assert_eq!(DataType::Int32, list_array.value_type());
754        assert_eq!(9, list_array.len());
755        assert_eq!(4, list_array.null_count());
756        assert_eq!(2, list_array.value_offsets()[3]);
757        assert_eq!(2, list_array.value_sizes()[3]);
758        assert_eq!(2, list_array.value_size(3));
759
760        let sliced_array = list_array.slice(1, 6);
761        assert_eq!(6, sliced_array.len());
762        assert_eq!(3, sliced_array.null_count());
763
764        for i in 0..sliced_array.len() {
765            if bit_util::get_bit(&null_bits, 1 + i) {
766                assert!(sliced_array.is_valid(i));
767            } else {
768                assert!(sliced_array.is_null(i));
769            }
770        }
771
772        // Check offset and length for each non-null value.
773        let sliced_list_array = sliced_array
774            .as_any()
775            .downcast_ref::<ListViewArray>()
776            .unwrap();
777        assert_eq!(2, sliced_list_array.value_offsets()[2]);
778        assert_eq!(2, sliced_list_array.value_sizes()[2]);
779        assert_eq!(2, sliced_list_array.value_size(2));
780
781        assert_eq!(4, sliced_list_array.value_offsets()[3]);
782        assert_eq!(2, sliced_list_array.value_sizes()[3]);
783        assert_eq!(2, sliced_list_array.value_size(3));
784
785        assert_eq!(6, sliced_list_array.value_offsets()[5]);
786        assert_eq!(3, sliced_list_array.value_sizes()[5]);
787        assert_eq!(3, sliced_list_array.value_size(5));
788    }
789
790    #[test]
791    fn test_large_list_view_array_slice() {
792        // Construct a value array
793        let value_data = ArrayData::builder(DataType::Int32)
794            .len(10)
795            .add_buffer(Buffer::from_slice_ref([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
796            .build()
797            .unwrap();
798
799        // 01011001 00000001
800        let mut null_bits: [u8; 2] = [0; 2];
801        bit_util::set_bit(&mut null_bits, 0);
802        bit_util::set_bit(&mut null_bits, 3);
803        bit_util::set_bit(&mut null_bits, 4);
804        bit_util::set_bit(&mut null_bits, 6);
805        bit_util::set_bit(&mut null_bits, 8);
806        let buffer = BooleanBuffer::new(Buffer::from(null_bits), 0, 9);
807        let null_buffer = NullBuffer::new(buffer);
808
809        // Construct a large list view array from the above two
810        let field = Arc::new(Field::new_list_field(DataType::Int32, true));
811        let sizes = ScalarBuffer::from(vec![2i64, 0, 0, 2, 2, 0, 3, 0, 1]);
812        let offsets = ScalarBuffer::from(vec![0i64, 2, 2, 2, 4, 6, 6, 9, 9]);
813        let values = Int32Array::from(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
814        let list_array =
815            LargeListViewArray::new(field, offsets, sizes, Arc::new(values), Some(null_buffer));
816
817        let values = list_array.values();
818        assert_eq!(value_data, values.to_data());
819        assert_eq!(DataType::Int32, list_array.value_type());
820        assert_eq!(9, list_array.len());
821        assert_eq!(4, list_array.null_count());
822        assert_eq!(2, list_array.value_offsets()[3]);
823        assert_eq!(2, list_array.value_sizes()[3]);
824        assert_eq!(2, list_array.value_size(3));
825
826        let sliced_array = list_array.slice(1, 6);
827        assert_eq!(6, sliced_array.len());
828        assert_eq!(3, sliced_array.null_count());
829
830        for i in 0..sliced_array.len() {
831            if bit_util::get_bit(&null_bits, 1 + i) {
832                assert!(sliced_array.is_valid(i));
833            } else {
834                assert!(sliced_array.is_null(i));
835            }
836        }
837
838        // Check offset and length for each non-null value.
839        let sliced_list_array = sliced_array
840            .as_any()
841            .downcast_ref::<LargeListViewArray>()
842            .unwrap();
843        assert_eq!(2, sliced_list_array.value_offsets()[2]);
844        assert_eq!(2, sliced_list_array.value_size(2));
845        assert_eq!(2, sliced_list_array.value_sizes()[2]);
846
847        assert_eq!(4, sliced_list_array.value_offsets()[3]);
848        assert_eq!(2, sliced_list_array.value_size(3));
849        assert_eq!(2, sliced_list_array.value_sizes()[3]);
850
851        assert_eq!(6, sliced_list_array.value_offsets()[5]);
852        assert_eq!(3, sliced_list_array.value_size(5));
853        assert_eq!(2, sliced_list_array.value_sizes()[3]);
854    }
855
856    #[test]
857    #[should_panic(expected = "index out of bounds: the len is 9 but the index is 10")]
858    fn test_list_view_array_index_out_of_bound() {
859        // 01011001 00000001
860        let mut null_bits: [u8; 2] = [0; 2];
861        bit_util::set_bit(&mut null_bits, 0);
862        bit_util::set_bit(&mut null_bits, 3);
863        bit_util::set_bit(&mut null_bits, 4);
864        bit_util::set_bit(&mut null_bits, 6);
865        bit_util::set_bit(&mut null_bits, 8);
866        let buffer = BooleanBuffer::new(Buffer::from(null_bits), 0, 9);
867        let null_buffer = NullBuffer::new(buffer);
868
869        // Construct a buffer for value offsets, for the nested array:
870        //  [[0, 1], null, null, [2, 3], [4, 5], null, [6, 7, 8], null, [9]]
871        // Construct a list array from the above two
872        let field = Arc::new(Field::new_list_field(DataType::Int32, true));
873        let sizes = ScalarBuffer::from(vec![2i32, 0, 0, 2, 2, 0, 3, 0, 1]);
874        let offsets = ScalarBuffer::from(vec![0i32, 2, 2, 2, 4, 6, 6, 9, 9]);
875        let values = Int32Array::from(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
876        let list_array =
877            ListViewArray::new(field, offsets, sizes, Arc::new(values), Some(null_buffer));
878
879        assert_eq!(9, list_array.len());
880        list_array.value(10);
881    }
882    #[test]
883    #[should_panic(
884        expected = "ListViewArray data should contain two buffers (value offsets & value sizes), had 0"
885    )]
886    #[cfg(not(feature = "force_validate"))]
887    fn test_list_view_array_invalid_buffer_len() {
888        let value_data = unsafe {
889            ArrayData::builder(DataType::Int32)
890                .len(8)
891                .add_buffer(Buffer::from_slice_ref([0, 1, 2, 3, 4, 5, 6, 7]))
892                .build_unchecked()
893        };
894        let list_data_type =
895            DataType::ListView(Arc::new(Field::new_list_field(DataType::Int32, false)));
896        let list_data = unsafe {
897            ArrayData::builder(list_data_type)
898                .len(3)
899                .add_child_data(value_data)
900                .build_unchecked()
901        };
902        drop(ListViewArray::from(list_data));
903    }
904
905    #[test]
906    #[should_panic(
907        expected = "ListViewArray data should contain two buffers (value offsets & value sizes), had 1"
908    )]
909    #[cfg(not(feature = "force_validate"))]
910    fn test_list_view_array_invalid_child_array_len() {
911        let value_offsets = Buffer::from_slice_ref([0, 2, 5, 7]);
912        let list_data_type =
913            DataType::ListView(Arc::new(Field::new_list_field(DataType::Int32, false)));
914        let list_data = unsafe {
915            ArrayData::builder(list_data_type)
916                .len(3)
917                .add_buffer(value_offsets)
918                .build_unchecked()
919        };
920        drop(ListViewArray::from(list_data));
921    }
922
923    #[test]
924    fn test_list_view_array_offsets_need_not_start_at_zero() {
925        let field = Arc::new(Field::new_list_field(DataType::Int32, true));
926        let sizes = ScalarBuffer::from(vec![0i32, 0, 3]);
927        let offsets = ScalarBuffer::from(vec![2i32, 2, 5]);
928        let values = Int32Array::from(vec![0, 1, 2, 3, 4, 5, 6, 7]);
929        let list_array = ListViewArray::new(field, offsets, sizes, Arc::new(values), None);
930
931        assert_eq!(list_array.value_size(0), 0);
932        assert_eq!(list_array.value_size(1), 0);
933        assert_eq!(list_array.value_size(2), 3);
934    }
935
936    #[test]
937    #[should_panic(expected = "Memory pointer is not aligned with the specified scalar type")]
938    #[cfg(not(feature = "force_validate"))]
939    fn test_list_view_array_alignment() {
940        let offset_buf = Buffer::from_slice_ref([0_u64]);
941        let offset_buf2 = offset_buf.slice(1);
942
943        let size_buf = Buffer::from_slice_ref([0_u64]);
944        let size_buf2 = size_buf.slice(1);
945
946        let values: [i32; 8] = [0; 8];
947        let value_data = unsafe {
948            ArrayData::builder(DataType::Int32)
949                .add_buffer(Buffer::from_slice_ref(values))
950                .build_unchecked()
951        };
952
953        let list_data_type =
954            DataType::ListView(Arc::new(Field::new_list_field(DataType::Int32, false)));
955        let list_data = unsafe {
956            ArrayData::builder(list_data_type)
957                .add_buffer(offset_buf2)
958                .add_buffer(size_buf2)
959                .add_child_data(value_data)
960                .build_unchecked()
961        };
962        drop(ListViewArray::from(list_data));
963    }
964
965    #[test]
966    fn test_empty_offsets() {
967        let f = Arc::new(Field::new("element", DataType::Int32, true));
968        let string = ListViewArray::from(
969            ArrayData::builder(DataType::ListView(f.clone()))
970                .buffers(vec![Buffer::from(&[]), Buffer::from(&[])])
971                .add_child_data(ArrayData::new_empty(&DataType::Int32))
972                .build()
973                .unwrap(),
974        );
975        assert_eq!(string.value_offsets(), &[] as &[i32; 0]);
976        assert_eq!(string.value_sizes(), &[] as &[i32; 0]);
977
978        let string = LargeListViewArray::from(
979            ArrayData::builder(DataType::LargeListView(f))
980                .buffers(vec![Buffer::from(&[]), Buffer::from(&[])])
981                .add_child_data(ArrayData::new_empty(&DataType::Int32))
982                .build()
983                .unwrap(),
984        );
985        assert_eq!(string.len(), 0);
986        assert_eq!(string.value_offsets(), &[] as &[i64; 0]);
987        assert_eq!(string.value_sizes(), &[] as &[i64; 0]);
988    }
989
990    #[test]
991    fn test_try_new() {
992        let offsets = ScalarBuffer::from(vec![0, 1, 4, 5]);
993        let sizes = ScalarBuffer::from(vec![1, 3, 1, 0]);
994        let values = Int32Array::new(vec![1, 2, 3, 4, 5].into(), None);
995        let values = Arc::new(values) as ArrayRef;
996
997        let field = Arc::new(Field::new("element", DataType::Int32, false));
998        ListViewArray::new(
999            field.clone(),
1000            offsets.clone(),
1001            sizes.clone(),
1002            values.clone(),
1003            None,
1004        );
1005
1006        let nulls = NullBuffer::new_null(4);
1007        ListViewArray::new(
1008            field.clone(),
1009            offsets,
1010            sizes.clone(),
1011            values.clone(),
1012            Some(nulls),
1013        );
1014
1015        let nulls = NullBuffer::new_null(4);
1016        let offsets = ScalarBuffer::from(vec![0, 1, 2, 3, 4]);
1017        let sizes = ScalarBuffer::from(vec![1, 1, 1, 1, 0]);
1018        let err = LargeListViewArray::try_new(
1019            field,
1020            offsets.clone(),
1021            sizes.clone(),
1022            values.clone(),
1023            Some(nulls),
1024        )
1025        .unwrap_err();
1026
1027        assert_eq!(
1028            err.to_string(),
1029            "Invalid argument error: Incorrect length of null buffer for LargeListViewArray, expected 5 got 4"
1030        );
1031
1032        let field = Arc::new(Field::new("element", DataType::Int64, false));
1033        let err = LargeListViewArray::try_new(
1034            field.clone(),
1035            offsets.clone(),
1036            sizes.clone(),
1037            values.clone(),
1038            None,
1039        )
1040        .unwrap_err();
1041
1042        assert_eq!(
1043            err.to_string(),
1044            "Invalid argument error: LargeListViewArray expected data type Int64 got Int32 for \"element\""
1045        );
1046
1047        let nulls = NullBuffer::new_null(7);
1048        let values = Int64Array::new(vec![0; 7].into(), Some(nulls));
1049        let values = Arc::new(values);
1050
1051        let err = LargeListViewArray::try_new(
1052            field,
1053            offsets.clone(),
1054            sizes.clone(),
1055            values.clone(),
1056            None,
1057        )
1058        .unwrap_err();
1059
1060        assert_eq!(
1061            err.to_string(),
1062            "Invalid argument error: Non-nullable field of LargeListViewArray \"element\" cannot contain nulls"
1063        );
1064    }
1065
1066    #[test]
1067    fn test_from_fixed_size_list() {
1068        let mut builder = FixedSizeListBuilder::new(Int32Builder::new(), 3);
1069        builder.values().append_slice(&[1, 2, 3]);
1070        builder.append(true);
1071        builder.values().append_slice(&[0, 0, 0]);
1072        builder.append(false);
1073        builder.values().append_slice(&[4, 5, 6]);
1074        builder.append(true);
1075        let list: ListViewArray = builder.finish().into();
1076        let values: Vec<_> = list
1077            .iter()
1078            .map(|x| x.map(|x| x.as_primitive::<Int32Type>().values().to_vec()))
1079            .collect();
1080        assert_eq!(values, vec![Some(vec![1, 2, 3]), None, Some(vec![4, 5, 6])]);
1081        let offsets = list.value_offsets();
1082        assert_eq!(offsets, &[0, 3, 6]);
1083        let sizes = list.value_sizes();
1084        assert_eq!(sizes, &[3, 3, 3]);
1085    }
1086
1087    #[test]
1088    fn test_list_view_array_overlap_lists() {
1089        let value_data = unsafe {
1090            ArrayData::builder(DataType::Int32)
1091                .len(8)
1092                .add_buffer(Buffer::from_slice_ref([0, 1, 2, 3, 4, 5, 6, 7]))
1093                .build_unchecked()
1094        };
1095        let list_data_type =
1096            DataType::ListView(Arc::new(Field::new_list_field(DataType::Int32, false)));
1097        let list_data = unsafe {
1098            ArrayData::builder(list_data_type)
1099                .len(2)
1100                .add_buffer(Buffer::from_slice_ref([0, 3])) // offsets
1101                .add_buffer(Buffer::from_slice_ref([5, 5])) // sizes
1102                .add_child_data(value_data)
1103                .build_unchecked()
1104        };
1105        let array = ListViewArray::from(list_data);
1106
1107        assert_eq!(array.len(), 2);
1108        assert_eq!(array.value_size(0), 5);
1109        assert_eq!(array.value_size(1), 5);
1110
1111        let values: Vec<_> = array
1112            .iter()
1113            .map(|x| x.map(|x| x.as_primitive::<Int32Type>().values().to_vec()))
1114            .collect();
1115        assert_eq!(
1116            values,
1117            vec![Some(vec![0, 1, 2, 3, 4]), Some(vec![3, 4, 5, 6, 7])]
1118        );
1119    }
1120
1121    #[test]
1122    fn test_list_view_array_incomplete_offsets() {
1123        let value_data = unsafe {
1124            ArrayData::builder(DataType::Int32)
1125                .len(50)
1126                .add_buffer(Buffer::from_slice_ref((0..50).collect::<Vec<i32>>()))
1127                .build_unchecked()
1128        };
1129        let list_data_type =
1130            DataType::ListView(Arc::new(Field::new_list_field(DataType::Int32, false)));
1131        let list_data = unsafe {
1132            ArrayData::builder(list_data_type)
1133                .len(3)
1134                .add_buffer(Buffer::from_slice_ref([0, 5, 10])) // offsets
1135                .add_buffer(Buffer::from_slice_ref([0, 5, 10])) // sizes
1136                .add_child_data(value_data)
1137                .build_unchecked()
1138        };
1139        let array = ListViewArray::from(list_data);
1140
1141        assert_eq!(array.len(), 3);
1142        assert_eq!(array.value_size(0), 0);
1143        assert_eq!(array.value_size(1), 5);
1144        assert_eq!(array.value_size(2), 10);
1145
1146        let values: Vec<_> = array
1147            .iter()
1148            .map(|x| x.map(|x| x.as_primitive::<Int32Type>().values().to_vec()))
1149            .collect();
1150        assert_eq!(
1151            values,
1152            vec![
1153                Some(vec![]),
1154                Some(vec![5, 6, 7, 8, 9]),
1155                Some(vec![10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
1156            ]
1157        );
1158    }
1159
1160    #[test]
1161    fn test_list_view_array_empty_lists() {
1162        let value_data = unsafe {
1163            ArrayData::builder(DataType::Int32)
1164                .len(0)
1165                .add_buffer(Buffer::from_slice_ref::<i32, &[_; 0]>(&[]))
1166                .build_unchecked()
1167        };
1168        let list_data_type =
1169            DataType::ListView(Arc::new(Field::new_list_field(DataType::Int32, false)));
1170        let list_data = unsafe {
1171            ArrayData::builder(list_data_type)
1172                .len(3)
1173                .add_buffer(Buffer::from_slice_ref([0, 0, 0])) // offsets
1174                .add_buffer(Buffer::from_slice_ref([0, 0, 0])) // sizes
1175                .add_child_data(value_data)
1176                .build_unchecked()
1177        };
1178        let array = ListViewArray::from(list_data);
1179
1180        assert_eq!(array.len(), 3);
1181        assert_eq!(array.value_size(0), 0);
1182        assert_eq!(array.value_size(1), 0);
1183        assert_eq!(array.value_size(2), 0);
1184
1185        let values: Vec<_> = array
1186            .iter()
1187            .map(|x| x.map(|x| x.as_primitive::<Int32Type>().values().to_vec()))
1188            .collect();
1189        assert_eq!(values, vec![Some(vec![]), Some(vec![]), Some(vec![])]);
1190    }
1191
1192    #[test]
1193    fn test_list_view_new_null_len() {
1194        let field = Arc::new(Field::new_list_field(DataType::Int32, true));
1195        let array = ListViewArray::new_null(field, 5);
1196        assert_eq!(array.len(), 5);
1197    }
1198
1199    #[test]
1200    fn test_from_iter_primitive() {
1201        let data = vec![
1202            Some(vec![Some(0), Some(1), Some(2)]),
1203            None,
1204            Some(vec![Some(3), Some(4), Some(5)]),
1205            Some(vec![Some(6), Some(7)]),
1206        ];
1207        let list_array = ListViewArray::from_iter_primitive::<Int32Type, _, _>(data);
1208
1209        //  [[0, 1, 2], NULL, [3, 4, 5], [6, 7]]
1210        let values = Int32Array::from(vec![0, 1, 2, 3, 4, 5, 6, 7]);
1211        let offsets = ScalarBuffer::from(vec![0, 3, 3, 6]);
1212        let sizes = ScalarBuffer::from(vec![3, 0, 3, 2]);
1213        let field = Arc::new(Field::new_list_field(DataType::Int32, true));
1214
1215        let mut nulls = NullBufferBuilder::new(4);
1216        nulls.append(true);
1217        nulls.append(false);
1218        nulls.append_n_non_nulls(2);
1219        let another = ListViewArray::new(field, offsets, sizes, Arc::new(values), nulls.finish());
1220
1221        assert_eq!(list_array, another)
1222    }
1223}