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