vortex_array/arrays/bool/compute/
cast.rs

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