polars_core/datatypes/
into_scalar.rs1use 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), u64: (T::UInt64),
36 i8: (T::Int8),
37 i16: (T::Int16),
38 i32: (T::Int32), i64: (T::Int64), f32: (T::Float32),
41 f64: (T::Float64),
42 }
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), }