polars_ops/chunked_array/binary/
cast_binary_to_numerical.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
use arrow::array::{Array, BinaryViewArray, PrimitiveArray};
use arrow::datatypes::ArrowDataType;
use arrow::types::NativeType;
use polars_error::PolarsResult;

/// Trait for casting bytes to a primitive type
pub trait Cast {
    fn cast_le(val: &[u8]) -> Option<Self>
    where
        Self: Sized;
    fn cast_be(val: &[u8]) -> Option<Self>
    where
        Self: Sized;
}
macro_rules! impl_cast {
    ($primitive_type:ident) => {
        impl Cast for $primitive_type {
            fn cast_le(val: &[u8]) -> Option<Self> {
                Some($primitive_type::from_le_bytes(val.try_into().ok()?))
            }

            fn cast_be(val: &[u8]) -> Option<Self> {
                Some($primitive_type::from_be_bytes(val.try_into().ok()?))
            }
        }
    };
}

impl_cast!(i8);
impl_cast!(i16);
impl_cast!(i32);
impl_cast!(i64);
impl_cast!(i128);
impl_cast!(u8);
impl_cast!(u16);
impl_cast!(u32);
impl_cast!(u64);
impl_cast!(u128);
impl_cast!(f32);
impl_cast!(f64);

/// Casts a [`BinaryArray`] to a [`PrimitiveArray`], making any uncastable value a Null.
pub(super) fn cast_binview_to_primitive<T>(
    from: &BinaryViewArray,
    to: &ArrowDataType,
    is_little_endian: bool,
) -> PrimitiveArray<T>
where
    T: Cast + NativeType,
{
    let iter = from.iter().map(|x| {
        x.and_then::<T, _>(|x| {
            if is_little_endian {
                T::cast_le(x)
            } else {
                T::cast_be(x)
            }
        })
    });

    PrimitiveArray::<T>::from_trusted_len_iter(iter).to(to.clone())
}

/// Casts a [`BinaryArray`] to a [`PrimitiveArray`], making any uncastable value a Null.
pub(super) fn cast_binview_to_primitive_dyn<T>(
    from: &dyn Array,
    to: &ArrowDataType,
    is_little_endian: bool,
) -> PolarsResult<Box<dyn Array>>
where
    T: Cast + NativeType,
{
    let from = from.as_any().downcast_ref().unwrap();

    Ok(Box::new(cast_binview_to_primitive::<T>(
        from,
        to,
        is_little_endian,
    )))
}