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;
9use crate::arrays::BoolVTable;
10use crate::compute::CastKernel;
11use crate::compute::CastKernelAdapter;
12use crate::register_kernel;
13use crate::vtable::ValidityHelper;
14
15impl CastKernel for BoolVTable {
16    fn cast(&self, array: &BoolArray, dtype: &DType) -> VortexResult<Option<ArrayRef>> {
17        if !matches!(dtype, DType::Bool(_)) {
18            return Ok(None);
19        }
20
21        let new_nullability = dtype.nullability();
22        let new_validity = array
23            .validity()
24            .clone()
25            .cast_nullability(new_nullability, array.len())?;
26        Ok(Some(
27            BoolArray::from_bit_buffer(array.bit_buffer().clone(), new_validity).to_array(),
28        ))
29    }
30}
31
32register_kernel!(CastKernelAdapter(BoolVTable).lift());
33
34#[cfg(test)]
35mod tests {
36    use rstest::rstest;
37    use vortex_dtype::DType;
38    use vortex_dtype::Nullability;
39
40    use crate::arrays::BoolArray;
41    use crate::compute::cast;
42    use crate::compute::conformance::cast::test_cast_conformance;
43
44    #[test]
45    fn try_cast_bool_success() {
46        let bool = BoolArray::from_iter(vec![Some(true), Some(false), Some(true)]);
47
48        let res = cast(bool.as_ref(), &DType::Bool(Nullability::NonNullable));
49        assert!(res.is_ok());
50        assert_eq!(res.unwrap().dtype(), &DType::Bool(Nullability::NonNullable));
51    }
52
53    #[test]
54    #[should_panic]
55    fn try_cast_bool_fail() {
56        let bool = BoolArray::from_iter(vec![Some(true), Some(false), None]);
57        cast(bool.as_ref(), &DType::Bool(Nullability::NonNullable)).unwrap();
58    }
59
60    #[rstest]
61    #[case(BoolArray::from_iter(vec![true, false, true, true, false]))]
62    #[case(BoolArray::from_iter(vec![Some(true), Some(false), None, Some(true), None]))]
63    #[case(BoolArray::from_iter(vec![true]))]
64    #[case(BoolArray::from_iter(vec![false, false]))]
65    fn test_cast_bool_conformance(#[case] array: BoolArray) {
66        test_cast_conformance(array.as_ref());
67    }
68}