polars_compute/cast/
boolean_to.rs

1use arrow::array::{Array, BooleanArray, PrimitiveArray};
2use arrow::types::NativeType;
3use polars_error::PolarsResult;
4
5use super::{ArrayFromIter, BinaryViewArray, Utf8ViewArray};
6
7pub(super) fn boolean_to_primitive_dyn<T>(array: &dyn Array) -> PolarsResult<Box<dyn Array>>
8where
9    T: NativeType + num_traits::One,
10{
11    let array = array.as_any().downcast_ref().unwrap();
12    Ok(Box::new(boolean_to_primitive::<T>(array)))
13}
14
15/// Casts the [`BooleanArray`] to a [`PrimitiveArray`].
16pub fn boolean_to_primitive<T>(from: &BooleanArray) -> PrimitiveArray<T>
17where
18    T: NativeType + num_traits::One,
19{
20    let values = from
21        .values()
22        .iter()
23        .map(|x| if x { T::one() } else { T::default() })
24        .collect::<Vec<_>>();
25
26    PrimitiveArray::<T>::new(T::PRIMITIVE.into(), values.into(), from.validity().cloned())
27}
28
29pub fn boolean_to_utf8view(from: &BooleanArray) -> Utf8ViewArray {
30    unsafe { boolean_to_binaryview(from).to_utf8view_unchecked() }
31}
32
33pub(super) fn boolean_to_utf8view_dyn(array: &dyn Array) -> PolarsResult<Box<dyn Array>> {
34    let array = array.as_any().downcast_ref().unwrap();
35    Ok(boolean_to_utf8view(array).boxed())
36}
37
38/// Casts the [`BooleanArray`] to a [`BinaryArray`], casting trues to `"1"` and falses to `"0"`
39pub fn boolean_to_binaryview(from: &BooleanArray) -> BinaryViewArray {
40    let iter = from.iter().map(|opt_b| match opt_b {
41        Some(true) => Some("true".as_bytes()),
42        Some(false) => Some("false".as_bytes()),
43        None => None,
44    });
45    BinaryViewArray::arr_from_iter_trusted(iter)
46}
47
48pub(super) fn boolean_to_binaryview_dyn(array: &dyn Array) -> PolarsResult<Box<dyn Array>> {
49    let array = array.as_any().downcast_ref().unwrap();
50    Ok(boolean_to_binaryview(array).boxed())
51}