polars_core/scalar/
mod.rs

1mod from;
2pub mod reduce;
3
4use polars_utils::pl_str::PlSmallStr;
5#[cfg(feature = "serde")]
6use serde::{Deserialize, Serialize};
7
8use crate::datatypes::{AnyValue, DataType};
9use crate::prelude::{Column, Series};
10
11#[derive(Clone, Debug, PartialEq)]
12#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
13pub struct Scalar {
14    dtype: DataType,
15    value: AnyValue<'static>,
16}
17
18impl Default for Scalar {
19    fn default() -> Self {
20        Self {
21            dtype: DataType::Null,
22            value: AnyValue::Null,
23        }
24    }
25}
26
27impl Scalar {
28    #[inline(always)]
29    pub fn new(dtype: DataType, value: AnyValue<'static>) -> Self {
30        Self { dtype, value }
31    }
32
33    pub fn null(dtype: DataType) -> Self {
34        Self::new(dtype, AnyValue::Null)
35    }
36
37    #[inline(always)]
38    pub fn is_null(&self) -> bool {
39        self.value.is_null()
40    }
41
42    #[inline(always)]
43    pub fn is_nan(&self) -> bool {
44        self.value.is_nan()
45    }
46
47    #[inline(always)]
48    pub fn into_value(self) -> AnyValue<'static> {
49        self.value
50    }
51
52    #[inline(always)]
53    pub fn value(&self) -> &AnyValue<'static> {
54        &self.value
55    }
56
57    pub fn as_any_value(&self) -> AnyValue {
58        self.value
59            .strict_cast(&self.dtype)
60            .unwrap_or_else(|| self.value.clone())
61    }
62
63    pub fn into_series(self, name: PlSmallStr) -> Series {
64        Series::from_any_values_and_dtype(name, &[self.as_any_value()], &self.dtype, true).unwrap()
65    }
66
67    /// Turn a scalar into a column with `length=1`.
68    pub fn into_column(self, name: PlSmallStr) -> Column {
69        Column::new_scalar(name, self, 1)
70    }
71
72    #[inline(always)]
73    pub fn dtype(&self) -> &DataType {
74        &self.dtype
75    }
76
77    #[inline(always)]
78    pub fn update(&mut self, value: AnyValue<'static>) {
79        self.value = value;
80    }
81
82    #[inline(always)]
83    pub fn with_value(mut self, value: AnyValue<'static>) -> Self {
84        self.update(value);
85        self
86    }
87}