Skip to main content

polars_core/scalar/
new.rs

1use std::sync::Arc;
2
3use polars_error::PolarsResult;
4use polars_utils::pl_str::PlSmallStr;
5
6use super::Scalar;
7use crate::datatypes::time_unit::TimeUnit;
8use crate::prelude::{AnyValue, DataType, TimeZone};
9use crate::series::Series;
10
11impl Scalar {
12    #[cfg(feature = "dtype-date")]
13    pub fn new_date(value: i32) -> Self {
14        Scalar::new(DataType::Date, AnyValue::Date(value))
15    }
16
17    #[cfg(feature = "dtype-datetime")]
18    pub fn new_datetime(value: i64, time_unit: TimeUnit, tz: Option<TimeZone>) -> Self {
19        Scalar::new(
20            DataType::Datetime(time_unit, tz.clone()),
21            AnyValue::DatetimeOwned(value, time_unit, tz.map(Arc::new)),
22        )
23    }
24
25    #[cfg(feature = "dtype-duration")]
26    pub fn new_duration(value: i64, time_unit: TimeUnit) -> Self {
27        Scalar::new(
28            DataType::Duration(time_unit),
29            AnyValue::Duration(value, time_unit),
30        )
31    }
32
33    #[cfg(feature = "dtype-time")]
34    pub fn new_time(value: i64) -> Self {
35        Scalar::new(DataType::Time, AnyValue::Time(value))
36    }
37
38    pub fn new_list(values: Series) -> Self {
39        Scalar::new(
40            DataType::List(Box::new(values.dtype().clone())),
41            AnyValue::List(values),
42        )
43    }
44
45    /// One `Map` row from its flat key and value fields.
46    ///
47    /// Validation is deferred to `Series::from_any_values_and_dtype`, which calls
48    /// `MapChunked::try_from_storage`. Other consumers only read the entries.
49    #[cfg(feature = "dtype-map")]
50    pub fn new_map(keys: &Series, values: &Series) -> Self {
51        Scalar::new(
52            DataType::Map(
53                Box::new(keys.dtype().clone()),
54                Box::new(values.dtype().clone()),
55            ),
56            AnyValue::Map(crate::chunked_array::logical::pack_map_entries(
57                keys, values,
58            )),
59        )
60    }
61
62    /// For callers that already hold one row's entries, such as deserialization.
63    #[cfg(feature = "dtype-map")]
64    pub(crate) fn map_from_entries(entries: Series) -> Self {
65        let value = AnyValue::Map(entries);
66        Scalar::new(value.dtype(), value)
67    }
68
69    #[cfg(feature = "dtype-array")]
70    pub fn new_array(values: Series, width: usize) -> Self {
71        Scalar::new(
72            DataType::Array(Box::new(values.dtype().clone()), width),
73            AnyValue::Array(values, width),
74        )
75    }
76
77    #[cfg(feature = "dtype-decimal")]
78    pub fn new_decimal(value: i128, precision: usize, scale: usize) -> Self {
79        Scalar::new(
80            DataType::Decimal(precision, scale),
81            AnyValue::Decimal(value, precision, scale),
82        )
83    }
84
85    #[cfg(feature = "dtype-categorical")]
86    pub fn new_enum(
87        value: polars_dtype::categorical::CatSize,
88        categories: &polars_arrow::array::Utf8ViewArray,
89    ) -> PolarsResult<Self> {
90        use polars_arrow::array::Array;
91        use polars_dtype::categorical::FrozenCategories;
92
93        assert_eq!(categories.null_count(), 0);
94
95        let categories = FrozenCategories::new(categories.values_iter())?;
96        let mapping = categories.mapping();
97        Ok(Scalar::new(
98            DataType::Enum(categories.clone(), mapping.clone()),
99            AnyValue::EnumOwned(value, mapping.clone()),
100        ))
101    }
102
103    #[cfg(feature = "dtype-categorical")]
104    pub fn new_categorical(
105        value: &str,
106        name: PlSmallStr,
107        namespace: PlSmallStr,
108        physical: polars_dtype::categorical::CategoricalPhysical,
109    ) -> PolarsResult<Self> {
110        use polars_dtype::categorical::Categories;
111
112        let categories = Categories::new(name, namespace, physical);
113        let dt_mapping = categories.mapping();
114        let av_mapping = categories.mapping();
115
116        let value = av_mapping.insert_cat(value)?;
117
118        Ok(Scalar::new(
119            DataType::Categorical(categories, dt_mapping),
120            AnyValue::CategoricalOwned(value, av_mapping),
121        ))
122    }
123}