polars_core/scalar/
new.rs1use 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 #[cfg(feature = "dtype-array")]
46 pub fn new_array(values: Series, width: usize) -> Self {
47 Scalar::new(
48 DataType::Array(Box::new(values.dtype().clone()), width),
49 AnyValue::Array(values, width),
50 )
51 }
52
53 #[cfg(feature = "dtype-decimal")]
54 pub fn new_decimal(value: i128, scale: usize) -> Self {
55 Scalar::new(
56 DataType::Decimal(Some(38), Some(scale)),
57 AnyValue::Decimal(value, scale),
58 )
59 }
60
61 #[cfg(feature = "dtype-categorical")]
62 pub fn new_enum(
63 value: polars_dtype::categorical::CatSize,
64 categories: &arrow::array::Utf8ViewArray,
65 ) -> PolarsResult<Self> {
66 use arrow::array::Array;
67 use polars_dtype::categorical::FrozenCategories;
68
69 assert_eq!(categories.null_count(), 0);
70
71 let categories = FrozenCategories::new(categories.values_iter())?;
72 let mapping = categories.mapping();
73 Ok(Scalar::new(
74 DataType::Enum(categories.clone(), mapping.clone()),
75 AnyValue::EnumOwned(value, mapping.clone()),
76 ))
77 }
78
79 #[cfg(feature = "dtype-categorical")]
80 pub fn new_categorical(
81 value: &str,
82 name: PlSmallStr,
83 namespace: PlSmallStr,
84 physical: polars_dtype::categorical::CategoricalPhysical,
85 ) -> PolarsResult<Self> {
86 use polars_dtype::categorical::Categories;
87
88 let categories = Categories::new(name, namespace, physical);
89 let dt_mapping = categories.mapping();
90 let av_mapping = categories.mapping();
91
92 let value = av_mapping.insert_cat(value)?;
93
94 Ok(Scalar::new(
95 DataType::Categorical(categories, dt_mapping),
96 AnyValue::CategoricalOwned(value, av_mapping),
97 ))
98 }
99}