vortex_array/arrays/bool/compute/
cast.rs

1use vortex_dtype::DType;
2use vortex_error::{VortexResult, vortex_bail};
3
4use crate::array::ArrayRef;
5use crate::arrays::{BoolArray, BoolVTable};
6use crate::compute::{CastKernel, CastKernelAdapter};
7use crate::register_kernel;
8use crate::vtable::ValidityHelper;
9
10impl CastKernel for BoolVTable {
11    fn cast(&self, array: &BoolArray, dtype: &DType) -> VortexResult<ArrayRef> {
12        if !matches!(dtype, DType::Bool(_)) {
13            vortex_bail!("Cannot cast {} to {}", array.dtype(), dtype);
14        }
15
16        let new_nullability = dtype.nullability();
17        let new_validity = array.validity().clone().cast_nullability(new_nullability)?;
18        Ok(BoolArray::new(array.boolean_buffer().clone(), new_validity).to_array())
19    }
20}
21
22register_kernel!(CastKernelAdapter(BoolVTable).lift());
23
24#[cfg(test)]
25mod tests {
26    use vortex_dtype::{DType, Nullability};
27
28    use crate::arrays::BoolArray;
29    use crate::compute::cast;
30
31    #[test]
32    fn try_cast_bool_success() {
33        let bool = BoolArray::from_iter(vec![Some(true), Some(false), Some(true)]);
34
35        let res = cast(bool.as_ref(), &DType::Bool(Nullability::NonNullable));
36        assert!(res.is_ok());
37        assert_eq!(res.unwrap().dtype(), &DType::Bool(Nullability::NonNullable));
38    }
39
40    #[test]
41    #[should_panic]
42    fn try_cast_bool_fail() {
43        let bool = BoolArray::from_iter(vec![Some(true), Some(false), None]);
44        cast(bool.as_ref(), &DType::Bool(Nullability::NonNullable)).unwrap();
45    }
46}