arrow_array/
cast.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
18//! Defines helper functions for downcasting [`dyn Array`](Array) to concrete types
19
20use crate::array::*;
21use crate::types::*;
22use arrow_data::ArrayData;
23
24/// Re-export symbols needed for downcast macros
25///
26/// Name follows `serde` convention
27#[doc(hidden)]
28pub mod __private {
29    pub use arrow_schema::{DataType, IntervalUnit, TimeUnit};
30}
31
32/// Repeats the provided pattern based on the number of comma separated identifiers
33#[doc(hidden)]
34#[macro_export]
35macro_rules! repeat_pat {
36    ($e:pat, $v_:expr) => {
37        $e
38    };
39    ($e:pat, $v_:expr $(, $tail:expr)+) => {
40        ($e, $crate::repeat_pat!($e $(, $tail)+))
41    }
42}
43
44/// Given one or more expressions evaluating to an integer [`DataType`] invokes the provided macro
45/// `m` with the corresponding integer [`ArrowPrimitiveType`], followed by any additional arguments
46///
47/// ```
48/// # use arrow_array::{downcast_primitive, ArrowPrimitiveType, downcast_integer};
49/// # use arrow_schema::DataType;
50///
51/// macro_rules! dictionary_key_size_helper {
52///   ($t:ty, $o:ty) => {
53///       std::mem::size_of::<<$t as ArrowPrimitiveType>::Native>() as $o
54///   };
55/// }
56///
57/// fn dictionary_key_size(t: &DataType) -> u8 {
58///     match t {
59///         DataType::Dictionary(k, _) => downcast_integer! {
60///             k.as_ref() => (dictionary_key_size_helper, u8),
61///             _ => unreachable!(),
62///         },
63///         // You can also add a guard to the pattern
64///         DataType::LargeUtf8 if true => u8::MAX,
65///         _ => u8::MAX,
66///     }
67/// }
68///
69/// assert_eq!(dictionary_key_size(&DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8))), 4);
70/// assert_eq!(dictionary_key_size(&DataType::Dictionary(Box::new(DataType::Int64), Box::new(DataType::Utf8))), 8);
71/// assert_eq!(dictionary_key_size(&DataType::Dictionary(Box::new(DataType::UInt16), Box::new(DataType::Utf8))), 2);
72/// ```
73///
74/// [`DataType`]: arrow_schema::DataType
75#[macro_export]
76macro_rules! downcast_integer {
77    ($($data_type:expr),+ => ($m:path $(, $args:tt)*), $($p:pat $(if $pred:expr)* => $fallback:expr $(,)*)*) => {
78        match ($($data_type),+) {
79            $crate::repeat_pat!($crate::cast::__private::DataType::Int8, $($data_type),+) => {
80                $m!($crate::types::Int8Type $(, $args)*)
81            }
82            $crate::repeat_pat!($crate::cast::__private::DataType::Int16, $($data_type),+) => {
83                $m!($crate::types::Int16Type $(, $args)*)
84            }
85            $crate::repeat_pat!($crate::cast::__private::DataType::Int32, $($data_type),+) => {
86                $m!($crate::types::Int32Type $(, $args)*)
87            }
88            $crate::repeat_pat!($crate::cast::__private::DataType::Int64, $($data_type),+) => {
89                $m!($crate::types::Int64Type $(, $args)*)
90            }
91            $crate::repeat_pat!($crate::cast::__private::DataType::UInt8, $($data_type),+) => {
92                $m!($crate::types::UInt8Type $(, $args)*)
93            }
94            $crate::repeat_pat!($crate::cast::__private::DataType::UInt16, $($data_type),+) => {
95                $m!($crate::types::UInt16Type $(, $args)*)
96            }
97            $crate::repeat_pat!($crate::cast::__private::DataType::UInt32, $($data_type),+) => {
98                $m!($crate::types::UInt32Type $(, $args)*)
99            }
100            $crate::repeat_pat!($crate::cast::__private::DataType::UInt64, $($data_type),+) => {
101                $m!($crate::types::UInt64Type $(, $args)*)
102            }
103            $($p $(if $pred)* => $fallback,)*
104        }
105    };
106}
107
108/// Given one or more expressions evaluating to an integer [`PrimitiveArray`] invokes the provided macro
109/// with the corresponding array, along with match statements for any non integer array types
110///
111/// ```
112/// # use arrow_array::{Array, downcast_integer_array, cast::as_string_array, cast::as_largestring_array};
113/// # use arrow_schema::DataType;
114///
115/// fn print_integer(array: &dyn Array) {
116///     downcast_integer_array!(
117///         array => {
118///             for v in array {
119///                 println!("{:?}", v);
120///             }
121///         }
122///         DataType::Utf8 => {
123///             for v in as_string_array(array) {
124///                 println!("{:?}", v);
125///             }
126///         }
127///         // You can also add a guard to the pattern
128///         DataType::LargeUtf8 if true => {
129///             for v in as_largestring_array(array) {
130///                 println!("{:?}", v);
131///             }
132///         }
133///         t => println!("Unsupported datatype {}", t)
134///     )
135/// }
136/// ```
137///
138/// [`DataType`]: arrow_schema::DataType
139#[macro_export]
140macro_rules! downcast_integer_array {
141    ($values:ident => $e:expr, $($p:pat $(if $pred:expr)* => $fallback:expr $(,)*)*) => {
142        $crate::downcast_integer_array!($values => {$e} $($p $(if $pred)* => $fallback)*)
143    };
144    (($($values:ident),+) => $e:expr, $($p:pat $(if $pred:expr)* => $fallback:expr $(,)*)*) => {
145        $crate::downcast_integer_array!($($values),+ => {$e} $($p $(if $pred)* => $fallback)*)
146    };
147    ($($values:ident),+ => $e:block $($p:pat $(if $pred:expr)* => $fallback:expr $(,)*)*) => {
148        $crate::downcast_integer_array!(($($values),+) => $e $($p $(if $pred)* => $fallback)*)
149    };
150    (($($values:ident),+) => $e:block $($p:pat $(if $pred:expr)* => $fallback:expr $(,)*)*) => {
151        $crate::downcast_integer!{
152            $($values.data_type()),+ => ($crate::downcast_primitive_array_helper, $($values),+, $e),
153            $($p $(if $pred)* => $fallback,)*
154        }
155    };
156}
157
158/// Given one or more expressions evaluating to an integer [`DataType`] invokes the provided macro
159/// `m` with the corresponding integer [`RunEndIndexType`], followed by any additional arguments
160///
161/// ```
162/// # use std::sync::Arc;
163/// # use arrow_array::{downcast_primitive, ArrowPrimitiveType, downcast_run_end_index};
164/// # use arrow_schema::{DataType, Field};
165///
166/// macro_rules! run_end_size_helper {
167///   ($t:ty, $o:ty) => {
168///       std::mem::size_of::<<$t as ArrowPrimitiveType>::Native>() as $o
169///   };
170/// }
171///
172/// fn run_end_index_size(t: &DataType) -> u8 {
173///     match t {
174///         DataType::RunEndEncoded(k, _) => downcast_run_end_index! {
175///             k.data_type() => (run_end_size_helper, u8),
176///             _ => unreachable!(),
177///         },
178///         // You can also add a guard to the pattern
179///         DataType::LargeUtf8 if true => u8::MAX,
180///         _ => u8::MAX,
181///     }
182/// }
183///
184/// assert_eq!(run_end_index_size(&DataType::RunEndEncoded(Arc::new(Field::new("a", DataType::Int32, false)), Arc::new(Field::new("b", DataType::Utf8, true)))), 4);
185/// assert_eq!(run_end_index_size(&DataType::RunEndEncoded(Arc::new(Field::new("a", DataType::Int64, false)), Arc::new(Field::new("b", DataType::Utf8, true)))), 8);
186/// assert_eq!(run_end_index_size(&DataType::RunEndEncoded(Arc::new(Field::new("a", DataType::Int16, false)), Arc::new(Field::new("b", DataType::Utf8, true)))), 2);
187/// ```
188///
189/// [`DataType`]: arrow_schema::DataType
190#[macro_export]
191macro_rules! downcast_run_end_index {
192    ($($data_type:expr),+ => ($m:path $(, $args:tt)*), $($p:pat $(if $pred:expr)* => $fallback:expr $(,)*)*) => {
193        match ($($data_type),+) {
194            $crate::repeat_pat!($crate::cast::__private::DataType::Int16, $($data_type),+) => {
195                $m!($crate::types::Int16Type $(, $args)*)
196            }
197            $crate::repeat_pat!($crate::cast::__private::DataType::Int32, $($data_type),+) => {
198                $m!($crate::types::Int32Type $(, $args)*)
199            }
200            $crate::repeat_pat!($crate::cast::__private::DataType::Int64, $($data_type),+) => {
201                $m!($crate::types::Int64Type $(, $args)*)
202            }
203            $($p $(if $pred)* => $fallback,)*
204        }
205    };
206}
207
208/// Given one or more expressions evaluating to primitive [`DataType`] invokes the provided macro
209/// `m` with the corresponding [`ArrowPrimitiveType`], followed by any additional arguments
210///
211/// ```
212/// # use arrow_array::{downcast_temporal, ArrowPrimitiveType};
213/// # use arrow_schema::DataType;
214///
215/// macro_rules! temporal_size_helper {
216///   ($t:ty, $o:ty) => {
217///       std::mem::size_of::<<$t as ArrowPrimitiveType>::Native>() as $o
218///   };
219/// }
220///
221/// fn temporal_size(t: &DataType) -> u8 {
222///     downcast_temporal! {
223///         t => (temporal_size_helper, u8),
224///         // You can also add a guard to the pattern
225///         DataType::LargeUtf8 if true => u8::MAX,
226///         _ => u8::MAX
227///     }
228/// }
229///
230/// assert_eq!(temporal_size(&DataType::Date32), 4);
231/// assert_eq!(temporal_size(&DataType::Date64), 8);
232/// ```
233///
234/// [`DataType`]: arrow_schema::DataType
235#[macro_export]
236macro_rules! downcast_temporal {
237    ($($data_type:expr),+ => ($m:path $(, $args:tt)*), $($p:pat $(if $pred:expr)* => $fallback:expr $(,)*)*) => {
238        match ($($data_type),+) {
239            $crate::repeat_pat!($crate::cast::__private::DataType::Time32($crate::cast::__private::TimeUnit::Second), $($data_type),+) => {
240                $m!($crate::types::Time32SecondType $(, $args)*)
241            }
242            $crate::repeat_pat!($crate::cast::__private::DataType::Time32($crate::cast::__private::TimeUnit::Millisecond), $($data_type),+) => {
243                $m!($crate::types::Time32MillisecondType $(, $args)*)
244            }
245            $crate::repeat_pat!($crate::cast::__private::DataType::Time64($crate::cast::__private::TimeUnit::Microsecond), $($data_type),+) => {
246                $m!($crate::types::Time64MicrosecondType $(, $args)*)
247            }
248            $crate::repeat_pat!($crate::cast::__private::DataType::Time64($crate::cast::__private::TimeUnit::Nanosecond), $($data_type),+) => {
249                $m!($crate::types::Time64NanosecondType $(, $args)*)
250            }
251            $crate::repeat_pat!($crate::cast::__private::DataType::Date32, $($data_type),+) => {
252                $m!($crate::types::Date32Type $(, $args)*)
253            }
254            $crate::repeat_pat!($crate::cast::__private::DataType::Date64, $($data_type),+) => {
255                $m!($crate::types::Date64Type $(, $args)*)
256            }
257            $crate::repeat_pat!($crate::cast::__private::DataType::Timestamp($crate::cast::__private::TimeUnit::Second, _), $($data_type),+) => {
258                $m!($crate::types::TimestampSecondType $(, $args)*)
259            }
260            $crate::repeat_pat!($crate::cast::__private::DataType::Timestamp($crate::cast::__private::TimeUnit::Millisecond, _), $($data_type),+) => {
261                $m!($crate::types::TimestampMillisecondType $(, $args)*)
262            }
263            $crate::repeat_pat!($crate::cast::__private::DataType::Timestamp($crate::cast::__private::TimeUnit::Microsecond, _), $($data_type),+) => {
264                $m!($crate::types::TimestampMicrosecondType $(, $args)*)
265            }
266            $crate::repeat_pat!($crate::cast::__private::DataType::Timestamp($crate::cast::__private::TimeUnit::Nanosecond, _), $($data_type),+) => {
267                $m!($crate::types::TimestampNanosecondType $(, $args)*)
268            }
269            $($p $(if $pred)* => $fallback,)*
270        }
271    };
272}
273
274/// Downcast an [`Array`] to a temporal [`PrimitiveArray`] based on its [`DataType`]
275/// accepts a number of subsequent patterns to match the data type
276///
277/// ```
278/// # use arrow_array::{Array, downcast_temporal_array, cast::as_string_array, cast::as_largestring_array};
279/// # use arrow_schema::DataType;
280///
281/// fn print_temporal(array: &dyn Array) {
282///     downcast_temporal_array!(
283///         array => {
284///             for v in array {
285///                 println!("{:?}", v);
286///             }
287///         }
288///         DataType::Utf8 => {
289///             for v in as_string_array(array) {
290///                 println!("{:?}", v);
291///             }
292///         }
293///         // You can also add a guard to the pattern
294///         DataType::LargeUtf8 if true => {
295///             for v in as_largestring_array(array) {
296///                 println!("{:?}", v);
297///             }
298///         }
299///         t => println!("Unsupported datatype {}", t)
300///     )
301/// }
302/// ```
303///
304/// [`DataType`]: arrow_schema::DataType
305#[macro_export]
306macro_rules! downcast_temporal_array {
307    ($values:ident => $e:expr, $($p:pat $(if $pred:expr)* => $fallback:expr $(,)*)*) => {
308        $crate::downcast_temporal_array!($values => {$e} $($p $(if $pred)* => $fallback)*)
309    };
310    (($($values:ident),+) => $e:expr, $($p:pat $(if $pred:expr)* => $fallback:expr $(,)*)*) => {
311        $crate::downcast_temporal_array!($($values),+ => {$e} $($p $(if $pred)* => $fallback)*)
312    };
313    ($($values:ident),+ => $e:block $($p:pat $(if $pred:expr)* => $fallback:expr $(,)*)*) => {
314        $crate::downcast_temporal_array!(($($values),+) => $e $($p $(if $pred)* => $fallback)*)
315    };
316    (($($values:ident),+) => $e:block $($p:pat $(if $pred:expr)* => $fallback:expr $(,)*)*) => {
317        $crate::downcast_temporal!{
318            $($values.data_type()),+ => ($crate::downcast_primitive_array_helper, $($values),+, $e),
319            $($p $(if $pred)* => $fallback,)*
320        }
321    };
322}
323
324/// Given one or more expressions evaluating to primitive [`DataType`] invokes the provided macro
325/// `m` with the corresponding [`ArrowPrimitiveType`], followed by any additional arguments
326///
327/// ```
328/// # use arrow_array::{downcast_primitive, ArrowPrimitiveType};
329/// # use arrow_schema::DataType;
330///
331/// macro_rules! primitive_size_helper {
332///   ($t:ty, $o:ty) => {
333///       std::mem::size_of::<<$t as ArrowPrimitiveType>::Native>() as $o
334///   };
335/// }
336///
337/// fn primitive_size(t: &DataType) -> u8 {
338///     downcast_primitive! {
339///         t => (primitive_size_helper, u8),
340///         // You can also add a guard to the pattern
341///         DataType::LargeUtf8 if true => u8::MAX,
342///         _ => u8::MAX
343///     }
344/// }
345///
346/// assert_eq!(primitive_size(&DataType::Int32), 4);
347/// assert_eq!(primitive_size(&DataType::Int64), 8);
348/// assert_eq!(primitive_size(&DataType::Float16), 2);
349/// assert_eq!(primitive_size(&DataType::Decimal128(38, 10)), 16);
350/// assert_eq!(primitive_size(&DataType::Decimal256(76, 20)), 32);
351/// ```
352///
353/// [`DataType`]: arrow_schema::DataType
354#[macro_export]
355macro_rules! downcast_primitive {
356    ($($data_type:expr),+ => ($m:path $(, $args:tt)*), $($p:pat $(if $pred:expr)* => $fallback:expr $(,)*)*) => {
357        $crate::downcast_integer! {
358            $($data_type),+ => ($m $(, $args)*),
359            $crate::repeat_pat!($crate::cast::__private::DataType::Float16, $($data_type),+) => {
360                $m!($crate::types::Float16Type $(, $args)*)
361            }
362            $crate::repeat_pat!($crate::cast::__private::DataType::Float32, $($data_type),+) => {
363                $m!($crate::types::Float32Type $(, $args)*)
364            }
365            $crate::repeat_pat!($crate::cast::__private::DataType::Float64, $($data_type),+) => {
366                $m!($crate::types::Float64Type $(, $args)*)
367            }
368            $crate::repeat_pat!($crate::cast::__private::DataType::Decimal128(_, _), $($data_type),+) => {
369                $m!($crate::types::Decimal128Type $(, $args)*)
370            }
371            $crate::repeat_pat!($crate::cast::__private::DataType::Decimal256(_, _), $($data_type),+) => {
372                $m!($crate::types::Decimal256Type $(, $args)*)
373            }
374            $crate::repeat_pat!($crate::cast::__private::DataType::Interval($crate::cast::__private::IntervalUnit::YearMonth), $($data_type),+) => {
375                $m!($crate::types::IntervalYearMonthType $(, $args)*)
376            }
377            $crate::repeat_pat!($crate::cast::__private::DataType::Interval($crate::cast::__private::IntervalUnit::DayTime), $($data_type),+) => {
378                $m!($crate::types::IntervalDayTimeType $(, $args)*)
379            }
380            $crate::repeat_pat!($crate::cast::__private::DataType::Interval($crate::cast::__private::IntervalUnit::MonthDayNano), $($data_type),+) => {
381                $m!($crate::types::IntervalMonthDayNanoType $(, $args)*)
382            }
383            $crate::repeat_pat!($crate::cast::__private::DataType::Duration($crate::cast::__private::TimeUnit::Second), $($data_type),+) => {
384                $m!($crate::types::DurationSecondType $(, $args)*)
385            }
386            $crate::repeat_pat!($crate::cast::__private::DataType::Duration($crate::cast::__private::TimeUnit::Millisecond), $($data_type),+) => {
387                $m!($crate::types::DurationMillisecondType $(, $args)*)
388            }
389            $crate::repeat_pat!($crate::cast::__private::DataType::Duration($crate::cast::__private::TimeUnit::Microsecond), $($data_type),+) => {
390                $m!($crate::types::DurationMicrosecondType $(, $args)*)
391            }
392            $crate::repeat_pat!($crate::cast::__private::DataType::Duration($crate::cast::__private::TimeUnit::Nanosecond), $($data_type),+) => {
393                $m!($crate::types::DurationNanosecondType $(, $args)*)
394            }
395            _ => {
396                $crate::downcast_temporal! {
397                    $($data_type),+ => ($m $(, $args)*),
398                    $($p $(if $pred)* => $fallback,)*
399                }
400            }
401        }
402    };
403}
404
405#[macro_export]
406#[doc(hidden)]
407macro_rules! downcast_primitive_array_helper {
408    ($t:ty, $($values:ident),+, $e:block) => {{
409        $(let $values = $crate::cast::as_primitive_array::<$t>($values);)+
410        $e
411    }};
412}
413
414/// Downcast an [`Array`] to a [`PrimitiveArray`] based on its [`DataType`]
415/// accepts a number of subsequent patterns to match the data type
416///
417/// ```
418/// # use arrow_array::{Array, downcast_primitive_array, cast::as_string_array, cast::as_largestring_array};
419/// # use arrow_schema::DataType;
420///
421/// fn print_primitive(array: &dyn Array) {
422///     downcast_primitive_array!(
423///         array => {
424///             for v in array {
425///                 println!("{:?}", v);
426///             }
427///         }
428///         DataType::Utf8 => {
429///             for v in as_string_array(array) {
430///                 println!("{:?}", v);
431///             }
432///         }
433///         // You can also add a guard to the pattern
434///         DataType::LargeUtf8 if true => {
435///             for v in as_largestring_array(array) {
436///                 println!("{:?}", v);
437///             }
438///         }
439///         t => println!("Unsupported datatype {}", t)
440///     )
441/// }
442/// ```
443///
444/// [`DataType`]: arrow_schema::DataType
445#[macro_export]
446macro_rules! downcast_primitive_array {
447    ($values:ident => $e:expr, $($p:pat $(if $pred:expr)* => $fallback:expr $(,)*)*) => {
448        $crate::downcast_primitive_array!($values => {$e} $($p $(if $pred)* => $fallback)*)
449    };
450    (($($values:ident),+) => $e:expr, $($p:pat $(if $pred:expr)* => $fallback:expr $(,)*)*) => {
451        $crate::downcast_primitive_array!($($values),+ => {$e} $($p $(if $pred)* => $fallback)*)
452    };
453    ($($values:ident),+ => $e:block $($p:pat $(if $pred:expr)* => $fallback:expr $(,)*)*) => {
454        $crate::downcast_primitive_array!(($($values),+) => $e $($p $(if $pred)* => $fallback)*)
455    };
456    (($($values:ident),+) => $e:block $($p:pat $(if $pred:expr)* => $fallback:expr $(,)*)*) => {
457        $crate::downcast_primitive!{
458            $($values.data_type()),+ => ($crate::downcast_primitive_array_helper, $($values),+, $e),
459            $($p $(if $pred)* => $fallback,)*
460        }
461    };
462}
463
464/// Force downcast of an [`Array`], such as an [`ArrayRef`], to
465/// [`PrimitiveArray<T>`], panic'ing on failure.
466///
467/// # Example
468///
469/// ```
470/// # use std::sync::Arc;
471/// # use arrow_array::{ArrayRef, Int32Array};
472/// # use arrow_array::cast::as_primitive_array;
473/// # use arrow_array::types::Int32Type;
474///
475/// let arr: ArrayRef = Arc::new(Int32Array::from(vec![Some(1)]));
476///
477/// // Downcast an `ArrayRef` to Int32Array / PrimitiveArray<Int32>:
478/// let primitive_array: &Int32Array = as_primitive_array(&arr);
479///
480/// // Equivalently:
481/// let primitive_array = as_primitive_array::<Int32Type>(&arr);
482///
483/// // This is the equivalent of:
484/// let primitive_array = arr
485///     .as_any()
486///     .downcast_ref::<Int32Array>()
487///     .unwrap();
488/// ```
489pub fn as_primitive_array<T>(arr: &dyn Array) -> &PrimitiveArray<T>
490where
491    T: ArrowPrimitiveType,
492{
493    arr.as_any()
494        .downcast_ref::<PrimitiveArray<T>>()
495        .expect("Unable to downcast to primitive array")
496}
497
498#[macro_export]
499#[doc(hidden)]
500macro_rules! downcast_dictionary_array_helper {
501    ($t:ty, $($values:ident),+, $e:block) => {{
502        $(let $values = $crate::cast::as_dictionary_array::<$t>($values);)+
503        $e
504    }};
505}
506
507/// Downcast an [`Array`] to a [`DictionaryArray`] based on its [`DataType`], accepts
508/// a number of subsequent patterns to match the data type
509///
510/// ```
511/// # use arrow_array::{Array, StringArray, downcast_dictionary_array, cast::as_string_array, cast::as_largestring_array};
512/// # use arrow_schema::DataType;
513///
514/// fn print_strings(array: &dyn Array) {
515///     downcast_dictionary_array!(
516///         array => match array.values().data_type() {
517///             DataType::Utf8 => {
518///                 for v in array.downcast_dict::<StringArray>().unwrap() {
519///                     println!("{:?}", v);
520///                 }
521///             }
522///             t => println!("Unsupported dictionary value type {}", t),
523///         },
524///         DataType::Utf8 => {
525///             for v in as_string_array(array) {
526///                 println!("{:?}", v);
527///             }
528///         }
529///         // You can also add a guard to the pattern
530///         DataType::LargeUtf8 if true => {
531///             for v in as_largestring_array(array) {
532///                 println!("{:?}", v);
533///             }
534///         }
535///         t => println!("Unsupported datatype {}", t)
536///     )
537/// }
538/// ```
539///
540/// [`DataType`]: arrow_schema::DataType
541#[macro_export]
542macro_rules! downcast_dictionary_array {
543    ($values:ident => $e:expr, $($p:pat $(if $pred:expr)* => $fallback:expr $(,)*)*) => {
544        downcast_dictionary_array!($values => {$e} $($p $(if $pred)* => $fallback)*)
545    };
546
547    ($values:ident => $e:block $($p:pat $(if $pred:expr)* => $fallback:expr $(,)*)*) => {
548        match $values.data_type() {
549            $crate::cast::__private::DataType::Dictionary(k, _) => {
550                $crate::downcast_integer! {
551                    k.as_ref() => ($crate::downcast_dictionary_array_helper, $values, $e),
552                    k => unreachable!("unsupported dictionary key type: {}", k)
553                }
554            }
555            $($p $(if $pred)* => $fallback,)*
556        }
557    }
558}
559
560/// Force downcast of an [`Array`], such as an [`ArrayRef`] to
561/// [`DictionaryArray<T>`], panic'ing on failure.
562///
563/// # Example
564///
565/// ```
566/// # use arrow_array::{ArrayRef, DictionaryArray};
567/// # use arrow_array::cast::as_dictionary_array;
568/// # use arrow_array::types::Int32Type;
569///
570/// let arr: DictionaryArray<Int32Type> = vec![Some("foo")].into_iter().collect();
571/// let arr: ArrayRef = std::sync::Arc::new(arr);
572/// let dict_array: &DictionaryArray<Int32Type> = as_dictionary_array::<Int32Type>(&arr);
573/// ```
574pub fn as_dictionary_array<T>(arr: &dyn Array) -> &DictionaryArray<T>
575where
576    T: ArrowDictionaryKeyType,
577{
578    arr.as_any()
579        .downcast_ref::<DictionaryArray<T>>()
580        .expect("Unable to downcast to dictionary array")
581}
582
583/// Force downcast of an [`Array`], such as an [`ArrayRef`] to
584/// [`RunArray<T>`], panic'ing on failure.
585///
586/// # Example
587///
588/// ```
589/// # use arrow_array::{ArrayRef, RunArray};
590/// # use arrow_array::cast::as_run_array;
591/// # use arrow_array::types::Int32Type;
592///
593/// let arr: RunArray<Int32Type> = vec![Some("foo")].into_iter().collect();
594/// let arr: ArrayRef = std::sync::Arc::new(arr);
595/// let run_array: &RunArray<Int32Type> = as_run_array::<Int32Type>(&arr);
596/// ```
597pub fn as_run_array<T>(arr: &dyn Array) -> &RunArray<T>
598where
599    T: RunEndIndexType,
600{
601    arr.as_any()
602        .downcast_ref::<RunArray<T>>()
603        .expect("Unable to downcast to run array")
604}
605
606#[macro_export]
607#[doc(hidden)]
608macro_rules! downcast_run_array_helper {
609    ($t:ty, $($values:ident),+, $e:block) => {{
610        $(let $values = $crate::cast::as_run_array::<$t>($values);)+
611        $e
612    }};
613}
614
615/// Downcast an [`Array`] to a [`RunArray`] based on its [`DataType`], accepts
616/// a number of subsequent patterns to match the data type
617///
618/// ```
619/// # use arrow_array::{Array, StringArray, downcast_run_array, cast::as_string_array, cast::as_largestring_array};
620/// # use arrow_schema::DataType;
621///
622/// fn print_strings(array: &dyn Array) {
623///     downcast_run_array!(
624///         array => match array.values().data_type() {
625///             DataType::Utf8 => {
626///                 for v in array.downcast::<StringArray>().unwrap() {
627///                     println!("{:?}", v);
628///                 }
629///             }
630///             t => println!("Unsupported run array value type {}", t),
631///         },
632///         DataType::Utf8 => {
633///             for v in as_string_array(array) {
634///                 println!("{:?}", v);
635///             }
636///         }
637///         // You can also add a guard to the pattern
638///         DataType::LargeUtf8 if true => {
639///             for v in as_largestring_array(array) {
640///                 println!("{:?}", v);
641///             }
642///         }
643///         t => println!("Unsupported datatype {}", t)
644///     )
645/// }
646/// ```
647///
648/// [`DataType`]: arrow_schema::DataType
649#[macro_export]
650macro_rules! downcast_run_array {
651    ($values:ident => $e:expr, $($p:pat $(if $pred:expr)* => $fallback:expr $(,)*)*) => {
652        downcast_run_array!($values => {$e} $($p $(if $pred)* => $fallback)*)
653    };
654
655    ($values:ident => $e:block $($p:pat $(if $pred:expr)* => $fallback:expr $(,)*)*) => {
656        match $values.data_type() {
657            $crate::cast::__private::DataType::RunEndEncoded(k, _) => {
658                $crate::downcast_run_end_index! {
659                    k.data_type() => ($crate::downcast_run_array_helper, $values, $e),
660                    k => unreachable!("unsupported run end index type: {}", k)
661                }
662            }
663            $($p $(if $pred)* => $fallback,)*
664        }
665    }
666}
667
668/// Force downcast of an [`Array`], such as an [`ArrayRef`] to
669/// [`GenericListArray<T>`], panicking on failure.
670pub fn as_generic_list_array<S: OffsetSizeTrait>(arr: &dyn Array) -> &GenericListArray<S> {
671    arr.as_any()
672        .downcast_ref::<GenericListArray<S>>()
673        .expect("Unable to downcast to list array")
674}
675
676/// Force downcast of an [`Array`], such as an [`ArrayRef`] to
677/// [`ListArray`], panicking on failure.
678#[inline]
679pub fn as_list_array(arr: &dyn Array) -> &ListArray {
680    as_generic_list_array::<i32>(arr)
681}
682
683/// Force downcast of an [`Array`], such as an [`ArrayRef`] to
684/// [`FixedSizeListArray`], panicking on failure.
685#[inline]
686pub fn as_fixed_size_list_array(arr: &dyn Array) -> &FixedSizeListArray {
687    arr.as_any()
688        .downcast_ref::<FixedSizeListArray>()
689        .expect("Unable to downcast to fixed size list array")
690}
691
692/// Force downcast of an [`Array`], such as an [`ArrayRef`] to
693/// [`LargeListArray`], panicking on failure.
694#[inline]
695pub fn as_large_list_array(arr: &dyn Array) -> &LargeListArray {
696    as_generic_list_array::<i64>(arr)
697}
698
699/// Force downcast of an [`Array`], such as an [`ArrayRef`] to
700/// [`GenericBinaryArray<S>`], panicking on failure.
701#[inline]
702pub fn as_generic_binary_array<S: OffsetSizeTrait>(arr: &dyn Array) -> &GenericBinaryArray<S> {
703    arr.as_any()
704        .downcast_ref::<GenericBinaryArray<S>>()
705        .expect("Unable to downcast to binary array")
706}
707
708/// Force downcast of an [`Array`], such as an [`ArrayRef`] to
709/// [`StringArray`], panicking on failure.
710///
711/// # Example
712///
713/// ```
714/// # use std::sync::Arc;
715/// # use arrow_array::cast::as_string_array;
716/// # use arrow_array::{ArrayRef, StringArray};
717///
718/// let arr: ArrayRef = Arc::new(StringArray::from_iter(vec![Some("foo")]));
719/// let string_array = as_string_array(&arr);
720/// ```
721pub fn as_string_array(arr: &dyn Array) -> &StringArray {
722    arr.as_any()
723        .downcast_ref::<StringArray>()
724        .expect("Unable to downcast to StringArray")
725}
726
727/// Force downcast of an [`Array`], such as an [`ArrayRef`] to
728/// [`BooleanArray`], panicking on failure.
729///
730/// # Example
731///
732/// ```
733/// # use std::sync::Arc;
734/// # use arrow_array::{ArrayRef, BooleanArray};
735/// # use arrow_array::cast::as_boolean_array;
736///
737/// let arr: ArrayRef = Arc::new(BooleanArray::from_iter(vec![Some(true)]));
738/// let boolean_array = as_boolean_array(&arr);
739/// ```
740pub fn as_boolean_array(arr: &dyn Array) -> &BooleanArray {
741    arr.as_any()
742        .downcast_ref::<BooleanArray>()
743        .expect("Unable to downcast to BooleanArray")
744}
745
746macro_rules! array_downcast_fn {
747    ($name: ident, $arrty: ty, $arrty_str:expr) => {
748        #[doc = "Force downcast of an [`Array`], such as an [`ArrayRef`] to "]
749        #[doc = $arrty_str]
750        pub fn $name(arr: &dyn Array) -> &$arrty {
751            arr.as_any().downcast_ref::<$arrty>().expect(concat!(
752                "Unable to downcast to typed array through ",
753                stringify!($name)
754            ))
755        }
756    };
757
758    // use recursive macro to generate dynamic doc string for a given array type
759    ($name: ident, $arrty: ty) => {
760        array_downcast_fn!(
761            $name,
762            $arrty,
763            concat!("[`", stringify!($arrty), "`], panicking on failure.")
764        );
765    };
766}
767
768array_downcast_fn!(as_largestring_array, LargeStringArray);
769array_downcast_fn!(as_null_array, NullArray);
770array_downcast_fn!(as_struct_array, StructArray);
771array_downcast_fn!(as_union_array, UnionArray);
772array_downcast_fn!(as_map_array, MapArray);
773
774/// Downcasts a `dyn Array` to a concrete type
775///
776/// ```
777/// # use arrow_array::{BooleanArray, Int32Array, RecordBatch, StringArray};
778/// # use arrow_array::cast::downcast_array;
779/// struct ConcreteBatch {
780///     col1: Int32Array,
781///     col2: BooleanArray,
782///     col3: StringArray,
783/// }
784///
785/// impl ConcreteBatch {
786///     fn new(batch: &RecordBatch) -> Self {
787///         Self {
788///             col1: downcast_array(batch.column(0).as_ref()),
789///             col2: downcast_array(batch.column(1).as_ref()),
790///             col3: downcast_array(batch.column(2).as_ref()),
791///         }
792///     }
793/// }
794/// ```
795///
796/// # Panics
797///
798/// Panics if array is not of the correct data type
799pub fn downcast_array<T>(array: &dyn Array) -> T
800where
801    T: From<ArrayData>,
802{
803    T::from(array.to_data())
804}
805
806mod private {
807    pub trait Sealed {}
808}
809
810/// An extension trait for `dyn Array` that provides ergonomic downcasting
811///
812/// ```
813/// # use std::sync::Arc;
814/// # use arrow_array::{ArrayRef, Int32Array};
815/// # use arrow_array::cast::AsArray;
816/// # use arrow_array::types::Int32Type;
817/// let col = Arc::new(Int32Array::from(vec![1, 2, 3])) as ArrayRef;
818/// assert_eq!(col.as_primitive::<Int32Type>().values(), &[1, 2, 3]);
819/// ```
820pub trait AsArray: private::Sealed {
821    /// Downcast this to a [`BooleanArray`] returning `None` if not possible
822    fn as_boolean_opt(&self) -> Option<&BooleanArray>;
823
824    /// Downcast this to a [`BooleanArray`] panicking if not possible
825    fn as_boolean(&self) -> &BooleanArray {
826        self.as_boolean_opt().expect("boolean array")
827    }
828
829    /// Downcast this to a [`PrimitiveArray`] returning `None` if not possible
830    fn as_primitive_opt<T: ArrowPrimitiveType>(&self) -> Option<&PrimitiveArray<T>>;
831
832    /// Downcast this to a [`PrimitiveArray`] panicking if not possible
833    fn as_primitive<T: ArrowPrimitiveType>(&self) -> &PrimitiveArray<T> {
834        self.as_primitive_opt().expect("primitive array")
835    }
836
837    /// Downcast this to a [`GenericByteArray`] returning `None` if not possible
838    fn as_bytes_opt<T: ByteArrayType>(&self) -> Option<&GenericByteArray<T>>;
839
840    /// Downcast this to a [`GenericByteArray`] panicking if not possible
841    fn as_bytes<T: ByteArrayType>(&self) -> &GenericByteArray<T> {
842        self.as_bytes_opt().expect("byte array")
843    }
844
845    /// Downcast this to a [`GenericStringArray`] returning `None` if not possible
846    fn as_string_opt<O: OffsetSizeTrait>(&self) -> Option<&GenericStringArray<O>> {
847        self.as_bytes_opt()
848    }
849
850    /// Downcast this to a [`GenericStringArray`] panicking if not possible
851    fn as_string<O: OffsetSizeTrait>(&self) -> &GenericStringArray<O> {
852        self.as_bytes_opt().expect("string array")
853    }
854
855    /// Downcast this to a [`GenericBinaryArray`] returning `None` if not possible
856    fn as_binary_opt<O: OffsetSizeTrait>(&self) -> Option<&GenericBinaryArray<O>> {
857        self.as_bytes_opt()
858    }
859
860    /// Downcast this to a [`GenericBinaryArray`] panicking if not possible
861    fn as_binary<O: OffsetSizeTrait>(&self) -> &GenericBinaryArray<O> {
862        self.as_bytes_opt().expect("binary array")
863    }
864
865    /// Downcast this to a [`StringViewArray`] returning `None` if not possible
866    fn as_string_view_opt(&self) -> Option<&StringViewArray> {
867        self.as_byte_view_opt()
868    }
869
870    /// Downcast this to a [`StringViewArray`] panicking if not possible
871    fn as_string_view(&self) -> &StringViewArray {
872        self.as_byte_view_opt().expect("string view array")
873    }
874
875    /// Downcast this to a [`BinaryViewArray`] returning `None` if not possible
876    fn as_binary_view_opt(&self) -> Option<&BinaryViewArray> {
877        self.as_byte_view_opt()
878    }
879
880    /// Downcast this to a [`BinaryViewArray`] panicking if not possible
881    fn as_binary_view(&self) -> &BinaryViewArray {
882        self.as_byte_view_opt().expect("binary view array")
883    }
884
885    /// Downcast this to a [`GenericByteViewArray`] returning `None` if not possible
886    fn as_byte_view_opt<T: ByteViewType>(&self) -> Option<&GenericByteViewArray<T>>;
887
888    /// Downcast this to a [`GenericByteViewArray`] panicking if not possible
889    fn as_byte_view<T: ByteViewType>(&self) -> &GenericByteViewArray<T> {
890        self.as_byte_view_opt().expect("byte view array")
891    }
892
893    /// Downcast this to a [`StructArray`] returning `None` if not possible
894    fn as_struct_opt(&self) -> Option<&StructArray>;
895
896    /// Downcast this to a [`StructArray`] panicking if not possible
897    fn as_struct(&self) -> &StructArray {
898        self.as_struct_opt().expect("struct array")
899    }
900
901    /// Downcast this to a [`UnionArray`] returning `None` if not possible
902    fn as_union_opt(&self) -> Option<&UnionArray>;
903
904    /// Downcast this to a [`UnionArray`] panicking if not possible
905    fn as_union(&self) -> &UnionArray {
906        self.as_union_opt().expect("union array")
907    }
908
909    /// Downcast this to a [`GenericListArray`] returning `None` if not possible
910    fn as_list_opt<O: OffsetSizeTrait>(&self) -> Option<&GenericListArray<O>>;
911
912    /// Downcast this to a [`GenericListArray`] panicking if not possible
913    fn as_list<O: OffsetSizeTrait>(&self) -> &GenericListArray<O> {
914        self.as_list_opt().expect("list array")
915    }
916
917    /// Downcast this to a [`GenericListViewArray`] returning `None` if not possible
918    fn as_list_view_opt<O: OffsetSizeTrait>(&self) -> Option<&GenericListViewArray<O>>;
919
920    /// Downcast this to a [`GenericListViewArray`] panicking if not possible
921    fn as_list_view<O: OffsetSizeTrait>(&self) -> &GenericListViewArray<O> {
922        self.as_list_view_opt().expect("list view array")
923    }
924
925    /// Downcast this to a [`FixedSizeBinaryArray`] returning `None` if not possible
926    fn as_fixed_size_binary_opt(&self) -> Option<&FixedSizeBinaryArray>;
927
928    /// Downcast this to a [`FixedSizeBinaryArray`] panicking if not possible
929    fn as_fixed_size_binary(&self) -> &FixedSizeBinaryArray {
930        self.as_fixed_size_binary_opt()
931            .expect("fixed size binary array")
932    }
933
934    /// Downcast this to a [`FixedSizeListArray`] returning `None` if not possible
935    fn as_fixed_size_list_opt(&self) -> Option<&FixedSizeListArray>;
936
937    /// Downcast this to a [`FixedSizeListArray`] panicking if not possible
938    fn as_fixed_size_list(&self) -> &FixedSizeListArray {
939        self.as_fixed_size_list_opt()
940            .expect("fixed size list array")
941    }
942
943    /// Downcast this to a [`MapArray`] returning `None` if not possible
944    fn as_map_opt(&self) -> Option<&MapArray>;
945
946    /// Downcast this to a [`MapArray`] panicking if not possible
947    fn as_map(&self) -> &MapArray {
948        self.as_map_opt().expect("map array")
949    }
950
951    /// Downcast this to a [`DictionaryArray`] returning `None` if not possible
952    fn as_dictionary_opt<K: ArrowDictionaryKeyType>(&self) -> Option<&DictionaryArray<K>>;
953
954    /// Downcast this to a [`DictionaryArray`] panicking if not possible
955    fn as_dictionary<K: ArrowDictionaryKeyType>(&self) -> &DictionaryArray<K> {
956        self.as_dictionary_opt().expect("dictionary array")
957    }
958
959    /// Downcasts this to a [`AnyDictionaryArray`] returning `None` if not possible
960    fn as_any_dictionary_opt(&self) -> Option<&dyn AnyDictionaryArray>;
961
962    /// Downcasts this to a [`AnyDictionaryArray`] panicking if not possible
963    fn as_any_dictionary(&self) -> &dyn AnyDictionaryArray {
964        self.as_any_dictionary_opt().expect("any dictionary array")
965    }
966}
967
968impl private::Sealed for dyn Array + '_ {}
969impl AsArray for dyn Array + '_ {
970    fn as_boolean_opt(&self) -> Option<&BooleanArray> {
971        self.as_any().downcast_ref()
972    }
973
974    fn as_primitive_opt<T: ArrowPrimitiveType>(&self) -> Option<&PrimitiveArray<T>> {
975        self.as_any().downcast_ref()
976    }
977
978    fn as_bytes_opt<T: ByteArrayType>(&self) -> Option<&GenericByteArray<T>> {
979        self.as_any().downcast_ref()
980    }
981
982    fn as_byte_view_opt<T: ByteViewType>(&self) -> Option<&GenericByteViewArray<T>> {
983        self.as_any().downcast_ref()
984    }
985
986    fn as_struct_opt(&self) -> Option<&StructArray> {
987        self.as_any().downcast_ref()
988    }
989
990    fn as_union_opt(&self) -> Option<&UnionArray> {
991        self.as_any().downcast_ref()
992    }
993
994    fn as_list_opt<O: OffsetSizeTrait>(&self) -> Option<&GenericListArray<O>> {
995        self.as_any().downcast_ref()
996    }
997
998    fn as_list_view_opt<O: OffsetSizeTrait>(&self) -> Option<&GenericListViewArray<O>> {
999        self.as_any().downcast_ref()
1000    }
1001
1002    fn as_fixed_size_binary_opt(&self) -> Option<&FixedSizeBinaryArray> {
1003        self.as_any().downcast_ref()
1004    }
1005
1006    fn as_fixed_size_list_opt(&self) -> Option<&FixedSizeListArray> {
1007        self.as_any().downcast_ref()
1008    }
1009
1010    fn as_map_opt(&self) -> Option<&MapArray> {
1011        self.as_any().downcast_ref()
1012    }
1013
1014    fn as_dictionary_opt<K: ArrowDictionaryKeyType>(&self) -> Option<&DictionaryArray<K>> {
1015        self.as_any().downcast_ref()
1016    }
1017
1018    fn as_any_dictionary_opt(&self) -> Option<&dyn AnyDictionaryArray> {
1019        let array = self;
1020        downcast_dictionary_array! {
1021            array => Some(array),
1022            _ => None
1023        }
1024    }
1025}
1026
1027impl private::Sealed for ArrayRef {}
1028impl AsArray for ArrayRef {
1029    fn as_boolean_opt(&self) -> Option<&BooleanArray> {
1030        self.as_ref().as_boolean_opt()
1031    }
1032
1033    fn as_primitive_opt<T: ArrowPrimitiveType>(&self) -> Option<&PrimitiveArray<T>> {
1034        self.as_ref().as_primitive_opt()
1035    }
1036
1037    fn as_bytes_opt<T: ByteArrayType>(&self) -> Option<&GenericByteArray<T>> {
1038        self.as_ref().as_bytes_opt()
1039    }
1040
1041    fn as_byte_view_opt<T: ByteViewType>(&self) -> Option<&GenericByteViewArray<T>> {
1042        self.as_ref().as_byte_view_opt()
1043    }
1044
1045    fn as_struct_opt(&self) -> Option<&StructArray> {
1046        self.as_ref().as_struct_opt()
1047    }
1048
1049    fn as_union_opt(&self) -> Option<&UnionArray> {
1050        self.as_any().downcast_ref()
1051    }
1052
1053    fn as_list_opt<O: OffsetSizeTrait>(&self) -> Option<&GenericListArray<O>> {
1054        self.as_ref().as_list_opt()
1055    }
1056
1057    fn as_list_view_opt<O: OffsetSizeTrait>(&self) -> Option<&GenericListViewArray<O>> {
1058        self.as_ref().as_list_view_opt()
1059    }
1060
1061    fn as_fixed_size_binary_opt(&self) -> Option<&FixedSizeBinaryArray> {
1062        self.as_ref().as_fixed_size_binary_opt()
1063    }
1064
1065    fn as_fixed_size_list_opt(&self) -> Option<&FixedSizeListArray> {
1066        self.as_ref().as_fixed_size_list_opt()
1067    }
1068
1069    fn as_map_opt(&self) -> Option<&MapArray> {
1070        self.as_any().downcast_ref()
1071    }
1072
1073    fn as_dictionary_opt<K: ArrowDictionaryKeyType>(&self) -> Option<&DictionaryArray<K>> {
1074        self.as_ref().as_dictionary_opt()
1075    }
1076
1077    fn as_any_dictionary_opt(&self) -> Option<&dyn AnyDictionaryArray> {
1078        self.as_ref().as_any_dictionary_opt()
1079    }
1080}
1081
1082#[cfg(test)]
1083mod tests {
1084    use super::*;
1085    use arrow_buffer::i256;
1086    use arrow_schema::DataType;
1087    use std::sync::Arc;
1088
1089    #[test]
1090    fn test_as_primitive_array_ref() {
1091        let array: Int32Array = vec![1, 2, 3].into_iter().map(Some).collect();
1092        assert!(!as_primitive_array::<Int32Type>(&array).is_empty());
1093
1094        // should also work when wrapped in an Arc
1095        let array: ArrayRef = Arc::new(array);
1096        assert!(!as_primitive_array::<Int32Type>(&array).is_empty());
1097    }
1098
1099    #[test]
1100    fn test_as_string_array_ref() {
1101        let array: StringArray = vec!["foo", "bar"].into_iter().map(Some).collect();
1102        assert!(!as_string_array(&array).is_empty());
1103
1104        // should also work when wrapped in an Arc
1105        let array: ArrayRef = Arc::new(array);
1106        assert!(!as_string_array(&array).is_empty())
1107    }
1108
1109    #[test]
1110    fn test_decimal128array() {
1111        let a = Decimal128Array::from_iter_values([1, 2, 4, 5]);
1112        assert!(!as_primitive_array::<Decimal128Type>(&a).is_empty());
1113    }
1114
1115    #[test]
1116    fn test_decimal256array() {
1117        let a = Decimal256Array::from_iter_values([1, 2, 4, 5].into_iter().map(i256::from_i128));
1118        assert!(!as_primitive_array::<Decimal256Type>(&a).is_empty());
1119    }
1120
1121    #[test]
1122    fn downcast_integer_array_should_match_only_integers() {
1123        let i32_array: ArrayRef = Arc::new(Int32Array::new_null(1));
1124        let i32_array_ref = &i32_array;
1125        downcast_integer_array!(
1126            i32_array_ref => {
1127                assert_eq!(i32_array_ref.null_count(), 1);
1128            },
1129            _ => panic!("unexpected data type")
1130        );
1131    }
1132
1133    #[test]
1134    fn downcast_integer_array_should_not_match_primitive_that_are_not_integers() {
1135        let array: ArrayRef = Arc::new(Float32Array::new_null(1));
1136        let array_ref = &array;
1137        downcast_integer_array!(
1138            array_ref => {
1139                panic!("unexpected data type {}", array_ref.data_type())
1140            },
1141            DataType::Float32 => {
1142                assert_eq!(array_ref.null_count(), 1);
1143            },
1144            _ => panic!("unexpected data type")
1145        );
1146    }
1147
1148    #[test]
1149    fn downcast_integer_array_should_not_match_non_primitive() {
1150        let array: ArrayRef = Arc::new(StringArray::new_null(1));
1151        let array_ref = &array;
1152        downcast_integer_array!(
1153            array_ref => {
1154                panic!("unexpected data type {}", array_ref.data_type())
1155            },
1156            DataType::Utf8 => {
1157                assert_eq!(array_ref.null_count(), 1);
1158            },
1159            _ => panic!("unexpected data type")
1160        );
1161    }
1162}