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;
19use crate::scalar_fn::builtin::cast::TemporalCast;
20use crate::scalar_fn::builtin::cast::check_extension_cast;
21
22impl Scalar {
23    /// Cast this scalar to another data type.
24    ///
25    /// A cast can change the top-level nullability of an extension dtype, or perform an exact
26    /// conversion between two temporal dtypes. A scalar of dtype [`DType::Null`] can also become a
27    /// typed null of any nullable dtype.
28    ///
29    /// # Errors
30    ///
31    /// Returns an error if the cast is not supported or if a null value is cast to a non-nullable
32    /// type.
33    pub fn cast(&self, target_dtype: &DType) -> VortexResult<Scalar> {
34        // If the types are the same, return a clone.
35        if self.dtype() == target_dtype {
36            return Ok(self.clone());
37        }
38
39        // Check for solely nullability casting.
40        if self.dtype().eq_ignore_nullability(target_dtype) {
41            // Cast from non-nullable to nullable or vice versa.
42            // The `try_new` will handle nullability checks.
43            return Scalar::try_new(target_dtype.clone(), self.value().cloned());
44        }
45
46        if let Some(cast) = TemporalCast::classify(self.dtype(), target_dtype) {
47            return cast.cast_scalar(self, target_dtype);
48        }
49        check_extension_cast(self.dtype(), target_dtype)?;
50
51        if let (Some(source), Some(target)) = (self.dtype().as_map_opt(), target_dtype.as_map_opt())
52            && target.keys_sorted()
53            && !source.keys_sorted()
54        {
55            return Err(vortex_err!(
56                "Cannot cast {} to {target_dtype}: source does not assert sorted map keys",
57                self.dtype()
58            ));
59        }
60
61        // Cast nulls after checking the extension dtype restrictions.
62        if self.value().is_none() || matches!(self.dtype(), DType::Null) {
63            vortex_ensure!(
64                target_dtype.is_nullable(),
65                "Cannot cast null to {target_dtype}: target type is non-nullable"
66            );
67
68            return Scalar::try_new(target_dtype.clone(), self.value().cloned());
69        }
70
71        match &self.dtype() {
72            DType::Null => unreachable!("Handled by the if case above"),
73            DType::Bool(_) => {
74                let DType::Primitive(ptype, nullability) = target_dtype else {
75                    vortex_bail!(
76                        "Cannot cast bool to {target_dtype}: boolean scalars can only be cast to boolean or primitive types"
77                    );
78                };
79                let value = self
80                    .as_bool()
81                    .value()
82                    .vortex_expect("null scalars are handled above");
83                Ok(cast_bool_to_primitive(value, *ptype, *nullability))
84            }
85            DType::Primitive(..) => self.as_primitive().cast(target_dtype),
86            DType::Decimal(..) => self.as_decimal().cast(target_dtype),
87            DType::Utf8(_) => vortex_bail!(
88                "Cannot cast utf8 to {target_dtype}: UTF-8 scalars can only be cast to UTF-8 types with different nullability"
89            ),
90            DType::Binary(_) => vortex_bail!(
91                "Cannot cast binary to {target_dtype}: binary scalars can only be cast to binary types with different nullability"
92            ),
93            DType::List(..) | DType::FixedSizeList(..) => self.as_list().cast(target_dtype),
94            DType::Map(..) => self.as_map().cast(target_dtype),
95            DType::Struct(..) => self.as_struct().cast(target_dtype),
96            DType::Union(..) => vortex_bail!(
97                "union scalar cast from {} to {target_dtype} is not supported (yet)",
98                self.dtype()
99            ),
100            DType::Variant(_) => {
101                vortex_bail!("Variant scalars can't be cast to {target_dtype}")
102            }
103            DType::Extension(..) => unreachable!("Extension casts were checked above"),
104        }
105    }
106
107    /// Cast the scalar into a nullable version of its current type.
108    pub fn into_nullable(self) -> Scalar {
109        let (dtype, value) = self.into_parts();
110        Self::try_new(dtype.as_nullable(), value)
111            .vortex_expect("Casting to nullable should always succeed")
112    }
113}
114
115/// Casts `value` to `ptype` like the bool array cast: true is one, false is zero.
116fn cast_bool_to_primitive(value: bool, ptype: PType, nullability: Nullability) -> Scalar {
117    match_each_native_ptype!(ptype, |T| {
118        Scalar::primitive(
119            if value {
120                <T as One>::one()
121            } else {
122                <T as Zero>::zero()
123            },
124            nullability,
125        )
126    })
127}