Skip to main content

vortex_array/extension/datetime/
counts.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Apply a per-count conversion to a temporal array or scalar.
5//!
6//! Each temporal conversion that changes the stored counts, whether an exact `cast` or a named
7//! function such as `vortex_functions::expr::change_time_unit`, maps each count on its
8//! own and writes the result in the storage width of the target type. This module owns that
9//! plumbing, so that each conversion supplies only its per-count arithmetic.
10
11use vortex_buffer::Buffer;
12use vortex_buffer::BufferMut;
13use vortex_error::VortexError;
14use vortex_error::VortexExpect;
15use vortex_error::VortexResult;
16use vortex_error::vortex_ensure;
17use vortex_error::vortex_panic;
18use vortex_mask::Mask;
19
20use crate::ArrayRef;
21use crate::ExecutionCtx;
22use crate::IntoArray;
23use crate::arrays::ConstantArray;
24use crate::arrays::ExtensionArray;
25use crate::arrays::PrimitiveArray;
26use crate::arrays::extension::ExtensionArrayExt;
27use crate::canonical::Canonical;
28use crate::dtype::DType;
29use crate::dtype::NativePType;
30use crate::dtype::PType;
31use crate::dtype::extension::ExtDTypeRef;
32use crate::scalar::Scalar;
33
34/// Apply `convert` to each valid count of a temporal array, and return an array of `target`.
35///
36/// `target` **must** be a temporal dtype. A null row stays null, and `convert` never sees its
37/// payload. The conversion fails on the first count that `convert` rejects or that does not fit in
38/// the storage width of `target`.
39pub fn map_counts(
40    input: ArrayRef,
41    target: &DType,
42    ctx: &mut ExecutionCtx,
43    convert: impl Fn(i64) -> VortexResult<i64>,
44) -> VortexResult<ArrayRef> {
45    if input.is_empty() {
46        return Ok(Canonical::empty(target).into_array());
47    }
48    // A constant converts its one value, so the result stays constant.
49    if let Some(scalar) = input.as_constant() {
50        let converted = map_scalar_count(scalar, target, convert)?;
51        return Ok(ConstantArray::new(converted, input.len()).into_array());
52    }
53
54    let ext = input.execute::<ExtensionArray>(ctx)?;
55    let storage = ext.storage_array().clone().execute::<PrimitiveArray>(ctx)?;
56    let target = target
57        .as_extension_opt()
58        .vortex_expect("`map_counts` requires a temporal target dtype");
59
60    match storage.ptype() {
61        PType::I32 => map_storage_counts::<i32>(&storage, target, ctx, convert),
62        PType::I64 => map_storage_counts::<i64>(&storage, target, ctx, convert),
63        ptype => unsupported_storage(ptype),
64    }
65}
66
67/// Apply `convert` to the count of a temporal scalar, and return a scalar of `target`.
68///
69/// `target` **must** be a temporal dtype. A null scalar becomes a null of `target`, which therefore
70/// must be nullable.
71pub(crate) fn map_scalar_count(
72    input: &Scalar,
73    target: &DType,
74    convert: impl Fn(i64) -> VortexResult<i64>,
75) -> VortexResult<Scalar> {
76    if input.is_null() {
77        vortex_ensure!(
78            target.is_nullable(),
79            "Expected a nullable target for a null value, got {target}"
80        );
81        return Ok(Scalar::null(target.clone()));
82    }
83
84    let target_ext = target
85        .as_extension_opt()
86        .vortex_expect("`map_scalar_count` requires a temporal target dtype");
87    let storage = input.as_extension().to_storage_scalar();
88    let value = match storage.as_primitive().ptype() {
89        PType::I32 => storage.as_primitive().typed_value::<i32>().map(i64::from),
90        PType::I64 => storage.as_primitive().typed_value::<i64>(),
91        ptype => unsupported_storage(ptype),
92    }
93    .vortex_expect("the null check above returns early for a null input");
94    let value = convert(value)?;
95
96    let storage = match target_ext.storage_dtype().as_ptype() {
97        PType::I32 => Scalar::primitive(i32::try_from(value)?, target.nullability()),
98        PType::I64 => Scalar::primitive(value, target.nullability()),
99        ptype => unsupported_storage(ptype),
100    };
101    Scalar::try_extension_ref(target_ext.clone(), storage)
102}
103
104/// Select the output storage width and apply the conversion to valid rows.
105fn map_storage_counts<T: NativePType + Into<i64>>(
106    storage: &PrimitiveArray,
107    target: &ExtDTypeRef,
108    ctx: &mut ExecutionCtx,
109    convert: impl Fn(i64) -> VortexResult<i64>,
110) -> VortexResult<ArrayRef> {
111    let values = storage.as_slice::<T>();
112    let validity = storage.validity()?.cast_nullability(
113        target.storage_dtype().nullability(),
114        values.len(),
115        ctx,
116    )?;
117    let mask = validity.execute_mask(values.len(), ctx)?;
118
119    let output = match target.storage_dtype().as_ptype() {
120        PType::I32 => PrimitiveArray::new(
121            map_valid_counts::<T, i32>(values, &mask, convert)?,
122            validity,
123        ),
124        PType::I64 => PrimitiveArray::new(
125            map_valid_counts::<T, i64>(values, &mask, convert)?,
126            validity,
127        ),
128        ptype => unsupported_storage(ptype),
129    };
130
131    Ok(ExtensionArray::try_new(target.clone(), output.into_array())?.into_array())
132}
133
134/// Convert each valid count and fit the result into the output width.
135fn map_valid_counts<T, O>(
136    values: &[T],
137    mask: &Mask,
138    convert: impl Fn(i64) -> VortexResult<i64>,
139) -> VortexResult<Buffer<O>>
140where
141    T: NativePType + Into<i64>,
142    O: NativePType + TryFrom<i64>,
143    VortexError: From<<O as TryFrom<i64>>::Error>,
144{
145    let mut output = BufferMut::<O>::with_capacity(values.len());
146    for (&value, valid) in values.iter().zip(mask.iter()) {
147        // A null row can hold any payload, such as `i64::MAX`, so converting it could fail. Its
148        // output is only a placeholder under the null.
149        let count = if valid { convert(value.into())? } else { 0 };
150        output.push(O::try_from(count)?);
151    }
152    Ok(output.freeze())
153}
154
155/// Panic on a storage type that no built-in temporal dtype has.
156///
157/// The `storage_dtype` of each temporal extension type returns `i32` or `i64`, and an extension
158/// array or scalar must match the storage dtype of its type.
159fn unsupported_storage(ptype: PType) -> ! {
160    vortex_panic!("Expected i32 or i64 temporal storage, got {ptype}")
161}