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