Skip to main content

vortex_functions/zip/
decimal.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::ExecutionCtx;
7use vortex_array::arrays::Decimal;
8use vortex_error::VortexResult;
9use vortex_error::vortex_ensure;
10
11use crate::zip::ZipKernel;
12use crate::zip::fixed_width::zip_fixed_width;
13
14/// A decimal zip kernel that selects values branchlessly per row.
15///
16/// The row selection is shared with [`Primitive`](vortex_array::arrays::Primitive) through
17/// `zip_fixed_width`.
18impl ZipKernel for Decimal {
19    fn zip(
20        if_true: ArrayView<'_, Decimal>,
21        if_false: &ArrayRef,
22        mask: &ArrayRef,
23        ctx: &mut ExecutionCtx,
24    ) -> VortexResult<Option<ArrayRef>> {
25        let Some(if_false) = if_false.as_opt::<Decimal>() else {
26            return Ok(None);
27        };
28
29        vortex_ensure!(
30            if_true.dtype().eq_ignore_nullability(if_false.dtype()),
31            "zip requires if_true and if_false to share a decimal type, got {} and {}",
32            if_true.dtype(),
33            if_false.dtype()
34        );
35
36        zip_fixed_width(if_true, if_false, mask, ctx)
37    }
38}
39
40#[cfg(test)]
41mod tests {
42    #![allow(
43        clippy::cast_possible_truncation,
44        reason = "test fixtures use small indices that fit the target widths"
45    )]
46
47    use std::sync::LazyLock;
48
49    use rstest::rstest;
50    use vortex_array::ArrayRef;
51    use vortex_array::IntoArray;
52    use vortex_array::VortexSessionExecute;
53    use vortex_array::arrays::Decimal;
54    use vortex_array::arrays::DecimalArray;
55    use vortex_array::assert_arrays_eq;
56    use vortex_array::dtype::DecimalDType;
57    use vortex_array::dtype::NativeDecimalType;
58    use vortex_array::dtype::i256;
59    use vortex_array::validity::Validity;
60    use vortex_buffer::Buffer;
61    use vortex_error::VortexResult;
62    use vortex_mask::Mask;
63    use vortex_session::VortexSession;
64
65    use crate::builtins::ArrayFunctions;
66
67    static SESSION: LazyLock<VortexSession> = LazyLock::new(|| {
68        let session = VortexSession::empty();
69        vortex_array::initialize(&session);
70        crate::initialize(&session);
71        session
72    });
73
74    /// Builds a decimal array whose precision makes `T` its canonical storage width.
75    fn decimal<T: NativeDecimalType>(values: Vec<T>, validity: Validity) -> ArrayRef {
76        let mut ctx = SESSION.create_execution_ctx();
77        DecimalArray::new(
78            values.into_iter().collect::<Buffer<T>>(),
79            DecimalDType::new(T::MAX_PRECISION, 2),
80            validity,
81            &mut ctx,
82        )
83        .into_array()
84    }
85
86    /// The kernel selects values and validity from the chosen side across the 64-bit chunk
87    /// boundary and the trailing remainder, for every storage width.
88    #[test]
89    fn zip_selects_values_and_validity() -> VortexResult<()> {
90        check_selects_values_and_validity(|i| i as i32)?;
91        check_selects_values_and_validity(|i| i as i64)?;
92        check_selects_values_and_validity(|i| i as i128)?;
93        check_selects_values_and_validity(|i| i256::from_i128(i as i128))
94    }
95
96    fn check_selects_values_and_validity<T: NativeDecimalType>(
97        value: impl Fn(usize) -> T,
98    ) -> VortexResult<()> {
99        let len = 150usize;
100        let true_valid = |i: usize| !i.is_multiple_of(4);
101        let false_valid = |i: usize| !i.is_multiple_of(5);
102        let bits: Vec<bool> = (0..len).map(|i| i.is_multiple_of(3) || i == 64).collect();
103
104        let if_true = decimal(
105            (0..len).map(&value).collect(),
106            Validity::from_iter((0..len).map(true_valid)),
107        );
108        let if_false = decimal(
109            (0..len).map(|i| value(1_000 + i)).collect(),
110            Validity::from_iter((0..len).map(false_valid)),
111        );
112
113        let mut ctx = SESSION.create_execution_ctx();
114        let result = Mask::from_iter(bits.iter().copied())
115            .into_array()
116            .zip(if_true, if_false)?
117            .execute::<ArrayRef>(&mut ctx)?;
118        assert!(result.is::<Decimal>());
119
120        let expected = decimal(
121            (0..len)
122                .map(|i| if bits[i] { value(i) } else { value(1_000 + i) })
123                .collect(),
124            Validity::from_iter((0..len).map(|i| {
125                if bits[i] {
126                    true_valid(i)
127                } else {
128                    false_valid(i)
129                }
130            })),
131        );
132        assert_arrays_eq!(result, expected, &mut ctx);
133        Ok(())
134    }
135
136    /// Non-nullable branches stay non-nullable, and one nullable branch widens the result.
137    #[rstest]
138    #[case::non_nullable(Validity::NonNullable, Validity::NonNullable)]
139    #[case::nullable_if_true(Validity::AllValid, Validity::NonNullable)]
140    #[case::nullable_if_false(Validity::NonNullable, Validity::AllValid)]
141    fn zip_unions_nullability(
142        #[case] true_validity: Validity,
143        #[case] false_validity: Validity,
144    ) -> VortexResult<()> {
145        let nullability = true_validity.nullability() | false_validity.nullability();
146        let if_true = decimal(vec![1i64, 2, 3, 4], true_validity);
147        let if_false = decimal(vec![10i64, 20, 30, 40], false_validity);
148
149        let mut ctx = SESSION.create_execution_ctx();
150        let result = Mask::from_iter([true, false, false, true])
151            .into_array()
152            .zip(if_true, if_false)?;
153
154        let expected = decimal(vec![1i64, 20, 30, 4], Validity::from(nullability));
155        assert_arrays_eq!(result, expected, &mut ctx);
156        Ok(())
157    }
158}