Skip to main content

vortex_functions/zip/
extension.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use vortex_array::ArrayRef;
5use vortex_array::ArrayView;
6use vortex_array::IntoArray;
7use vortex_array::arrays::Extension;
8use vortex_array::arrays::ExtensionArray;
9use vortex_array::arrays::extension::ExtensionArrayExt;
10use vortex_error::VortexResult;
11use vortex_error::vortex_ensure;
12
13use crate::builtins::ArrayFunctions;
14use crate::zip::ZipReduce;
15
16/// Zips the storage arrays of two extension arrays and wraps the result in the extension type.
17impl ZipReduce for Extension {
18    fn zip(
19        if_true: ArrayView<'_, Extension>,
20        if_false: &ArrayRef,
21        mask: &ArrayRef,
22    ) -> VortexResult<Option<ArrayRef>> {
23        let Some(if_false) = if_false.as_opt::<Extension>() else {
24            return Ok(None);
25        };
26
27        vortex_ensure!(
28            if_true
29                .ext_dtype()
30                .eq_ignore_nullability(if_false.ext_dtype()),
31            "zip requires if_true and if_false to share an extension type, got {} and {}",
32            if_true.dtype(),
33            if_false.dtype()
34        );
35
36        let storage = mask.zip(
37            if_true.storage_array().clone(),
38            if_false.storage_array().clone(),
39        )?;
40        let ext_dtype = if_true
41            .ext_dtype()
42            .with_nullability(storage.dtype().nullability());
43
44        Ok(Some(
45            ExtensionArray::try_new(ext_dtype, storage)?.into_array(),
46        ))
47    }
48}
49
50#[cfg(test)]
51mod tests {
52    use std::sync::LazyLock;
53
54    use rstest::rstest;
55    use vortex_array::ArrayRef;
56    use vortex_array::IntoArray;
57    use vortex_array::VortexSessionExecute;
58    use vortex_array::arrays::Extension;
59    use vortex_array::arrays::ExtensionArray;
60    use vortex_array::arrays::PrimitiveArray;
61    use vortex_array::assert_arrays_eq;
62    use vortex_array::dtype::Nullability;
63    use vortex_array::extension::datetime::TimeUnit;
64    use vortex_array::extension::datetime::Timestamp;
65    use vortex_error::VortexResult;
66    use vortex_mask::Mask;
67    use vortex_session::VortexSession;
68
69    use crate::builtins::ArrayFunctions;
70
71    static SESSION: LazyLock<VortexSession> = LazyLock::new(|| {
72        let session = VortexSession::empty();
73        vortex_array::initialize(&session);
74        crate::initialize(&session);
75        session
76    });
77
78    fn timestamps(
79        values: impl IntoIterator<Item = Option<i64>>,
80        nullability: Nullability,
81    ) -> ArrayRef {
82        let storage = match nullability {
83            Nullability::NonNullable => PrimitiveArray::from_iter(
84                values
85                    .into_iter()
86                    .map(|value| value.expect("non-nullable timestamps have no nulls")),
87            ),
88            Nullability::Nullable => PrimitiveArray::from_option_iter(values),
89        };
90        ExtensionArray::new(
91            Timestamp::new(TimeUnit::Milliseconds, nullability).erased(),
92            storage.into_array(),
93        )
94        .into_array()
95    }
96
97    /// A fragmented mask selects timestamps and their nulls from the chosen side, and the result
98    /// is nullable when either side is nullable.
99    #[rstest]
100    #[case::non_nullable(Nullability::NonNullable, Nullability::NonNullable)]
101    #[case::nullable_if_true(Nullability::Nullable, Nullability::NonNullable)]
102    #[case::nullable_if_false(Nullability::NonNullable, Nullability::Nullable)]
103    #[case::nullable(Nullability::Nullable, Nullability::Nullable)]
104    fn zip_timestamps(
105        #[case] true_nullability: Nullability,
106        #[case] false_nullability: Nullability,
107    ) -> VortexResult<()> {
108        let len = 100i64;
109        let true_value = |i: i64| (!true_nullability.is_nullable() || i % 7 != 0).then_some(i);
110        let false_value =
111            |i: i64| (!false_nullability.is_nullable() || i % 5 != 0).then_some(1_000 + i);
112        let selected = |i: i64| i % 3 == 0;
113
114        let if_true = timestamps((0..len).map(true_value), true_nullability);
115        let if_false = timestamps((0..len).map(false_value), false_nullability);
116        let mask = Mask::from_iter((0..len).map(selected));
117
118        let mut ctx = SESSION.create_execution_ctx();
119        let result = mask
120            .into_array()
121            .zip(if_true, if_false)?
122            .execute::<ArrayRef>(&mut ctx)?;
123        assert!(result.is::<Extension>());
124
125        let expected = timestamps(
126            (0..len).map(|i| {
127                if selected(i) {
128                    true_value(i)
129                } else {
130                    false_value(i)
131                }
132            }),
133            true_nullability | false_nullability,
134        );
135        assert_arrays_eq!(result, expected, &mut ctx);
136        Ok(())
137    }
138}