arrow_array/array/
fixed_size_list_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 crate::array::print_long_array;
19use crate::builder::{FixedSizeListBuilder, PrimitiveBuilder};
20use crate::iterator::FixedSizeListIter;
21use crate::{make_array, Array, ArrayAccessor, ArrayRef, ArrowPrimitiveType};
22use arrow_buffer::buffer::NullBuffer;
23use arrow_buffer::ArrowNativeType;
24use arrow_data::{ArrayData, ArrayDataBuilder};
25use arrow_schema::{ArrowError, DataType, FieldRef};
26use std::any::Any;
27use std::sync::Arc;
28
29/// An array of [fixed length lists], similar to JSON arrays
30/// (e.g. `["A", "B"]`).
31///
32/// Lists are represented using a `values` child
33/// array where each list has a fixed size of `value_length`.
34///
35/// Use [`FixedSizeListBuilder`] to construct a [`FixedSizeListArray`].
36///
37/// # Representation
38///
39/// A [`FixedSizeListArray`] can represent a list of values of any other
40/// supported Arrow type. Each element of the `FixedSizeListArray` itself is
41/// a list which may contain NULL and non-null values,
42/// or may itself be NULL.
43///
44/// For example, this `FixedSizeListArray` stores lists of strings:
45///
46/// ```text
47/// ┌─────────────┐
48/// │    [A,B]    │
49/// ├─────────────┤
50/// │    NULL     │
51/// ├─────────────┤
52/// │   [C,NULL]  │
53/// └─────────────┘
54/// ```
55///
56/// The `values` of this `FixedSizeListArray`s are stored in a child
57/// [`StringArray`] where logical null values take up `values_length` slots in the array
58/// as shown in the following diagram. The logical values
59/// are shown on the left, and the actual `FixedSizeListArray` encoding on the right
60///
61/// ```text
62///                                 ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
63///                                                         ┌ ─ ─ ─ ─ ─ ─ ─ ─┐
64///  ┌─────────────┐                │     ┌───┐               ┌───┐ ┌──────┐      │
65///  │   [A,B]     │                      │ 1 │             │ │ 1 │ │  A   │ │ 0
66///  ├─────────────┤                │     ├───┤               ├───┤ ├──────┤      │
67///  │    NULL     │                      │ 0 │             │ │ 1 │ │  B   │ │ 1
68///  ├─────────────┤                │     ├───┤               ├───┤ ├──────┤      │
69///  │  [C,NULL]   │                      │ 1 │             │ │ 0 │ │ ???? │ │ 2
70///  └─────────────┘                │     └───┘               ├───┤ ├──────┤      │
71///                                                         | │ 0 │ │ ???? │ │ 3
72///  Logical Values                 │   Validity              ├───┤ ├──────┤      │
73///                                     (nulls)             │ │ 1 │ │  C   │ │ 4
74///                                 │                         ├───┤ ├──────┤      │
75///                                                         │ │ 0 │ │ ???? │ │ 5
76///                                 │                         └───┘ └──────┘      │
77///                                                         │     Values     │
78///                                 │   FixedSizeListArray        (Array)         │
79///                                                         └ ─ ─ ─ ─ ─ ─ ─ ─┘
80///                                 └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘
81/// ```
82///
83/// # Example
84///
85/// ```
86/// # use std::sync::Arc;
87/// # use arrow_array::{Array, FixedSizeListArray, Int32Array};
88/// # use arrow_data::ArrayData;
89/// # use arrow_schema::{DataType, Field};
90/// # use arrow_buffer::Buffer;
91/// // Construct a value array
92/// let value_data = ArrayData::builder(DataType::Int32)
93///     .len(9)
94///     .add_buffer(Buffer::from_slice_ref(&[0, 1, 2, 3, 4, 5, 6, 7, 8]))
95///     .build()
96///     .unwrap();
97/// let list_data_type = DataType::FixedSizeList(
98///     Arc::new(Field::new_list_field(DataType::Int32, false)),
99///     3,
100/// );
101/// let list_data = ArrayData::builder(list_data_type.clone())
102///     .len(3)
103///     .add_child_data(value_data.clone())
104///     .build()
105///     .unwrap();
106/// let list_array = FixedSizeListArray::from(list_data);
107/// let list0 = list_array.value(0);
108/// let list1 = list_array.value(1);
109/// let list2 = list_array.value(2);
110///
111/// assert_eq!( &[0, 1, 2], list0.as_any().downcast_ref::<Int32Array>().unwrap().values());
112/// assert_eq!( &[3, 4, 5], list1.as_any().downcast_ref::<Int32Array>().unwrap().values());
113/// assert_eq!( &[6, 7, 8], list2.as_any().downcast_ref::<Int32Array>().unwrap().values());
114/// ```
115///
116/// [`StringArray`]: crate::array::StringArray
117/// [fixed size arrays](https://arrow.apache.org/docs/format/Columnar.html#fixed-size-list-layout)
118#[derive(Clone)]
119pub struct FixedSizeListArray {
120    data_type: DataType, // Must be DataType::FixedSizeList(value_length)
121    values: ArrayRef,
122    nulls: Option<NullBuffer>,
123    value_length: i32,
124    len: usize,
125}
126
127impl FixedSizeListArray {
128    /// Create a new [`FixedSizeListArray`] with `size` element size, panicking on failure
129    ///
130    /// # Panics
131    ///
132    /// Panics if [`Self::try_new`] returns an error
133    pub fn new(field: FieldRef, size: i32, values: ArrayRef, nulls: Option<NullBuffer>) -> Self {
134        Self::try_new(field, size, values, nulls).unwrap()
135    }
136
137    /// Create a new [`FixedSizeListArray`] from the provided parts, returning an error on failure
138    ///
139    /// # Errors
140    ///
141    /// * `size < 0`
142    /// * `values.len() / size != nulls.len()`
143    /// * `values.data_type() != field.data_type()`
144    /// * `!field.is_nullable() && !nulls.expand(size).contains(values.logical_nulls())`
145    pub fn try_new(
146        field: FieldRef,
147        size: i32,
148        values: ArrayRef,
149        nulls: Option<NullBuffer>,
150    ) -> Result<Self, ArrowError> {
151        let s = size.to_usize().ok_or_else(|| {
152            ArrowError::InvalidArgumentError(format!("Size cannot be negative, got {}", size))
153        })?;
154
155        let len = match s {
156            0 => nulls.as_ref().map(|x| x.len()).unwrap_or_default(),
157            _ => {
158                let len = values.len() / s.max(1);
159                if let Some(n) = nulls.as_ref() {
160                    if n.len() != len {
161                        return Err(ArrowError::InvalidArgumentError(format!(
162                            "Incorrect length of null buffer for FixedSizeListArray, expected {} got {}",
163                            len,
164                            n.len(),
165                        )));
166                    }
167                }
168                len
169            }
170        };
171
172        if field.data_type() != values.data_type() {
173            return Err(ArrowError::InvalidArgumentError(format!(
174                "FixedSizeListArray expected data type {} got {} for {:?}",
175                field.data_type(),
176                values.data_type(),
177                field.name()
178            )));
179        }
180
181        if let Some(a) = values.logical_nulls() {
182            let nulls_valid = field.is_nullable()
183                || nulls
184                    .as_ref()
185                    .map(|n| n.expand(size as _).contains(&a))
186                    .unwrap_or_default()
187                || (nulls.is_none() && a.null_count() == 0);
188
189            if !nulls_valid {
190                return Err(ArrowError::InvalidArgumentError(format!(
191                    "Found unmasked nulls for non-nullable FixedSizeListArray field {:?}",
192                    field.name()
193                )));
194            }
195        }
196
197        let data_type = DataType::FixedSizeList(field, size);
198        Ok(Self {
199            data_type,
200            values,
201            value_length: size,
202            nulls,
203            len,
204        })
205    }
206
207    /// Create a new [`FixedSizeListArray`] of length `len` where all values are null
208    ///
209    /// # Panics
210    ///
211    /// Panics if
212    ///
213    /// * `size < 0`
214    /// * `size * len` would overflow `usize`
215    pub fn new_null(field: FieldRef, size: i32, len: usize) -> Self {
216        let capacity = size.to_usize().unwrap().checked_mul(len).unwrap();
217        Self {
218            values: make_array(ArrayData::new_null(field.data_type(), capacity)),
219            data_type: DataType::FixedSizeList(field, size),
220            nulls: Some(NullBuffer::new_null(len)),
221            value_length: size,
222            len,
223        }
224    }
225
226    /// Deconstruct this array into its constituent parts
227    pub fn into_parts(self) -> (FieldRef, i32, ArrayRef, Option<NullBuffer>) {
228        let f = match self.data_type {
229            DataType::FixedSizeList(f, _) => f,
230            _ => unreachable!(),
231        };
232        (f, self.value_length, self.values, self.nulls)
233    }
234
235    /// Returns a reference to the values of this list.
236    pub fn values(&self) -> &ArrayRef {
237        &self.values
238    }
239
240    /// Returns a clone of the value type of this list.
241    pub fn value_type(&self) -> DataType {
242        self.values.data_type().clone()
243    }
244
245    /// Returns ith value of this list array.
246    pub fn value(&self, i: usize) -> ArrayRef {
247        self.values
248            .slice(self.value_offset_at(i), self.value_length() as usize)
249    }
250
251    /// Returns the offset for value at index `i`.
252    ///
253    /// Note this doesn't do any bound checking, for performance reason.
254    #[inline]
255    pub fn value_offset(&self, i: usize) -> i32 {
256        self.value_offset_at(i) as i32
257    }
258
259    /// Returns the length for an element.
260    ///
261    /// All elements have the same length as the array is a fixed size.
262    #[inline]
263    pub const fn value_length(&self) -> i32 {
264        self.value_length
265    }
266
267    #[inline]
268    const fn value_offset_at(&self, i: usize) -> usize {
269        i * self.value_length as usize
270    }
271
272    /// Returns a zero-copy slice of this array with the indicated offset and length.
273    pub fn slice(&self, offset: usize, len: usize) -> Self {
274        assert!(
275            offset.saturating_add(len) <= self.len,
276            "the length + offset of the sliced FixedSizeListArray cannot exceed the existing length"
277        );
278        let size = self.value_length as usize;
279
280        Self {
281            data_type: self.data_type.clone(),
282            values: self.values.slice(offset * size, len * size),
283            nulls: self.nulls.as_ref().map(|n| n.slice(offset, len)),
284            value_length: self.value_length,
285            len,
286        }
287    }
288
289    /// Creates a [`FixedSizeListArray`] from an iterator of primitive values
290    /// # Example
291    /// ```
292    /// # use arrow_array::FixedSizeListArray;
293    /// # use arrow_array::types::Int32Type;
294    ///
295    /// let data = vec![
296    ///    Some(vec![Some(0), Some(1), Some(2)]),
297    ///    None,
298    ///    Some(vec![Some(3), None, Some(5)]),
299    ///    Some(vec![Some(6), Some(7), Some(45)]),
300    /// ];
301    /// let list_array = FixedSizeListArray::from_iter_primitive::<Int32Type, _, _>(data, 3);
302    /// println!("{:?}", list_array);
303    /// ```
304    pub fn from_iter_primitive<T, P, I>(iter: I, length: i32) -> Self
305    where
306        T: ArrowPrimitiveType,
307        P: IntoIterator<Item = Option<<T as ArrowPrimitiveType>::Native>>,
308        I: IntoIterator<Item = Option<P>>,
309    {
310        let l = length as usize;
311        let iter = iter.into_iter();
312        let size_hint = iter.size_hint().0;
313        let mut builder = FixedSizeListBuilder::with_capacity(
314            PrimitiveBuilder::<T>::with_capacity(size_hint * l),
315            length,
316            size_hint,
317        );
318
319        for i in iter {
320            match i {
321                Some(p) => {
322                    for t in p {
323                        builder.values().append_option(t);
324                    }
325                    builder.append(true);
326                }
327                None => {
328                    builder.values().append_nulls(l);
329                    builder.append(false)
330                }
331            }
332        }
333        builder.finish()
334    }
335
336    /// constructs a new iterator
337    pub fn iter(&self) -> FixedSizeListIter<'_> {
338        FixedSizeListIter::new(self)
339    }
340}
341
342impl From<ArrayData> for FixedSizeListArray {
343    fn from(data: ArrayData) -> Self {
344        let value_length = match data.data_type() {
345            DataType::FixedSizeList(_, len) => *len,
346            _ => {
347                panic!("FixedSizeListArray data should contain a FixedSizeList data type")
348            }
349        };
350
351        let size = value_length as usize;
352        let values =
353            make_array(data.child_data()[0].slice(data.offset() * size, data.len() * size));
354        Self {
355            data_type: data.data_type().clone(),
356            values,
357            nulls: data.nulls().cloned(),
358            value_length,
359            len: data.len(),
360        }
361    }
362}
363
364impl From<FixedSizeListArray> for ArrayData {
365    fn from(array: FixedSizeListArray) -> Self {
366        let builder = ArrayDataBuilder::new(array.data_type)
367            .len(array.len)
368            .nulls(array.nulls)
369            .child_data(vec![array.values.to_data()]);
370
371        unsafe { builder.build_unchecked() }
372    }
373}
374
375impl Array for FixedSizeListArray {
376    fn as_any(&self) -> &dyn Any {
377        self
378    }
379
380    fn to_data(&self) -> ArrayData {
381        self.clone().into()
382    }
383
384    fn into_data(self) -> ArrayData {
385        self.into()
386    }
387
388    fn data_type(&self) -> &DataType {
389        &self.data_type
390    }
391
392    fn slice(&self, offset: usize, length: usize) -> ArrayRef {
393        Arc::new(self.slice(offset, length))
394    }
395
396    fn len(&self) -> usize {
397        self.len
398    }
399
400    fn is_empty(&self) -> bool {
401        self.len == 0
402    }
403
404    fn shrink_to_fit(&mut self) {
405        self.values.shrink_to_fit();
406        if let Some(nulls) = &mut self.nulls {
407            nulls.shrink_to_fit();
408        }
409    }
410
411    fn offset(&self) -> usize {
412        0
413    }
414
415    fn nulls(&self) -> Option<&NullBuffer> {
416        self.nulls.as_ref()
417    }
418
419    fn logical_null_count(&self) -> usize {
420        // More efficient that the default implementation
421        self.null_count()
422    }
423
424    fn get_buffer_memory_size(&self) -> usize {
425        let mut size = self.values.get_buffer_memory_size();
426        if let Some(n) = self.nulls.as_ref() {
427            size += n.buffer().capacity();
428        }
429        size
430    }
431
432    fn get_array_memory_size(&self) -> usize {
433        let mut size = std::mem::size_of::<Self>() + self.values.get_array_memory_size();
434        if let Some(n) = self.nulls.as_ref() {
435            size += n.buffer().capacity();
436        }
437        size
438    }
439}
440
441impl ArrayAccessor for FixedSizeListArray {
442    type Item = ArrayRef;
443
444    fn value(&self, index: usize) -> Self::Item {
445        FixedSizeListArray::value(self, index)
446    }
447
448    unsafe fn value_unchecked(&self, index: usize) -> Self::Item {
449        FixedSizeListArray::value(self, index)
450    }
451}
452
453impl std::fmt::Debug for FixedSizeListArray {
454    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
455        write!(f, "FixedSizeListArray<{}>\n[\n", self.value_length())?;
456        print_long_array(self, f, |array, index, f| {
457            std::fmt::Debug::fmt(&array.value(index), f)
458        })?;
459        write!(f, "]")
460    }
461}
462
463impl ArrayAccessor for &FixedSizeListArray {
464    type Item = ArrayRef;
465
466    fn value(&self, index: usize) -> Self::Item {
467        FixedSizeListArray::value(self, index)
468    }
469
470    unsafe fn value_unchecked(&self, index: usize) -> Self::Item {
471        FixedSizeListArray::value(self, index)
472    }
473}
474
475#[cfg(test)]
476mod tests {
477    use arrow_buffer::{bit_util, BooleanBuffer, Buffer};
478    use arrow_schema::Field;
479
480    use crate::cast::AsArray;
481    use crate::types::Int32Type;
482    use crate::{new_empty_array, Int32Array};
483
484    use super::*;
485
486    #[test]
487    fn test_fixed_size_list_array() {
488        // Construct a value array
489        let value_data = ArrayData::builder(DataType::Int32)
490            .len(9)
491            .add_buffer(Buffer::from_slice_ref([0, 1, 2, 3, 4, 5, 6, 7, 8]))
492            .build()
493            .unwrap();
494
495        // Construct a list array from the above two
496        let list_data_type =
497            DataType::FixedSizeList(Arc::new(Field::new_list_field(DataType::Int32, false)), 3);
498        let list_data = ArrayData::builder(list_data_type.clone())
499            .len(3)
500            .add_child_data(value_data.clone())
501            .build()
502            .unwrap();
503        let list_array = FixedSizeListArray::from(list_data);
504
505        assert_eq!(value_data, list_array.values().to_data());
506        assert_eq!(DataType::Int32, list_array.value_type());
507        assert_eq!(3, list_array.len());
508        assert_eq!(0, list_array.null_count());
509        assert_eq!(6, list_array.value_offset(2));
510        assert_eq!(3, list_array.value_length());
511        assert_eq!(0, list_array.value(0).as_primitive::<Int32Type>().value(0));
512        for i in 0..3 {
513            assert!(list_array.is_valid(i));
514            assert!(!list_array.is_null(i));
515        }
516
517        // Now test with a non-zero offset
518        let list_data = ArrayData::builder(list_data_type)
519            .len(2)
520            .offset(1)
521            .add_child_data(value_data.clone())
522            .build()
523            .unwrap();
524        let list_array = FixedSizeListArray::from(list_data);
525
526        assert_eq!(value_data.slice(3, 6), list_array.values().to_data());
527        assert_eq!(DataType::Int32, list_array.value_type());
528        assert_eq!(2, list_array.len());
529        assert_eq!(0, list_array.null_count());
530        assert_eq!(3, list_array.value(0).as_primitive::<Int32Type>().value(0));
531        assert_eq!(3, list_array.value_offset(1));
532        assert_eq!(3, list_array.value_length());
533    }
534
535    #[test]
536    #[should_panic(expected = "assertion failed: (offset + length) <= self.len()")]
537    // Different error messages, so skip for now
538    // https://github.com/apache/arrow-rs/issues/1545
539    #[cfg(not(feature = "force_validate"))]
540    fn test_fixed_size_list_array_unequal_children() {
541        // Construct a value array
542        let value_data = ArrayData::builder(DataType::Int32)
543            .len(8)
544            .add_buffer(Buffer::from_slice_ref([0, 1, 2, 3, 4, 5, 6, 7]))
545            .build()
546            .unwrap();
547
548        // Construct a list array from the above two
549        let list_data_type =
550            DataType::FixedSizeList(Arc::new(Field::new_list_field(DataType::Int32, false)), 3);
551        let list_data = unsafe {
552            ArrayData::builder(list_data_type)
553                .len(3)
554                .add_child_data(value_data)
555                .build_unchecked()
556        };
557        drop(FixedSizeListArray::from(list_data));
558    }
559
560    #[test]
561    fn test_fixed_size_list_array_slice() {
562        // Construct a value array
563        let value_data = ArrayData::builder(DataType::Int32)
564            .len(10)
565            .add_buffer(Buffer::from_slice_ref([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
566            .build()
567            .unwrap();
568
569        // Set null buts for the nested array:
570        //  [[0, 1], null, null, [6, 7], [8, 9]]
571        // 01011001 00000001
572        let mut null_bits: [u8; 1] = [0; 1];
573        bit_util::set_bit(&mut null_bits, 0);
574        bit_util::set_bit(&mut null_bits, 3);
575        bit_util::set_bit(&mut null_bits, 4);
576
577        // Construct a fixed size list array from the above two
578        let list_data_type =
579            DataType::FixedSizeList(Arc::new(Field::new_list_field(DataType::Int32, false)), 2);
580        let list_data = ArrayData::builder(list_data_type)
581            .len(5)
582            .add_child_data(value_data.clone())
583            .null_bit_buffer(Some(Buffer::from(null_bits)))
584            .build()
585            .unwrap();
586        let list_array = FixedSizeListArray::from(list_data);
587
588        assert_eq!(value_data, list_array.values().to_data());
589        assert_eq!(DataType::Int32, list_array.value_type());
590        assert_eq!(5, list_array.len());
591        assert_eq!(2, list_array.null_count());
592        assert_eq!(6, list_array.value_offset(3));
593        assert_eq!(2, list_array.value_length());
594
595        let sliced_array = list_array.slice(1, 4);
596        assert_eq!(4, sliced_array.len());
597        assert_eq!(2, sliced_array.null_count());
598
599        for i in 0..sliced_array.len() {
600            if bit_util::get_bit(&null_bits, 1 + i) {
601                assert!(sliced_array.is_valid(i));
602            } else {
603                assert!(sliced_array.is_null(i));
604            }
605        }
606
607        // Check offset and length for each non-null value.
608        let sliced_list_array = sliced_array
609            .as_any()
610            .downcast_ref::<FixedSizeListArray>()
611            .unwrap();
612        assert_eq!(2, sliced_list_array.value_length());
613        assert_eq!(4, sliced_list_array.value_offset(2));
614        assert_eq!(6, sliced_list_array.value_offset(3));
615    }
616
617    #[test]
618    #[should_panic(expected = "the offset of the new Buffer cannot exceed the existing length")]
619    fn test_fixed_size_list_array_index_out_of_bound() {
620        // Construct a value array
621        let value_data = ArrayData::builder(DataType::Int32)
622            .len(10)
623            .add_buffer(Buffer::from_slice_ref([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
624            .build()
625            .unwrap();
626
627        // Set null buts for the nested array:
628        //  [[0, 1], null, null, [6, 7], [8, 9]]
629        // 01011001 00000001
630        let mut null_bits: [u8; 1] = [0; 1];
631        bit_util::set_bit(&mut null_bits, 0);
632        bit_util::set_bit(&mut null_bits, 3);
633        bit_util::set_bit(&mut null_bits, 4);
634
635        // Construct a fixed size list array from the above two
636        let list_data_type =
637            DataType::FixedSizeList(Arc::new(Field::new_list_field(DataType::Int32, false)), 2);
638        let list_data = ArrayData::builder(list_data_type)
639            .len(5)
640            .add_child_data(value_data)
641            .null_bit_buffer(Some(Buffer::from(null_bits)))
642            .build()
643            .unwrap();
644        let list_array = FixedSizeListArray::from(list_data);
645
646        list_array.value(10);
647    }
648
649    #[test]
650    fn test_fixed_size_list_constructors() {
651        let values = Arc::new(Int32Array::from_iter([
652            Some(1),
653            Some(2),
654            None,
655            None,
656            Some(3),
657            Some(4),
658        ]));
659
660        let field = Arc::new(Field::new_list_field(DataType::Int32, true));
661        let list = FixedSizeListArray::new(field.clone(), 2, values.clone(), None);
662        assert_eq!(list.len(), 3);
663
664        let nulls = NullBuffer::new_null(3);
665        let list = FixedSizeListArray::new(field.clone(), 2, values.clone(), Some(nulls));
666        assert_eq!(list.len(), 3);
667
668        let list = FixedSizeListArray::new(field.clone(), 4, values.clone(), None);
669        assert_eq!(list.len(), 1);
670
671        let err = FixedSizeListArray::try_new(field.clone(), -1, values.clone(), None).unwrap_err();
672        assert_eq!(
673            err.to_string(),
674            "Invalid argument error: Size cannot be negative, got -1"
675        );
676
677        let list = FixedSizeListArray::new(field.clone(), 0, values.clone(), None);
678        assert_eq!(list.len(), 0);
679
680        let nulls = NullBuffer::new_null(2);
681        let err = FixedSizeListArray::try_new(field, 2, values.clone(), Some(nulls)).unwrap_err();
682        assert_eq!(err.to_string(), "Invalid argument error: Incorrect length of null buffer for FixedSizeListArray, expected 3 got 2");
683
684        let field = Arc::new(Field::new_list_field(DataType::Int32, false));
685        let err = FixedSizeListArray::try_new(field.clone(), 2, values.clone(), None).unwrap_err();
686        assert_eq!(err.to_string(), "Invalid argument error: Found unmasked nulls for non-nullable FixedSizeListArray field \"item\"");
687
688        // Valid as nulls in child masked by parent
689        let nulls = NullBuffer::new(BooleanBuffer::new(Buffer::from([0b0000101]), 0, 3));
690        FixedSizeListArray::new(field, 2, values.clone(), Some(nulls));
691
692        let field = Arc::new(Field::new_list_field(DataType::Int64, true));
693        let err = FixedSizeListArray::try_new(field, 2, values, None).unwrap_err();
694        assert_eq!(err.to_string(), "Invalid argument error: FixedSizeListArray expected data type Int64 got Int32 for \"item\"");
695    }
696
697    #[test]
698    fn empty_fixed_size_list() {
699        let field = Arc::new(Field::new_list_field(DataType::Int32, true));
700        let nulls = NullBuffer::new_null(2);
701        let values = new_empty_array(&DataType::Int32);
702        let list = FixedSizeListArray::new(field.clone(), 0, values, Some(nulls));
703        assert_eq!(list.len(), 2);
704    }
705}