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