Skip to main content

polars_core/scalar/
mod.rs

1mod from;
2mod new;
3#[cfg(any(feature = "serde", feature = "dsl-schema"))]
4mod serde;
5
6use std::hash::Hash;
7
8use polars_error::PolarsResult;
9use polars_utils::IdxSize;
10use polars_utils::pl_str::PlSmallStr;
11
12use crate::chunked_array::cast::CastOptions;
13use crate::datatypes::{AnyValue, DataType};
14use crate::prelude::{Column, Series};
15
16#[derive(Clone, Debug, PartialEq, Eq)]
17pub struct Scalar {
18    dtype: DataType,
19    value: AnyValue<'static>,
20}
21
22impl Hash for Scalar {
23    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
24        self.dtype.hash(state);
25        self.value.hash_impl(state, false);
26    }
27}
28
29impl Default for Scalar {
30    fn default() -> Self {
31        Self {
32            dtype: DataType::Null,
33            value: AnyValue::Null,
34        }
35    }
36}
37
38impl Scalar {
39    #[inline(always)]
40    pub const fn new(dtype: DataType, value: AnyValue<'static>) -> Self {
41        Self { dtype, value }
42    }
43
44    pub const fn null(dtype: DataType) -> Self {
45        Self::new(dtype, AnyValue::Null)
46    }
47
48    pub fn new_idxsize(value: IdxSize) -> Self {
49        value.into()
50    }
51
52    pub fn cast_with_options(self, dtype: &DataType, options: CastOptions) -> PolarsResult<Self> {
53        if self.dtype() == dtype {
54            return Ok(self);
55        }
56
57        // @Optimize: If we have fully fleshed out casting semantics, we could just specify the
58        // cast on AnyValue.
59        let s = self
60            .into_series(PlSmallStr::from_static("scalar"))
61            .cast_with_options(dtype, options)?;
62        let value = s.get(0).unwrap();
63        Ok(Self::new(s.dtype().clone(), value.into_static()))
64    }
65
66    #[inline(always)]
67    pub fn is_null(&self) -> bool {
68        self.value.is_null()
69    }
70
71    #[inline(always)]
72    pub fn is_nan(&self) -> bool {
73        self.value.is_nan()
74    }
75
76    #[inline(always)]
77    pub fn into_value(self) -> AnyValue<'static> {
78        self.value
79    }
80
81    #[inline(always)]
82    pub fn value(&self) -> &AnyValue<'static> {
83        &self.value
84    }
85
86    pub fn as_any_value(&self) -> AnyValue<'_> {
87        self.value.clone()
88    }
89
90    pub fn into_series(self, name: PlSmallStr) -> Series {
91        // A Map scalar holds deduplicated keys, so its row skips deduplication.
92        // `from_any_values_and_dtype` can't skip it: Python dicts reach it with
93        // keys that collide after conversion (two NaNs, datetimes truncated to `ms`).
94        #[cfg(feature = "dtype-map")]
95        if let AnyValue::Map(entries) = &self.value
96            && let Some(map) =
97                crate::prelude::MapChunked::from_row_entries(name.clone(), &self.dtype, entries)
98        {
99            return crate::prelude::IntoSeries::into_series(map);
100        }
101        Series::from_any_values_and_dtype(name, &[self.as_any_value()], &self.dtype, true).unwrap()
102    }
103
104    /// Turn a scalar into a column with `length=1`.
105    pub fn into_column(self, name: PlSmallStr) -> Column {
106        Column::new_scalar(name, self, 1)
107    }
108
109    #[inline(always)]
110    pub fn dtype(&self) -> &DataType {
111        &self.dtype
112    }
113
114    #[inline(always)]
115    pub fn update(&mut self, value: AnyValue<'static>) {
116        self.value = value;
117    }
118
119    #[inline(always)]
120    pub fn with_value(mut self, value: AnyValue<'static>) -> Self {
121        self.update(value);
122        self
123    }
124
125    #[inline(always)]
126    pub fn any_value_mut(&mut self) -> &mut AnyValue<'static> {
127        &mut self.value
128    }
129
130    pub fn to_physical(mut self) -> Scalar {
131        self.dtype = self.dtype.to_physical();
132        self.value = self.value.to_physical();
133        self
134    }
135}
136
137#[cfg(all(test, feature = "proptest", not(miri)))]
138mod tests {
139    use std::rc::Rc;
140
141    use proptest::prelude::*;
142
143    use crate::chunked_array::cast::CastOptions;
144    use crate::datatypes::proptest::{
145        AnyValueArbitraryOptions, AnyValueArbitrarySelection, DataTypeArbitraryOptions,
146        DataTypeArbitrarySelection, anyvalue_strategy, dtypes_strategy,
147    };
148    use crate::scalar::Scalar;
149
150    fn test_anyvalue_options() -> AnyValueArbitraryOptions {
151        AnyValueArbitraryOptions {
152            allowed_dtypes: AnyValueArbitrarySelection::all()
153                & !AnyValueArbitrarySelection::CATEGORICAL
154                & !AnyValueArbitrarySelection::CATEGORICAL_OWNED
155                & !AnyValueArbitrarySelection::ENUM
156                & !AnyValueArbitrarySelection::ENUM_OWNED
157                & !AnyValueArbitrarySelection::OBJECT
158                & !AnyValueArbitrarySelection::OBJECT_OWNED
159                & !AnyValueArbitrarySelection::LIST
160                & !AnyValueArbitrarySelection::ARRAY
161                & !AnyValueArbitrarySelection::STRUCT
162                & !AnyValueArbitrarySelection::STRUCT_OWNED
163                & !AnyValueArbitrarySelection::DATETIME
164                & !AnyValueArbitrarySelection::DATETIME_OWNED
165                & !AnyValueArbitrarySelection::DATE
166                & !AnyValueArbitrarySelection::TIME
167                & !AnyValueArbitrarySelection::DURATION
168                & !AnyValueArbitrarySelection::BINARY_OWNED,
169            categories_range: 1..=3,
170            ..Default::default()
171        }
172    }
173
174    fn test_dtype_options() -> DataTypeArbitraryOptions {
175        DataTypeArbitraryOptions {
176            allowed_dtypes: DataTypeArbitrarySelection::all()
177                & !DataTypeArbitrarySelection::CATEGORICAL
178                & !DataTypeArbitrarySelection::ENUM
179                & !DataTypeArbitrarySelection::OBJECT
180                & !DataTypeArbitrarySelection::LIST
181                & !DataTypeArbitrarySelection::ARRAY
182                & !DataTypeArbitrarySelection::STRUCT
183                & !DataTypeArbitrarySelection::DATETIME
184                & !DataTypeArbitrarySelection::DATE
185                & !DataTypeArbitrarySelection::TIME
186                & !DataTypeArbitrarySelection::DURATION
187                & !DataTypeArbitrarySelection::BINARY_OFFSET,
188            categories_range: 1..=3,
189            ..Default::default()
190        }
191    }
192
193    proptest! {
194        #![proptest_config(ProptestConfig::with_cases(100))]
195        #[test]
196        fn test_scalar_cast_with_options(
197            source_value in anyvalue_strategy(Rc::new(test_anyvalue_options()), 0),
198            target_dtype in dtypes_strategy(Rc::new(test_dtype_options()), 0),
199        ) {
200            let source_dtype = source_value.dtype();
201            let scalar = Scalar::new(source_dtype.clone(), source_value.clone());
202
203            let cast_result = scalar.cast_with_options(&target_dtype, CastOptions::default());
204
205            if let Ok(casted_scalar) = cast_result {
206                prop_assert_eq!(casted_scalar.dtype(), &target_dtype);
207            }
208        }
209    }
210
211    proptest! {
212        #![proptest_config(ProptestConfig::with_cases(100))]
213        #[test]
214        fn test_scalar_cast_identity(
215            source_value in anyvalue_strategy(Rc::new(test_anyvalue_options()), 0),
216        ) {
217            let source_dtype = source_value.dtype();
218            let scalar = Scalar::new(source_dtype.clone(), source_value);
219
220            let result = scalar.clone().cast_with_options(&source_dtype, CastOptions::default());
221
222            prop_assert!(result.is_ok());
223            if let Ok(casted) = result {
224                prop_assert_eq!(casted.dtype(), scalar.dtype());
225            }
226        }
227    }
228}