polars_core/datatypes/
into_scalar.rs

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