vortex_compute/cast/
binaryview.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use vortex_dtype::DType;
5use vortex_error::VortexResult;
6use vortex_error::vortex_bail;
7use vortex_vector::Scalar;
8use vortex_vector::ScalarOps;
9use vortex_vector::Vector;
10use vortex_vector::VectorOps;
11use vortex_vector::binaryview::BinaryViewScalar;
12use vortex_vector::binaryview::BinaryViewType;
13use vortex_vector::binaryview::BinaryViewVector;
14
15use crate::cast::Cast;
16use crate::cast::try_cast_scalar_common;
17use crate::cast::try_cast_vector_common;
18
19impl<T: BinaryViewType> Cast for BinaryViewVector<T> {
20    type Output = Vector;
21
22    /// Casts to Utf8 or Binary (identity cast with compatible nullability).
23    fn cast(&self, target_dtype: &DType) -> VortexResult<Vector> {
24        if let Some(result) = try_cast_vector_common(self, target_dtype)? {
25            return Ok(result);
26        }
27
28        match target_dtype {
29            // Identity cast: same type with compatible nullability.
30            dt if T::matches_dtype(dt) && (dt.is_nullable() || self.validity().all_true()) => {
31                Ok(self.clone().into())
32            }
33            // Cross-cast between Utf8 and Binary is not supported.
34            DType::Utf8(_) | DType::Binary(_) => {
35                vortex_bail!(
36                    "Cannot cast BinaryViewVector to {} (cross-cast not supported)",
37                    target_dtype
38                );
39            }
40            _ => {
41                vortex_bail!("Cannot cast BinaryViewVector to {}", target_dtype);
42            }
43        }
44    }
45}
46
47impl<T: BinaryViewType> Cast for BinaryViewScalar<T> {
48    type Output = Scalar;
49
50    /// Casts to Utf8 or Binary (identity cast with compatible nullability).
51    fn cast(&self, target_dtype: &DType) -> VortexResult<Scalar> {
52        if let Some(result) = try_cast_scalar_common(self, target_dtype)? {
53            return Ok(result);
54        }
55
56        match target_dtype {
57            // Identity cast: same type with compatible nullability.
58            dt if T::matches_dtype(dt) && (dt.is_nullable() || self.is_valid()) => {
59                Ok(self.clone().into())
60            }
61            // Cross-cast between Utf8 and Binary is not supported.
62            DType::Utf8(_) | DType::Binary(_) => {
63                vortex_bail!(
64                    "Cannot cast BinaryViewScalar to {} (cross-cast not supported)",
65                    target_dtype
66                );
67            }
68            _ => {
69                vortex_bail!("Cannot cast BinaryViewScalar to {}", target_dtype);
70            }
71        }
72    }
73}