Skip to main content

vortex_array/extension/datetime/
unit.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt::Display;
5use std::fmt::Formatter;
6
7use jiff::Span;
8use num_enum::IntoPrimitive;
9use vortex_error::VortexError;
10use vortex_error::VortexResult;
11use vortex_error::vortex_bail;
12
13/// Time units for temporal data.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd, IntoPrimitive)]
15#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
16#[repr(u8)]
17pub enum TimeUnit {
18    /// Nanoseconds
19    Nanoseconds = 0,
20    /// Microseconds
21    Microseconds = 1,
22    /// Milliseconds
23    Milliseconds = 2,
24    /// Seconds
25    Seconds = 3,
26    /// Days
27    Days = 4,
28}
29
30impl TryFrom<u8> for TimeUnit {
31    type Error = VortexError;
32
33    fn try_from(value: u8) -> Result<Self, Self::Error> {
34        match value {
35            0 => Ok(TimeUnit::Nanoseconds),
36            1 => Ok(TimeUnit::Microseconds),
37            2 => Ok(TimeUnit::Milliseconds),
38            3 => Ok(TimeUnit::Seconds),
39            4 => Ok(TimeUnit::Days),
40            _ => vortex_bail!("invalid time unit: {value}u8"),
41        }
42    }
43}
44
45impl TimeUnit {
46    /// Convert to a Jiff span.
47    pub fn to_jiff_span(&self, v: i64) -> VortexResult<Span> {
48        Ok(match self {
49            TimeUnit::Nanoseconds => Span::new().try_nanoseconds(v)?,
50            TimeUnit::Microseconds => Span::new().try_microseconds(v)?,
51            TimeUnit::Milliseconds => Span::new().try_milliseconds(v)?,
52            TimeUnit::Seconds => Span::new().try_seconds(v)?,
53            TimeUnit::Days => Span::new().try_days(v)?,
54        })
55    }
56
57    /// Return the length of one unit in nanoseconds.
58    ///
59    /// A day is always 86,400 seconds, as in Arrow, so no unit accounts for leap seconds.
60    pub const fn nanos_per_unit(self) -> i64 {
61        match self {
62            TimeUnit::Nanoseconds => 1,
63            TimeUnit::Microseconds => 1_000,
64            TimeUnit::Milliseconds => 1_000_000,
65            TimeUnit::Seconds => 1_000_000_000,
66            TimeUnit::Days => 86_400_000_000_000,
67        }
68    }
69
70    /// Return the number of units in one day.
71    pub const fn units_per_day(self) -> i64 {
72        TimeUnit::Days.nanos_per_unit() / self.nanos_per_unit()
73    }
74}
75
76impl Display for TimeUnit {
77    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
78        match self {
79            Self::Nanoseconds => write!(f, "ns"),
80            Self::Microseconds => write!(f, "µs"),
81            Self::Milliseconds => write!(f, "ms"),
82            Self::Seconds => write!(f, "s"),
83            Self::Days => write!(f, "days"),
84        }
85    }
86}