Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pola-rs
GitHub Repository: pola-rs/polars
Path: blob/main/crates/polars-compute/src/cast/boolean_to.rs
6939 views
1
use arrow::array::{Array, BooleanArray, PrimitiveArray};
2
use arrow::types::NativeType;
3
use polars_error::PolarsResult;
4
5
use super::{ArrayFromIter, BinaryViewArray, Utf8ViewArray};
6
7
pub(super) fn boolean_to_primitive_dyn<T>(array: &dyn Array) -> PolarsResult<Box<dyn Array>>
8
where
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`].
16
pub fn boolean_to_primitive<T>(from: &BooleanArray) -> PrimitiveArray<T>
17
where
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
29
pub fn boolean_to_utf8view(from: &BooleanArray) -> Utf8ViewArray {
30
unsafe { boolean_to_binaryview(from).to_utf8view_unchecked() }
31
}
32
33
pub(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"`
39
pub 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
48
pub(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
}
52
53