Skip to main content

arrow_cast/cast/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Cast kernels to convert [`ArrayRef`]  between supported datatypes.
6//!
7//! See [`cast_with_options`] for more information on specific conversions.
8//!
9//! Example:
10//!
11//! ```
12//! # use arrow_array::*;
13//! # use arrow_cast::cast;
14//! # use arrow_schema::DataType;
15//! # use std::sync::Arc;
16//! # use arrow_array::types::Float64Type;
17//! # use arrow_array::cast::AsArray;
18//! // int32 to float64
19//! let a = Int32Array::from(vec![5, 6, 7]);
20//! let b = cast(&a, &DataType::Float64).unwrap();
21//! let c = b.as_primitive::<Float64Type>();
22//! assert_eq!(5.0, c.value(0));
23//! assert_eq!(6.0, c.value(1));
24//! assert_eq!(7.0, c.value(2));
25//! ```
26
27mod binary;
28mod decimal;
29mod dictionary;
30mod list;
31mod map;
32mod numeric;
33mod run_array;
34mod string;
35mod structs;
36mod temporal;
37mod union;
38
39use crate::cast::binary::*;
40use crate::cast::decimal::*;
41use crate::cast::dictionary::*;
42use crate::cast::list::*;
43use crate::cast::map::*;
44pub(crate) use crate::cast::numeric::{
45    cast_bool_to_numeric, cast_numeric_arrays, cast_numeric_to_bool,
46};
47pub use crate::cast::numeric::{cast_num_to_bool, num_cast, single_bool_to_numeric};
48use crate::cast::run_array::*;
49use crate::cast::string::*;
50use crate::cast::structs::*;
51use crate::cast::temporal::*;
52pub use crate::cast::union::*;
53
54use chrono::{TimeZone, Utc};
55use std::cmp::Ordering;
56use std::sync::Arc;
57
58use crate::display::{ArrayFormatter, FormatOptions};
59use crate::parse::{
60    Parser, parse_interval_day_time, parse_interval_month_day_nano, parse_interval_year_month,
61    string_to_datetime,
62};
63use arrow_array::{builder::*, cast::*, temporal_conversions::*, timezone::Tz, types::*, *};
64use arrow_buffer::{ArrowNativeType, OffsetBuffer, i256};
65use arrow_data::ArrayData;
66use arrow_data::transform::MutableArrayData;
67use arrow_schema::*;
68use arrow_select::take::take;
69use num_traits::{NumCast, ToPrimitive, cast::AsPrimitive};
70
71pub use decimal::{DecimalCast, float_to_decimal, float_to_decimal_opt, rescale_decimal};
72#[expect(deprecated)]
73pub use decimal::{parse_string_to_decimal_native, single_float_to_decimal};
74pub use string::cast_single_string_to_boolean_default;
75
76/// Integers below 2^53 convert to an `f64` exactly.
77const F64_EXACT_INT_LIMIT: f64 = 9_007_199_254_740_992.0;
78/// Integers below 2^24 convert to an `f32` exactly.
79const F32_EXACT_INT_LIMIT: f64 = 16_777_216.0;
80
81/// Lossy conversion from decimal to float.
82///
83/// Returns the `f64` nearest to the decimal's exact value, rounding once, for any
84/// scale that fits in an `i8` -- as every Arrow decimal's does.
85///
86/// Conversion is lossy and follows standard floating point semantics. Values
87/// that exceed the representable range become `INFINITY` or `-INFINITY` without
88/// returning an error.
89#[inline(always)]
90pub fn single_decimal_to_float_lossy<D, F>(f: &F, x: D::Native, scale: i32) -> f64
91where
92    D: DecimalType,
93    F: Fn(D::Native) -> f64,
94{
95    let unscaled = f(x);
96    // Both operands are exact in this range, so this rounds once. A negative scale
97    // multiplies, since `10^-scale` is the exact power of ten there.
98    if (-22..=22).contains(&scale) && unscaled.abs() < F64_EXACT_INT_LIMIT {
99        return if scale >= 0 {
100            unscaled / 10_f64.powi(scale)
101        } else {
102            unscaled * 10_f64.powi(-scale)
103        };
104    }
105    match i8::try_from(scale) {
106        Ok(scale) => decimal_to_f64_rounded_once::<D>(x, scale, unscaled),
107        Err(_) => unscaled / 10_f64.powi(scale),
108    }
109}
110
111/// Rounds once for the values the arithmetic cannot convert exactly, by parsing
112/// the decimal's own text.
113#[cold]
114#[inline(never)]
115fn decimal_to_f64_rounded_once<D: DecimalType>(x: D::Native, scale: i8, unscaled: f64) -> f64 {
116    // `format_decimal` always writes a decimal literal, so the parse cannot fail.
117    // The fallback is there to keep that from being a panic, not because it runs.
118    D::format_decimal(x, u8::MAX, scale)
119        .parse::<f64>()
120        .unwrap_or_else(|_| unscaled / 10_f64.powi(scale.into()))
121}
122
123/// As [`decimal_to_f64_rounded_once`], but narrowing to `f32` in one step.
124/// Rounding to `f64` first and then to `f32` rounds twice: a decimal just above an
125/// `f32` midpoint can collapse onto that midpoint in `f64`, and round-half-even
126/// then sends it the wrong way.
127#[cold]
128#[inline(never)]
129fn decimal_to_f32_rounded_once<D: DecimalType>(x: D::Native, scale: i8, unscaled: f64) -> f32 {
130    // Unreachable, as in [`decimal_to_f64_rounded_once`].
131    D::format_decimal(x, u8::MAX, scale)
132        .parse::<f32>()
133        .unwrap_or_else(|_| unscaled as f32 / 10_f32.powi(scale.into()))
134}
135
136/// Casts a decimal array to `Float64`, rounding each value once.
137fn cast_decimal_to_f64<D, F>(
138    array: &dyn Array,
139    as_float: &F,
140    scale: i8,
141) -> Result<ArrayRef, ArrowError>
142where
143    D: DecimalType + ArrowPrimitiveType,
144    F: Fn(D::Native) -> f64,
145{
146    let array = array.as_primitive::<D>();
147    // No power of ten outside this range is exactly representable.
148    if !(-22..=22).contains(&scale) {
149        let values = array
150            .unary::<_, Float64Type>(|x| decimal_to_f64_rounded_once::<D>(x, scale, as_float(x)));
151        return Ok(Arc::new(values));
152    }
153    let pow = 10_f64.powi(scale.unsigned_abs().into());
154    let values = if scale >= 0 {
155        array.unary::<_, Float64Type>(|x| {
156            let unscaled = as_float(x);
157            if unscaled.abs() < F64_EXACT_INT_LIMIT {
158                unscaled / pow
159            } else {
160                decimal_to_f64_rounded_once::<D>(x, scale, unscaled)
161            }
162        })
163    } else {
164        array.unary::<_, Float64Type>(|x| {
165            let unscaled = as_float(x);
166            if unscaled.abs() < F64_EXACT_INT_LIMIT {
167                unscaled * pow
168            } else {
169                decimal_to_f64_rounded_once::<D>(x, scale, unscaled)
170            }
171        })
172    };
173    Ok(Arc::new(values))
174}
175
176/// Casts a decimal array to `Float32`, rounding each value once. Same shape as
177/// [`cast_decimal_to_f64`], with the smaller bounds an `f32` allows: integers are
178/// exact below 2^24, and `10^k` only up to `k = 10`.
179fn cast_decimal_to_f32<D, F>(
180    array: &dyn Array,
181    as_float: &F,
182    scale: i8,
183) -> Result<ArrayRef, ArrowError>
184where
185    D: DecimalType + ArrowPrimitiveType,
186    F: Fn(D::Native) -> f64,
187{
188    let array = array.as_primitive::<D>();
189    // No power of ten outside this range is exactly representable.
190    if !(-10..=10).contains(&scale) {
191        let values = array
192            .unary::<_, Float32Type>(|x| decimal_to_f32_rounded_once::<D>(x, scale, as_float(x)));
193        return Ok(Arc::new(values));
194    }
195    let pow = 10_f32.powi(scale.unsigned_abs().into());
196    let values = if scale >= 0 {
197        array.unary::<_, Float32Type>(|x| {
198            let unscaled = as_float(x);
199            if unscaled.abs() < F32_EXACT_INT_LIMIT {
200                unscaled as f32 / pow
201            } else {
202                decimal_to_f32_rounded_once::<D>(x, scale, unscaled)
203            }
204        })
205    } else {
206        array.unary::<_, Float32Type>(|x| {
207            let unscaled = as_float(x);
208            if unscaled.abs() < F32_EXACT_INT_LIMIT {
209                unscaled as f32 * pow
210            } else {
211                decimal_to_f32_rounded_once::<D>(x, scale, unscaled)
212            }
213        })
214    };
215    Ok(Arc::new(values))
216}
217
218/// CastOptions provides a way to override the default cast behaviors
219#[derive(Debug, Clone, PartialEq, Eq, Hash)]
220pub struct CastOptions<'a> {
221    /// how to handle cast failures, either return NULL (safe=true) or return ERR (safe=false)
222    pub safe: bool,
223    /// Formatting options when casting from temporal types to string
224    pub format_options: FormatOptions<'a>,
225}
226
227impl Default for CastOptions<'_> {
228    fn default() -> Self {
229        Self {
230            safe: true,
231            format_options: FormatOptions::default(),
232        }
233    }
234}
235
236/// Return true if a value of type `from_type` can be cast into a value of `to_type`.
237///
238/// See [`cast_with_options`] for more information
239pub fn can_cast_types(from_type: &DataType, to_type: &DataType) -> bool {
240    use self::DataType::*;
241    use self::IntervalUnit::*;
242    use self::TimeUnit::*;
243    if from_type == to_type {
244        return true;
245    }
246
247    match (from_type, to_type) {
248        (Null, _) => true,
249        // Dictionary/List conditions should be put in front of others
250        (Dictionary(_, from_value_type), Dictionary(_, to_value_type)) => {
251            can_cast_types(from_value_type, to_value_type)
252        }
253        (Dictionary(_, value_type), _) => can_cast_types(value_type, to_type),
254        (Union(fields, _), _) => union::resolve_child_array(fields, to_type).is_some(),
255        (_, Union(_, _)) => false,
256        (RunEndEncoded(_, value_type), _) => can_cast_types(value_type.data_type(), to_type),
257        (_, RunEndEncoded(_, value_type)) => can_cast_types(from_type, value_type.data_type()),
258        (_, Dictionary(_, value_type)) => can_cast_types(from_type, value_type),
259        (
260            List(list_from) | LargeList(list_from) | ListView(list_from) | LargeListView(list_from),
261            List(list_to) | LargeList(list_to) | ListView(list_to) | LargeListView(list_to),
262        ) => can_cast_types(list_from.data_type(), list_to.data_type()),
263        (
264            List(list_from) | LargeList(list_from) | ListView(list_from) | LargeListView(list_from),
265            Utf8 | LargeUtf8 | Utf8View,
266        ) => can_cast_types(list_from.data_type(), to_type),
267        (
268            FixedSizeList(list_from, _),
269            List(list_to) | LargeList(list_to) | ListView(list_to) | LargeListView(list_to),
270        ) => can_cast_types(list_from.data_type(), list_to.data_type()),
271        (
272            List(list_from) | LargeList(list_from) | ListView(list_from) | LargeListView(list_from),
273            FixedSizeList(list_to, _),
274        ) => can_cast_types(list_from.data_type(), list_to.data_type()),
275        (FixedSizeList(inner, size), FixedSizeList(inner_to, size_to)) if size == size_to => {
276            can_cast_types(inner.data_type(), inner_to.data_type())
277        }
278        (_, List(list_to) | LargeList(list_to) | ListView(list_to) | LargeListView(list_to)) => {
279            can_cast_types(from_type, list_to.data_type())
280        }
281        (_, FixedSizeList(list_to, size)) if *size == 1 => {
282            can_cast_types(from_type, list_to.data_type())
283        }
284        (FixedSizeList(list_from, size), _) if *size == 1 => {
285            can_cast_types(list_from.data_type(), to_type)
286        }
287        (Map(from_entries, ordered_from), Map(to_entries, ordered_to))
288            if ordered_from == ordered_to =>
289        {
290            match (
291                key_field(from_entries),
292                key_field(to_entries),
293                value_field(from_entries),
294                value_field(to_entries),
295            ) {
296                (Some(from_key), Some(to_key), Some(from_value), Some(to_value)) => {
297                    can_cast_types(from_key.data_type(), to_key.data_type())
298                        && can_cast_types(from_value.data_type(), to_value.data_type())
299                }
300                _ => false,
301            }
302        }
303        // cast one decimal type to another decimal type
304        (
305            Decimal32(_, _) | Decimal64(_, _) | Decimal128(_, _) | Decimal256(_, _),
306            Decimal32(_, _) | Decimal64(_, _) | Decimal128(_, _) | Decimal256(_, _),
307        ) => true,
308        // unsigned integer to decimal
309        (
310            UInt8 | UInt16 | UInt32 | UInt64,
311            Decimal32(_, _) | Decimal64(_, _) | Decimal128(_, _) | Decimal256(_, _),
312        ) => true,
313        // signed numeric to decimal
314        (
315            Int8 | Int16 | Int32 | Int64 | Float16 | Float32 | Float64,
316            Decimal32(_, _) | Decimal64(_, _) | Decimal128(_, _) | Decimal256(_, _),
317        ) => true,
318        // decimal to unsigned numeric
319        (
320            Decimal32(_, _) | Decimal64(_, _) | Decimal128(_, _) | Decimal256(_, _),
321            UInt8 | UInt16 | UInt32 | UInt64,
322        ) => true,
323        // decimal to signed numeric
324        (
325            Decimal32(_, _) | Decimal64(_, _) | Decimal128(_, _) | Decimal256(_, _),
326            Null | Int8 | Int16 | Int32 | Int64 | Float16 | Float32 | Float64,
327        ) => true,
328        // decimal to string
329        (
330            Decimal32(_, _) | Decimal64(_, _) | Decimal128(_, _) | Decimal256(_, _),
331            Utf8View | Utf8 | LargeUtf8,
332        ) => true,
333        // string to decimal
334        (
335            Utf8View | Utf8 | LargeUtf8,
336            Decimal32(_, _) | Decimal64(_, _) | Decimal128(_, _) | Decimal256(_, _),
337        ) => true,
338        (Struct(from_fields), Struct(to_fields)) => {
339            if from_fields.len() != to_fields.len() {
340                return false;
341            }
342
343            // fast path, all field names are in the same order and same number of fields
344            if from_fields
345                .iter()
346                .zip(to_fields.iter())
347                .all(|(f1, f2)| f1.name() == f2.name())
348            {
349                return from_fields.iter().zip(to_fields.iter()).all(|(f1, f2)| {
350                    // Assume that nullability between two structs are compatible, if not,
351                    // cast kernel will return error.
352                    can_cast_types(f1.data_type(), f2.data_type())
353                });
354            }
355
356            // slow path, we match the fields by name
357            if to_fields.iter().all(|to_field| {
358                from_fields
359                    .iter()
360                    .find(|from_field| from_field.name() == to_field.name())
361                    .is_some_and(|from_field| {
362                        // Assume that nullability between two structs are compatible, if not,
363                        // cast kernel will return error.
364                        can_cast_types(from_field.data_type(), to_field.data_type())
365                    })
366            }) {
367                return true;
368            }
369
370            // if we couldn't match by name, we try to see if they can be matched by position
371            from_fields
372                .iter()
373                .zip(to_fields.iter())
374                .all(|(f1, f2)| can_cast_types(f1.data_type(), f2.data_type()))
375        }
376        (Struct(_), _) => false,
377        (_, Struct(_)) => false,
378        (_, Boolean) => from_type.is_integer() || from_type.is_floating() || from_type.is_string(),
379        (Boolean, _) => to_type.is_integer() || to_type.is_floating() || to_type.is_string(),
380
381        (Binary, LargeBinary | Utf8 | LargeUtf8 | FixedSizeBinary(_) | BinaryView | Utf8View) => {
382            true
383        }
384        (LargeBinary, Binary | Utf8 | LargeUtf8 | FixedSizeBinary(_) | BinaryView | Utf8View) => {
385            true
386        }
387        (FixedSizeBinary(_), Binary | LargeBinary | BinaryView) => true,
388        (
389            Utf8 | LargeUtf8 | Utf8View,
390            Binary
391            | LargeBinary
392            | Utf8
393            | LargeUtf8
394            | Date32
395            | Date64
396            | Time32(Second | Millisecond)
397            | Time64(Microsecond | Nanosecond)
398            | Timestamp(Second | Millisecond | Microsecond | Nanosecond, _)
399            | Interval(_)
400            | Duration(_)
401            | BinaryView,
402        ) => true,
403        (Utf8 | LargeUtf8, Utf8View) => true,
404        (BinaryView, Binary | LargeBinary | Utf8 | LargeUtf8 | Utf8View) => true,
405        (Utf8View | Utf8 | LargeUtf8, _) => to_type.is_numeric(),
406        (_, Utf8 | Utf8View | LargeUtf8) => from_type.is_primitive(),
407
408        (_, Binary | LargeBinary) => from_type.is_integer(),
409
410        // start numeric casts
411        (
412            UInt8 | UInt16 | UInt32 | UInt64 | Int8 | Int16 | Int32 | Int64 | Float16 | Float32
413            | Float64,
414            UInt8 | UInt16 | UInt32 | UInt64 | Int8 | Int16 | Int32 | Int64 | Float16 | Float32
415            | Float64,
416        ) => true,
417        // end numeric casts
418
419        // temporal casts
420        (Int32, Date32 | Date64 | Time32(_)) => true,
421        (Date32, Int32 | Int64) => true,
422        (Time32(_), Int32 | Int64) => true,
423        (Int64, Date64 | Date32 | Time64(_)) => true,
424        (Date64, Int64 | Int32) => true,
425        (Time64(_), Int64) => true,
426        (Date32 | Date64, Date32 | Date64) => true,
427        // time casts
428        (Time32(_), Time32(_)) => true,
429        (Time32(_), Time64(_)) => true,
430        (Time64(_), Time64(_)) => true,
431        (Time64(_), Time32(to_unit)) => {
432            matches!(to_unit, Second | Millisecond)
433        }
434        (Timestamp(_, _), _) if to_type.is_numeric() => true,
435        (_, Timestamp(_, _)) if from_type.is_numeric() => true,
436        (Date64, Timestamp(_, _)) => true,
437        (Date32, Timestamp(_, _)) => true,
438        (
439            Timestamp(_, _),
440            Timestamp(_, _)
441            | Date32
442            | Date64
443            | Time32(Second | Millisecond)
444            | Time64(Microsecond | Nanosecond),
445        ) => true,
446        (_, Duration(_)) if from_type.is_numeric() => true,
447        (Duration(_), _) if to_type.is_numeric() => true,
448        (Duration(_), Duration(_)) => true,
449        // No `(Interval(_), Int64)` arm: `cast_with_options` implements no such cast.
450        (Int32, Interval(to_type)) => match to_type {
451            YearMonth => true,
452            DayTime => false,
453            MonthDayNano => false,
454        },
455        (Duration(_), Interval(MonthDayNano)) => true,
456        (Interval(MonthDayNano), Duration(_)) => true,
457        (Interval(YearMonth), Interval(MonthDayNano)) => true,
458        (Interval(DayTime), Interval(MonthDayNano)) => true,
459        (_, _) => false,
460    }
461}
462
463/// Cast `array` to the provided data type and return a new Array with type `to_type`, if possible.
464///
465/// See [`cast_with_options`] for more information.
466///
467/// # Errors
468///
469/// See [cast_with_options](cast_with_options#errors) for error conditions.
470pub fn cast(array: &dyn Array, to_type: &DataType) -> Result<ArrayRef, ArrowError> {
471    cast_with_options(array, to_type, &CastOptions::default())
472}
473
474/// Cast the primitive array using [`PrimitiveArray::reinterpret_cast`]
475fn cast_reinterpret_arrays<I: ArrowPrimitiveType, O: ArrowPrimitiveType<Native = I::Native>>(
476    array: &dyn Array,
477) -> Result<ArrayRef, ArrowError> {
478    Ok(Arc::new(array.as_primitive::<I>().reinterpret_cast::<O>()))
479}
480
481/// Try to cast `array` to `to_type` if possible.
482///
483/// Returns a new Array with type `to_type` if possible.
484///
485/// Accepts [`CastOptions`] to specify cast behavior. See also [`cast()`].
486///
487/// # Behavior
488/// * `Boolean` to `Utf8`, `LargeUtf8`, or `Utf8View`: `true` => `"true"`, `false` => `"false"`
489/// * `Utf8` to `Boolean`: `true`, `yes`, `on`, `1` => `true`, `false`, `no`, `off`, `0` => `false`,
490///   short variants are accepted, other strings return null or error
491/// * `Utf8` to Numeric: strings that can't be parsed to numbers return null, float strings
492///   in integer casts return null
493/// * Numeric to `Boolean`: 0 returns `false`, any other value returns `true`
494/// * `List` to `List`: the underlying data type is cast
495/// * `List` to `FixedSizeList`: the underlying data type is cast. If safe is true and a list element
496///   has the wrong length it will be replaced with NULL, otherwise an error will be returned
497/// * Primitive to `List`: a list array with 1 value per slot is created
498/// * `Date32` and `Date64`: precision lost when going to higher interval
499/// * `Time32` and `Time64`: precision lost when going to higher interval
500/// * `Timestamp` and `Date{32|64}`: precision lost when going to higher interval
501/// * `Timestamp` to `Date32`, `Time32`, or `Time64`: timestamps without a timezone
502///   support the full `i64` range; timestamps with a timezone must lie within Chrono's
503///   date range. If safe is true, a timestamp outside that range or a `Date32` day
504///   count that does not fit in `i32` becomes NULL, otherwise an error is returned
505/// * Temporal to/from backing Primitive: zero-copy with data type change
506/// * `Float16/Float32/Float64` to `Decimal(precision, scale)` rounds to the `scale` decimals
507///   (i.e. casting `6.4999` to `Decimal(10, 1)` becomes `6.5`).
508/// * `Decimal` to `Float16/Float32/Float64` is lossy and values outside the representable
509///   range become `INFINITY` or `-INFINITY` without error.
510///
511/// Unsupported Casts (check with `can_cast_types` before calling):
512/// * To or from `StructArray`
513/// * `List` to `Primitive`
514/// * `Interval` and `Duration`
515///
516/// # Errors
517///
518/// Returns [`ArrowError::InvalidArgumentError`] when the conversion between the
519/// source and target types is unsupported, regardless of [`CastOptions::safe`].
520/// Use [`can_cast_types`] to check whether a conversion is supported.
521///
522/// [`ArrowError::CastError`] reports failures to convert input values, such as
523/// numeric overflow or invalid strings. See [`CastOptions::safe`] for whether
524/// failed conversions produce nulls or errors.
525///
526/// # Durations and Intervals
527///
528/// Casting integer types directly to interval types such as
529/// [`IntervalMonthDayNano`] is not supported because the meaning of the integer
530/// is ambiguous. For example, the integer  could represent either nanoseconds
531/// or months.
532///
533/// To cast an integer type to an interval type, first convert to a Duration
534/// type, and then cast that to the desired interval type.
535///
536/// For example, to convert an `Int64` representing nanoseconds to an
537/// `IntervalMonthDayNano` you would first convert the `Int64` to a
538/// `DurationNanoseconds`, and then cast that to `IntervalMonthDayNano`.
539///
540/// # Timestamps and Timezones
541///
542/// Timestamps are stored with an optional timezone in Arrow.
543///
544/// ## Casting timestamps to a timestamp without timezone / UTC
545/// ```
546/// # use arrow_array::Int64Array;
547/// # use arrow_array::types::TimestampSecondType;
548/// # use arrow_cast::{cast, display};
549/// # use arrow_array::cast::AsArray;
550/// # use arrow_schema::{DataType, TimeUnit};
551/// // can use "UTC" if chrono-tz feature is enabled, here use offset based timezone
552/// let data_type = DataType::Timestamp(TimeUnit::Second, None);
553/// let a = Int64Array::from(vec![1_000_000_000, 2_000_000_000, 3_000_000_000]);
554/// let b = cast(&a, &data_type).unwrap();
555/// let b = b.as_primitive::<TimestampSecondType>(); // downcast to result type
556/// assert_eq!(2_000_000_000, b.value(1)); // values are the same as the type has no timezone
557/// // use display to show them (note has no trailing Z)
558/// assert_eq!("2033-05-18T03:33:20", display::array_value_to_string(&b, 1).unwrap());
559/// ```
560///
561/// ## Casting timestamps to a timestamp with timezone
562///
563/// Similarly to the previous example, if you cast numeric values to a timestamp
564/// with timezone, the cast kernel will not change the underlying values
565/// but display and other functions will interpret them as being in the provided timezone.
566///
567/// ```
568/// # use arrow_array::Int64Array;
569/// # use arrow_array::types::TimestampSecondType;
570/// # use arrow_cast::{cast, display};
571/// # use arrow_array::cast::AsArray;
572/// # use arrow_schema::{DataType, TimeUnit};
573/// // can use "Americas/New_York" if chrono-tz feature is enabled, here use offset based timezone
574/// let data_type = DataType::Timestamp(TimeUnit::Second, Some("-05:00".into()));
575/// let a = Int64Array::from(vec![1_000_000_000, 2_000_000_000, 3_000_000_000]);
576/// let b = cast(&a, &data_type).unwrap();
577/// let b = b.as_primitive::<TimestampSecondType>(); // downcast to result type
578/// assert_eq!(2_000_000_000, b.value(1)); // values are still the same
579/// // displayed in the target timezone (note the offset -05:00)
580/// assert_eq!("2033-05-17T22:33:20-05:00", display::array_value_to_string(&b, 1).unwrap());
581/// ```
582/// # Casting timestamps without timezone to timestamps with timezone
583///
584/// When casting from a timestamp without timezone to a timestamp with
585/// timezone, the cast kernel interprets the timestamp values as being in
586/// the destination timezone and then adjusts the underlying value to UTC as required
587///
588/// However, note that when casting from a timestamp with timezone BACK to a
589/// timestamp without timezone the cast kernel does not adjust the values.
590///
591/// Thus round trip casting a timestamp without timezone to a timestamp with
592/// timezone and back to a timestamp without timezone results in different
593/// values than the starting values.
594///
595/// ```
596/// # use arrow_array::Int64Array;
597/// # use arrow_array::types::{TimestampSecondType};
598/// # use arrow_cast::{cast, display};
599/// # use arrow_array::cast::AsArray;
600/// # use arrow_schema::{DataType, TimeUnit};
601/// let data_type  = DataType::Timestamp(TimeUnit::Second, None);
602/// let data_type_tz = DataType::Timestamp(TimeUnit::Second, Some("-05:00".into()));
603/// let a = Int64Array::from(vec![1_000_000_000, 2_000_000_000, 3_000_000_000]);
604/// let b = cast(&a, &data_type).unwrap(); // cast to timestamp without timezone
605/// let b = b.as_primitive::<TimestampSecondType>(); // downcast to result type
606/// assert_eq!(2_000_000_000, b.value(1)); // values are still the same
607/// // displayed without a timezone (note lack of offset or Z)
608/// assert_eq!("2033-05-18T03:33:20", display::array_value_to_string(&b, 1).unwrap());
609///
610/// // Convert timestamps without a timezone to timestamps with a timezone
611/// let c = cast(&b, &data_type_tz).unwrap();
612/// let c = c.as_primitive::<TimestampSecondType>(); // downcast to result type
613/// assert_eq!(2_000_018_000, c.value(1)); // value has been adjusted by offset
614/// // displayed with the target timezone offset (-05:00)
615/// assert_eq!("2033-05-18T03:33:20-05:00", display::array_value_to_string(&c, 1).unwrap());
616///
617/// // Convert from timestamp with timezone back to timestamp without timezone
618/// let d = cast(&c, &data_type).unwrap();
619/// let d = d.as_primitive::<TimestampSecondType>(); // downcast to result type
620/// assert_eq!(2_000_018_000, d.value(1)); // value has not been adjusted
621/// // NOTE: the timestamp is adjusted (08:33:20 instead of 03:33:20 as in previous example)
622/// assert_eq!("2033-05-18T08:33:20", display::array_value_to_string(&d, 1).unwrap());
623/// ```
624pub fn cast_with_options(
625    array: &dyn Array,
626    to_type: &DataType,
627    cast_options: &CastOptions,
628) -> Result<ArrayRef, ArrowError> {
629    use DataType::*;
630    let from_type = array.data_type();
631    // clone array if types are the same
632    if from_type == to_type {
633        return Ok(array.to_arc());
634    }
635    match (from_type, to_type) {
636        (Null, _) => Ok(new_null_array(to_type, array.len())),
637        (RunEndEncoded(index_type, _), _) => match index_type.data_type() {
638            Int16 => run_end_encoded_cast::<Int16Type>(array, to_type, cast_options),
639            Int32 => run_end_encoded_cast::<Int32Type>(array, to_type, cast_options),
640            Int64 => run_end_encoded_cast::<Int64Type>(array, to_type, cast_options),
641            _ => Err(ArrowError::InvalidArgumentError(format!(
642                "Casting from run end encoded type {from_type:?} to {to_type:?} not supported",
643            ))),
644        },
645        (_, RunEndEncoded(index_type, value_type)) => {
646            let array_ref = array.to_arc();
647            match index_type.data_type() {
648                Int16 => cast_to_run_end_encoded::<Int16Type>(
649                    &array_ref,
650                    value_type.data_type(),
651                    cast_options,
652                ),
653                Int32 => cast_to_run_end_encoded::<Int32Type>(
654                    &array_ref,
655                    value_type.data_type(),
656                    cast_options,
657                ),
658                Int64 => cast_to_run_end_encoded::<Int64Type>(
659                    &array_ref,
660                    value_type.data_type(),
661                    cast_options,
662                ),
663                _ => Err(ArrowError::InvalidArgumentError(format!(
664                    "Casting from type {from_type:?} to run end encoded type {to_type:?} not supported",
665                ))),
666            }
667        }
668        (Union(_, _), _) => union_extract_by_type(
669            array.as_any().downcast_ref::<UnionArray>().unwrap(),
670            to_type,
671            cast_options,
672        ),
673        (_, Union(_, _)) => Err(ArrowError::InvalidArgumentError(format!(
674            "Casting from {from_type} to {to_type} not supported"
675        ))),
676        (Dictionary(index_type, _), _) => match **index_type {
677            Int8 => dictionary_cast::<Int8Type>(array, to_type, cast_options),
678            Int16 => dictionary_cast::<Int16Type>(array, to_type, cast_options),
679            Int32 => dictionary_cast::<Int32Type>(array, to_type, cast_options),
680            Int64 => dictionary_cast::<Int64Type>(array, to_type, cast_options),
681            UInt8 => dictionary_cast::<UInt8Type>(array, to_type, cast_options),
682            UInt16 => dictionary_cast::<UInt16Type>(array, to_type, cast_options),
683            UInt32 => dictionary_cast::<UInt32Type>(array, to_type, cast_options),
684            UInt64 => dictionary_cast::<UInt64Type>(array, to_type, cast_options),
685            _ => Err(ArrowError::InvalidArgumentError(format!(
686                "Casting from dictionary type {from_type} to {to_type} not supported",
687            ))),
688        },
689        (_, Dictionary(index_type, value_type)) => match **index_type {
690            Int8 => cast_to_dictionary::<Int8Type>(array, value_type, cast_options),
691            Int16 => cast_to_dictionary::<Int16Type>(array, value_type, cast_options),
692            Int32 => cast_to_dictionary::<Int32Type>(array, value_type, cast_options),
693            Int64 => cast_to_dictionary::<Int64Type>(array, value_type, cast_options),
694            UInt8 => cast_to_dictionary::<UInt8Type>(array, value_type, cast_options),
695            UInt16 => cast_to_dictionary::<UInt16Type>(array, value_type, cast_options),
696            UInt32 => cast_to_dictionary::<UInt32Type>(array, value_type, cast_options),
697            UInt64 => cast_to_dictionary::<UInt64Type>(array, value_type, cast_options),
698            _ => Err(ArrowError::InvalidArgumentError(format!(
699                "Casting from type {from_type} to dictionary type {to_type} not supported",
700            ))),
701        },
702        // Casting between lists of same types (cast inner values)
703        (List(_), List(to)) => cast_list_values::<i32>(array, to, cast_options),
704        (LargeList(_), LargeList(to)) => cast_list_values::<i64>(array, to, cast_options),
705        (FixedSizeList(_, size_from), FixedSizeList(list_to, size_to)) => {
706            if size_from != size_to {
707                return Err(ArrowError::InvalidArgumentError(
708                    "cannot cast fixed-size-list to fixed-size-list with different size".into(),
709                ));
710            }
711            let array = array.as_fixed_size_list();
712            let values = cast_with_options(array.values(), list_to.data_type(), cast_options)?;
713            let nulls = array.nulls().cloned();
714            let len = array.len();
715            Ok(Arc::new(FixedSizeListArray::try_new_with_length(
716                list_to.clone(),
717                *size_from,
718                values,
719                nulls,
720                len,
721            )?))
722        }
723        (ListView(_), ListView(to)) => cast_list_view_values::<i32>(array, to, cast_options),
724        (LargeListView(_), LargeListView(to)) => {
725            cast_list_view_values::<i64>(array, to, cast_options)
726        }
727        // Casting between different types of lists
728        // List
729        (List(_), LargeList(list_to)) => cast_list::<i32, i64>(array, list_to, cast_options),
730        (List(_), FixedSizeList(field, size)) => {
731            cast_list_to_fixed_size_list::<i32>(array, field, *size, cast_options)
732        }
733        (List(_), ListView(list_to)) => {
734            cast_list_to_list_view::<i32, i32>(array, list_to, cast_options)
735        }
736        (List(_), LargeListView(list_to)) => {
737            cast_list_to_list_view::<i32, i64>(array, list_to, cast_options)
738        }
739        // LargeList
740        (LargeList(_), List(list_to)) => cast_list::<i64, i32>(array, list_to, cast_options),
741        (LargeList(_), FixedSizeList(field, size)) => {
742            cast_list_to_fixed_size_list::<i64>(array, field, *size, cast_options)
743        }
744        (LargeList(_), ListView(list_to)) => {
745            cast_list_to_list_view::<i64, i32>(array, list_to, cast_options)
746        }
747        (LargeList(_), LargeListView(list_to)) => {
748            cast_list_to_list_view::<i64, i64>(array, list_to, cast_options)
749        }
750        // ListView
751        (ListView(_), List(list_to)) => {
752            cast_list_view_to_list::<i32, Int32Type>(array, list_to, cast_options)
753        }
754        (ListView(_), LargeList(list_to)) => {
755            cast_list_view_to_list::<i32, Int64Type>(array, list_to, cast_options)
756        }
757        (ListView(_), LargeListView(list_to)) => {
758            cast_list_view::<i32, i64>(array, list_to, cast_options)
759        }
760        (ListView(_), FixedSizeList(field, size)) => {
761            cast_list_view_to_fixed_size_list::<i32>(array, field, *size, cast_options)
762        }
763        // LargeListView
764        (LargeListView(_), LargeList(list_to)) => {
765            cast_list_view_to_list::<i64, Int64Type>(array, list_to, cast_options)
766        }
767        (LargeListView(_), List(list_to)) => {
768            cast_list_view_to_list::<i64, Int32Type>(array, list_to, cast_options)
769        }
770        (LargeListView(_), ListView(list_to)) => {
771            cast_list_view::<i64, i32>(array, list_to, cast_options)
772        }
773        (LargeListView(_), FixedSizeList(field, size)) => {
774            cast_list_view_to_fixed_size_list::<i64>(array, field, *size, cast_options)
775        }
776        // FixedSizeList
777        (FixedSizeList(_, _), List(list_to)) => {
778            cast_fixed_size_list_to_list::<i32>(array, list_to, cast_options)
779        }
780        (FixedSizeList(_, _), LargeList(list_to)) => {
781            cast_fixed_size_list_to_list::<i64>(array, list_to, cast_options)
782        }
783        (FixedSizeList(_, _), ListView(list_to)) => {
784            cast_fixed_size_list_to_list_view::<i32>(array, list_to, cast_options)
785        }
786        (FixedSizeList(_, _), LargeListView(list_to)) => {
787            cast_fixed_size_list_to_list_view::<i64>(array, list_to, cast_options)
788        }
789        // List to/from other types
790        (FixedSizeList(_, size), _) if *size == 1 => {
791            cast_single_element_fixed_size_list_to_values(array, to_type, cast_options)
792        }
793        // NOTE: we could support FSL to string here too but might be confusing
794        //       since behaviour for size 1 would be different (see arm above)
795        (List(_) | LargeList(_) | ListView(_) | LargeListView(_), _) => match to_type {
796            Utf8 => value_to_string::<i32>(array, cast_options),
797            LargeUtf8 => value_to_string::<i64>(array, cast_options),
798            Utf8View => value_to_string_view(array, cast_options),
799            dt => Err(ArrowError::InvalidArgumentError(format!(
800                "Cannot cast LIST to non-list data type {dt}"
801            ))),
802        },
803        (_, List(to)) => cast_values_to_list::<i32>(array, to, cast_options),
804        (_, LargeList(to)) => cast_values_to_list::<i64>(array, to, cast_options),
805        (_, ListView(to)) => cast_values_to_list_view::<i32>(array, to, cast_options),
806        (_, LargeListView(to)) => cast_values_to_list_view::<i64>(array, to, cast_options),
807        (_, FixedSizeList(to, size)) if *size == 1 => {
808            let values = cast_with_options(array, to.data_type(), cast_options)?;
809            let list = FixedSizeListArray::try_new(to.clone(), 1, values, None)?;
810            Ok(Arc::new(list))
811        }
812        // Map
813        (Map(_, ordered1), Map(_, ordered2)) if ordered1 == ordered2 => {
814            cast_map_values(array.as_map(), to_type, cast_options, ordered1.to_owned())
815        }
816        // Decimal to decimal, same width
817        (Decimal32(p1, s1), Decimal32(p2, s2)) => {
818            cast_decimal_to_decimal_same_type::<Decimal32Type>(
819                array.as_primitive(),
820                *p1,
821                *s1,
822                *p2,
823                *s2,
824                cast_options,
825            )
826        }
827        (Decimal64(p1, s1), Decimal64(p2, s2)) => {
828            cast_decimal_to_decimal_same_type::<Decimal64Type>(
829                array.as_primitive(),
830                *p1,
831                *s1,
832                *p2,
833                *s2,
834                cast_options,
835            )
836        }
837        (Decimal128(p1, s1), Decimal128(p2, s2)) => {
838            cast_decimal_to_decimal_same_type::<Decimal128Type>(
839                array.as_primitive(),
840                *p1,
841                *s1,
842                *p2,
843                *s2,
844                cast_options,
845            )
846        }
847        (Decimal256(p1, s1), Decimal256(p2, s2)) => {
848            cast_decimal_to_decimal_same_type::<Decimal256Type>(
849                array.as_primitive(),
850                *p1,
851                *s1,
852                *p2,
853                *s2,
854                cast_options,
855            )
856        }
857        // Decimal to decimal, different width
858        (Decimal32(p1, s1), Decimal64(p2, s2)) => {
859            cast_decimal_to_decimal::<Decimal32Type, Decimal64Type>(
860                array.as_primitive(),
861                *p1,
862                *s1,
863                *p2,
864                *s2,
865                cast_options,
866            )
867        }
868        (Decimal32(p1, s1), Decimal128(p2, s2)) => {
869            cast_decimal_to_decimal::<Decimal32Type, Decimal128Type>(
870                array.as_primitive(),
871                *p1,
872                *s1,
873                *p2,
874                *s2,
875                cast_options,
876            )
877        }
878        (Decimal32(p1, s1), Decimal256(p2, s2)) => {
879            cast_decimal_to_decimal::<Decimal32Type, Decimal256Type>(
880                array.as_primitive(),
881                *p1,
882                *s1,
883                *p2,
884                *s2,
885                cast_options,
886            )
887        }
888        (Decimal64(p1, s1), Decimal32(p2, s2)) => {
889            cast_decimal_to_decimal::<Decimal64Type, Decimal32Type>(
890                array.as_primitive(),
891                *p1,
892                *s1,
893                *p2,
894                *s2,
895                cast_options,
896            )
897        }
898        (Decimal64(p1, s1), Decimal128(p2, s2)) => {
899            cast_decimal_to_decimal::<Decimal64Type, Decimal128Type>(
900                array.as_primitive(),
901                *p1,
902                *s1,
903                *p2,
904                *s2,
905                cast_options,
906            )
907        }
908        (Decimal64(p1, s1), Decimal256(p2, s2)) => {
909            cast_decimal_to_decimal::<Decimal64Type, Decimal256Type>(
910                array.as_primitive(),
911                *p1,
912                *s1,
913                *p2,
914                *s2,
915                cast_options,
916            )
917        }
918        (Decimal128(p1, s1), Decimal32(p2, s2)) => {
919            cast_decimal_to_decimal::<Decimal128Type, Decimal32Type>(
920                array.as_primitive(),
921                *p1,
922                *s1,
923                *p2,
924                *s2,
925                cast_options,
926            )
927        }
928        (Decimal128(p1, s1), Decimal64(p2, s2)) => {
929            cast_decimal_to_decimal::<Decimal128Type, Decimal64Type>(
930                array.as_primitive(),
931                *p1,
932                *s1,
933                *p2,
934                *s2,
935                cast_options,
936            )
937        }
938        (Decimal128(p1, s1), Decimal256(p2, s2)) => {
939            cast_decimal_to_decimal::<Decimal128Type, Decimal256Type>(
940                array.as_primitive(),
941                *p1,
942                *s1,
943                *p2,
944                *s2,
945                cast_options,
946            )
947        }
948        (Decimal256(p1, s1), Decimal32(p2, s2)) => {
949            cast_decimal_to_decimal::<Decimal256Type, Decimal32Type>(
950                array.as_primitive(),
951                *p1,
952                *s1,
953                *p2,
954                *s2,
955                cast_options,
956            )
957        }
958        (Decimal256(p1, s1), Decimal64(p2, s2)) => {
959            cast_decimal_to_decimal::<Decimal256Type, Decimal64Type>(
960                array.as_primitive(),
961                *p1,
962                *s1,
963                *p2,
964                *s2,
965                cast_options,
966            )
967        }
968        (Decimal256(p1, s1), Decimal128(p2, s2)) => {
969            cast_decimal_to_decimal::<Decimal256Type, Decimal128Type>(
970                array.as_primitive(),
971                *p1,
972                *s1,
973                *p2,
974                *s2,
975                cast_options,
976            )
977        }
978        // Decimal to non-decimal
979        (Decimal32(_, scale), _) if !to_type.is_temporal() => {
980            cast_from_decimal::<Decimal32Type, _>(
981                array,
982                scale,
983                from_type,
984                to_type,
985                |x: i32| x as f64,
986                cast_options,
987            )
988        }
989        (Decimal64(_, scale), _) if !to_type.is_temporal() => {
990            cast_from_decimal::<Decimal64Type, _>(
991                array,
992                scale,
993                from_type,
994                to_type,
995                |x: i64| x as f64,
996                cast_options,
997            )
998        }
999        (Decimal128(_, scale), _) if !to_type.is_temporal() => {
1000            cast_from_decimal::<Decimal128Type, _>(
1001                array,
1002                scale,
1003                from_type,
1004                to_type,
1005                |x: i128| x as f64,
1006                cast_options,
1007            )
1008        }
1009        (Decimal256(_, scale), _) if !to_type.is_temporal() => {
1010            cast_from_decimal::<Decimal256Type, _>(
1011                array,
1012                scale,
1013                from_type,
1014                to_type,
1015                |x: i256| x.to_f64().expect("All i256 values fit in f64"),
1016                cast_options,
1017            )
1018        }
1019        // Non-decimal to decimal
1020        (_, Decimal32(precision, scale)) if !from_type.is_temporal() => {
1021            cast_to_decimal::<Decimal32Type, _>(
1022                array,
1023                precision,
1024                scale,
1025                from_type,
1026                to_type,
1027                cast_options,
1028            )
1029        }
1030        (_, Decimal64(precision, scale)) if !from_type.is_temporal() => {
1031            cast_to_decimal::<Decimal64Type, _>(
1032                array,
1033                precision,
1034                scale,
1035                from_type,
1036                to_type,
1037                cast_options,
1038            )
1039        }
1040        (_, Decimal128(precision, scale)) if !from_type.is_temporal() => {
1041            cast_to_decimal::<Decimal128Type, _>(
1042                array,
1043                precision,
1044                scale,
1045                from_type,
1046                to_type,
1047                cast_options,
1048            )
1049        }
1050        (_, Decimal256(precision, scale)) if !from_type.is_temporal() => {
1051            cast_to_decimal::<Decimal256Type, _>(
1052                array,
1053                precision,
1054                scale,
1055                from_type,
1056                to_type,
1057                cast_options,
1058            )
1059        }
1060        (Struct(from_fields), Struct(to_fields)) => cast_struct_to_struct(
1061            array.as_struct(),
1062            from_fields.clone(),
1063            to_fields.clone(),
1064            cast_options,
1065        ),
1066        (Struct(_), _) => Err(ArrowError::InvalidArgumentError(format!(
1067            "Casting from {from_type} to {to_type} not supported"
1068        ))),
1069        (_, Struct(_)) => Err(ArrowError::InvalidArgumentError(format!(
1070            "Casting from {from_type} to {to_type} not supported"
1071        ))),
1072        (_, Boolean) => match from_type {
1073            UInt8 => cast_numeric_to_bool::<UInt8Type>(array),
1074            UInt16 => cast_numeric_to_bool::<UInt16Type>(array),
1075            UInt32 => cast_numeric_to_bool::<UInt32Type>(array),
1076            UInt64 => cast_numeric_to_bool::<UInt64Type>(array),
1077            Int8 => cast_numeric_to_bool::<Int8Type>(array),
1078            Int16 => cast_numeric_to_bool::<Int16Type>(array),
1079            Int32 => cast_numeric_to_bool::<Int32Type>(array),
1080            Int64 => cast_numeric_to_bool::<Int64Type>(array),
1081            Float16 => cast_numeric_to_bool::<Float16Type>(array),
1082            Float32 => cast_numeric_to_bool::<Float32Type>(array),
1083            Float64 => cast_numeric_to_bool::<Float64Type>(array),
1084            Utf8View => cast_utf8view_to_boolean(array, cast_options),
1085            Utf8 => cast_utf8_to_boolean::<i32>(array, cast_options),
1086            LargeUtf8 => cast_utf8_to_boolean::<i64>(array, cast_options),
1087            _ => Err(ArrowError::InvalidArgumentError(format!(
1088                "Casting from {from_type} to {to_type} not supported",
1089            ))),
1090        },
1091        (Boolean, _) => match to_type {
1092            UInt8 => cast_bool_to_numeric::<UInt8Type>(array, cast_options),
1093            UInt16 => cast_bool_to_numeric::<UInt16Type>(array, cast_options),
1094            UInt32 => cast_bool_to_numeric::<UInt32Type>(array, cast_options),
1095            UInt64 => cast_bool_to_numeric::<UInt64Type>(array, cast_options),
1096            Int8 => cast_bool_to_numeric::<Int8Type>(array, cast_options),
1097            Int16 => cast_bool_to_numeric::<Int16Type>(array, cast_options),
1098            Int32 => cast_bool_to_numeric::<Int32Type>(array, cast_options),
1099            Int64 => cast_bool_to_numeric::<Int64Type>(array, cast_options),
1100            Float16 => cast_bool_to_numeric::<Float16Type>(array, cast_options),
1101            Float32 => cast_bool_to_numeric::<Float32Type>(array, cast_options),
1102            Float64 => cast_bool_to_numeric::<Float64Type>(array, cast_options),
1103            Utf8View => cast_bool_to_string::<StringViewArray>(array),
1104            Utf8 => cast_bool_to_string::<StringArray>(array),
1105            LargeUtf8 => cast_bool_to_string::<LargeStringArray>(array),
1106            _ => Err(ArrowError::InvalidArgumentError(format!(
1107                "Casting from {from_type} to {to_type} not supported",
1108            ))),
1109        },
1110        (Utf8, _) => match to_type {
1111            UInt8 => parse_string::<UInt8Type, i32>(array, cast_options),
1112            UInt16 => parse_string::<UInt16Type, i32>(array, cast_options),
1113            UInt32 => parse_string::<UInt32Type, i32>(array, cast_options),
1114            UInt64 => parse_string::<UInt64Type, i32>(array, cast_options),
1115            Int8 => parse_string::<Int8Type, i32>(array, cast_options),
1116            Int16 => parse_string::<Int16Type, i32>(array, cast_options),
1117            Int32 => parse_string::<Int32Type, i32>(array, cast_options),
1118            Int64 => parse_string::<Int64Type, i32>(array, cast_options),
1119            Float16 => parse_string::<Float16Type, i32>(array, cast_options),
1120            Float32 => parse_string::<Float32Type, i32>(array, cast_options),
1121            Float64 => parse_string::<Float64Type, i32>(array, cast_options),
1122            Date32 => parse_string::<Date32Type, i32>(array, cast_options),
1123            Date64 => parse_string::<Date64Type, i32>(array, cast_options),
1124            Binary => Ok(Arc::new(BinaryArray::from(
1125                array.as_string::<i32>().clone(),
1126            ))),
1127            LargeBinary => {
1128                let binary = BinaryArray::from(array.as_string::<i32>().clone());
1129                cast_byte_container::<BinaryType, LargeBinaryType>(&binary)
1130            }
1131            Utf8View => Ok(Arc::new(StringViewArray::from(array.as_string::<i32>()))),
1132            BinaryView => Ok(Arc::new(
1133                StringViewArray::from(array.as_string::<i32>()).to_binary_view(),
1134            )),
1135            LargeUtf8 => cast_byte_container::<Utf8Type, LargeUtf8Type>(array),
1136            Time32(TimeUnit::Second) => parse_string::<Time32SecondType, i32>(array, cast_options),
1137            Time32(TimeUnit::Millisecond) => {
1138                parse_string::<Time32MillisecondType, i32>(array, cast_options)
1139            }
1140            Time64(TimeUnit::Microsecond) => {
1141                parse_string::<Time64MicrosecondType, i32>(array, cast_options)
1142            }
1143            Time64(TimeUnit::Nanosecond) => {
1144                parse_string::<Time64NanosecondType, i32>(array, cast_options)
1145            }
1146            Timestamp(TimeUnit::Second, to_tz) => cast_string_to_timestamp::<
1147                i32,
1148                TimestampSecondType,
1149            >(array, to_tz.as_ref(), cast_options),
1150            Timestamp(TimeUnit::Millisecond, to_tz) => cast_string_to_timestamp::<
1151                i32,
1152                TimestampMillisecondType,
1153            >(
1154                array, to_tz.as_ref(), cast_options
1155            ),
1156            Timestamp(TimeUnit::Microsecond, to_tz) => cast_string_to_timestamp::<
1157                i32,
1158                TimestampMicrosecondType,
1159            >(
1160                array, to_tz.as_ref(), cast_options
1161            ),
1162            Timestamp(TimeUnit::Nanosecond, to_tz) => cast_string_to_timestamp::<
1163                i32,
1164                TimestampNanosecondType,
1165            >(
1166                array, to_tz.as_ref(), cast_options
1167            ),
1168            Interval(IntervalUnit::YearMonth) => {
1169                cast_string_to_year_month_interval::<i32>(array, cast_options)
1170            }
1171            Interval(IntervalUnit::DayTime) => {
1172                cast_string_to_day_time_interval::<i32>(array, cast_options)
1173            }
1174            Interval(IntervalUnit::MonthDayNano) => {
1175                cast_string_to_month_day_nano_interval::<i32>(array, cast_options)
1176            }
1177            Duration(TimeUnit::Second) => {
1178                cast_string_to_duration::<DurationSecondType, i32>(array, cast_options)
1179            }
1180            Duration(TimeUnit::Millisecond) => {
1181                cast_string_to_duration::<DurationMillisecondType, i32>(array, cast_options)
1182            }
1183            Duration(TimeUnit::Microsecond) => {
1184                cast_string_to_duration::<DurationMicrosecondType, i32>(array, cast_options)
1185            }
1186            Duration(TimeUnit::Nanosecond) => {
1187                cast_string_to_duration::<DurationNanosecondType, i32>(array, cast_options)
1188            }
1189            _ => Err(ArrowError::InvalidArgumentError(format!(
1190                "Casting from {from_type} to {to_type} not supported",
1191            ))),
1192        },
1193        (Utf8View, _) => match to_type {
1194            UInt8 => parse_string_view::<UInt8Type>(array, cast_options),
1195            UInt16 => parse_string_view::<UInt16Type>(array, cast_options),
1196            UInt32 => parse_string_view::<UInt32Type>(array, cast_options),
1197            UInt64 => parse_string_view::<UInt64Type>(array, cast_options),
1198            Int8 => parse_string_view::<Int8Type>(array, cast_options),
1199            Int16 => parse_string_view::<Int16Type>(array, cast_options),
1200            Int32 => parse_string_view::<Int32Type>(array, cast_options),
1201            Int64 => parse_string_view::<Int64Type>(array, cast_options),
1202            Float16 => parse_string_view::<Float16Type>(array, cast_options),
1203            Float32 => parse_string_view::<Float32Type>(array, cast_options),
1204            Float64 => parse_string_view::<Float64Type>(array, cast_options),
1205            Date32 => parse_string_view::<Date32Type>(array, cast_options),
1206            Date64 => parse_string_view::<Date64Type>(array, cast_options),
1207            Binary => cast_view_to_byte::<StringViewType, GenericBinaryType<i32>>(array),
1208            LargeBinary => cast_view_to_byte::<StringViewType, GenericBinaryType<i64>>(array),
1209            BinaryView => Ok(Arc::new(array.as_string_view().clone().to_binary_view())),
1210            Utf8 => cast_view_to_byte::<StringViewType, GenericStringType<i32>>(array),
1211            LargeUtf8 => cast_view_to_byte::<StringViewType, GenericStringType<i64>>(array),
1212            Time32(TimeUnit::Second) => parse_string_view::<Time32SecondType>(array, cast_options),
1213            Time32(TimeUnit::Millisecond) => {
1214                parse_string_view::<Time32MillisecondType>(array, cast_options)
1215            }
1216            Time64(TimeUnit::Microsecond) => {
1217                parse_string_view::<Time64MicrosecondType>(array, cast_options)
1218            }
1219            Time64(TimeUnit::Nanosecond) => {
1220                parse_string_view::<Time64NanosecondType>(array, cast_options)
1221            }
1222            Timestamp(TimeUnit::Second, to_tz) => {
1223                cast_view_to_timestamp::<TimestampSecondType>(array, to_tz.as_ref(), cast_options)
1224            }
1225            Timestamp(TimeUnit::Millisecond, to_tz) => cast_view_to_timestamp::<
1226                TimestampMillisecondType,
1227            >(
1228                array, to_tz.as_ref(), cast_options
1229            ),
1230            Timestamp(TimeUnit::Microsecond, to_tz) => cast_view_to_timestamp::<
1231                TimestampMicrosecondType,
1232            >(
1233                array, to_tz.as_ref(), cast_options
1234            ),
1235            Timestamp(TimeUnit::Nanosecond, to_tz) => cast_view_to_timestamp::<
1236                TimestampNanosecondType,
1237            >(
1238                array, to_tz.as_ref(), cast_options
1239            ),
1240            Interval(IntervalUnit::YearMonth) => {
1241                cast_view_to_year_month_interval(array, cast_options)
1242            }
1243            Interval(IntervalUnit::DayTime) => cast_view_to_day_time_interval(array, cast_options),
1244            Interval(IntervalUnit::MonthDayNano) => {
1245                cast_view_to_month_day_nano_interval(array, cast_options)
1246            }
1247            Duration(TimeUnit::Second) => {
1248                cast_view_to_duration::<DurationSecondType>(array, cast_options)
1249            }
1250            Duration(TimeUnit::Millisecond) => {
1251                cast_view_to_duration::<DurationMillisecondType>(array, cast_options)
1252            }
1253            Duration(TimeUnit::Microsecond) => {
1254                cast_view_to_duration::<DurationMicrosecondType>(array, cast_options)
1255            }
1256            Duration(TimeUnit::Nanosecond) => {
1257                cast_view_to_duration::<DurationNanosecondType>(array, cast_options)
1258            }
1259            _ => Err(ArrowError::InvalidArgumentError(format!(
1260                "Casting from {from_type} to {to_type} not supported",
1261            ))),
1262        },
1263        (LargeUtf8, _) => match to_type {
1264            UInt8 => parse_string::<UInt8Type, i64>(array, cast_options),
1265            UInt16 => parse_string::<UInt16Type, i64>(array, cast_options),
1266            UInt32 => parse_string::<UInt32Type, i64>(array, cast_options),
1267            UInt64 => parse_string::<UInt64Type, i64>(array, cast_options),
1268            Int8 => parse_string::<Int8Type, i64>(array, cast_options),
1269            Int16 => parse_string::<Int16Type, i64>(array, cast_options),
1270            Int32 => parse_string::<Int32Type, i64>(array, cast_options),
1271            Int64 => parse_string::<Int64Type, i64>(array, cast_options),
1272            Float16 => parse_string::<Float16Type, i64>(array, cast_options),
1273            Float32 => parse_string::<Float32Type, i64>(array, cast_options),
1274            Float64 => parse_string::<Float64Type, i64>(array, cast_options),
1275            Date32 => parse_string::<Date32Type, i64>(array, cast_options),
1276            Date64 => parse_string::<Date64Type, i64>(array, cast_options),
1277            Utf8 => cast_byte_container::<LargeUtf8Type, Utf8Type>(array),
1278            Binary => {
1279                let large_binary = LargeBinaryArray::from(array.as_string::<i64>().clone());
1280                cast_byte_container::<LargeBinaryType, BinaryType>(&large_binary)
1281            }
1282            LargeBinary => Ok(Arc::new(LargeBinaryArray::from(
1283                array.as_string::<i64>().clone(),
1284            ))),
1285            Utf8View => Ok(Arc::new(StringViewArray::from(array.as_string::<i64>()))),
1286            BinaryView => Ok(Arc::new(BinaryViewArray::from(
1287                array
1288                    .as_string::<i64>()
1289                    .into_iter()
1290                    .map(|x| x.map(|x| x.as_bytes()))
1291                    .collect::<Vec<_>>(),
1292            ))),
1293            Time32(TimeUnit::Second) => parse_string::<Time32SecondType, i64>(array, cast_options),
1294            Time32(TimeUnit::Millisecond) => {
1295                parse_string::<Time32MillisecondType, i64>(array, cast_options)
1296            }
1297            Time64(TimeUnit::Microsecond) => {
1298                parse_string::<Time64MicrosecondType, i64>(array, cast_options)
1299            }
1300            Time64(TimeUnit::Nanosecond) => {
1301                parse_string::<Time64NanosecondType, i64>(array, cast_options)
1302            }
1303            Timestamp(TimeUnit::Second, to_tz) => cast_string_to_timestamp::<
1304                i64,
1305                TimestampSecondType,
1306            >(array, to_tz.as_ref(), cast_options),
1307            Timestamp(TimeUnit::Millisecond, to_tz) => cast_string_to_timestamp::<
1308                i64,
1309                TimestampMillisecondType,
1310            >(
1311                array, to_tz.as_ref(), cast_options
1312            ),
1313            Timestamp(TimeUnit::Microsecond, to_tz) => cast_string_to_timestamp::<
1314                i64,
1315                TimestampMicrosecondType,
1316            >(
1317                array, to_tz.as_ref(), cast_options
1318            ),
1319            Timestamp(TimeUnit::Nanosecond, to_tz) => cast_string_to_timestamp::<
1320                i64,
1321                TimestampNanosecondType,
1322            >(
1323                array, to_tz.as_ref(), cast_options
1324            ),
1325            Interval(IntervalUnit::YearMonth) => {
1326                cast_string_to_year_month_interval::<i64>(array, cast_options)
1327            }
1328            Interval(IntervalUnit::DayTime) => {
1329                cast_string_to_day_time_interval::<i64>(array, cast_options)
1330            }
1331            Interval(IntervalUnit::MonthDayNano) => {
1332                cast_string_to_month_day_nano_interval::<i64>(array, cast_options)
1333            }
1334            Duration(TimeUnit::Second) => {
1335                cast_string_to_duration::<DurationSecondType, i64>(array, cast_options)
1336            }
1337            Duration(TimeUnit::Millisecond) => {
1338                cast_string_to_duration::<DurationMillisecondType, i64>(array, cast_options)
1339            }
1340            Duration(TimeUnit::Microsecond) => {
1341                cast_string_to_duration::<DurationMicrosecondType, i64>(array, cast_options)
1342            }
1343            Duration(TimeUnit::Nanosecond) => {
1344                cast_string_to_duration::<DurationNanosecondType, i64>(array, cast_options)
1345            }
1346            _ => Err(ArrowError::InvalidArgumentError(format!(
1347                "Casting from {from_type} to {to_type} not supported",
1348            ))),
1349        },
1350        (Binary, _) => match to_type {
1351            Utf8 => cast_binary_to_string::<i32>(array, cast_options),
1352            LargeUtf8 => {
1353                let array = cast_binary_to_string::<i32>(array, cast_options)?;
1354                cast_byte_container::<Utf8Type, LargeUtf8Type>(array.as_ref())
1355            }
1356            LargeBinary => cast_byte_container::<BinaryType, LargeBinaryType>(array),
1357            FixedSizeBinary(size) => {
1358                cast_binary_to_fixed_size_binary::<i32>(array, *size, cast_options)
1359            }
1360            BinaryView => Ok(Arc::new(BinaryViewArray::from(array.as_binary::<i32>()))),
1361            Utf8View => Ok(Arc::new(StringViewArray::from(
1362                cast_binary_to_string::<i32>(array, cast_options)?.as_string::<i32>(),
1363            ))),
1364            _ => Err(ArrowError::InvalidArgumentError(format!(
1365                "Casting from {from_type} to {to_type} not supported",
1366            ))),
1367        },
1368        (LargeBinary, _) => match to_type {
1369            Utf8 => {
1370                let array = cast_binary_to_string::<i64>(array, cast_options)?;
1371                cast_byte_container::<LargeUtf8Type, Utf8Type>(array.as_ref())
1372            }
1373            LargeUtf8 => cast_binary_to_string::<i64>(array, cast_options),
1374            Binary => cast_byte_container::<LargeBinaryType, BinaryType>(array),
1375            FixedSizeBinary(size) => {
1376                cast_binary_to_fixed_size_binary::<i64>(array, *size, cast_options)
1377            }
1378            BinaryView => Ok(Arc::new(BinaryViewArray::from(array.as_binary::<i64>()))),
1379            Utf8View => {
1380                let array = cast_binary_to_string::<i64>(array, cast_options)?;
1381                Ok(Arc::new(StringViewArray::from(array.as_string::<i64>())))
1382            }
1383            _ => Err(ArrowError::InvalidArgumentError(format!(
1384                "Casting from {from_type} to {to_type} not supported",
1385            ))),
1386        },
1387        (FixedSizeBinary(size), _) => match to_type {
1388            Binary => cast_fixed_size_binary_to_binary::<i32>(array, *size),
1389            LargeBinary => cast_fixed_size_binary_to_binary::<i64>(array, *size),
1390            BinaryView => cast_fixed_size_binary_to_binary_view(array, *size),
1391            _ => Err(ArrowError::InvalidArgumentError(format!(
1392                "Casting from {from_type} to {to_type} not supported",
1393            ))),
1394        },
1395        (BinaryView, Binary) => cast_view_to_byte::<BinaryViewType, GenericBinaryType<i32>>(array),
1396        (BinaryView, LargeBinary) => {
1397            cast_view_to_byte::<BinaryViewType, GenericBinaryType<i64>>(array)
1398        }
1399        (BinaryView, Utf8) => {
1400            let binary_arr = cast_view_to_byte::<BinaryViewType, GenericBinaryType<i32>>(array)?;
1401            cast_binary_to_string::<i32>(&binary_arr, cast_options)
1402        }
1403        (BinaryView, LargeUtf8) => {
1404            let binary_arr = cast_view_to_byte::<BinaryViewType, GenericBinaryType<i64>>(array)?;
1405            cast_binary_to_string::<i64>(&binary_arr, cast_options)
1406        }
1407        (BinaryView, Utf8View) => cast_binary_view_to_string_view(array, cast_options),
1408        (BinaryView, _) => Err(ArrowError::InvalidArgumentError(format!(
1409            "Casting from {from_type} to {to_type} not supported",
1410        ))),
1411        (from_type, Utf8View) if from_type.is_primitive() => {
1412            value_to_string_view(array, cast_options)
1413        }
1414        (from_type, LargeUtf8) if from_type.is_primitive() => {
1415            value_to_string::<i64>(array, cast_options)
1416        }
1417        (from_type, Utf8) if from_type.is_primitive() => {
1418            value_to_string::<i32>(array, cast_options)
1419        }
1420        (from_type, Binary) if from_type.is_integer() => match from_type {
1421            UInt8 => cast_numeric_to_binary::<UInt8Type, i32>(array),
1422            UInt16 => cast_numeric_to_binary::<UInt16Type, i32>(array),
1423            UInt32 => cast_numeric_to_binary::<UInt32Type, i32>(array),
1424            UInt64 => cast_numeric_to_binary::<UInt64Type, i32>(array),
1425            Int8 => cast_numeric_to_binary::<Int8Type, i32>(array),
1426            Int16 => cast_numeric_to_binary::<Int16Type, i32>(array),
1427            Int32 => cast_numeric_to_binary::<Int32Type, i32>(array),
1428            Int64 => cast_numeric_to_binary::<Int64Type, i32>(array),
1429            _ => unreachable!(),
1430        },
1431        (from_type, LargeBinary) if from_type.is_integer() => match from_type {
1432            UInt8 => cast_numeric_to_binary::<UInt8Type, i64>(array),
1433            UInt16 => cast_numeric_to_binary::<UInt16Type, i64>(array),
1434            UInt32 => cast_numeric_to_binary::<UInt32Type, i64>(array),
1435            UInt64 => cast_numeric_to_binary::<UInt64Type, i64>(array),
1436            Int8 => cast_numeric_to_binary::<Int8Type, i64>(array),
1437            Int16 => cast_numeric_to_binary::<Int16Type, i64>(array),
1438            Int32 => cast_numeric_to_binary::<Int32Type, i64>(array),
1439            Int64 => cast_numeric_to_binary::<Int64Type, i64>(array),
1440            _ => unreachable!(),
1441        },
1442        // start numeric casts
1443        (UInt8, UInt16) => cast_numeric_arrays::<UInt8Type, UInt16Type>(array, cast_options),
1444        (UInt8, UInt32) => cast_numeric_arrays::<UInt8Type, UInt32Type>(array, cast_options),
1445        (UInt8, UInt64) => cast_numeric_arrays::<UInt8Type, UInt64Type>(array, cast_options),
1446        (UInt8, Int8) => cast_numeric_arrays::<UInt8Type, Int8Type>(array, cast_options),
1447        (UInt8, Int16) => cast_numeric_arrays::<UInt8Type, Int16Type>(array, cast_options),
1448        (UInt8, Int32) => cast_numeric_arrays::<UInt8Type, Int32Type>(array, cast_options),
1449        (UInt8, Int64) => cast_numeric_arrays::<UInt8Type, Int64Type>(array, cast_options),
1450        (UInt8, Float16) => cast_numeric_arrays::<UInt8Type, Float16Type>(array, cast_options),
1451        (UInt8, Float32) => cast_numeric_arrays::<UInt8Type, Float32Type>(array, cast_options),
1452        (UInt8, Float64) => cast_numeric_arrays::<UInt8Type, Float64Type>(array, cast_options),
1453
1454        (UInt16, UInt8) => cast_numeric_arrays::<UInt16Type, UInt8Type>(array, cast_options),
1455        (UInt16, UInt32) => cast_numeric_arrays::<UInt16Type, UInt32Type>(array, cast_options),
1456        (UInt16, UInt64) => cast_numeric_arrays::<UInt16Type, UInt64Type>(array, cast_options),
1457        (UInt16, Int8) => cast_numeric_arrays::<UInt16Type, Int8Type>(array, cast_options),
1458        (UInt16, Int16) => cast_numeric_arrays::<UInt16Type, Int16Type>(array, cast_options),
1459        (UInt16, Int32) => cast_numeric_arrays::<UInt16Type, Int32Type>(array, cast_options),
1460        (UInt16, Int64) => cast_numeric_arrays::<UInt16Type, Int64Type>(array, cast_options),
1461        (UInt16, Float16) => cast_numeric_arrays::<UInt16Type, Float16Type>(array, cast_options),
1462        (UInt16, Float32) => cast_numeric_arrays::<UInt16Type, Float32Type>(array, cast_options),
1463        (UInt16, Float64) => cast_numeric_arrays::<UInt16Type, Float64Type>(array, cast_options),
1464
1465        (UInt32, UInt8) => cast_numeric_arrays::<UInt32Type, UInt8Type>(array, cast_options),
1466        (UInt32, UInt16) => cast_numeric_arrays::<UInt32Type, UInt16Type>(array, cast_options),
1467        (UInt32, UInt64) => cast_numeric_arrays::<UInt32Type, UInt64Type>(array, cast_options),
1468        (UInt32, Int8) => cast_numeric_arrays::<UInt32Type, Int8Type>(array, cast_options),
1469        (UInt32, Int16) => cast_numeric_arrays::<UInt32Type, Int16Type>(array, cast_options),
1470        (UInt32, Int32) => cast_numeric_arrays::<UInt32Type, Int32Type>(array, cast_options),
1471        (UInt32, Int64) => cast_numeric_arrays::<UInt32Type, Int64Type>(array, cast_options),
1472        (UInt32, Float16) => cast_numeric_arrays::<UInt32Type, Float16Type>(array, cast_options),
1473        (UInt32, Float32) => cast_numeric_arrays::<UInt32Type, Float32Type>(array, cast_options),
1474        (UInt32, Float64) => cast_numeric_arrays::<UInt32Type, Float64Type>(array, cast_options),
1475
1476        (UInt64, UInt8) => cast_numeric_arrays::<UInt64Type, UInt8Type>(array, cast_options),
1477        (UInt64, UInt16) => cast_numeric_arrays::<UInt64Type, UInt16Type>(array, cast_options),
1478        (UInt64, UInt32) => cast_numeric_arrays::<UInt64Type, UInt32Type>(array, cast_options),
1479        (UInt64, Int8) => cast_numeric_arrays::<UInt64Type, Int8Type>(array, cast_options),
1480        (UInt64, Int16) => cast_numeric_arrays::<UInt64Type, Int16Type>(array, cast_options),
1481        (UInt64, Int32) => cast_numeric_arrays::<UInt64Type, Int32Type>(array, cast_options),
1482        (UInt64, Int64) => cast_numeric_arrays::<UInt64Type, Int64Type>(array, cast_options),
1483        (UInt64, Float16) => cast_numeric_arrays::<UInt64Type, Float16Type>(array, cast_options),
1484        (UInt64, Float32) => cast_numeric_arrays::<UInt64Type, Float32Type>(array, cast_options),
1485        (UInt64, Float64) => cast_numeric_arrays::<UInt64Type, Float64Type>(array, cast_options),
1486
1487        (Int8, UInt8) => cast_numeric_arrays::<Int8Type, UInt8Type>(array, cast_options),
1488        (Int8, UInt16) => cast_numeric_arrays::<Int8Type, UInt16Type>(array, cast_options),
1489        (Int8, UInt32) => cast_numeric_arrays::<Int8Type, UInt32Type>(array, cast_options),
1490        (Int8, UInt64) => cast_numeric_arrays::<Int8Type, UInt64Type>(array, cast_options),
1491        (Int8, Int16) => cast_numeric_arrays::<Int8Type, Int16Type>(array, cast_options),
1492        (Int8, Int32) => cast_numeric_arrays::<Int8Type, Int32Type>(array, cast_options),
1493        (Int8, Int64) => cast_numeric_arrays::<Int8Type, Int64Type>(array, cast_options),
1494        (Int8, Float16) => cast_numeric_arrays::<Int8Type, Float16Type>(array, cast_options),
1495        (Int8, Float32) => cast_numeric_arrays::<Int8Type, Float32Type>(array, cast_options),
1496        (Int8, Float64) => cast_numeric_arrays::<Int8Type, Float64Type>(array, cast_options),
1497
1498        (Int16, UInt8) => cast_numeric_arrays::<Int16Type, UInt8Type>(array, cast_options),
1499        (Int16, UInt16) => cast_numeric_arrays::<Int16Type, UInt16Type>(array, cast_options),
1500        (Int16, UInt32) => cast_numeric_arrays::<Int16Type, UInt32Type>(array, cast_options),
1501        (Int16, UInt64) => cast_numeric_arrays::<Int16Type, UInt64Type>(array, cast_options),
1502        (Int16, Int8) => cast_numeric_arrays::<Int16Type, Int8Type>(array, cast_options),
1503        (Int16, Int32) => cast_numeric_arrays::<Int16Type, Int32Type>(array, cast_options),
1504        (Int16, Int64) => cast_numeric_arrays::<Int16Type, Int64Type>(array, cast_options),
1505        (Int16, Float16) => cast_numeric_arrays::<Int16Type, Float16Type>(array, cast_options),
1506        (Int16, Float32) => cast_numeric_arrays::<Int16Type, Float32Type>(array, cast_options),
1507        (Int16, Float64) => cast_numeric_arrays::<Int16Type, Float64Type>(array, cast_options),
1508
1509        (Int32, UInt8) => cast_numeric_arrays::<Int32Type, UInt8Type>(array, cast_options),
1510        (Int32, UInt16) => cast_numeric_arrays::<Int32Type, UInt16Type>(array, cast_options),
1511        (Int32, UInt32) => cast_numeric_arrays::<Int32Type, UInt32Type>(array, cast_options),
1512        (Int32, UInt64) => cast_numeric_arrays::<Int32Type, UInt64Type>(array, cast_options),
1513        (Int32, Int8) => cast_numeric_arrays::<Int32Type, Int8Type>(array, cast_options),
1514        (Int32, Int16) => cast_numeric_arrays::<Int32Type, Int16Type>(array, cast_options),
1515        (Int32, Int64) => cast_numeric_arrays::<Int32Type, Int64Type>(array, cast_options),
1516        (Int32, Float16) => cast_numeric_arrays::<Int32Type, Float16Type>(array, cast_options),
1517        (Int32, Float32) => cast_numeric_arrays::<Int32Type, Float32Type>(array, cast_options),
1518        (Int32, Float64) => cast_numeric_arrays::<Int32Type, Float64Type>(array, cast_options),
1519
1520        (Int64, UInt8) => cast_numeric_arrays::<Int64Type, UInt8Type>(array, cast_options),
1521        (Int64, UInt16) => cast_numeric_arrays::<Int64Type, UInt16Type>(array, cast_options),
1522        (Int64, UInt32) => cast_numeric_arrays::<Int64Type, UInt32Type>(array, cast_options),
1523        (Int64, UInt64) => cast_numeric_arrays::<Int64Type, UInt64Type>(array, cast_options),
1524        (Int64, Int8) => cast_numeric_arrays::<Int64Type, Int8Type>(array, cast_options),
1525        (Int64, Int16) => cast_numeric_arrays::<Int64Type, Int16Type>(array, cast_options),
1526        (Int64, Int32) => cast_numeric_arrays::<Int64Type, Int32Type>(array, cast_options),
1527        (Int64, Float16) => cast_numeric_arrays::<Int64Type, Float16Type>(array, cast_options),
1528        (Int64, Float32) => cast_numeric_arrays::<Int64Type, Float32Type>(array, cast_options),
1529        (Int64, Float64) => cast_numeric_arrays::<Int64Type, Float64Type>(array, cast_options),
1530
1531        (Float16, UInt8) => cast_numeric_arrays::<Float16Type, UInt8Type>(array, cast_options),
1532        (Float16, UInt16) => cast_numeric_arrays::<Float16Type, UInt16Type>(array, cast_options),
1533        (Float16, UInt32) => cast_numeric_arrays::<Float16Type, UInt32Type>(array, cast_options),
1534        (Float16, UInt64) => cast_numeric_arrays::<Float16Type, UInt64Type>(array, cast_options),
1535        (Float16, Int8) => cast_numeric_arrays::<Float16Type, Int8Type>(array, cast_options),
1536        (Float16, Int16) => cast_numeric_arrays::<Float16Type, Int16Type>(array, cast_options),
1537        (Float16, Int32) => cast_numeric_arrays::<Float16Type, Int32Type>(array, cast_options),
1538        (Float16, Int64) => cast_numeric_arrays::<Float16Type, Int64Type>(array, cast_options),
1539        (Float16, Float32) => cast_numeric_arrays::<Float16Type, Float32Type>(array, cast_options),
1540        (Float16, Float64) => cast_numeric_arrays::<Float16Type, Float64Type>(array, cast_options),
1541
1542        (Float32, UInt8) => cast_numeric_arrays::<Float32Type, UInt8Type>(array, cast_options),
1543        (Float32, UInt16) => cast_numeric_arrays::<Float32Type, UInt16Type>(array, cast_options),
1544        (Float32, UInt32) => cast_numeric_arrays::<Float32Type, UInt32Type>(array, cast_options),
1545        (Float32, UInt64) => cast_numeric_arrays::<Float32Type, UInt64Type>(array, cast_options),
1546        (Float32, Int8) => cast_numeric_arrays::<Float32Type, Int8Type>(array, cast_options),
1547        (Float32, Int16) => cast_numeric_arrays::<Float32Type, Int16Type>(array, cast_options),
1548        (Float32, Int32) => cast_numeric_arrays::<Float32Type, Int32Type>(array, cast_options),
1549        (Float32, Int64) => cast_numeric_arrays::<Float32Type, Int64Type>(array, cast_options),
1550        (Float32, Float16) => cast_numeric_arrays::<Float32Type, Float16Type>(array, cast_options),
1551        (Float32, Float64) => cast_numeric_arrays::<Float32Type, Float64Type>(array, cast_options),
1552
1553        (Float64, UInt8) => cast_numeric_arrays::<Float64Type, UInt8Type>(array, cast_options),
1554        (Float64, UInt16) => cast_numeric_arrays::<Float64Type, UInt16Type>(array, cast_options),
1555        (Float64, UInt32) => cast_numeric_arrays::<Float64Type, UInt32Type>(array, cast_options),
1556        (Float64, UInt64) => cast_numeric_arrays::<Float64Type, UInt64Type>(array, cast_options),
1557        (Float64, Int8) => cast_numeric_arrays::<Float64Type, Int8Type>(array, cast_options),
1558        (Float64, Int16) => cast_numeric_arrays::<Float64Type, Int16Type>(array, cast_options),
1559        (Float64, Int32) => cast_numeric_arrays::<Float64Type, Int32Type>(array, cast_options),
1560        (Float64, Int64) => cast_numeric_arrays::<Float64Type, Int64Type>(array, cast_options),
1561        (Float64, Float16) => cast_numeric_arrays::<Float64Type, Float16Type>(array, cast_options),
1562        (Float64, Float32) => cast_numeric_arrays::<Float64Type, Float32Type>(array, cast_options),
1563        // end numeric casts
1564
1565        // temporal casts
1566        (Int32, Date32) => cast_reinterpret_arrays::<Int32Type, Date32Type>(array),
1567        (Int32, Date64) => cast_with_options(
1568            &cast_with_options(array, &Date32, cast_options)?,
1569            &Date64,
1570            cast_options,
1571        ),
1572        (Int32, Time32(TimeUnit::Second)) => {
1573            cast_reinterpret_arrays::<Int32Type, Time32SecondType>(array)
1574        }
1575        (Int32, Time32(TimeUnit::Millisecond)) => {
1576            cast_reinterpret_arrays::<Int32Type, Time32MillisecondType>(array)
1577        }
1578        // No support for microsecond/nanosecond with i32
1579        (Date32, Int32) => cast_reinterpret_arrays::<Date32Type, Int32Type>(array),
1580        (Date32, Int64) => cast_with_options(
1581            &cast_with_options(array, &Int32, cast_options)?,
1582            &Int64,
1583            cast_options,
1584        ),
1585        (Time32(TimeUnit::Second), Int32) => {
1586            cast_reinterpret_arrays::<Time32SecondType, Int32Type>(array)
1587        }
1588        (Time32(TimeUnit::Millisecond), Int32) => {
1589            cast_reinterpret_arrays::<Time32MillisecondType, Int32Type>(array)
1590        }
1591        (Time32(TimeUnit::Second), Int64) => cast_with_options(
1592            &cast_with_options(array, &Int32, cast_options)?,
1593            &Int64,
1594            cast_options,
1595        ),
1596        (Time32(TimeUnit::Millisecond), Int64) => cast_with_options(
1597            &cast_with_options(array, &Int32, cast_options)?,
1598            &Int64,
1599            cast_options,
1600        ),
1601        (Int64, Date64) => cast_reinterpret_arrays::<Int64Type, Date64Type>(array),
1602        (Int64, Date32) => cast_with_options(
1603            &cast_with_options(array, &Int32, cast_options)?,
1604            &Date32,
1605            cast_options,
1606        ),
1607        // No support for second/milliseconds with i64
1608        (Int64, Time64(TimeUnit::Microsecond)) => {
1609            cast_reinterpret_arrays::<Int64Type, Time64MicrosecondType>(array)
1610        }
1611        (Int64, Time64(TimeUnit::Nanosecond)) => {
1612            cast_reinterpret_arrays::<Int64Type, Time64NanosecondType>(array)
1613        }
1614
1615        (Date64, Int64) => cast_reinterpret_arrays::<Date64Type, Int64Type>(array),
1616        (Date64, Int32) => cast_with_options(
1617            &cast_with_options(array, &Int64, cast_options)?,
1618            &Int32,
1619            cast_options,
1620        ),
1621        (Time64(TimeUnit::Microsecond), Int64) => {
1622            cast_reinterpret_arrays::<Time64MicrosecondType, Int64Type>(array)
1623        }
1624        (Time64(TimeUnit::Nanosecond), Int64) => {
1625            cast_reinterpret_arrays::<Time64NanosecondType, Int64Type>(array)
1626        }
1627        (Date32, Date64) => Ok(Arc::new(
1628            array
1629                .as_primitive::<Date32Type>()
1630                .unary::<_, Date64Type>(|x| x as i64 * MILLISECONDS_IN_DAY),
1631        )),
1632        (Date64, Date32) => {
1633            let array = array.as_primitive::<Date64Type>();
1634            let result = if cast_options.safe {
1635                array.unary_opt::<_, Date32Type>(|x| {
1636                    i32::try_from(x.div_euclid(MILLISECONDS_IN_DAY)).ok()
1637                })
1638            } else {
1639                array.try_unary::<_, Date32Type, _>(|x| {
1640                    i32::try_from(x.div_euclid(MILLISECONDS_IN_DAY)).map_err(|_| {
1641                        ArrowError::CastError(format!(
1642                            "Cannot cast Date64 value {x} to Date32 without overflow"
1643                        ))
1644                    })
1645                })?
1646            };
1647            Ok(Arc::new(result))
1648        }
1649
1650        (Time32(TimeUnit::Second), Time32(TimeUnit::Millisecond)) => {
1651            let array = array.as_primitive::<Time32SecondType>();
1652            let result = if cast_options.safe {
1653                array.unary_opt::<_, Time32MillisecondType>(|x| x.checked_mul(MILLISECONDS as i32))
1654            } else {
1655                array.try_unary::<_, Time32MillisecondType, _>(|x| {
1656                    x.mul_checked(MILLISECONDS as i32)
1657                })?
1658            };
1659            Ok(Arc::new(result))
1660        }
1661        (Time32(TimeUnit::Second), Time64(TimeUnit::Microsecond)) => Ok(Arc::new(
1662            array
1663                .as_primitive::<Time32SecondType>()
1664                .unary::<_, Time64MicrosecondType>(|x| x as i64 * MICROSECONDS),
1665        )),
1666        (Time32(TimeUnit::Second), Time64(TimeUnit::Nanosecond)) => Ok(Arc::new(
1667            array
1668                .as_primitive::<Time32SecondType>()
1669                .unary::<_, Time64NanosecondType>(|x| x as i64 * NANOSECONDS),
1670        )),
1671
1672        (Time32(TimeUnit::Millisecond), Time32(TimeUnit::Second)) => Ok(Arc::new(
1673            array
1674                .as_primitive::<Time32MillisecondType>()
1675                .unary::<_, Time32SecondType>(|x| x / MILLISECONDS as i32),
1676        )),
1677        (Time32(TimeUnit::Millisecond), Time64(TimeUnit::Microsecond)) => Ok(Arc::new(
1678            array
1679                .as_primitive::<Time32MillisecondType>()
1680                .unary::<_, Time64MicrosecondType>(|x| x as i64 * (MICROSECONDS / MILLISECONDS)),
1681        )),
1682        (Time32(TimeUnit::Millisecond), Time64(TimeUnit::Nanosecond)) => Ok(Arc::new(
1683            array
1684                .as_primitive::<Time32MillisecondType>()
1685                .unary::<_, Time64NanosecondType>(|x| x as i64 * (NANOSECONDS / MILLISECONDS)),
1686        )),
1687
1688        (Time64(TimeUnit::Microsecond), Time32(TimeUnit::Second)) => cast_time64_to_time32::<
1689            Time64MicrosecondType,
1690            Time32SecondType,
1691            MICROSECONDS,
1692        >(array, cast_options),
1693        (Time64(TimeUnit::Microsecond), Time32(TimeUnit::Millisecond)) => {
1694            cast_time64_to_time32::<
1695                Time64MicrosecondType,
1696                Time32MillisecondType,
1697                { MICROSECONDS / MILLISECONDS },
1698            >(array, cast_options)
1699        }
1700        (Time64(TimeUnit::Microsecond), Time64(TimeUnit::Nanosecond)) => {
1701            let array = array.as_primitive::<Time64MicrosecondType>();
1702            let result = if cast_options.safe {
1703                array.unary_opt::<_, Time64NanosecondType>(|x| {
1704                    x.checked_mul(NANOSECONDS / MICROSECONDS)
1705                })
1706            } else {
1707                array.try_unary::<_, Time64NanosecondType, _>(|x| {
1708                    x.mul_checked(NANOSECONDS / MICROSECONDS)
1709                })?
1710            };
1711            Ok(Arc::new(result))
1712        }
1713
1714        (Time64(TimeUnit::Nanosecond), Time32(TimeUnit::Second)) => cast_time64_to_time32::<
1715            Time64NanosecondType,
1716            Time32SecondType,
1717            NANOSECONDS,
1718        >(array, cast_options),
1719        (Time64(TimeUnit::Nanosecond), Time32(TimeUnit::Millisecond)) => {
1720            cast_time64_to_time32::<
1721                Time64NanosecondType,
1722                Time32MillisecondType,
1723                { NANOSECONDS / MILLISECONDS },
1724            >(array, cast_options)
1725        }
1726        (Time64(TimeUnit::Nanosecond), Time64(TimeUnit::Microsecond)) => Ok(Arc::new(
1727            array
1728                .as_primitive::<Time64NanosecondType>()
1729                .unary::<_, Time64MicrosecondType>(|x| x / (NANOSECONDS / MICROSECONDS)),
1730        )),
1731
1732        // Timestamp to integer/floating/decimals
1733        (Timestamp(TimeUnit::Second, _), _) if to_type.is_numeric() => {
1734            let array = cast_reinterpret_arrays::<TimestampSecondType, Int64Type>(array)?;
1735            cast_with_options(&array, to_type, cast_options)
1736        }
1737        (Timestamp(TimeUnit::Millisecond, _), _) if to_type.is_numeric() => {
1738            let array = cast_reinterpret_arrays::<TimestampMillisecondType, Int64Type>(array)?;
1739            cast_with_options(&array, to_type, cast_options)
1740        }
1741        (Timestamp(TimeUnit::Microsecond, _), _) if to_type.is_numeric() => {
1742            let array = cast_reinterpret_arrays::<TimestampMicrosecondType, Int64Type>(array)?;
1743            cast_with_options(&array, to_type, cast_options)
1744        }
1745        (Timestamp(TimeUnit::Nanosecond, _), _) if to_type.is_numeric() => {
1746            let array = cast_reinterpret_arrays::<TimestampNanosecondType, Int64Type>(array)?;
1747            cast_with_options(&array, to_type, cast_options)
1748        }
1749
1750        (_, Timestamp(unit, tz)) if from_type.is_numeric() => {
1751            let array = cast_with_options(array, &Int64, cast_options)?;
1752            Ok(make_timestamp_array(
1753                array.as_primitive(),
1754                *unit,
1755                tz.clone(),
1756            ))
1757        }
1758
1759        (Timestamp(from_unit, from_tz), Timestamp(to_unit, to_tz)) => {
1760            let array = cast_with_options(array, &Int64, cast_options)?;
1761            let time_array = array.as_primitive::<Int64Type>();
1762            let from_size = time_unit_multiple(from_unit);
1763            let to_size = time_unit_multiple(to_unit);
1764            // we either divide or multiply, depending on size of each unit
1765            // units are never the same when the types are the same
1766            let converted = match from_size.cmp(&to_size) {
1767                Ordering::Greater => {
1768                    // A constant divisor lets the compiler replace each division with a multiply
1769                    // and shifts. The ratio of two time units is always one of these three
1770                    match from_size / to_size {
1771                        1_000 => time_array.unary::<_, Int64Type>(|o| o / 1_000),
1772                        1_000_000 => time_array.unary::<_, Int64Type>(|o| o / 1_000_000),
1773                        1_000_000_000 => time_array.unary::<_, Int64Type>(|o| o / 1_000_000_000),
1774                        divisor => time_array.unary::<_, Int64Type>(|o| o / divisor),
1775                    }
1776                }
1777                Ordering::Equal => time_array.clone(),
1778                Ordering::Less => {
1779                    let mul = to_size / from_size;
1780                    if cast_options.safe {
1781                        time_array.unary_opt::<_, Int64Type>(|o| o.checked_mul(mul))
1782                    } else {
1783                        time_array.try_unary::<_, Int64Type, _>(|o| o.mul_checked(mul))?
1784                    }
1785                }
1786            };
1787            // Normalize timezone
1788            let adjusted = match (from_tz, to_tz) {
1789                // Only this case needs to be adjusted because we're casting from
1790                // unknown time offset to some time offset, we want the time to be
1791                // unchanged.
1792                //
1793                // i.e. Timestamp('2001-01-01T00:00', None) -> Timestamp('2001-01-01T00:00', '+0700')
1794                //
1795                // For IANA timezones a wall clock reading is not always a unique
1796                // instant: a "fall back" DST transition makes an hour occur twice
1797                // and a "spring forward" transition skips an hour entirely. See
1798                // `resolve_local_offset` for how those readings are resolved.
1799                (None, Some(to_tz)) => {
1800                    let to_tz: Tz = to_tz.parse()?;
1801                    match to_unit {
1802                        TimeUnit::Second => adjust_timestamp_to_timezone::<TimestampSecondType>(
1803                            converted,
1804                            &to_tz,
1805                            cast_options,
1806                        )?,
1807                        TimeUnit::Millisecond => adjust_timestamp_to_timezone::<
1808                            TimestampMillisecondType,
1809                        >(
1810                            converted, &to_tz, cast_options
1811                        )?,
1812                        TimeUnit::Microsecond => adjust_timestamp_to_timezone::<
1813                            TimestampMicrosecondType,
1814                        >(
1815                            converted, &to_tz, cast_options
1816                        )?,
1817                        TimeUnit::Nanosecond => adjust_timestamp_to_timezone::<
1818                            TimestampNanosecondType,
1819                        >(
1820                            converted, &to_tz, cast_options
1821                        )?,
1822                    }
1823                }
1824                _ => converted,
1825            };
1826            Ok(make_timestamp_array(&adjusted, *to_unit, to_tz.clone()))
1827        }
1828        (Timestamp(TimeUnit::Microsecond, _), Date32) => timestamp_to_date32(
1829            array.as_primitive::<TimestampMicrosecondType>(),
1830            cast_options,
1831        ),
1832        (Timestamp(TimeUnit::Millisecond, _), Date32) => timestamp_to_date32(
1833            array.as_primitive::<TimestampMillisecondType>(),
1834            cast_options,
1835        ),
1836        (Timestamp(TimeUnit::Second, _), Date32) => {
1837            timestamp_to_date32(array.as_primitive::<TimestampSecondType>(), cast_options)
1838        }
1839        (Timestamp(TimeUnit::Nanosecond, _), Date32) => timestamp_to_date32(
1840            array.as_primitive::<TimestampNanosecondType>(),
1841            cast_options,
1842        ),
1843        (Timestamp(TimeUnit::Second, _), Date64) => {
1844            timestamp_to_date64(array.as_primitive::<TimestampSecondType>(), cast_options)
1845        }
1846        (Timestamp(TimeUnit::Millisecond, _), Date64) => timestamp_to_date64(
1847            array.as_primitive::<TimestampMillisecondType>(),
1848            cast_options,
1849        ),
1850        (Timestamp(TimeUnit::Microsecond, _), Date64) => timestamp_to_date64(
1851            array.as_primitive::<TimestampMicrosecondType>(),
1852            cast_options,
1853        ),
1854        (Timestamp(TimeUnit::Nanosecond, _), Date64) => timestamp_to_date64(
1855            array.as_primitive::<TimestampNanosecondType>(),
1856            cast_options,
1857        ),
1858        (Timestamp(TimeUnit::Second, _), Time32(_) | Time64(_)) => {
1859            cast_timestamp_to_time::<TimestampSecondType>(array, to_type, cast_options)
1860        }
1861        (Timestamp(TimeUnit::Millisecond, _), Time32(_) | Time64(_)) => {
1862            cast_timestamp_to_time::<TimestampMillisecondType>(array, to_type, cast_options)
1863        }
1864        (Timestamp(TimeUnit::Microsecond, _), Time32(_) | Time64(_)) => {
1865            cast_timestamp_to_time::<TimestampMicrosecondType>(array, to_type, cast_options)
1866        }
1867        (Timestamp(TimeUnit::Nanosecond, _), Time32(_) | Time64(_)) => {
1868            cast_timestamp_to_time::<TimestampNanosecondType>(array, to_type, cast_options)
1869        }
1870        (Date64, Timestamp(TimeUnit::Second, _)) => {
1871            let array = array
1872                .as_primitive::<Date64Type>()
1873                .unary::<_, TimestampSecondType>(|x| x / MILLISECONDS);
1874
1875            cast_with_options(&array, to_type, cast_options)
1876        }
1877        (Date64, Timestamp(TimeUnit::Millisecond, _)) => {
1878            let array = array
1879                .as_primitive::<Date64Type>()
1880                .reinterpret_cast::<TimestampMillisecondType>();
1881
1882            cast_with_options(&array, to_type, cast_options)
1883        }
1884
1885        (Date64, Timestamp(TimeUnit::Microsecond, _)) => {
1886            let array = array
1887                .as_primitive::<Date64Type>()
1888                .reinterpret_cast::<TimestampMillisecondType>();
1889
1890            cast_with_options(&array, to_type, cast_options)
1891        }
1892        (Date64, Timestamp(TimeUnit::Nanosecond, _)) => {
1893            let array = array
1894                .as_primitive::<Date64Type>()
1895                .reinterpret_cast::<TimestampMillisecondType>();
1896
1897            cast_with_options(&array, to_type, cast_options)
1898        }
1899        (Date32, Timestamp(TimeUnit::Second, _)) => {
1900            let array = array
1901                .as_primitive::<Date32Type>()
1902                .unary::<_, TimestampSecondType>(|x| (x as i64) * SECONDS_IN_DAY);
1903
1904            cast_with_options(&array, to_type, cast_options)
1905        }
1906        (Date32, Timestamp(TimeUnit::Millisecond, _)) => {
1907            let array = array
1908                .as_primitive::<Date32Type>()
1909                .unary::<_, TimestampMillisecondType>(|x| (x as i64) * MILLISECONDS_IN_DAY);
1910
1911            cast_with_options(&array, to_type, cast_options)
1912        }
1913        (Date32, Timestamp(TimeUnit::Microsecond, _)) => {
1914            let date_array = array.as_primitive::<Date32Type>();
1915            let converted = if cast_options.safe {
1916                date_array.unary_opt::<_, TimestampMicrosecondType>(|x| {
1917                    (x as i64).checked_mul(MICROSECONDS_IN_DAY)
1918                })
1919            } else {
1920                date_array.try_unary::<_, TimestampMicrosecondType, _>(|x| {
1921                    (x as i64).mul_checked(MICROSECONDS_IN_DAY)
1922                })?
1923            };
1924            cast_with_options(&converted, to_type, cast_options)
1925        }
1926        (Date32, Timestamp(TimeUnit::Nanosecond, _)) => {
1927            let date_array = array.as_primitive::<Date32Type>();
1928            let converted = if cast_options.safe {
1929                date_array.unary_opt::<_, TimestampNanosecondType>(|x| {
1930                    (x as i64).checked_mul(NANOSECONDS_IN_DAY)
1931                })
1932            } else {
1933                date_array.try_unary::<_, TimestampNanosecondType, _>(|x| {
1934                    (x as i64).mul_checked(NANOSECONDS_IN_DAY)
1935                })?
1936            };
1937            cast_with_options(&converted, to_type, cast_options)
1938        }
1939
1940        (_, Duration(unit)) if from_type.is_numeric() => {
1941            let array = cast_with_options(array, &Int64, cast_options)?;
1942            Ok(make_duration_array(array.as_primitive(), *unit))
1943        }
1944        (Duration(TimeUnit::Second), _) if to_type.is_numeric() => {
1945            let array = cast_reinterpret_arrays::<DurationSecondType, Int64Type>(array)?;
1946            cast_with_options(&array, to_type, cast_options)
1947        }
1948        (Duration(TimeUnit::Millisecond), _) if to_type.is_numeric() => {
1949            let array = cast_reinterpret_arrays::<DurationMillisecondType, Int64Type>(array)?;
1950            cast_with_options(&array, to_type, cast_options)
1951        }
1952        (Duration(TimeUnit::Microsecond), _) if to_type.is_numeric() => {
1953            let array = cast_reinterpret_arrays::<DurationMicrosecondType, Int64Type>(array)?;
1954            cast_with_options(&array, to_type, cast_options)
1955        }
1956        (Duration(TimeUnit::Nanosecond), _) if to_type.is_numeric() => {
1957            let array = cast_reinterpret_arrays::<DurationNanosecondType, Int64Type>(array)?;
1958            cast_with_options(&array, to_type, cast_options)
1959        }
1960
1961        (Duration(from_unit), Duration(to_unit)) => {
1962            let array = cast_with_options(array, &Int64, cast_options)?;
1963            let time_array = array.as_primitive::<Int64Type>();
1964            let from_size = time_unit_multiple(from_unit);
1965            let to_size = time_unit_multiple(to_unit);
1966            // we either divide or multiply, depending on size of each unit
1967            // units are never the same when the types are the same
1968            let converted = match from_size.cmp(&to_size) {
1969                Ordering::Greater => {
1970                    // A constant divisor lets the compiler replace each division with a multiply
1971                    // and shifts. The ratio of two time units is always one of these three
1972                    match from_size / to_size {
1973                        1_000 => time_array.unary::<_, Int64Type>(|o| o / 1_000),
1974                        1_000_000 => time_array.unary::<_, Int64Type>(|o| o / 1_000_000),
1975                        1_000_000_000 => time_array.unary::<_, Int64Type>(|o| o / 1_000_000_000),
1976                        divisor => time_array.unary::<_, Int64Type>(|o| o / divisor),
1977                    }
1978                }
1979                Ordering::Equal => time_array.clone(),
1980                Ordering::Less => {
1981                    let mul = to_size / from_size;
1982                    if cast_options.safe {
1983                        time_array.unary_opt::<_, Int64Type>(|o| o.checked_mul(mul))
1984                    } else {
1985                        time_array.try_unary::<_, Int64Type, _>(|o| o.mul_checked(mul))?
1986                    }
1987                }
1988            };
1989            Ok(make_duration_array(&converted, *to_unit))
1990        }
1991
1992        (Duration(TimeUnit::Second), Interval(IntervalUnit::MonthDayNano)) => {
1993            cast_duration_to_interval::<DurationSecondType>(array, cast_options)
1994        }
1995        (Duration(TimeUnit::Millisecond), Interval(IntervalUnit::MonthDayNano)) => {
1996            cast_duration_to_interval::<DurationMillisecondType>(array, cast_options)
1997        }
1998        (Duration(TimeUnit::Microsecond), Interval(IntervalUnit::MonthDayNano)) => {
1999            cast_duration_to_interval::<DurationMicrosecondType>(array, cast_options)
2000        }
2001        (Duration(TimeUnit::Nanosecond), Interval(IntervalUnit::MonthDayNano)) => {
2002            cast_duration_to_interval::<DurationNanosecondType>(array, cast_options)
2003        }
2004        (Interval(IntervalUnit::MonthDayNano), Duration(TimeUnit::Second)) => {
2005            cast_month_day_nano_to_duration::<DurationSecondType>(array, cast_options)
2006        }
2007        (Interval(IntervalUnit::MonthDayNano), Duration(TimeUnit::Millisecond)) => {
2008            cast_month_day_nano_to_duration::<DurationMillisecondType>(array, cast_options)
2009        }
2010        (Interval(IntervalUnit::MonthDayNano), Duration(TimeUnit::Microsecond)) => {
2011            cast_month_day_nano_to_duration::<DurationMicrosecondType>(array, cast_options)
2012        }
2013        (Interval(IntervalUnit::MonthDayNano), Duration(TimeUnit::Nanosecond)) => {
2014            cast_month_day_nano_to_duration::<DurationNanosecondType>(array, cast_options)
2015        }
2016        (Interval(IntervalUnit::YearMonth), Interval(IntervalUnit::MonthDayNano)) => {
2017            cast_interval_year_month_to_interval_month_day_nano(array, cast_options)
2018        }
2019        (Interval(IntervalUnit::DayTime), Interval(IntervalUnit::MonthDayNano)) => {
2020            cast_interval_day_time_to_interval_month_day_nano(array, cast_options)
2021        }
2022        (Int32, Interval(IntervalUnit::YearMonth)) => {
2023            cast_reinterpret_arrays::<Int32Type, IntervalYearMonthType>(array)
2024        }
2025        (_, _) => Err(ArrowError::InvalidArgumentError(format!(
2026            "Casting from {from_type} to {to_type} not supported",
2027        ))),
2028    }
2029}
2030
2031/// Number of `T` units in one day
2032const fn units_per_day<T: ArrowTimestampType>() -> i64 {
2033    SECONDS_IN_DAY * time_unit_multiple(&T::UNIT)
2034}
2035
2036/// Get the time unit as a multiple of a second
2037const fn time_unit_multiple(unit: &TimeUnit) -> i64 {
2038    match unit {
2039        TimeUnit::Second => 1,
2040        TimeUnit::Millisecond => MILLISECONDS,
2041        TimeUnit::Microsecond => MICROSECONDS,
2042        TimeUnit::Nanosecond => NANOSECONDS,
2043    }
2044}
2045
2046/// `DIVISOR` is a const parameter so that each division is by a constant, which the compiler
2047/// replaces with a multiply and shifts even when the loops aren't inlined into this function
2048fn cast_time64_to_time32<FROM, TO, const DIVISOR: i64>(
2049    array: &dyn Array,
2050    cast_options: &CastOptions,
2051) -> Result<ArrayRef, ArrowError>
2052where
2053    FROM: ArrowPrimitiveType<Native = i64>,
2054    TO: ArrowPrimitiveType<Native = i32>,
2055{
2056    let array = array.as_primitive::<FROM>();
2057    let result = if cast_options.safe {
2058        array.unary_opt::<_, TO>(|value| i32::try_from(value / DIVISOR).ok())
2059    } else {
2060        array.try_unary::<_, TO, _>(|value| {
2061            let value = value / DIVISOR;
2062            i32::try_from(value).map_err(|_| {
2063                ArrowError::CastError(format!(
2064                    "Can't cast value {value:?} to type {}",
2065                    TO::DATA_TYPE
2066                ))
2067            })
2068        })?
2069    };
2070
2071    Ok(Arc::new(result))
2072}