vortex_array/extension/datetime/
unit.rs1use 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#[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 = 0,
20 Microseconds = 1,
22 Milliseconds = 2,
24 Seconds = 3,
26 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 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
58impl Display for TimeUnit {
59 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
60 match self {
61 Self::Nanoseconds => write!(f, "ns"),
62 Self::Microseconds => write!(f, "µs"),
63 Self::Milliseconds => write!(f, "ms"),
64 Self::Seconds => write!(f, "s"),
65 Self::Days => write!(f, "days"),
66 }
67 }
68}