This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch 
gh-readonly-queue/main/pr-12422-aa0514addf9f5032df061a696e54f5d3b11f89c4
in repository https://gitbox.apache.org/repos/asf/arrow-rs.git

commit 5dc64fb782fcea05798b598961d37d31157c41db
Author: Matt Butrovich <[email protected]>
AuthorDate: Tue Nov 24 20:59:59 2026 +0000

    perf(arrow-cast): divide by a constant in timestamp and duration casts to a 
coarser unit (#12422)
    
    # Which issue does this PR close?
    
    - Closes #12173.
    - Part of #11421.
    
    # Rationale for this change
    
    Casts of `Timestamp`, `Duration`, and `Time64` to a coarser time unit
    divide every value by a ratio that the compiler doesn't see as a
    constant, so each value takes a hardware divide.
    
    # What changes are included in this PR?
    
    - `Timestamp` and `Duration` casts match the ratio against 1000, 10^6,
    and 10^9, the only ratios between two time units, and divide by that
    constant. With a constant divisor, the compiler replaces each division
    with a multiply and a shift.
    - This is simpler than the `DivisorI64` that #12173 suggests.
    - `cast_time64_to_time32`, the third site in #12173, takes its divisor
    as a const parameter. With thin LTO, its `unary_opt` and `try_unary`
    loops aren't inlined into its four callers, so a divisor passed as an
    argument kept a hardware divide in each loop.
    - 5e759e5fd0 adds `Timestamp` and `Duration` unit casts to the
    `cast_timestamp` benchmark, with and without nulls, so the benchmark bot
    can compare against it.
    
    # Are these changes tested?
    
    `test_cast_timestamp_and_duration_to_coarser_unit` in
    `arrow-cast/tests/cast/date_time.rs`.
    
    The benchmark bot ran `cast_timestamp` against 5e759e5fd0 on Neoverse-V2
    and Xeon Platinum 8581C, the latter also at `x86-64-v3`, each with and
    without code alignment. Casts to a coarser unit are 3.9x to 9.3x faster
    in all six runs. The chart shows the runs without alignment.
    
    <img width="1600" height="2468" alt="time-unit-cast-bot-11501a9"
    
src="https://github.com/user-attachments/assets/483e07b3-c1b1-4e3c-9de3-9c802855d807";
    />
    
    The other 84 cases don't go through the changed code. Casts to a finer
    unit read 0.62x to 1.23x in the [Xeon run without
    
alignment](https://github.com/apache/arrow-rs/pull/12422#issuecomment-7107088951)
    and 0.94x to 1.03x in the [aligned
    one](https://github.com/apache/arrow-rs/pull/12422#issuecomment-7107140951),
    so that spread comes from code layout. The rest stay within 0.87x to
    1.13x in every run.
    
    <details><summary>Neoverse-V2</summary>
    
    Times in us from the
    
[default](https://github.com/apache/arrow-rs/pull/12422#issuecomment-7107120901)
    and
    
[aligned](https://github.com/apache/arrow-rs/pull/12422#issuecomment-7107087098)
    runs.
    
    | Case | Baseline | PR | Speedup | Baseline, aligned | PR, aligned |
    Speedup, aligned |
    |---|--:|--:|--:|--:|--:|--:|
    | `timestamp_ns/timestamp_us/no_nulls` | 47 | 5.1 | 9.22x | 47.2 | 5.1 |
    9.25x |
    | `timestamp_ns/timestamp_us/mixed_nulls` | 40.5 | 5.1 | 7.94x | 40.6 |
    5.2 | 7.81x |
    | `timestamp_ns/timestamp_ms/no_nulls` | 40.8 | 5.1 | 8.00x | 41 | 5.1 |
    8.04x |
    | `timestamp_ns/timestamp_ms/mixed_nulls` | 35.5 | 5.1 | 6.96x | 35.7 |
    5.2 | 6.87x |
    | `timestamp_ns/timestamp_s/no_nulls` | 33.2 | 5.1 | 6.51x | 33.4 | 5.1
    | 6.55x |
    | `timestamp_ns/timestamp_s/mixed_nulls` | 29.4 | 5.1 | 5.76x | 29.6 |
    5.2 | 5.69x |
    | `timestamp_us/timestamp_ms/no_nulls` | 40.8 | 5.1 | 8.00x | 40.9 | 5.1
    | 8.02x |
    | `timestamp_us/timestamp_ms/mixed_nulls` | 35.5 | 5.1 | 6.96x | 35.6 |
    5.1 | 6.98x |
    | `timestamp_us/timestamp_s/no_nulls` | 33.2 | 5 | 6.64x | 33.3 | 5.1 |
    6.53x |
    | `timestamp_us/timestamp_s/mixed_nulls` | 29.5 | 5.1 | 5.78x | 29.5 |
    5.2 | 5.67x |
    | `timestamp_ms/timestamp_s/no_nulls` | 33.2 | 5.1 | 6.51x | 33.3 | 5.1
    | 6.53x |
    | `timestamp_ms/timestamp_s/mixed_nulls` | 29.5 | 5.1 | 5.78x | 29.5 |
    5.1 | 5.78x |
    | `duration_ns/duration_us/no_nulls` | 46.9 | 5.1 | 9.20x | 47 | 5.1 |
    9.22x |
    | `duration_ns/duration_us/mixed_nulls` | 40.4 | 5.1 | 7.92x | 40.6 |
    5.1 | 7.96x |
    | `duration_ns/duration_ms/no_nulls` | 40.7 | 5 | 8.14x | 40.9 | 5.1 |
    8.02x |
    | `duration_ns/duration_ms/mixed_nulls` | 35.5 | 5.1 | 6.96x | 35.6 |
    5.1 | 6.98x |
    | `duration_ns/duration_s/no_nulls` | 33.2 | 5 | 6.64x | 33.3 | 5.1 |
    6.53x |
    | `duration_ns/duration_s/mixed_nulls` | 29.4 | 5.1 | 5.76x | 29.5 | 5.1
    | 5.78x |
    | `duration_us/duration_ms/no_nulls` | 40.8 | 5 | 8.16x | 41 | 5.1 |
    8.04x |
    | `duration_us/duration_ms/mixed_nulls` | 35.5 | 5.1 | 6.96x | 35.7 |
    5.1 | 7.00x |
    | `duration_us/duration_s/no_nulls` | 33.2 | 5.1 | 6.51x | 33.3 | 5.1 |
    6.53x |
    | `duration_us/duration_s/mixed_nulls` | 29.4 | 5.1 | 5.76x | 29.5 | 5.1
    | 5.78x |
    | `duration_ms/duration_s/no_nulls` | 33.2 | 5 | 6.64x | 33.4 | 5.1 |
    6.55x |
    | `duration_ms/duration_s/mixed_nulls` | 29.5 | 5.1 | 5.78x | 29.6 | 5.2
    | 5.69x |
    
    </details>
    
    <details><summary>Xeon Platinum 8581C</summary>
    
    Times in us from the
    
[default](https://github.com/apache/arrow-rs/pull/12422#issuecomment-7107088951)
    and
    
[aligned](https://github.com/apache/arrow-rs/pull/12422#issuecomment-7107140951)
    runs.
    
    | Case | Baseline | PR | Speedup | Baseline, aligned | PR, aligned |
    Speedup, aligned |
    |---|--:|--:|--:|--:|--:|--:|
    | `timestamp_ns/timestamp_us/no_nulls` | 21 | 4.5 | 4.67x | 20.6 | 4.8 |
    4.29x |
    | `timestamp_ns/timestamp_us/mixed_nulls` | 19.5 | 4.5 | 4.33x | 19.1 |
    4.8 | 3.98x |
    | `timestamp_ns/timestamp_ms/no_nulls` | 21.2 | 4.5 | 4.71x | 20.8 | 4.8
    | 4.33x |
    | `timestamp_ns/timestamp_ms/mixed_nulls` | 19.3 | 4.5 | 4.29x | 19.1 |
    4.9 | 3.90x |
    | `timestamp_ns/timestamp_s/no_nulls` | 21 | 4.5 | 4.67x | 20.6 | 4.7 |
    4.38x |
    | `timestamp_ns/timestamp_s/mixed_nulls` | 19.5 | 4.5 | 4.33x | 19.1 |
    4.6 | 4.15x |
    | `timestamp_us/timestamp_ms/no_nulls` | 21 | 4.5 | 4.67x | 20.7 | 4.7 |
    4.40x |
    | `timestamp_us/timestamp_ms/mixed_nulls` | 19.4 | 4.6 | 4.22x | 19.1 |
    4.8 | 3.98x |
    | `timestamp_us/timestamp_s/no_nulls` | 21 | 4.5 | 4.67x | 20.7 | 4.8 |
    4.31x |
    | `timestamp_us/timestamp_s/mixed_nulls` | 19.4 | 4.5 | 4.31x | 19.2 |
    4.8 | 4.00x |
    | `timestamp_ms/timestamp_s/no_nulls` | 21 | 4.5 | 4.67x | 20.4 | 4.8 |
    4.25x |
    | `timestamp_ms/timestamp_s/mixed_nulls` | 19.5 | 4.5 | 4.33x | 19.2 |
    4.8 | 4.00x |
    | `duration_ns/duration_us/no_nulls` | 21 | 4.5 | 4.67x | 20.6 | 4.7 |
    4.38x |
    | `duration_ns/duration_us/mixed_nulls` | 19.4 | 4.5 | 4.31x | 19.1 |
    4.8 | 3.98x |
    | `duration_ns/duration_ms/no_nulls` | 21.1 | 4.5 | 4.69x | 20.6 | 4.7 |
    4.38x |
    | `duration_ns/duration_ms/mixed_nulls` | 19.4 | 4.5 | 4.31x | 19.1 |
    4.8 | 3.98x |
    | `duration_ns/duration_s/no_nulls` | 21 | 4.5 | 4.67x | 20.7 | 4.7 |
    4.40x |
    | `duration_ns/duration_s/mixed_nulls` | 19.4 | 4.5 | 4.31x | 19.2 | 4.8
    | 4.00x |
    | `duration_us/duration_ms/no_nulls` | 21 | 4.5 | 4.67x | 20.8 | 4.8 |
    4.33x |
    | `duration_us/duration_ms/mixed_nulls` | 19.4 | 4.5 | 4.31x | 19.2 |
    4.8 | 4.00x |
    | `duration_us/duration_s/no_nulls` | 21.1 | 4.5 | 4.69x | 20.4 | 4.7 |
    4.34x |
    | `duration_us/duration_s/mixed_nulls` | 19.4 | 4.5 | 4.31x | 19.1 | 4.8
    | 3.98x |
    | `duration_ms/duration_s/no_nulls` | 21 | 4.5 | 4.67x | 20.5 | 4.7 |
    4.36x |
    | `duration_ms/duration_s/mixed_nulls` | 19.5 | 4.5 | 4.33x | 18.9 | 4.8
    | 3.94x |
    
    </details>
    
    <details><summary>Xeon Platinum 8581C, x86-64-v3</summary>
    
    Times in us from the
    
[default](https://github.com/apache/arrow-rs/pull/12422#issuecomment-7107174994)
    and
    
[aligned](https://github.com/apache/arrow-rs/pull/12422#issuecomment-7107214326)
    runs.
    
    | Case | Baseline | PR | Speedup | Baseline, aligned | PR, aligned |
    Speedup, aligned |
    |---|--:|--:|--:|--:|--:|--:|
    | `timestamp_ns/timestamp_us/no_nulls` | 21 | 3.9 | 5.38x | 25 | 4.9 |
    5.10x |
    | `timestamp_ns/timestamp_us/mixed_nulls` | 19.3 | 4 | 4.83x | 23.3 | 5
    | 4.66x |
    | `timestamp_ns/timestamp_ms/no_nulls` | 21 | 3.6 | 5.83x | 25.1 | 5 |
    5.02x |
    | `timestamp_ns/timestamp_ms/mixed_nulls` | 19.3 | 3.6 | 5.36x | 23.2 |
    5 | 4.64x |
    | `timestamp_ns/timestamp_s/no_nulls` | 20.7 | 3.4 | 6.09x | 23.5 | 5 |
    4.70x |
    | `timestamp_ns/timestamp_s/mixed_nulls` | 19.3 | 3.5 | 5.51x | 21.7 |
    5.2 | 4.17x |
    | `timestamp_us/timestamp_ms/no_nulls` | 20.8 | 3.9 | 5.33x | 22.8 | 5.1
    | 4.47x |
    | `timestamp_us/timestamp_ms/mixed_nulls` | 19 | 4 | 4.75x | 20.9 | 5.1
    | 4.10x |
    | `timestamp_us/timestamp_s/no_nulls` | 20.8 | 3.6 | 5.78x | 22.8 | 5.1
    | 4.47x |
    | `timestamp_us/timestamp_s/mixed_nulls` | 19.3 | 3.6 | 5.36x | 21.5 |
    5.1 | 4.22x |
    | `timestamp_ms/timestamp_s/no_nulls` | 20.8 | 3.9 | 5.33x | 23.6 | 5.2
    | 4.54x |
    | `timestamp_ms/timestamp_s/mixed_nulls` | 19.3 | 3.9 | 4.95x | 21.9 |
    5.2 | 4.21x |
    | `duration_ns/duration_us/no_nulls` | 20.9 | 3.9 | 5.36x | 24.9 | 5.4 |
    4.61x |
    | `duration_ns/duration_us/mixed_nulls` | 19.3 | 3.9 | 4.95x | 22.9 |
    5.5 | 4.16x |
    | `duration_ns/duration_ms/no_nulls` | 20.9 | 3.5 | 5.97x | 24.9 | 5.4 |
    4.61x |
    | `duration_ns/duration_ms/mixed_nulls` | 19.4 | 3.5 | 5.54x | 22.9 |
    5.4 | 4.24x |
    | `duration_ns/duration_s/no_nulls` | 20.9 | 3.5 | 5.97x | 24.7 | 5.4 |
    4.57x |
    | `duration_ns/duration_s/mixed_nulls` | 19.3 | 3.6 | 5.36x | 23 | 5.5 |
    4.18x |
    | `duration_us/duration_ms/no_nulls` | 20.9 | 3.9 | 5.36x | 25 | 5 |
    5.00x |
    | `duration_us/duration_ms/mixed_nulls` | 19.3 | 4 | 4.83x | 23 | 5 |
    4.60x |
    | `duration_us/duration_s/no_nulls` | 20.8 | 3.6 | 5.78x | 24.7 | 5.1 |
    4.84x |
    | `duration_us/duration_s/mixed_nulls` | 19.4 | 3.6 | 5.39x | 22.7 | 5 |
    4.54x |
    | `duration_ms/duration_s/no_nulls` | 20.9 | 3.9 | 5.36x | 24.9 | 4.7 |
    5.30x |
    | `duration_ms/duration_s/mixed_nulls` | 19.2 | 3.9 | 4.92x | 22.7 | 4.8
    | 4.73x |
    
    </details>
    
    # Are there any significant user-facing changes?
    
    No.
    
    # AI usage disclosure
    
    I wrote this PR with help from Claude but understand and support the
    core approach, implementation, and test coverage.
---
 arrow-cast/benches/cast_timestamp.rs | 58 ++++++++++++++++++++++++++--
 arrow-cast/src/cast/mod.rs           | 73 ++++++++++++++++++++----------------
 arrow-cast/tests/cast/date_time.rs   | 55 +++++++++++++++++++++++++++
 3 files changed, 151 insertions(+), 35 deletions(-)

diff --git a/arrow-cast/benches/cast_timestamp.rs 
b/arrow-cast/benches/cast_timestamp.rs
index 805ae637a1..7589d28076 100644
--- a/arrow-cast/benches/cast_timestamp.rs
+++ b/arrow-cast/benches/cast_timestamp.rs
@@ -13,8 +13,11 @@ use rand::{RngExt, SeedableRng};
 
 const SIZE: usize = 8192;
 
-fn benchmark<T: ArrowTimestampType>(c: &mut Criterion, unit: &str, 
units_per_second: i64) {
-    // Timestamps spread over roughly 63 years either side of the epoch.
+/// Returns `SIZE` values spread over roughly 63 years either side of zero, 
without nulls and
+/// with a fifth of them null
+fn arrays<T: ArrowPrimitiveType<Native = i64>>(
+    units_per_second: i64,
+) -> (PrimitiveArray<T>, PrimitiveArray<T>) {
     let mut rng = StdRng::seed_from_u64(42);
     let range = -2_000_000_000 * units_per_second..2_000_000_000 * 
units_per_second;
     let values: Vec<i64> = (0..SIZE).map(|_| 
rng.random_range(range.clone())).collect();
@@ -24,7 +27,11 @@ fn benchmark<T: ArrowTimestampType>(c: &mut Criterion, unit: 
&str, units_per_sec
             .enumerate()
             .map(|(i, &v)| (i % 5 != 0).then_some(v)),
     );
-    let no_nulls = PrimitiveArray::<T>::new(values.into(), None);
+    (PrimitiveArray::<T>::new(values.into(), None), mixed_nulls)
+}
+
+fn benchmark<T: ArrowTimestampType>(c: &mut Criterion, unit: &str, 
units_per_second: i64) {
+    let (no_nulls, mixed_nulls) = arrays::<T>(units_per_second);
     // Timezone-aware casts go through Chrono and serve as a control.
     let zoned = no_nulls.clone().with_timezone("+05:45");
     let inputs = [
@@ -48,6 +55,47 @@ fn benchmark<T: ArrowTimestampType>(c: &mut Criterion, unit: 
&str, units_per_sec
             });
         }
     }
+    // Casts to a coarser unit divide each value, and casts to a finer unit 
multiply it
+    for (to_unit, to) in other_units(T::UNIT) {
+        let target = DataType::Timestamp(to, None);
+        for (input, array) in [("no_nulls", &no_nulls), ("mixed_nulls", 
&mixed_nulls)] {
+            group.bench_function(format!("timestamp_{to_unit}/{input}"), |b| {
+                b.iter(|| black_box(cast(black_box(array), &target).unwrap()))
+            });
+        }
+    }
+    group.finish();
+}
+
+/// Returns the names and units other than `unit`
+fn other_units(unit: TimeUnit) -> impl Iterator<Item = (&'static str, 
TimeUnit)> {
+    [
+        ("s", TimeUnit::Second),
+        ("ms", TimeUnit::Millisecond),
+        ("us", TimeUnit::Microsecond),
+        ("ns", TimeUnit::Nanosecond),
+    ]
+    .into_iter()
+    .filter(move |(_, u)| *u != unit)
+}
+
+fn duration_benchmark<T: ArrowPrimitiveType<Native = i64>>(
+    c: &mut Criterion,
+    unit: &str,
+    from: TimeUnit,
+    units_per_second: i64,
+) {
+    let (no_nulls, mixed_nulls) = arrays::<T>(units_per_second);
+    let mut group = c.benchmark_group(format!("duration_{unit}"));
+    group.throughput(Throughput::Elements(SIZE as u64));
+    for (to_unit, to) in other_units(from) {
+        let target = DataType::Duration(to);
+        for (input, array) in [("no_nulls", &no_nulls), ("mixed_nulls", 
&mixed_nulls)] {
+            group.bench_function(format!("duration_{to_unit}/{input}"), |b| {
+                b.iter(|| black_box(cast(black_box(array), &target).unwrap()))
+            });
+        }
+    }
     group.finish();
 }
 
@@ -56,6 +104,10 @@ fn cast_timestamp(c: &mut Criterion) {
     benchmark::<TimestampMillisecondType>(c, "ms", 1_000);
     benchmark::<TimestampMicrosecondType>(c, "us", 1_000_000);
     benchmark::<TimestampNanosecondType>(c, "ns", 1_000_000_000);
+    duration_benchmark::<DurationSecondType>(c, "s", TimeUnit::Second, 1);
+    duration_benchmark::<DurationMillisecondType>(c, "ms", 
TimeUnit::Millisecond, 1_000);
+    duration_benchmark::<DurationMicrosecondType>(c, "us", 
TimeUnit::Microsecond, 1_000_000);
+    duration_benchmark::<DurationNanosecondType>(c, "ns", 
TimeUnit::Nanosecond, 1_000_000_000);
 }
 
 criterion_group!(benches, cast_timestamp);
diff --git a/arrow-cast/src/cast/mod.rs b/arrow-cast/src/cast/mod.rs
index 504330c9ed..e69cb66dcf 100644
--- a/arrow-cast/src/cast/mod.rs
+++ b/arrow-cast/src/cast/mod.rs
@@ -1685,19 +1685,17 @@ pub fn cast_with_options(
                 .unary::<_, Time64NanosecondType>(|x| x as i64 * (NANOSECONDS 
/ MILLISECONDS)),
         )),
 
-        (Time64(TimeUnit::Microsecond), Time32(TimeUnit::Second)) => {
-            cast_time64_to_time32::<Time64MicrosecondType, Time32SecondType>(
-                array,
-                MICROSECONDS,
-                cast_options,
-            )
-        }
+        (Time64(TimeUnit::Microsecond), Time32(TimeUnit::Second)) => 
cast_time64_to_time32::<
+            Time64MicrosecondType,
+            Time32SecondType,
+            MICROSECONDS,
+        >(array, cast_options),
         (Time64(TimeUnit::Microsecond), Time32(TimeUnit::Millisecond)) => {
-            cast_time64_to_time32::<Time64MicrosecondType, 
Time32MillisecondType>(
-                array,
-                MICROSECONDS / MILLISECONDS,
-                cast_options,
-            )
+            cast_time64_to_time32::<
+                Time64MicrosecondType,
+                Time32MillisecondType,
+                { MICROSECONDS / MILLISECONDS },
+            >(array, cast_options)
         }
         (Time64(TimeUnit::Microsecond), Time64(TimeUnit::Nanosecond)) => {
             let array = array.as_primitive::<Time64MicrosecondType>();
@@ -1713,19 +1711,17 @@ pub fn cast_with_options(
             Ok(Arc::new(result))
         }
 
-        (Time64(TimeUnit::Nanosecond), Time32(TimeUnit::Second)) => {
-            cast_time64_to_time32::<Time64NanosecondType, Time32SecondType>(
-                array,
-                NANOSECONDS,
-                cast_options,
-            )
-        }
+        (Time64(TimeUnit::Nanosecond), Time32(TimeUnit::Second)) => 
cast_time64_to_time32::<
+            Time64NanosecondType,
+            Time32SecondType,
+            NANOSECONDS,
+        >(array, cast_options),
         (Time64(TimeUnit::Nanosecond), Time32(TimeUnit::Millisecond)) => {
-            cast_time64_to_time32::<Time64NanosecondType, 
Time32MillisecondType>(
-                array,
-                NANOSECONDS / MILLISECONDS,
-                cast_options,
-            )
+            cast_time64_to_time32::<
+                Time64NanosecondType,
+                Time32MillisecondType,
+                { NANOSECONDS / MILLISECONDS },
+            >(array, cast_options)
         }
         (Time64(TimeUnit::Nanosecond), Time64(TimeUnit::Microsecond)) => 
Ok(Arc::new(
             array
@@ -1769,8 +1765,14 @@ pub fn cast_with_options(
             // units are never the same when the types are the same
             let converted = match from_size.cmp(&to_size) {
                 Ordering::Greater => {
-                    let divisor = from_size / to_size;
-                    time_array.unary::<_, Int64Type>(|o| o / divisor)
+                    // A constant divisor lets the compiler replace each 
division with a multiply
+                    // and shifts. The ratio of two time units is always one 
of these three
+                    match from_size / to_size {
+                        1_000 => time_array.unary::<_, Int64Type>(|o| o / 
1_000),
+                        1_000_000 => time_array.unary::<_, Int64Type>(|o| o / 
1_000_000),
+                        1_000_000_000 => time_array.unary::<_, Int64Type>(|o| 
o / 1_000_000_000),
+                        divisor => time_array.unary::<_, Int64Type>(|o| o / 
divisor),
+                    }
                 }
                 Ordering::Equal => time_array.clone(),
                 Ordering::Less => {
@@ -1965,8 +1967,14 @@ pub fn cast_with_options(
             // units are never the same when the types are the same
             let converted = match from_size.cmp(&to_size) {
                 Ordering::Greater => {
-                    let divisor = from_size / to_size;
-                    time_array.unary::<_, Int64Type>(|o| o / divisor)
+                    // A constant divisor lets the compiler replace each 
division with a multiply
+                    // and shifts. The ratio of two time units is always one 
of these three
+                    match from_size / to_size {
+                        1_000 => time_array.unary::<_, Int64Type>(|o| o / 
1_000),
+                        1_000_000 => time_array.unary::<_, Int64Type>(|o| o / 
1_000_000),
+                        1_000_000_000 => time_array.unary::<_, Int64Type>(|o| 
o / 1_000_000_000),
+                        divisor => time_array.unary::<_, Int64Type>(|o| o / 
divisor),
+                    }
                 }
                 Ordering::Equal => time_array.clone(),
                 Ordering::Less => {
@@ -2035,9 +2043,10 @@ const fn time_unit_multiple(unit: &TimeUnit) -> i64 {
     }
 }
 
-fn cast_time64_to_time32<FROM, TO>(
+/// `DIVISOR` is a const parameter so that each division is by a constant, 
which the compiler
+/// replaces with a multiply and shifts even when the loops aren't inlined 
into this function
+fn cast_time64_to_time32<FROM, TO, const DIVISOR: i64>(
     array: &dyn Array,
-    divisor: i64,
     cast_options: &CastOptions,
 ) -> Result<ArrayRef, ArrowError>
 where
@@ -2046,10 +2055,10 @@ where
 {
     let array = array.as_primitive::<FROM>();
     let result = if cast_options.safe {
-        array.unary_opt::<_, TO>(|value| i32::try_from(value / divisor).ok())
+        array.unary_opt::<_, TO>(|value| i32::try_from(value / DIVISOR).ok())
     } else {
         array.try_unary::<_, TO, _>(|value| {
-            let value = value / divisor;
+            let value = value / DIVISOR;
             i32::try_from(value).map_err(|_| {
                 ArrowError::CastError(format!(
                     "Can't cast value {value:?} to type {}",
diff --git a/arrow-cast/tests/cast/date_time.rs 
b/arrow-cast/tests/cast/date_time.rs
index ec00ae6685..17d8870f8c 100644
--- a/arrow-cast/tests/cast/date_time.rs
+++ b/arrow-cast/tests/cast/date_time.rs
@@ -2723,3 +2723,58 @@ fn test_cast_temporal_scaling_boundaries() {
     check::<Date64Type, TimestampMicrosecondType>(MICROSECONDS / MILLISECONDS);
     check::<Date64Type, TimestampNanosecondType>(NANOSECONDS / MILLISECONDS);
 }
+
+#[test]
+fn test_cast_timestamp_and_duration_to_coarser_unit() {
+    // Truncates toward zero, as `/` does, and keeps nulls
+    let edges = [
+        i64::MIN,
+        i64::MIN + 1,
+        -1_000_000_001,
+        -1_000_000_000,
+        -999_999_999,
+        -1001,
+        -1000,
+        -999,
+        -1,
+        0,
+        1,
+        999,
+        1000,
+        1001,
+        999_999_999,
+        1_000_000_000,
+        1_000_000_001,
+        i64::MAX - 1,
+        i64::MAX,
+    ];
+    let values: Int64Array = 
edges.into_iter().map(Some).chain([None]).collect();
+    let units = [
+        TimeUnit::Second,
+        TimeUnit::Millisecond,
+        TimeUnit::Microsecond,
+        TimeUnit::Nanosecond,
+    ];
+    for array in [values.clone(), values.slice(3, 15)] {
+        for (i, from) in units.into_iter().enumerate() {
+            for to in &units[..i] {
+                let ratio = time_unit_multiple(&from) / time_unit_multiple(to);
+                let expected: Int64Array = array.iter().map(|v| v.map(|v| v / 
ratio)).collect();
+                for (from_type, to_type) in [
+                    (Timestamp(from, None), Timestamp(*to, None)),
+                    (Duration(from), Duration(*to)),
+                ] {
+                    let input = cast(&array, &from_type).unwrap();
+                    let output = cast(&input, &to_type).unwrap();
+                    assert_eq!(output.data_type(), &to_type);
+                    let output = cast(&output, &Int64).unwrap();
+                    assert_eq!(
+                        output.as_primitive::<Int64Type>(),
+                        &expected,
+                        "{from_type} to {to_type}"
+                    );
+                }
+            }
+        }
+    }
+}

Reply via email to