|
3 | 3 |
|
4 | 4 | //! Scalar casting between [`DType`]s. |
5 | 5 |
|
| 6 | +use num_traits::One; |
| 7 | +use num_traits::Zero; |
6 | 8 | use vortex_error::VortexExpect; |
7 | 9 | use vortex_error::VortexResult; |
8 | 10 | use vortex_error::vortex_bail; |
9 | 11 | use vortex_error::vortex_ensure; |
10 | 12 | use vortex_error::vortex_err; |
11 | 13 |
|
12 | 14 | use crate::dtype::DType; |
| 15 | +use crate::dtype::Nullability; |
| 16 | +use crate::dtype::PType; |
| 17 | +use crate::match_each_native_ptype; |
13 | 18 | use crate::scalar::Scalar; |
14 | 19 |
|
15 | 20 | impl Scalar { |
@@ -62,9 +67,18 @@ impl Scalar { |
62 | 67 |
|
63 | 68 | match &self.dtype() { |
64 | 69 | DType::Null => unreachable!("Handled by the if case above"), |
65 | | - DType::Bool(_) => vortex_bail!( |
66 | | - "Cannot cast bool to {target_dtype}: boolean scalars can only be cast to boolean types with different nullability" |
67 | | - ), |
| 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 | + } |
68 | 82 | DType::Primitive(..) => self.as_primitive().cast(target_dtype), |
69 | 83 | DType::Decimal(..) => self.as_decimal().cast(target_dtype), |
70 | 84 | DType::Utf8(_) => vortex_bail!( |
@@ -94,3 +108,17 @@ impl Scalar { |
94 | 108 | .vortex_expect("Casting to nullable should always succeed") |
95 | 109 | } |
96 | 110 | } |
| 111 | + |
| 112 | +/// Casts `value` to `ptype` like the bool array cast: true is one, false is zero. |
| 113 | +fn 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 | +} |
0 commit comments