Skip to main content

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