Skip to main content

vortex_array/scalar/
cast.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Scalar casting between [`DType`]s.
5
6use num_traits::One;
7use num_traits::Zero;
8use vortex_error::VortexExpect;
9use vortex_error::VortexResult;
10use vortex_error::vortex_bail;
11use vortex_error::vortex_ensure;
12use vortex_error::vortex_err;
13
14use crate::dtype::DType;
15use crate::dtype::Nullability;
16use crate::dtype::PType;
17use crate::match_each_native_ptype;
18use crate::scalar::Scalar;
19
20impl Scalar {
21    /// Cast this scalar to another data type.
22    ///
23    /// # Errors
24    ///
25    /// Returns an error if the cast is not supported or if a null value is cast to a non-nullable
26    /// type.
27    pub fn cast(&self, target_dtype: &DType) -> VortexResult<Scalar> {
28        // If the types are the same, return a clone.
29        if self.dtype() == target_dtype {
30            return Ok(self.clone());
31        }
32
33        // Check for solely nullability casting.
34        if self.dtype().eq_ignore_nullability(target_dtype) {
35            // Cast from non-nullable to nullable or vice versa.
36            // The `try_new` will handle nullability checks.
37            return Scalar::try_new(target_dtype.clone(), self.value().cloned());
38        }
39
40        if let (Some(source), Some(target)) = (self.dtype().as_map_opt(), target_dtype.as_map_opt())
41            && target.keys_sorted()
42            && !source.keys_sorted()
43        {
44            return Err(vortex_err!(
45                "Cannot cast {} to {target_dtype}: source does not assert sorted map keys",
46                self.dtype()
47            ));
48        }
49
50        // Null can be cast into any nullable type as null.
51        // Note that the `matches` clause is technically unnecessary here, just protective.
52        if self.value().is_none() || matches!(self.dtype(), DType::Null) {
53            vortex_ensure!(
54                target_dtype.is_nullable(),
55                "Cannot cast null to {target_dtype}: target type is non-nullable"
56            );
57
58            return Scalar::try_new(target_dtype.clone(), self.value().cloned());
59        }
60
61        // TODO(connor): This isn't really correct for extension types.
62        // If the target is an extension type, then we want to cast to its storage type.
63        if let Some(ext_dtype) = target_dtype.as_extension_opt() {
64            let cast_storage_scalar_value = self.cast(ext_dtype.storage_dtype())?.into_value();
65            return Scalar::try_new(target_dtype.clone(), cast_storage_scalar_value);
66        }
67
68        match &self.dtype() {
69            DType::Null => unreachable!("Handled by the if case above"),
70            DType::Bool(_) => {
71                let DType::Primitive(ptype, nullability) = target_dtype else {
72                    vortex_bail!(
73                        "Cannot cast bool to {target_dtype}: boolean scalars can only be cast to boolean or primitive types"
74                    );
75                };
76                let value = self
77                    .as_bool()
78                    .value()
79                    .vortex_expect("null scalars are handled above");
80                Ok(cast_bool_to_primitive(value, *ptype, *nullability))
81            }
82            DType::Primitive(..) => self.as_primitive().cast(target_dtype),
83            DType::Decimal(..) => self.as_decimal().cast(target_dtype),
84            DType::Utf8(_) => vortex_bail!(
85                "Cannot cast utf8 to {target_dtype}: UTF-8 scalars can only be cast to UTF-8 types with different nullability"
86            ),
87            DType::Binary(_) => vortex_bail!(
88                "Cannot cast binary to {target_dtype}: binary scalars can only be cast to binary types with different nullability"
89            ),
90            DType::List(..) | DType::FixedSizeList(..) => self.as_list().cast(target_dtype),
91            DType::Map(..) => self.as_map().cast(target_dtype),
92            DType::Struct(..) => self.as_struct().cast(target_dtype),
93            DType::Union(..) => vortex_bail!(
94                "union scalar cast from {} to {target_dtype} is not supported (yet)",
95                self.dtype()
96            ),
97            DType::Variant(_) => {
98                vortex_bail!("Variant scalars can't be cast to {target_dtype}")
99            }
100            DType::Extension(..) => self.as_extension().cast(target_dtype),
101        }
102    }
103
104    /// Cast the scalar into a nullable version of its current type.
105    pub fn into_nullable(self) -> Scalar {
106        let (dtype, value) = self.into_parts();
107        Self::try_new(dtype.as_nullable(), value)
108            .vortex_expect("Casting to nullable should always succeed")
109    }
110}
111
112/// Casts `value` to `ptype` like the bool array cast: true is one, false is zero.
113fn cast_bool_to_primitive(value: bool, ptype: PType, nullability: Nullability) -> Scalar {
114    match_each_native_ptype!(ptype, |T| {
115        Scalar::primitive(
116            if value {
117                <T as One>::one()
118            } else {
119                <T as Zero>::zero()
120            },
121            nullability,
122        )
123    })
124}