Skip to main content

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