Skip to main content

polars_core/datatypes/
into_scalar.rs

1use polars_error::{PolarsResult, polars_bail};
2#[cfg(feature = "dtype-f16")]
3use polars_utils::float16::pf16;
4
5use super::{AnyValue, DataType, Scalar};
6
7pub trait IntoScalar {
8    fn into_scalar(self, dtype: DataType) -> PolarsResult<Scalar>;
9}
10
11macro_rules! impl_into_scalar {
12    ($(
13        $ty:ty: ($($dt:pat),+ $(,)?),
14    )+) => {
15        $(
16        impl IntoScalar for $ty {
17            fn into_scalar(self, dtype: DataType) -> PolarsResult<Scalar> {
18                Ok(match &dtype {
19                    T::Null => Scalar::new(dtype, AnyValue::Null),
20                    $($dt => Scalar::new(dtype, self.into()),)+
21                    _ => polars_bail!(InvalidOperation: "Cannot cast `{}` to `Scalar` with dtype={dtype}", stringify!($ty)),
22                })
23            }
24        }
25        )+
26    };
27}
28
29use DataType as T;
30impl_into_scalar! {
31    bool: (T::Boolean),
32    u8: (T::UInt8),
33    u16: (T::UInt16),
34    u32: (T::UInt32), // T::Categorical, T::Enum
35    u64: (T::UInt64),
36    i8: (T::Int8),
37    i16: (T::Int16),
38    i32: (T::Int32), // T::Date
39    i64: (T::Int64), // T::Datetime, T::Duration, T::Time
40    f32: (T::Float32),
41    f64: (T::Float64),
42    // Vec<u8>: (T::Binary),
43    // String: (T::String),
44    // Series: (T::List, T::Array),
45    // /// Can be used to fmt and implements Any, so can be downcasted to the proper value type.
46    // #[cfg(feature = "object")]
47    // Object(&'a dyn PolarsObjectSafe),
48    // #[cfg(feature = "object")]
49    // ObjectOwned(OwnedObject),
50    // #[cfg(feature = "dtype-struct")]
51    // // 3 pointers and thus not larger than string/vec
52    // // - idx in the `&StructArray`
53    // // - The array itself
54    // // - The fields
55    // Struct(usize, &'a StructArray, &'a [Field]),
56    // #[cfg(feature = "dtype-struct")]
57    // StructOwned(Box<(Vec<AnyValue<'a>>, Vec<Field>)>),
58}
59
60#[cfg(feature = "dtype-f16")]
61impl_into_scalar! {
62    pf16: (T::Float16),
63}
64
65#[cfg(feature = "dtype-u128")]
66impl_into_scalar! {
67    u128: (T::UInt128),
68}
69
70#[cfg(feature = "dtype-i128")]
71impl_into_scalar! {
72    i128: (T::Int128), // T::Decimal
73}