Skip to main content

vortex_sequence/compute/
cast.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::dtype::DType;
8use vortex_array::dtype::Nullability;
9use vortex_array::scalar::Scalar;
10use vortex_array::scalar::ScalarValue;
11use vortex_array::scalar_fn::fns::cast::CastReduce;
12use vortex_error::VortexResult;
13use vortex_error::vortex_err;
14
15use crate::Sequence;
16impl CastReduce for Sequence {
17    fn cast(array: ArrayView<'_, Self>, dtype: &DType) -> VortexResult<Option<ArrayRef>> {
18        // SequenceArray represents arithmetic sequences (base + i * multiplier) which
19        // only makes sense for integer types. Floating-point sequences would accumulate
20        // rounding errors, and other types don't support arithmetic operations.
21        let DType::Primitive(target_ptype, target_nullability) = dtype else {
22            return Ok(None);
23        };
24
25        if !target_ptype.is_int() {
26            return Ok(None);
27        }
28
29        // Check if this is just a nullability change
30        if array.ptype() == *target_ptype && array.dtype().nullability() != *target_nullability {
31            // For SequenceArray, we can just create a new one with the same parameters
32            // but different nullability
33            return Ok(Some(
34                Sequence::try_new(
35                    array.base(),
36                    array.multiplier(),
37                    *target_ptype,
38                    *target_nullability,
39                    array.len(),
40                )?
41                .into_array(),
42            ));
43        }
44
45        // For type changes, we need to cast the base and multiplier
46        if array.ptype() != *target_ptype {
47            // Create scalars from PValues and cast them
48            let base_scalar = Scalar::try_new(
49                DType::Primitive(array.ptype(), Nullability::NonNullable),
50                Some(ScalarValue::Primitive(array.base())),
51            )?;
52            let multiplier_scalar = Scalar::try_new(
53                DType::Primitive(array.ptype(), Nullability::NonNullable),
54                Some(ScalarValue::Primitive(array.multiplier())),
55            )?;
56
57            let new_base_scalar =
58                base_scalar.cast(&DType::Primitive(*target_ptype, Nullability::NonNullable))?;
59            let new_multiplier_scalar = multiplier_scalar
60                .cast(&DType::Primitive(*target_ptype, Nullability::NonNullable))?;
61
62            // Extract PValues from the casted scalars
63            let new_base = new_base_scalar
64                .as_primitive()
65                .pvalue()
66                .ok_or_else(|| vortex_err!("Cast resulted in null base value"))?;
67            let new_multiplier = new_multiplier_scalar
68                .as_primitive()
69                .pvalue()
70                .ok_or_else(|| vortex_err!("Cast resulted in null multiplier value"))?;
71
72            return Ok(Some(
73                Sequence::try_new(
74                    new_base,
75                    new_multiplier,
76                    *target_ptype,
77                    *target_nullability,
78                    array.len(),
79                )?
80                .into_array(),
81            ));
82        }
83
84        Ok(None)
85    }
86}
87
88#[cfg(test)]
89mod tests {
90    use rstest::rstest;
91    use vortex_array::IntoArray;
92    use vortex_array::ToCanonical;
93    use vortex_array::arrays::PrimitiveArray;
94    use vortex_array::assert_arrays_eq;
95    use vortex_array::builtins::ArrayBuiltins;
96    use vortex_array::compute::conformance::cast::test_cast_conformance;
97    use vortex_array::dtype::DType;
98    use vortex_array::dtype::Nullability;
99    use vortex_array::dtype::PType;
100
101    use crate::Sequence;
102    use crate::SequenceArray;
103
104    #[test]
105    fn test_cast_sequence_nullability() {
106        let sequence = Sequence::try_new_typed(0u32, 1u32, Nullability::NonNullable, 4).unwrap();
107
108        // Cast to nullable
109        let casted = sequence
110            .into_array()
111            .cast(DType::Primitive(PType::U32, Nullability::Nullable))
112            .unwrap();
113        assert_eq!(
114            casted.dtype(),
115            &DType::Primitive(PType::U32, Nullability::Nullable)
116        );
117    }
118
119    #[test]
120    fn test_cast_sequence_u32_to_i64() {
121        let sequence = Sequence::try_new_typed(100u32, 10u32, Nullability::NonNullable, 4).unwrap();
122
123        let casted = sequence
124            .into_array()
125            .cast(DType::Primitive(PType::I64, Nullability::NonNullable))
126            .unwrap();
127        assert_eq!(
128            casted.dtype(),
129            &DType::Primitive(PType::I64, Nullability::NonNullable)
130        );
131
132        // Verify the values
133        let decoded = casted.to_primitive();
134        assert_arrays_eq!(decoded, PrimitiveArray::from_iter([100i64, 110, 120, 130]));
135    }
136
137    #[test]
138    fn test_cast_sequence_i16_to_i32_nullable() {
139        // Test ptype change AND nullability change in one cast
140        let sequence = Sequence::try_new_typed(5i16, 3i16, Nullability::NonNullable, 3).unwrap();
141
142        let casted = sequence
143            .into_array()
144            .cast(DType::Primitive(PType::I32, Nullability::Nullable))
145            .unwrap();
146        assert_eq!(
147            casted.dtype(),
148            &DType::Primitive(PType::I32, Nullability::Nullable)
149        );
150
151        // Verify the values
152        let decoded = casted.to_primitive();
153        assert_arrays_eq!(
154            decoded,
155            PrimitiveArray::from_option_iter([Some(5i32), Some(8), Some(11)])
156        );
157    }
158
159    #[test]
160    fn test_cast_sequence_to_float_delegates_to_canonical() {
161        let sequence = Sequence::try_new_typed(0i32, 1i32, Nullability::NonNullable, 5).unwrap();
162
163        // Cast to float should delegate to canonical (SequenceArray doesn't support float)
164        let casted = sequence
165            .into_array()
166            .cast(DType::Primitive(PType::F32, Nullability::NonNullable))
167            .unwrap();
168        // Should still succeed by decoding to canonical first
169        assert_eq!(
170            casted.dtype(),
171            &DType::Primitive(PType::F32, Nullability::NonNullable)
172        );
173
174        // Verify the values were correctly converted
175        let decoded = casted.to_primitive();
176        assert_arrays_eq!(
177            decoded,
178            PrimitiveArray::from_iter([0.0f32, 1.0, 2.0, 3.0, 4.0])
179        );
180    }
181
182    #[rstest]
183    #[case::i32(Sequence::try_new_typed(0i32, 1i32, Nullability::NonNullable, 5).unwrap())]
184    #[case::u64(Sequence::try_new_typed(1000u64, 100u64, Nullability::NonNullable, 4).unwrap())]
185    // TODO(DK): SequenceArray does not actually conform. You cannot cast this array to u8 even
186    // though all its values are representable therein.
187    //
188    // #[case::negative_step(Sequence::try_new_typed(100i32, -10i32, Nullability::NonNullable,
189    // 5).unwrap())]
190    #[case::single(Sequence::try_new_typed(42i64, 0i64, Nullability::NonNullable, 1).unwrap())]
191    #[case::constant(Sequence::try_new_typed(
192        100i32,
193        0i32, // multiplier of 0 means constant array
194        Nullability::NonNullable,
195        5,
196    ).unwrap())]
197    fn test_cast_sequence_conformance(#[case] sequence: SequenceArray) {
198        test_cast_conformance(&sequence.into_array());
199    }
200}