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 rstest::rstest;
32    use vortex_dtype::{DType, Nullability};
33
34    use crate::arrays::BoolArray;
35    use crate::compute::cast;
36    use crate::compute::conformance::cast::test_cast_conformance;
37
38    #[test]
39    fn try_cast_bool_success() {
40        let bool = BoolArray::from_iter(vec![Some(true), Some(false), Some(true)]);
41
42        let res = cast(bool.as_ref(), &DType::Bool(Nullability::NonNullable));
43        assert!(res.is_ok());
44        assert_eq!(res.unwrap().dtype(), &DType::Bool(Nullability::NonNullable));
45    }
46
47    #[test]
48    #[should_panic]
49    fn try_cast_bool_fail() {
50        let bool = BoolArray::from_iter(vec![Some(true), Some(false), None]);
51        cast(bool.as_ref(), &DType::Bool(Nullability::NonNullable)).unwrap();
52    }
53
54    #[rstest]
55    #[case(BoolArray::from_iter(vec![true, false, true, true, false]))]
56    #[case(BoolArray::from_iter(vec![Some(true), Some(false), None, Some(true), None]))]
57    #[case(BoolArray::from_iter(vec![true]))]
58    #[case(BoolArray::from_iter(vec![false, false]))]
59    fn test_cast_bool_conformance(#[case] array: BoolArray) {
60        test_cast_conformance(array.as_ref());
61    }
62}