Skip to main content

arrow_array/array/
list_array.rs

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