Skip to main content

vortex_array/extension/datetime/
duration.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt;
5
6use vortex_error::VortexExpect;
7use vortex_error::VortexResult;
8use vortex_error::vortex_bail;
9use vortex_error::vortex_ensure;
10use vortex_session::registry::CachedId;
11
12use crate::dtype::DType;
13use crate::dtype::Nullability;
14use crate::dtype::PType;
15use crate::dtype::extension::ExtDType;
16use crate::dtype::extension::ExtId;
17use crate::dtype::extension::ExtVTable;
18use crate::extension::datetime::TimeUnit;
19use crate::scalar::ScalarValue;
20
21/// A signed duration stored as an `i64` count of seconds, milliseconds, microseconds, or
22/// nanoseconds.
23///
24/// Every storage value is valid. Formatting falls back to the raw count when jiff cannot format it.
25#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
26pub struct Duration;
27
28impl Duration {
29    /// Creates a duration dtype with the given time unit and nullability.
30    ///
31    /// # Errors
32    ///
33    /// Returns an error for [`TimeUnit::Days`].
34    pub fn try_new(time_unit: TimeUnit, nullability: Nullability) -> VortexResult<ExtDType<Self>> {
35        ExtDType::try_new(time_unit, nullability)
36    }
37
38    /// Creates a duration dtype with the given time unit and nullability.
39    ///
40    /// # Panics
41    ///
42    /// Panics if `time_unit` is [`TimeUnit::Days`].
43    pub fn new(time_unit: TimeUnit, nullability: Nullability) -> ExtDType<Self> {
44        Self::try_new(time_unit, nullability)
45            .vortex_expect("duration time unit must be finer than days")
46    }
47}
48
49/// Unpacked value of a [`Duration`] extension scalar.
50#[derive(Clone, Copy, Debug, PartialEq, Eq)]
51pub enum DurationValue {
52    /// Seconds.
53    Seconds(i64),
54    /// Milliseconds.
55    Milliseconds(i64),
56    /// Microseconds.
57    Microseconds(i64),
58    /// Nanoseconds.
59    Nanoseconds(i64),
60}
61
62impl fmt::Display for DurationValue {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        let (unit, value) = match *self {
65            DurationValue::Seconds(v) => (TimeUnit::Seconds, v),
66            DurationValue::Milliseconds(v) => (TimeUnit::Milliseconds, v),
67            DurationValue::Microseconds(v) => (TimeUnit::Microseconds, v),
68            DurationValue::Nanoseconds(v) => (TimeUnit::Nanoseconds, v),
69        };
70
71        // jiff cannot hold every i64 storage value.
72        let Ok(span) = unit.to_jiff_span(value) else {
73            return write!(f, "{value}{unit}");
74        };
75
76        write!(f, "{span}")
77    }
78}
79
80impl ExtVTable for Duration {
81    type Metadata = TimeUnit;
82    type StoredMetadata = Self::Metadata;
83    type NativeValue<'a> = DurationValue;
84
85    fn id(&self) -> ExtId {
86        static ID: CachedId = CachedId::new("vortex.duration");
87        *ID
88    }
89
90    fn serialize_metadata(&self, metadata: &Self::Metadata) -> VortexResult<Vec<u8>> {
91        Ok(vec![u8::from(*metadata)])
92    }
93
94    fn deserialize_metadata(&self, data: &[u8]) -> VortexResult<Self::StoredMetadata> {
95        vortex_ensure!(!data.is_empty(), "Duration metadata must not be empty");
96
97        let tag = data[0];
98        TimeUnit::try_from(tag)
99    }
100
101    fn metadata_from_storage(
102        &self,
103        stored_metadata: Self::StoredMetadata,
104        _storage_dtype: &DType,
105    ) -> VortexResult<Self::Metadata> {
106        Ok(stored_metadata)
107    }
108
109    fn storage_dtype(_metadata: &Self::Metadata) -> DType {
110        DType::Primitive(PType::I64, Nullability::NonNullable)
111    }
112
113    fn validate_metadata(metadata: &Self::Metadata) -> VortexResult<()> {
114        vortex_ensure!(
115            *metadata != TimeUnit::Days,
116            "Duration time unit must be finer than days, got {metadata}"
117        );
118
119        Ok(())
120    }
121
122    fn unpack_native<'a>(
123        ext_dtype: &'a ExtDType<Self>,
124        storage_value: &'a ScalarValue,
125    ) -> VortexResult<Self::NativeValue<'a>> {
126        let value = storage_value.as_primitive().cast::<i64>()?;
127
128        Ok(match *ext_dtype.metadata() {
129            TimeUnit::Nanoseconds => DurationValue::Nanoseconds(value),
130            TimeUnit::Microseconds => DurationValue::Microseconds(value),
131            TimeUnit::Milliseconds => DurationValue::Milliseconds(value),
132            TimeUnit::Seconds => DurationValue::Seconds(value),
133            TimeUnit::Days => {
134                vortex_bail!("Duration time unit must be finer than days, got days")
135            }
136        })
137    }
138}
139
140#[cfg(test)]
141mod tests {
142    use rstest::rstest;
143    use vortex_error::VortexResult;
144
145    use crate::dtype::DType;
146    use crate::dtype::Nullability::Nullable;
147    use crate::dtype::extension::ExtDTypePlugin;
148    use crate::dtype::extension::ExtVTable;
149    use crate::extension::datetime::Duration;
150    use crate::extension::datetime::TimeUnit;
151    use crate::scalar::PValue;
152    use crate::scalar::Scalar;
153    use crate::scalar::ScalarValue;
154
155    #[test]
156    fn validate_duration_scalar() -> VortexResult<()> {
157        let dtype = DType::Extension(Duration::new(TimeUnit::Seconds, Nullable).erased());
158        Scalar::try_new(dtype, Some(ScalarValue::Primitive(PValue::I64(0))))?;
159
160        Ok(())
161    }
162
163    #[test]
164    fn test_reject_duration_days() {
165        assert!(Duration::try_new(TimeUnit::Days, Nullable).is_err());
166    }
167
168    #[test]
169    fn test_read_rejects_non_i64_storage() {
170        let result = Duration.deserialize(&[u8::from(TimeUnit::Seconds)], DType::Utf8(Nullable));
171        assert!(result.is_err_and(|error| {
172            error
173                .to_string()
174                .contains("vortex.duration storage must be i64?, got utf8?")
175        }));
176    }
177
178    #[rstest]
179    #[case::seconds_max(TimeUnit::Seconds, i64::MAX)]
180    #[case::milliseconds_max(TimeUnit::Milliseconds, i64::MAX)]
181    #[case::microseconds_max(TimeUnit::Microseconds, i64::MAX)]
182    #[case::nanoseconds_min(TimeUnit::Nanoseconds, i64::MIN)]
183    fn test_accept_duration_storage_extremes(
184        #[case] unit: TimeUnit,
185        #[case] value: i64,
186    ) -> VortexResult<()> {
187        let dtype = DType::Extension(Duration::new(unit, Nullable).erased());
188        Scalar::try_new(dtype, Some(ScalarValue::from(value)))?;
189
190        Ok(())
191    }
192
193    #[rstest]
194    #[case::seconds(TimeUnit::Seconds, 10, "PT10S")]
195    #[case::negative_ms(TimeUnit::Milliseconds, -250, "-PT0.25S")]
196    #[case::zero_us(TimeUnit::Microseconds, 0, "PT0S")]
197    #[case::overflow_seconds(TimeUnit::Seconds, i64::MAX, "9223372036854775807s")]
198    #[case::overflow_nanos(TimeUnit::Nanoseconds, i64::MIN, "-9223372036854775808ns")]
199    fn display_duration_scalar(
200        #[case] unit: TimeUnit,
201        #[case] value: i64,
202        #[case] expected: &str,
203    ) -> VortexResult<()> {
204        let dtype = DType::Extension(Duration::new(unit, Nullable).erased());
205        let scalar = Scalar::try_new(dtype, Some(ScalarValue::from(value)))?;
206        assert_eq!(scalar.as_extension().to_string(), expected);
207
208        Ok(())
209    }
210
211    #[test]
212    fn deserialize_empty_metadata_returns_error() {
213        assert!(Duration.deserialize_metadata(&[]).is_err());
214    }
215
216    #[test]
217    fn deserialize_invalid_tag_returns_error() {
218        assert!(Duration.deserialize_metadata(&[0xFF]).is_err());
219    }
220}