Skip to main content

arrow_array/array/
mod.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
5//! The concrete array definitions
6
7mod binary_array;
8
9use crate::types::*;
10use arrow_buffer::{ArrowNativeType, Buffer, NullBuffer, OffsetBuffer, ScalarBuffer};
11use arrow_data::ArrayData;
12use arrow_schema::{DataType, IntervalUnit, TimeUnit};
13use std::any::Any;
14use std::sync::Arc;
15
16pub use binary_array::*;
17
18mod boolean_array;
19pub use boolean_array::*;
20
21mod byte_array;
22pub use byte_array::*;
23
24mod dictionary_array;
25pub use dictionary_array::*;
26
27mod fixed_size_binary_array;
28pub use fixed_size_binary_array::*;
29
30mod fixed_size_list_array;
31pub use fixed_size_list_array::*;
32
33mod list_array;
34pub use list_array::*;
35
36mod map_array;
37pub use map_array::*;
38
39mod null_array;
40pub use null_array::*;
41
42mod primitive_array;
43pub use primitive_array::*;
44
45mod string_array;
46pub use string_array::*;
47
48mod struct_array;
49pub use struct_array::*;
50
51mod union_array;
52pub use union_array::*;
53
54mod run_array;
55
56pub use run_array::*;
57
58mod byte_view_array;
59
60pub use byte_view_array::*;
61
62mod list_view_array;
63
64pub use list_view_array::*;
65
66use crate::iterator::ArrayIter;
67
68/// An array in the [Arrow Columnar Format](https://arrow.apache.org/docs/format/Columnar.html)
69///
70/// # Safety
71///
72/// Implementations of this trait must ensure that all methods implementations comply with
73/// the Arrow specification. No safety guards are placed and failing to comply with it can
74/// translate into panics or undefined behavior. For example, a value computed based on `len`
75/// may be used as a direct index into memory regions without checks.
76///
77/// Note that it is likely impossible to correctly implement the trait for a
78/// third party type, as substantial arrow-rs functionality is based on the
79/// return values of [`Array::data_type`] and third party types cannot extend
80/// the [`DataType`] enum. So any code that attempts casting based on data type
81/// (including internal arrow library code) risks a panic or undefined behavior.
82/// See [this discussion] for more details.
83///
84/// This trait might be sealed in the future. Use at your own risk.
85///
86/// [this discussion]: https://github.com/apache/arrow-rs/pull/9234#pullrequestreview-3708950936
87pub unsafe trait Array: std::fmt::Debug + Send + Sync {
88    /// Returns the array as [`Any`] so that it can be
89    /// downcasted to a specific implementation.
90    ///
91    /// # Example:
92    ///
93    /// ```
94    /// # use std::sync::Arc;
95    /// # use arrow_array::{Int32Array, RecordBatch};
96    /// # use arrow_schema::{Schema, Field, DataType, ArrowError};
97    ///
98    /// let id = Int32Array::from(vec![1, 2, 3, 4, 5]);
99    /// let batch = RecordBatch::try_new(
100    ///     Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])),
101    ///     vec![Arc::new(id)]
102    /// ).unwrap();
103    ///
104    /// let int32array = batch
105    ///     .column(0)
106    ///     .as_any()
107    ///     .downcast_ref::<Int32Array>()
108    ///     .expect("Failed to downcast");
109    /// ```
110    fn as_any(&self) -> &dyn Any;
111
112    /// Returns an [`ArrayRef`] with the same contents as `self`, sharing its buffers.
113    ///
114    /// If `self` is or wraps an `ArrayRef`, this only bumps the reference count, as if by
115    /// [`Arc::clone`]. The concrete arrow-rs array types all construct a new [`Arc`] from a shallow
116    /// clone of the array, which avoids the null-count recomputation and child re-slicing of
117    /// [`Self::slice`].
118    ///
119    /// The default implementation is `self.slice(0, self.len())`.
120    ///
121    /// # Example:
122    ///
123    /// ```
124    /// # use arrow_array::{Array, ArrayRef, Int32Array};
125    /// # use std::sync::Arc;
126    /// #
127    /// fn to_array_ref(array: &dyn Array) -> ArrayRef {
128    ///     array.to_arc()
129    /// }
130    ///
131    /// let array = Int32Array::from(vec![1, 2, 3]);
132    /// assert_eq!(to_array_ref(&array).as_ref(), &array);
133    ///
134    /// let array: ArrayRef = Arc::new(array);
135    /// assert!(Arc::ptr_eq(&to_array_ref(&array), &array));
136    /// ```
137    fn to_arc(&self) -> ArrayRef {
138        self.slice(0, self.len())
139    }
140
141    /// Returns the underlying data of this array
142    fn to_data(&self) -> ArrayData;
143
144    /// Returns the underlying data of this array
145    ///
146    /// Unlike [`Array::to_data`] this consumes self, allowing it avoid unnecessary clones
147    fn into_data(self) -> ArrayData;
148
149    /// Returns a reference to the [`DataType`] of this array.
150    ///
151    /// # Example:
152    ///
153    /// ```
154    /// use arrow_schema::DataType;
155    /// use arrow_array::{Array, Int32Array};
156    ///
157    /// let array = Int32Array::from(vec![1, 2, 3, 4, 5]);
158    ///
159    /// assert_eq!(*array.data_type(), DataType::Int32);
160    /// ```
161    fn data_type(&self) -> &DataType;
162
163    /// Returns a zero-copy slice of this array with the indicated offset and length.
164    ///
165    /// # Example:
166    ///
167    /// ```
168    /// use arrow_array::{Array, Int32Array};
169    ///
170    /// let array = Int32Array::from(vec![1, 2, 3, 4, 5]);
171    /// // Make slice over the values [2, 3, 4]
172    /// let array_slice = array.slice(1, 3);
173    ///
174    /// assert_eq!(&array_slice, &Int32Array::from(vec![2, 3, 4]));
175    /// ```
176    ///
177    /// # Panics
178    /// Panics if `offset + length > self.len()`
179    fn slice(&self, offset: usize, length: usize) -> ArrayRef;
180
181    /// Returns the length (i.e., number of elements) of this array.
182    ///
183    /// # Example:
184    ///
185    /// ```
186    /// use arrow_array::{Array, Int32Array};
187    ///
188    /// let array = Int32Array::from(vec![1, 2, 3, 4, 5]);
189    ///
190    /// assert_eq!(array.len(), 5);
191    /// ```
192    fn len(&self) -> usize;
193
194    /// Returns whether this array is empty.
195    ///
196    /// # Example:
197    ///
198    /// ```
199    /// use arrow_array::{Array, Int32Array};
200    ///
201    /// let array = Int32Array::from(vec![1, 2, 3, 4, 5]);
202    ///
203    /// assert_eq!(array.is_empty(), false);
204    /// ```
205    fn is_empty(&self) -> bool;
206
207    /// Shrinks the capacity of any exclusively owned buffer as much as possible
208    ///
209    /// Shared or externally allocated buffers will be ignored, and
210    /// any buffer offsets will be preserved.
211    fn shrink_to_fit(&mut self) {}
212
213    /// Returns the offset into the underlying data used by this array(-slice).
214    /// Note that the underlying data can be shared by many arrays.
215    /// This defaults to `0`.
216    ///
217    /// # Example:
218    ///
219    /// ```
220    /// use arrow_array::{Array, BooleanArray};
221    ///
222    /// let array = BooleanArray::from(vec![false, false, true, true]);
223    /// let array_slice = array.slice(1, 3);
224    ///
225    /// assert_eq!(array.offset(), 0);
226    /// assert_eq!(array_slice.offset(), 1);
227    /// ```
228    fn offset(&self) -> usize;
229
230    /// Returns the null buffer of this array if any.
231    ///
232    /// The null buffer contains the "physical" nulls of an array, that is how
233    /// the nulls are represented in the underlying arrow format.
234    ///
235    /// The physical representation is efficient, but is sometimes non intuitive
236    /// for certain array types such as those with nullable child arrays like
237    /// [`DictionaryArray::values`], [`RunArray::values`] or [`UnionArray`], or without a
238    /// null buffer, such as [`NullArray`].
239    ///
240    /// To determine if each element of such an array is "logically" null,
241    /// use the slower [`Array::logical_nulls`] to obtain a computed mask.
242    fn nulls(&self) -> Option<&NullBuffer>;
243
244    /// Returns a potentially computed [`NullBuffer`] that represents the logical
245    /// null values of this array, if any.
246    ///
247    /// Logical nulls represent the values that are null in the array,
248    /// regardless of the underlying physical arrow representation.
249    ///
250    /// For most array types, this is equivalent to the "physical" nulls
251    /// returned by [`Array::nulls`]. It is different for the following cases, because which
252    /// elements are null is not encoded in a single null buffer:
253    ///
254    /// * [`DictionaryArray`] where [`DictionaryArray::values`] contains nulls
255    /// * [`RunArray`] where [`RunArray::values`] contains nulls
256    /// * [`NullArray`] where all indices are nulls
257    /// * [`UnionArray`] where the selected values contains nulls
258    ///
259    /// In these cases a logical [`NullBuffer`] will be computed, encoding the
260    /// logical nullability of these arrays, beyond what is encoded in
261    /// [`Array::nulls`]
262    fn logical_nulls(&self) -> Option<NullBuffer> {
263        self.nulls().cloned()
264    }
265
266    /// Returns whether the element at `index` is null according to [`Array::nulls`]
267    ///
268    /// Note: For performance reasons, this method returns nullability solely as determined by the
269    /// null buffer. This difference can lead to surprising results, for example, [`NullArray::is_null`] always
270    /// returns `false` as the array lacks a null buffer. Similarly [`DictionaryArray`], [`RunArray`] and [`UnionArray`] may
271    /// encode nullability in their children. See [`Self::logical_nulls`] for more information.
272    ///
273    /// # Example:
274    ///
275    /// ```
276    /// use arrow_array::{Array, Int32Array, NullArray};
277    ///
278    /// let array = Int32Array::from(vec![Some(1), None]);
279    /// assert_eq!(array.is_null(0), false);
280    /// assert_eq!(array.is_null(1), true);
281    ///
282    /// // NullArrays do not have a null buffer, and therefore always
283    /// // return false for is_null.
284    /// let array = NullArray::new(1);
285    /// assert_eq!(array.is_null(0), false);
286    /// ```
287    ///
288    /// # Panics
289    ///
290    /// Panics if `index >= self.len()`.
291    ///
292    /// Note: arrays without a null buffer currently return `false` instead of
293    /// panicking, but callers must not rely on this.
294    fn is_null(&self, index: usize) -> bool {
295        self.nulls().is_some_and(|n| n.is_null(index))
296    }
297
298    /// Returns whether the element at `index` is *not* null, the
299    /// opposite of [`Self::is_null`].
300    ///
301    /// # Example:
302    ///
303    /// ```
304    /// use arrow_array::{Array, Int32Array};
305    ///
306    /// let array = Int32Array::from(vec![Some(1), None]);
307    ///
308    /// assert_eq!(array.is_valid(0), true);
309    /// assert_eq!(array.is_valid(1), false);
310    /// ```
311    ///
312    /// # Panics
313    ///
314    /// Panics if `index >= self.len()`.
315    ///
316    /// Note: arrays without a null buffer currently return `true` instead of
317    /// panicking, but callers must not rely on this.
318    fn is_valid(&self, index: usize) -> bool {
319        !self.is_null(index)
320    }
321
322    /// Returns the total number of physical null values in this array.
323    ///
324    /// Note: this method returns the physical null count, i.e. that encoded in [`Array::nulls`],
325    /// see [`Array::logical_nulls`] for logical nullability
326    ///
327    /// # Example:
328    ///
329    /// ```
330    /// use arrow_array::{Array, Int32Array};
331    ///
332    /// // Construct an array with values [1, NULL, NULL]
333    /// let array = Int32Array::from(vec![Some(1), None, None]);
334    ///
335    /// assert_eq!(array.null_count(), 2);
336    /// ```
337    fn null_count(&self) -> usize {
338        self.nulls().map(|n| n.null_count()).unwrap_or_default()
339    }
340
341    /// Returns the total number of logical null values in this array.
342    ///
343    /// Note: this method returns the logical null count, i.e. that encoded in
344    /// [`Array::logical_nulls`]. In general this is equivalent to [`Array::null_count`] but may differ in the
345    /// presence of logical nullability, see [`Array::nulls`] and [`Array::logical_nulls`].
346    ///
347    /// # Example:
348    ///
349    /// ```
350    /// use arrow_array::{Array, Int32Array};
351    ///
352    /// // Construct an array with values [1, NULL, NULL]
353    /// let array = Int32Array::from(vec![Some(1), None, None]);
354    ///
355    /// assert_eq!(array.logical_null_count(), 2);
356    /// ```
357    fn logical_null_count(&self) -> usize {
358        self.logical_nulls()
359            .map(|n| n.null_count())
360            .unwrap_or_default()
361    }
362
363    /// Returns `false` if the array is guaranteed to not contain any logical nulls
364    ///
365    /// This is generally equivalent to `Array::logical_null_count() != 0` unless determining
366    /// the logical nulls is expensive, in which case this method can return true even for an
367    /// array without nulls.
368    ///
369    /// This is also generally equivalent to `Array::null_count() != 0` but may differ in the
370    /// presence of logical nullability, see [`Array::logical_null_count`] and [`Array::null_count`].
371    ///
372    /// Implementations will return `true` unless they can cheaply prove no logical nulls
373    /// are present. For example a [`DictionaryArray`] with nullable values will still return true,
374    /// even if the nulls present in [`DictionaryArray::values`] are not referenced by any key,
375    /// and therefore would not appear in [`Array::logical_nulls`].
376    fn is_nullable(&self) -> bool {
377        self.logical_null_count() != 0
378    }
379
380    /// Returns the total number of bytes of memory pointed to by this array.
381    /// The buffers store bytes in the Arrow memory format, and include the data as well as the validity map.
382    /// Note that this does not always correspond to the exact memory usage of an array,
383    /// since multiple arrays can share the same buffers or slices thereof.
384    fn get_buffer_memory_size(&self) -> usize;
385
386    /// Returns the total number of bytes of memory occupied physically by this array.
387    /// This value will always be greater than returned by `get_buffer_memory_size()` and
388    /// includes the overhead of the data structures that contain the pointers to the various buffers.
389    fn get_array_memory_size(&self) -> usize;
390
391    /// Claim memory used by this array in the provided memory pool.
392    ///
393    /// This recursively claims memory for:
394    /// - All data buffers in this array
395    /// - All child arrays (for nested types like List, Struct, etc.)
396    /// - The null bitmap buffer if present
397    ///
398    /// This method guarantees that the memory pool will only compute occupied memory
399    /// exactly once. For example, if this array is derived from operations like `slice`,
400    /// calling `claim` on it would not change the memory pool's usage if the underlying buffers
401    /// are already counted before.
402    ///
403    /// # Example
404    /// ```
405    /// # use arrow_array::{Int32Array, Array};
406    /// # use arrow_buffer::TrackingMemoryPool;
407    /// # use arrow_buffer::MemoryPool;
408    ///
409    /// let pool = TrackingMemoryPool::default();
410    ///
411    /// let small_array = Int32Array::from(vec![1, 2, 3, 4, 5]);
412    /// let small_array_size = small_array.get_buffer_memory_size();
413    ///
414    /// // Claim the array's memory in the pool
415    /// small_array.claim(&pool);
416    ///
417    /// // Create and claim slices of `small_array`; should not increase memory usage
418    /// let slice1 = small_array.slice(0, 2);
419    /// let slice2 = small_array.slice(2, 2);
420    /// slice1.claim(&pool);
421    /// slice2.claim(&pool);
422    ///
423    /// assert_eq!(pool.used(), small_array_size);
424    ///
425    /// // Create a `large_array` which does not derive from the original `small_array`
426    ///
427    /// let large_array = Int32Array::from((0..1000).collect::<Vec<i32>>());
428    /// let large_array_size = large_array.get_buffer_memory_size();
429    ///
430    /// large_array.claim(&pool);
431    ///
432    /// // Trying to claim more than once is a no-op
433    /// large_array.claim(&pool);
434    /// large_array.claim(&pool);
435    ///
436    /// assert_eq!(pool.used(), small_array_size + large_array_size);
437    ///
438    /// let sum_of_all_sizes = small_array_size + large_array_size + slice1.get_buffer_memory_size() + slice2.get_buffer_memory_size();
439    ///
440    /// // `get_buffer_memory_size` works independently of the memory pool, so a sum of all the
441    /// // arrays in scope will always be >= the memory used reported by the memory pool.
442    /// assert_ne!(pool.used(), sum_of_all_sizes);
443    ///
444    /// // Until the final claim is dropped the buffer size remains accounted for
445    /// drop(small_array);
446    /// drop(slice1);
447    ///
448    /// assert_eq!(pool.used(), small_array_size + large_array_size);
449    ///
450    /// // Dropping this finally releases the buffer that was backing `small_array`
451    /// drop(slice2);
452    ///
453    /// assert_eq!(pool.used(), large_array_size);
454    /// ```
455    #[cfg(feature = "pool")]
456    fn claim(&self, pool: &dyn arrow_buffer::MemoryPool) {
457        self.to_data().claim(pool)
458    }
459}
460
461/// A reference-counted reference to a generic `Array`
462pub type ArrayRef = Arc<dyn Array>;
463
464/// Ergonomics: Allow use of an ArrayRef as an `&dyn Array`
465unsafe impl Array for ArrayRef {
466    fn as_any(&self) -> &dyn Any {
467        self.as_ref().as_any()
468    }
469
470    fn to_arc(&self) -> ArrayRef {
471        Arc::clone(self)
472    }
473
474    fn to_data(&self) -> ArrayData {
475        self.as_ref().to_data()
476    }
477
478    fn into_data(self) -> ArrayData {
479        self.to_data()
480    }
481
482    fn data_type(&self) -> &DataType {
483        self.as_ref().data_type()
484    }
485
486    fn slice(&self, offset: usize, length: usize) -> ArrayRef {
487        self.as_ref().slice(offset, length)
488    }
489
490    fn len(&self) -> usize {
491        self.as_ref().len()
492    }
493
494    fn is_empty(&self) -> bool {
495        self.as_ref().is_empty()
496    }
497
498    /// For shared buffers, this is a no-op.
499    fn shrink_to_fit(&mut self) {
500        if let Some(slf) = Arc::get_mut(self) {
501            slf.shrink_to_fit();
502        } else {
503            // We ignore shared buffers.
504        }
505    }
506
507    fn offset(&self) -> usize {
508        self.as_ref().offset()
509    }
510
511    fn nulls(&self) -> Option<&NullBuffer> {
512        self.as_ref().nulls()
513    }
514
515    fn logical_nulls(&self) -> Option<NullBuffer> {
516        self.as_ref().logical_nulls()
517    }
518
519    fn is_null(&self, index: usize) -> bool {
520        self.as_ref().is_null(index)
521    }
522
523    fn is_valid(&self, index: usize) -> bool {
524        self.as_ref().is_valid(index)
525    }
526
527    fn null_count(&self) -> usize {
528        self.as_ref().null_count()
529    }
530
531    fn logical_null_count(&self) -> usize {
532        self.as_ref().logical_null_count()
533    }
534
535    fn is_nullable(&self) -> bool {
536        self.as_ref().is_nullable()
537    }
538
539    fn get_buffer_memory_size(&self) -> usize {
540        self.as_ref().get_buffer_memory_size()
541    }
542
543    fn get_array_memory_size(&self) -> usize {
544        self.as_ref().get_array_memory_size()
545    }
546
547    #[cfg(feature = "pool")]
548    fn claim(&self, pool: &dyn arrow_buffer::MemoryPool) {
549        self.as_ref().claim(pool)
550    }
551}
552
553unsafe impl<T: Array> Array for &T {
554    fn as_any(&self) -> &dyn Any {
555        T::as_any(self)
556    }
557
558    fn to_arc(&self) -> ArrayRef {
559        T::to_arc(self)
560    }
561
562    fn to_data(&self) -> ArrayData {
563        T::to_data(self)
564    }
565
566    fn into_data(self) -> ArrayData {
567        self.to_data()
568    }
569
570    fn data_type(&self) -> &DataType {
571        T::data_type(self)
572    }
573
574    fn slice(&self, offset: usize, length: usize) -> ArrayRef {
575        T::slice(self, offset, length)
576    }
577
578    fn len(&self) -> usize {
579        T::len(self)
580    }
581
582    fn is_empty(&self) -> bool {
583        T::is_empty(self)
584    }
585
586    fn offset(&self) -> usize {
587        T::offset(self)
588    }
589
590    fn nulls(&self) -> Option<&NullBuffer> {
591        T::nulls(self)
592    }
593
594    fn logical_nulls(&self) -> Option<NullBuffer> {
595        T::logical_nulls(self)
596    }
597
598    fn is_null(&self, index: usize) -> bool {
599        T::is_null(self, index)
600    }
601
602    fn is_valid(&self, index: usize) -> bool {
603        T::is_valid(self, index)
604    }
605
606    fn null_count(&self) -> usize {
607        T::null_count(self)
608    }
609
610    fn logical_null_count(&self) -> usize {
611        T::logical_null_count(self)
612    }
613
614    fn is_nullable(&self) -> bool {
615        T::is_nullable(self)
616    }
617
618    fn get_buffer_memory_size(&self) -> usize {
619        T::get_buffer_memory_size(self)
620    }
621
622    fn get_array_memory_size(&self) -> usize {
623        T::get_array_memory_size(self)
624    }
625
626    #[cfg(feature = "pool")]
627    fn claim(&self, pool: &dyn arrow_buffer::MemoryPool) {
628        T::claim(self, pool)
629    }
630}
631
632/// A generic trait for accessing the values of an [`Array`]
633///
634/// This trait helps write specialized implementations of algorithms for
635/// different array types. Specialized implementations allow the compiler
636/// to optimize the code for the specific array type, which can lead to
637/// significant performance improvements.
638///
639/// # Example
640/// For example, to write three different implementations of a string length function
641/// for [`StringArray`], [`LargeStringArray`], and [`StringViewArray`], you can write
642///
643/// ```
644/// # use std::sync::Arc;
645/// # use arrow_array::{ArrayAccessor, ArrayRef, ArrowPrimitiveType, OffsetSizeTrait, PrimitiveArray};
646/// # use arrow_buffer::ArrowNativeType;
647/// # use arrow_array::cast::AsArray;
648/// # use arrow_array::iterator::ArrayIter;
649/// # use arrow_array::types::{Int32Type, Int64Type};
650/// # use arrow_schema::{ArrowError, DataType};
651/// /// This function takes a dynamically typed `ArrayRef` and calls
652/// /// calls one of three specialized implementations
653/// fn character_length(arg: ArrayRef) -> Result<ArrayRef, ArrowError> {
654///     match arg.data_type() {
655///         DataType::Utf8 => {
656///             // downcast the ArrayRef to a StringArray and call the specialized implementation
657///             let string_array = arg.as_string::<i32>();
658///             character_length_general::<Int32Type, _>(string_array)
659///         }
660///         DataType::LargeUtf8 => {
661///             character_length_general::<Int64Type, _>(arg.as_string::<i64>())
662///         }
663///         DataType::Utf8View => {
664///             character_length_general::<Int32Type, _>(arg.as_string_view())
665///         }
666///         _ => Err(ArrowError::InvalidArgumentError("Unsupported data type".to_string())),
667///     }
668/// }
669///
670/// /// A generic implementation of the character_length function
671/// /// This function uses the `ArrayAccessor` trait to access the values of the array
672/// /// so the compiler can generated specialized implementations for different array types
673/// ///
674/// /// Returns a new array with the length of each string in the input array
675/// /// * Int32Array for Utf8 and Utf8View arrays (lengths are 32-bit integers)
676/// /// * Int64Array for LargeUtf8 arrays (lengths are 64-bit integers)
677/// ///
678/// /// This is generic on the type of the primitive array (different string arrays have
679/// /// different lengths) and the type of the array accessor (different string arrays
680/// /// have different ways to access the values)
681/// fn character_length_general<'a, T: ArrowPrimitiveType, V: ArrayAccessor<Item = &'a str>>(
682///     array: V,
683/// ) -> Result<ArrayRef, ArrowError>
684/// where
685///     T::Native: OffsetSizeTrait,
686/// {
687///     let iter = ArrayIter::new(array);
688///     // Create a Int32Array / Int64Array with the length of each string
689///     let result = iter
690///         .map(|string| {
691///             string.map(|string: &str| {
692///                 T::Native::from_usize(string.chars().count())
693///                     .expect("should not fail as string.chars will always return integer")
694///             })
695///         })
696///         .collect::<PrimitiveArray<T>>();
697///
698///     /// Return the result as a new ArrayRef (dynamically typed)
699///     Ok(Arc::new(result) as ArrayRef)
700/// }
701/// ```
702///
703/// # Validity
704///
705/// An [`ArrayAccessor`] must always return a well-defined value for an index
706/// that is within the bounds `0..Array::len`, including for null indexes where
707/// [`Array::is_null`] is true.
708///
709/// The value at null indexes is unspecified, and implementations must not rely
710/// on a specific value such as [`Default::default`] being returned, however, it
711/// must not be undefined
712pub trait ArrayAccessor: Array {
713    /// The Arrow type of the element being accessed.
714    type Item: Send + Sync;
715
716    /// Returns the element at index `i`
717    /// # Panics
718    /// Panics if the value is outside the bounds of the array
719    fn value(&self, index: usize) -> Self::Item;
720
721    /// Returns the element at index `i`
722    /// # Safety
723    /// Caller is responsible for ensuring that the index is within the bounds of the array
724    unsafe fn value_unchecked(&self, index: usize) -> Self::Item;
725}
726
727/// A trait for Arrow String Arrays, currently three types are supported:
728/// - `StringArray`
729/// - `LargeStringArray`
730/// - `StringViewArray`
731///
732/// This trait helps to abstract over the different types of string arrays
733/// so that we don't need to duplicate the implementation for each type.
734pub trait StringArrayType<'a>: ArrayAccessor<Item = &'a str> + Sized {
735    /// Returns true if all data within this string array is ASCII
736    fn is_ascii(&self) -> bool;
737
738    /// Constructs a new iterator
739    fn iter(&self) -> ArrayIter<Self>;
740}
741
742impl<'a, O: OffsetSizeTrait> StringArrayType<'a> for &'a GenericStringArray<O> {
743    fn is_ascii(&self) -> bool {
744        GenericStringArray::<O>::is_ascii(self)
745    }
746
747    fn iter(&self) -> ArrayIter<Self> {
748        GenericStringArray::<O>::iter(self)
749    }
750}
751impl<'a> StringArrayType<'a> for &'a StringViewArray {
752    fn is_ascii(&self) -> bool {
753        StringViewArray::is_ascii(self)
754    }
755
756    fn iter(&self) -> ArrayIter<Self> {
757        StringViewArray::iter(self)
758    }
759}
760
761/// A trait for Arrow Binary Arrays, currently four types are supported:
762/// - `BinaryArray`
763/// - `LargeBinaryArray`
764/// - `BinaryViewArray`
765/// - `FixedSizeBinaryArray`
766///
767/// This trait helps to abstract over the different types of binary arrays
768/// so that we don't need to duplicate the implementation for each type.
769pub trait BinaryArrayType<'a>: ArrayAccessor<Item = &'a [u8]> + Sized {
770    /// Constructs a new iterator
771    fn iter(&self) -> ArrayIter<Self>;
772}
773
774impl<'a, O: OffsetSizeTrait> BinaryArrayType<'a> for &'a GenericBinaryArray<O> {
775    fn iter(&self) -> ArrayIter<Self> {
776        GenericBinaryArray::<O>::iter(self)
777    }
778}
779impl<'a> BinaryArrayType<'a> for &'a BinaryViewArray {
780    fn iter(&self) -> ArrayIter<Self> {
781        BinaryViewArray::iter(self)
782    }
783}
784impl<'a> BinaryArrayType<'a> for &'a FixedSizeBinaryArray {
785    fn iter(&self) -> ArrayIter<Self> {
786        FixedSizeBinaryArray::iter(self)
787    }
788}
789
790/// A trait for Arrow list-like arrays, abstracting over
791/// [`GenericListArray`], [`GenericListViewArray`], and [`FixedSizeListArray`].
792///
793/// This trait provides a uniform interface for accessing the child values and
794/// computing the element range for a given index, regardless of the underlying
795/// list layout (offsets, offsets+sizes, or fixed-size).
796pub trait ListLikeArray: Array {
797    /// Returns the child values array.
798    fn values(&self) -> &ArrayRef;
799
800    /// Returns the start and end indices into the values array for the list
801    /// element at `index`.
802    fn element_range(&self, index: usize) -> std::ops::Range<usize>;
803}
804
805impl PartialEq for dyn Array + '_ {
806    fn eq(&self, other: &Self) -> bool {
807        self.to_data().eq(&other.to_data())
808    }
809}
810
811impl<T: Array> PartialEq<T> for dyn Array + '_ {
812    fn eq(&self, other: &T) -> bool {
813        self.to_data().eq(&other.to_data())
814    }
815}
816
817impl PartialEq for NullArray {
818    fn eq(&self, other: &NullArray) -> bool {
819        self.to_data().eq(&other.to_data())
820    }
821}
822
823impl<T: ArrowPrimitiveType> PartialEq for PrimitiveArray<T> {
824    fn eq(&self, other: &PrimitiveArray<T>) -> bool {
825        self.to_data().eq(&other.to_data())
826    }
827}
828
829impl<K: ArrowDictionaryKeyType> PartialEq for DictionaryArray<K> {
830    fn eq(&self, other: &Self) -> bool {
831        self.to_data().eq(&other.to_data())
832    }
833}
834
835impl PartialEq for BooleanArray {
836    fn eq(&self, other: &BooleanArray) -> bool {
837        self.to_data().eq(&other.to_data())
838    }
839}
840
841impl<OffsetSize: OffsetSizeTrait> PartialEq for GenericStringArray<OffsetSize> {
842    fn eq(&self, other: &Self) -> bool {
843        self.to_data().eq(&other.to_data())
844    }
845}
846
847impl<OffsetSize: OffsetSizeTrait> PartialEq for GenericBinaryArray<OffsetSize> {
848    fn eq(&self, other: &Self) -> bool {
849        self.to_data().eq(&other.to_data())
850    }
851}
852
853impl PartialEq for FixedSizeBinaryArray {
854    fn eq(&self, other: &Self) -> bool {
855        self.to_data().eq(&other.to_data())
856    }
857}
858
859impl<OffsetSize: OffsetSizeTrait> PartialEq for GenericListArray<OffsetSize> {
860    fn eq(&self, other: &Self) -> bool {
861        self.to_data().eq(&other.to_data())
862    }
863}
864
865impl<OffsetSize: OffsetSizeTrait> PartialEq for GenericListViewArray<OffsetSize> {
866    fn eq(&self, other: &Self) -> bool {
867        self.to_data().eq(&other.to_data())
868    }
869}
870
871impl PartialEq for MapArray {
872    fn eq(&self, other: &Self) -> bool {
873        self.to_data().eq(&other.to_data())
874    }
875}
876
877impl PartialEq for FixedSizeListArray {
878    fn eq(&self, other: &Self) -> bool {
879        self.to_data().eq(&other.to_data())
880    }
881}
882
883impl PartialEq for StructArray {
884    fn eq(&self, other: &Self) -> bool {
885        self.to_data().eq(&other.to_data())
886    }
887}
888
889impl<T: ByteViewType + ?Sized> PartialEq for GenericByteViewArray<T> {
890    fn eq(&self, other: &Self) -> bool {
891        self.to_data().eq(&other.to_data())
892    }
893}
894
895impl<R: RunEndIndexType> PartialEq for RunArray<R> {
896    fn eq(&self, other: &Self) -> bool {
897        self.to_data().eq(&other.to_data())
898    }
899}
900
901/// Constructs an [`ArrayRef`] from an [`ArrayData`].
902///
903/// # Notes:
904///
905/// It is more efficient to directly construct the concrete array type rather
906/// than using this function as creating an `ArrayData` requires at least one
907/// additional allocation (the Vec of buffers).
908///
909/// # Example:
910/// ```
911/// # use std::sync::Arc;
912/// # use arrow_data::ArrayData;
913/// # use arrow_array::{make_array, ArrayRef, Int32Array};
914/// # use arrow_buffer::{Buffer, ScalarBuffer};
915/// # use arrow_schema::DataType;
916/// // Create an Int32Array with values [1, 2, 3]
917/// let values_buffer = Buffer::from_slice_ref(&[1, 2, 3]);
918/// // ArrayData can be constructed using ArrayDataBuilder
919///  let builder = ArrayData::builder(DataType::Int32)
920///    .len(3)
921///    .add_buffer(values_buffer.clone());
922/// let array_data = builder.build().unwrap();
923/// // Create the ArrayRef from the ArrayData
924/// let array = make_array(array_data);
925///
926/// // It is equivalent to directly constructing the Int32Array
927/// let scalar_buffer = ScalarBuffer::from(values_buffer);
928/// let int32_array: ArrayRef = Arc::new(Int32Array::new(scalar_buffer, None));
929/// assert_eq!(&array, &int32_array);
930/// ```
931pub fn make_array(data: ArrayData) -> ArrayRef {
932    match data.data_type() {
933        DataType::Boolean => Arc::new(BooleanArray::from(data)) as ArrayRef,
934        DataType::Int8 => Arc::new(Int8Array::from(data)) as ArrayRef,
935        DataType::Int16 => Arc::new(Int16Array::from(data)) as ArrayRef,
936        DataType::Int32 => Arc::new(Int32Array::from(data)) as ArrayRef,
937        DataType::Int64 => Arc::new(Int64Array::from(data)) as ArrayRef,
938        DataType::UInt8 => Arc::new(UInt8Array::from(data)) as ArrayRef,
939        DataType::UInt16 => Arc::new(UInt16Array::from(data)) as ArrayRef,
940        DataType::UInt32 => Arc::new(UInt32Array::from(data)) as ArrayRef,
941        DataType::UInt64 => Arc::new(UInt64Array::from(data)) as ArrayRef,
942        DataType::Float16 => Arc::new(Float16Array::from(data)) as ArrayRef,
943        DataType::Float32 => Arc::new(Float32Array::from(data)) as ArrayRef,
944        DataType::Float64 => Arc::new(Float64Array::from(data)) as ArrayRef,
945        DataType::Date32 => Arc::new(Date32Array::from(data)) as ArrayRef,
946        DataType::Date64 => Arc::new(Date64Array::from(data)) as ArrayRef,
947        DataType::Time32(TimeUnit::Second) => Arc::new(Time32SecondArray::from(data)) as ArrayRef,
948        DataType::Time32(TimeUnit::Millisecond) => {
949            Arc::new(Time32MillisecondArray::from(data)) as ArrayRef
950        }
951        DataType::Time64(TimeUnit::Microsecond) => {
952            Arc::new(Time64MicrosecondArray::from(data)) as ArrayRef
953        }
954        DataType::Time64(TimeUnit::Nanosecond) => {
955            Arc::new(Time64NanosecondArray::from(data)) as ArrayRef
956        }
957        DataType::Timestamp(TimeUnit::Second, _) => {
958            Arc::new(TimestampSecondArray::from(data)) as ArrayRef
959        }
960        DataType::Timestamp(TimeUnit::Millisecond, _) => {
961            Arc::new(TimestampMillisecondArray::from(data)) as ArrayRef
962        }
963        DataType::Timestamp(TimeUnit::Microsecond, _) => {
964            Arc::new(TimestampMicrosecondArray::from(data)) as ArrayRef
965        }
966        DataType::Timestamp(TimeUnit::Nanosecond, _) => {
967            Arc::new(TimestampNanosecondArray::from(data)) as ArrayRef
968        }
969        DataType::Interval(IntervalUnit::YearMonth) => {
970            Arc::new(IntervalYearMonthArray::from(data)) as ArrayRef
971        }
972        DataType::Interval(IntervalUnit::DayTime) => {
973            Arc::new(IntervalDayTimeArray::from(data)) as ArrayRef
974        }
975        DataType::Interval(IntervalUnit::MonthDayNano) => {
976            Arc::new(IntervalMonthDayNanoArray::from(data)) as ArrayRef
977        }
978        DataType::Duration(TimeUnit::Second) => {
979            Arc::new(DurationSecondArray::from(data)) as ArrayRef
980        }
981        DataType::Duration(TimeUnit::Millisecond) => {
982            Arc::new(DurationMillisecondArray::from(data)) as ArrayRef
983        }
984        DataType::Duration(TimeUnit::Microsecond) => {
985            Arc::new(DurationMicrosecondArray::from(data)) as ArrayRef
986        }
987        DataType::Duration(TimeUnit::Nanosecond) => {
988            Arc::new(DurationNanosecondArray::from(data)) as ArrayRef
989        }
990        DataType::Binary => Arc::new(BinaryArray::from(data)) as ArrayRef,
991        DataType::LargeBinary => Arc::new(LargeBinaryArray::from(data)) as ArrayRef,
992        DataType::FixedSizeBinary(_) => Arc::new(FixedSizeBinaryArray::from(data)) as ArrayRef,
993        DataType::BinaryView => Arc::new(BinaryViewArray::from(data)) as ArrayRef,
994        DataType::Utf8 => Arc::new(StringArray::from(data)) as ArrayRef,
995        DataType::LargeUtf8 => Arc::new(LargeStringArray::from(data)) as ArrayRef,
996        DataType::Utf8View => Arc::new(StringViewArray::from(data)) as ArrayRef,
997        DataType::List(_) => Arc::new(ListArray::from(data)) as ArrayRef,
998        DataType::LargeList(_) => Arc::new(LargeListArray::from(data)) as ArrayRef,
999        DataType::ListView(_) => Arc::new(ListViewArray::from(data)) as ArrayRef,
1000        DataType::LargeListView(_) => Arc::new(LargeListViewArray::from(data)) as ArrayRef,
1001        DataType::Struct(_) => Arc::new(StructArray::from(data)) as ArrayRef,
1002        DataType::Map(_, _) => Arc::new(MapArray::from(data)) as ArrayRef,
1003        DataType::Union(_, _) => Arc::new(UnionArray::from(data)) as ArrayRef,
1004        DataType::FixedSizeList(_, _) => Arc::new(FixedSizeListArray::from(data)) as ArrayRef,
1005        DataType::Dictionary(key_type, _) => match key_type.as_ref() {
1006            DataType::Int8 => Arc::new(DictionaryArray::<Int8Type>::from(data)) as ArrayRef,
1007            DataType::Int16 => Arc::new(DictionaryArray::<Int16Type>::from(data)) as ArrayRef,
1008            DataType::Int32 => Arc::new(DictionaryArray::<Int32Type>::from(data)) as ArrayRef,
1009            DataType::Int64 => Arc::new(DictionaryArray::<Int64Type>::from(data)) as ArrayRef,
1010            DataType::UInt8 => Arc::new(DictionaryArray::<UInt8Type>::from(data)) as ArrayRef,
1011            DataType::UInt16 => Arc::new(DictionaryArray::<UInt16Type>::from(data)) as ArrayRef,
1012            DataType::UInt32 => Arc::new(DictionaryArray::<UInt32Type>::from(data)) as ArrayRef,
1013            DataType::UInt64 => Arc::new(DictionaryArray::<UInt64Type>::from(data)) as ArrayRef,
1014            dt => unimplemented!("Unexpected dictionary key type {dt}"),
1015        },
1016        DataType::RunEndEncoded(run_ends_type, _) => match run_ends_type.data_type() {
1017            DataType::Int16 => Arc::new(RunArray::<Int16Type>::from(data)) as ArrayRef,
1018            DataType::Int32 => Arc::new(RunArray::<Int32Type>::from(data)) as ArrayRef,
1019            DataType::Int64 => Arc::new(RunArray::<Int64Type>::from(data)) as ArrayRef,
1020            dt => unimplemented!("Unexpected data type for run_ends array {dt}"),
1021        },
1022        DataType::Null => Arc::new(NullArray::from(data)) as ArrayRef,
1023        DataType::Decimal32(_, _) => Arc::new(Decimal32Array::from(data)) as ArrayRef,
1024        DataType::Decimal64(_, _) => Arc::new(Decimal64Array::from(data)) as ArrayRef,
1025        DataType::Decimal128(_, _) => Arc::new(Decimal128Array::from(data)) as ArrayRef,
1026        DataType::Decimal256(_, _) => Arc::new(Decimal256Array::from(data)) as ArrayRef,
1027        dt => unimplemented!("Unexpected data type {dt}"),
1028    }
1029}
1030
1031/// Creates a new empty array
1032///
1033/// ```
1034/// use std::sync::Arc;
1035/// use arrow_schema::DataType;
1036/// use arrow_array::{ArrayRef, Int32Array, new_empty_array};
1037///
1038/// let empty_array = new_empty_array(&DataType::Int32);
1039/// let array: ArrayRef = Arc::new(Int32Array::from(vec![] as Vec<i32>));
1040///
1041/// assert_eq!(&array, &empty_array);
1042/// ```
1043pub fn new_empty_array(data_type: &DataType) -> ArrayRef {
1044    let data = ArrayData::new_empty(data_type);
1045    make_array(data)
1046}
1047
1048/// Creates a new array of `data_type` of length `length` filled
1049/// entirely of `NULL` values
1050///
1051/// ```
1052/// use std::sync::Arc;
1053/// use arrow_schema::DataType;
1054/// use arrow_array::{ArrayRef, Int32Array, new_null_array};
1055///
1056/// let null_array = new_null_array(&DataType::Int32, 3);
1057/// let array: ArrayRef = Arc::new(Int32Array::from(vec![None, None, None]));
1058///
1059/// assert_eq!(&array, &null_array);
1060/// ```
1061pub fn new_null_array(data_type: &DataType, length: usize) -> ArrayRef {
1062    make_array(ArrayData::new_null(data_type, length))
1063}
1064
1065/// Helper function that creates an [`OffsetBuffer`] from a buffer and array offset/ length
1066///
1067/// # Safety
1068///
1069/// - buffer must contain valid arrow offsets ( [`OffsetBuffer`] ) for the
1070///   given length and offset.
1071unsafe fn get_offsets_from_buffer<O: ArrowNativeType>(
1072    buffer: Buffer,
1073    offset: usize,
1074    len: usize,
1075) -> OffsetBuffer<O> {
1076    if len == 0 && buffer.is_empty() {
1077        return OffsetBuffer::new_empty();
1078    }
1079
1080    let scalar_buffer = ScalarBuffer::new(buffer, offset, len + 1);
1081    // Safety:
1082    // Arguments were valid
1083    unsafe { OffsetBuffer::new_unchecked(scalar_buffer) }
1084}
1085
1086/// Helper function for printing potentially long arrays.
1087///
1088/// Note this function is deliberately not generic over the array or closure
1089/// type: it is called from `Debug` impls that are instantiated for many
1090/// concrete array types, and using dynamic dispatch here avoids duplicating
1091/// this function's code in each of those instantiations
1092fn print_long_array(
1093    array: &dyn Array,
1094    f: &mut std::fmt::Formatter,
1095    print_item: &mut dyn FnMut(usize, &mut std::fmt::Formatter) -> std::fmt::Result,
1096) -> std::fmt::Result {
1097    let head = std::cmp::min(10, array.len());
1098
1099    for i in 0..head {
1100        if array.is_null(i) {
1101            writeln!(f, "  null,")?;
1102        } else {
1103            write!(f, "  ")?;
1104            print_item(i, f)?;
1105            writeln!(f, ",")?;
1106        }
1107    }
1108    if array.len() > 10 {
1109        if array.len() > 20 {
1110            writeln!(f, "  ...{} elements...,", array.len() - 20)?;
1111        }
1112
1113        let tail = std::cmp::max(head, array.len() - 10);
1114
1115        for i in tail..array.len() {
1116            if array.is_null(i) {
1117                writeln!(f, "  null,")?;
1118            } else {
1119                write!(f, "  ")?;
1120                print_item(i, f)?;
1121                writeln!(f, ",")?;
1122            }
1123        }
1124    }
1125    Ok(())
1126}
1127
1128#[cfg(test)]
1129mod tests {
1130    use super::*;
1131    use crate::cast::{as_union_array, downcast_array};
1132    use crate::downcast_run_array;
1133    use arrow_buffer::MutableBuffer;
1134    use arrow_schema::{Field, Fields, UnionFields, UnionMode};
1135
1136    #[test]
1137    fn test_empty_primitive() {
1138        let array = new_empty_array(&DataType::Int32);
1139        let a = array.as_any().downcast_ref::<Int32Array>().unwrap();
1140        assert_eq!(a.len(), 0);
1141        let expected: &[i32] = &[];
1142        assert_eq!(a.values(), expected);
1143    }
1144
1145    #[test]
1146    fn test_empty_variable_sized() {
1147        let array = new_empty_array(&DataType::Utf8);
1148        let a = array.as_any().downcast_ref::<StringArray>().unwrap();
1149        assert_eq!(a.len(), 0);
1150        assert_eq!(a.value_offsets()[0], 0i32);
1151    }
1152
1153    #[test]
1154    fn test_empty_list_primitive() {
1155        let data_type = DataType::List(Arc::new(Field::new_list_field(DataType::Int32, false)));
1156        let array = new_empty_array(&data_type);
1157        let a = array.as_any().downcast_ref::<ListArray>().unwrap();
1158        assert_eq!(a.len(), 0);
1159        assert_eq!(a.value_offsets()[0], 0i32);
1160    }
1161
1162    #[test]
1163    fn test_null_boolean() {
1164        let array = new_null_array(&DataType::Boolean, 9);
1165        let a = array.as_any().downcast_ref::<BooleanArray>().unwrap();
1166        assert_eq!(a.len(), 9);
1167        for i in 0..9 {
1168            assert!(a.is_null(i));
1169        }
1170    }
1171
1172    #[test]
1173    fn test_null_primitive() {
1174        let array = new_null_array(&DataType::Int32, 9);
1175        let a = array.as_any().downcast_ref::<Int32Array>().unwrap();
1176        assert_eq!(a.len(), 9);
1177        for i in 0..9 {
1178            assert!(a.is_null(i));
1179        }
1180    }
1181
1182    #[test]
1183    fn test_null_struct() {
1184        // It is possible to create a null struct containing a non-nullable child
1185        // see https://github.com/apache/arrow-rs/pull/3244 for details
1186        let struct_type = DataType::Struct(vec![Field::new("data", DataType::Int64, false)].into());
1187        let array = new_null_array(&struct_type, 9);
1188
1189        let a = array.as_any().downcast_ref::<StructArray>().unwrap();
1190        assert_eq!(a.len(), 9);
1191        assert_eq!(a.column(0).len(), 9);
1192        for i in 0..9 {
1193            assert!(a.is_null(i));
1194        }
1195
1196        // Make sure we can slice the resulting array.
1197        a.slice(0, 5);
1198    }
1199
1200    #[test]
1201    fn test_null_variable_sized() {
1202        let array = new_null_array(&DataType::Utf8, 9);
1203        let a = array.as_any().downcast_ref::<StringArray>().unwrap();
1204        assert_eq!(a.len(), 9);
1205        assert_eq!(a.value_offsets()[9], 0i32);
1206        for i in 0..9 {
1207            assert!(a.is_null(i));
1208        }
1209    }
1210
1211    #[test]
1212    fn test_null_list_primitive() {
1213        let data_type = DataType::List(Arc::new(Field::new_list_field(DataType::Int32, true)));
1214        let array = new_null_array(&data_type, 9);
1215        let a = array.as_any().downcast_ref::<ListArray>().unwrap();
1216        assert_eq!(a.len(), 9);
1217        assert_eq!(a.value_offsets()[9], 0i32);
1218        for i in 0..9 {
1219            assert!(a.is_null(i));
1220        }
1221    }
1222
1223    #[test]
1224    fn test_null_map() {
1225        let data_type = DataType::Map(
1226            Arc::new(Field::new(
1227                Field::MAP_ENTRIES_FIELD_DEFAULT_NAME,
1228                DataType::Struct(Fields::from(vec![
1229                    Field::new(Field::MAP_KEY_FIELD_DEFAULT_NAME, DataType::Utf8, false),
1230                    Field::new(Field::MAP_VALUE_FIELD_DEFAULT_NAME, DataType::Int32, true),
1231                ])),
1232                false,
1233            )),
1234            false,
1235        );
1236        let array = new_null_array(&data_type, 9);
1237        let a = array.as_any().downcast_ref::<MapArray>().unwrap();
1238        assert_eq!(a.len(), 9);
1239        assert_eq!(a.value_offsets()[9], 0i32);
1240        for i in 0..9 {
1241            assert!(a.is_null(i));
1242        }
1243    }
1244
1245    #[test]
1246    fn test_null_dictionary() {
1247        let values =
1248            vec![None, None, None, None, None, None, None, None, None] as Vec<Option<&str>>;
1249
1250        let array: DictionaryArray<Int8Type> = values.into_iter().collect();
1251        let array = Arc::new(array) as ArrayRef;
1252
1253        let null_array = new_null_array(array.data_type(), 9);
1254        assert_eq!(&array, &null_array);
1255        assert_eq!(
1256            array.to_data().buffers()[0].len(),
1257            null_array.to_data().buffers()[0].len()
1258        );
1259    }
1260
1261    #[test]
1262    fn test_null_union() {
1263        for mode in [UnionMode::Sparse, UnionMode::Dense] {
1264            let data_type = DataType::Union(
1265                UnionFields::try_new(
1266                    vec![2, 1],
1267                    vec![
1268                        Field::new("foo", DataType::Int32, true),
1269                        Field::new("bar", DataType::Int64, true),
1270                    ],
1271                )
1272                .unwrap(),
1273                mode,
1274            );
1275            let array = new_null_array(&data_type, 4);
1276
1277            let array = as_union_array(array.as_ref());
1278            assert_eq!(array.len(), 4);
1279            assert_eq!(array.null_count(), 0);
1280            assert_eq!(array.logical_null_count(), 4);
1281
1282            for i in 0..4 {
1283                let a = array.value(i);
1284                assert_eq!(a.len(), 1);
1285                assert_eq!(a.null_count(), 1);
1286                assert_eq!(a.logical_null_count(), 1);
1287                assert!(a.is_null(0))
1288            }
1289
1290            array.to_data().validate_full().unwrap();
1291        }
1292    }
1293
1294    #[test]
1295    fn test_null_runs() {
1296        for r in [DataType::Int16, DataType::Int32, DataType::Int64] {
1297            let data_type = DataType::RunEndEncoded(
1298                Arc::new(Field::new(Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME, r, false)),
1299                Arc::new(Field::new(
1300                    Field::REE_VALUES_FIELD_DEFAULT_NAME,
1301                    DataType::Utf8,
1302                    true,
1303                )),
1304            );
1305
1306            let array = new_null_array(&data_type, 4);
1307            let array = array.as_ref();
1308
1309            downcast_run_array! {
1310                array => {
1311                    assert_eq!(array.len(), 4);
1312                    assert_eq!(array.null_count(), 0);
1313                    assert_eq!(array.logical_null_count(), 4);
1314                    assert_eq!(array.values().len(), 1);
1315                    assert_eq!(array.values().null_count(), 1);
1316                    assert_eq!(array.run_ends().len(), 4);
1317                    assert_eq!(array.run_ends().values(), &[4]);
1318
1319                    let idx = array.get_physical_indices(&[0, 1, 2, 3]).unwrap();
1320                    assert_eq!(idx, &[0,0,0,0]);
1321                }
1322                d => unreachable!("{d}")
1323            }
1324        }
1325    }
1326
1327    #[test]
1328    fn test_null_fixed_size_binary() {
1329        for size in [1, 2, 7] {
1330            let array = new_null_array(&DataType::FixedSizeBinary(size), 6);
1331            let array = array
1332                .as_ref()
1333                .as_any()
1334                .downcast_ref::<FixedSizeBinaryArray>()
1335                .unwrap();
1336
1337            assert_eq!(array.len(), 6);
1338            assert_eq!(array.null_count(), 6);
1339            assert_eq!(array.logical_null_count(), 6);
1340            array.iter().for_each(|x| assert!(x.is_none()));
1341        }
1342    }
1343
1344    #[test]
1345    fn test_memory_size_null() {
1346        let null_arr = NullArray::new(32);
1347
1348        assert_eq!(0, null_arr.get_buffer_memory_size());
1349        assert_eq!(
1350            std::mem::size_of::<usize>(),
1351            null_arr.get_array_memory_size()
1352        );
1353    }
1354
1355    #[test]
1356    fn test_memory_size_primitive() {
1357        let arr = PrimitiveArray::<Int64Type>::from_iter_values(0..128);
1358        let empty = PrimitiveArray::<Int64Type>::from(ArrayData::new_empty(arr.data_type()));
1359
1360        // subtract empty array to avoid magic numbers for the size of additional fields
1361        assert_eq!(
1362            arr.get_array_memory_size() - empty.get_array_memory_size(),
1363            128 * std::mem::size_of::<i64>()
1364        );
1365    }
1366
1367    #[test]
1368    fn test_memory_size_primitive_sliced() {
1369        let arr = PrimitiveArray::<Int64Type>::from_iter_values(0..128);
1370        let slice1 = arr.slice(0, 64);
1371        let slice2 = arr.slice(64, 64);
1372
1373        // both slices report the full buffer memory usage, even though the buffers are shared
1374        assert_eq!(slice1.get_array_memory_size(), arr.get_array_memory_size());
1375        assert_eq!(slice2.get_array_memory_size(), arr.get_array_memory_size());
1376    }
1377
1378    #[test]
1379    fn test_memory_size_primitive_nullable() {
1380        let arr: PrimitiveArray<Int64Type> = (0..128)
1381            .map(|i| if i % 20 == 0 { Some(i) } else { None })
1382            .collect();
1383        let empty_with_bitmap = PrimitiveArray::<Int64Type>::from(
1384            ArrayData::builder(arr.data_type().clone())
1385                .add_buffer(MutableBuffer::new(0).into())
1386                .null_bit_buffer(Some(MutableBuffer::new_null(0).into()))
1387                .build()
1388                .unwrap(),
1389        );
1390
1391        // expected size is the size of the PrimitiveArray struct,
1392        // which includes the optional validity buffer
1393        // plus one buffer on the heap
1394        assert_eq!(
1395            std::mem::size_of::<PrimitiveArray<Int64Type>>(),
1396            empty_with_bitmap.get_array_memory_size()
1397        );
1398
1399        // subtract empty array to avoid magic numbers for the size of additional fields
1400        // the size of the validity bitmap is rounded up to 64 bytes
1401        assert_eq!(
1402            arr.get_array_memory_size() - empty_with_bitmap.get_array_memory_size(),
1403            128 * std::mem::size_of::<i64>() + 64
1404        );
1405    }
1406
1407    #[test]
1408    fn test_memory_size_dictionary() {
1409        let values = PrimitiveArray::<Int64Type>::from_iter_values(0..16);
1410        let keys = PrimitiveArray::<Int16Type>::from_iter_values(
1411            (0..256).map(|i| (i % values.len()) as i16),
1412        );
1413
1414        let dict_data_type = DataType::Dictionary(
1415            Box::new(keys.data_type().clone()),
1416            Box::new(values.data_type().clone()),
1417        );
1418        let dict_data = keys
1419            .into_data()
1420            .into_builder()
1421            .data_type(dict_data_type)
1422            .child_data(vec![values.into_data()])
1423            .build()
1424            .unwrap();
1425
1426        let empty_data = ArrayData::new_empty(&DataType::Dictionary(
1427            Box::new(DataType::Int16),
1428            Box::new(DataType::Int64),
1429        ));
1430
1431        let arr = DictionaryArray::<Int16Type>::from(dict_data);
1432        let empty = DictionaryArray::<Int16Type>::from(empty_data);
1433
1434        let expected_keys_size = 256 * std::mem::size_of::<i16>();
1435        assert_eq!(
1436            arr.keys().get_array_memory_size() - empty.keys().get_array_memory_size(),
1437            expected_keys_size
1438        );
1439
1440        let expected_values_size = 16 * std::mem::size_of::<i64>();
1441        assert_eq!(
1442            arr.values().get_array_memory_size() - empty.values().get_array_memory_size(),
1443            expected_values_size
1444        );
1445
1446        let expected_size = expected_keys_size + expected_values_size;
1447        assert_eq!(
1448            arr.get_array_memory_size() - empty.get_array_memory_size(),
1449            expected_size
1450        );
1451    }
1452
1453    /// Test function that takes an &dyn Array
1454    fn compute_my_thing(arr: &dyn Array) -> bool {
1455        !arr.is_empty()
1456    }
1457
1458    #[test]
1459    fn test_array_ref_as_array() {
1460        let arr: Int32Array = vec![1, 2, 3].into_iter().map(Some).collect();
1461
1462        // works well!
1463        assert!(compute_my_thing(&arr));
1464
1465        // Should also work when wrapped as an ArrayRef
1466        let arr: ArrayRef = Arc::new(arr);
1467        assert!(compute_my_thing(&arr));
1468        assert!(compute_my_thing(arr.as_ref()));
1469    }
1470
1471    #[test]
1472    fn test_to_arc() {
1473        // Array equality ignores offsets, so compare them separately.
1474        fn check(array: &dyn Array) {
1475            let expected = array.slice(0, array.len());
1476            let actual = array.to_arc();
1477            assert_eq!(actual.as_ref(), expected.as_ref());
1478            assert_eq!(actual.offset(), array.offset());
1479        }
1480
1481        let primitive = Int32Array::from(vec![Some(1), None, Some(3), Some(4)]);
1482        let dict: DictionaryArray<Int32Type> =
1483            vec![Some("a"), None, Some("b")].into_iter().collect();
1484        let run_ends = Int32Array::from(vec![2, 3, 5]);
1485        let run = RunArray::try_new(&run_ends, &primitive.slice(0, 3)).unwrap();
1486
1487        // The typed wrappers' `slice` returns the inner untyped array, so `to_arc` must as well.
1488        check(&dict.downcast_dict::<StringArray>().unwrap());
1489        check(&run.slice(1, 3).downcast::<Int32Array>().unwrap());
1490
1491        let array_ref: ArrayRef = Arc::new(primitive.clone());
1492        let dyn_ref: &dyn Array = &array_ref;
1493        assert!(Arc::ptr_eq(&dyn_ref.to_arc(), &array_ref));
1494        let dyn_ref: &dyn Array = &&primitive;
1495        assert_eq!(dyn_ref.to_arc().as_ref(), &primitive);
1496    }
1497
1498    #[test]
1499    fn test_downcast_array() {
1500        let array: Int32Array = vec![1, 2, 3].into_iter().map(Some).collect();
1501
1502        let boxed: ArrayRef = Arc::new(array);
1503        let array: Int32Array = downcast_array(&boxed);
1504
1505        let expected: Int32Array = vec![1, 2, 3].into_iter().map(Some).collect();
1506        assert_eq!(array, expected);
1507    }
1508}