Skip to main content

vortex_array/extension/datetime/
rounding.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Rounding modes for a temporal count in a coarser unit.
5//!
6//! `cast` performs only the temporal conversions that are exact for every valid value. A coarser
7//! unit can drop part of a count, so the caller selects a [`TemporalRounding`] through
8//! `vortex_functions::expr::change_time_unit` instead.
9
10use std::fmt;
11
12use vortex_error::VortexResult;
13use vortex_error::vortex_ensure_eq;
14
15/// How to handle fractional counts in a coarser temporal unit.
16#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
17pub enum TemporalRounding {
18    /// Require the value to be exactly representable in the target unit.
19    Exact,
20    /// Discard the remainder toward zero.
21    TowardZero,
22    /// Round toward negative infinity.
23    Floor,
24    /// Round to the nearest count, resolving ties away from zero.
25    NearestTiesAwayFromZero,
26}
27
28impl TemporalRounding {
29    /// Divide a signed count by the positive factor between two temporal units.
30    pub fn divide(self, value: i64, divisor: i64) -> VortexResult<i64> {
31        let quotient = value / divisor;
32        let remainder = value % divisor;
33
34        Ok(match self {
35            Self::Exact => {
36                vortex_ensure_eq!(
37                    remainder,
38                    0,
39                    "Expected an exact temporal conversion, got {value}"
40                );
41                quotient
42            }
43            Self::TowardZero => quotient,
44            Self::Floor => value.div_euclid(divisor),
45            Self::NearestTiesAwayFromZero if remainder.abs() * 2 >= divisor => {
46                quotient + remainder.signum()
47            }
48            Self::NearestTiesAwayFromZero => quotient,
49        })
50    }
51}
52
53impl fmt::Display for TemporalRounding {
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        f.write_str(match self {
56            Self::Exact => "exact",
57            Self::TowardZero => "toward_zero",
58            Self::Floor => "floor",
59            Self::NearestTiesAwayFromZero => "nearest_ties_away_from_zero",
60        })
61    }
62}