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    #[inline(always)]
34    pub fn is_null(&self) -> bool {
35        self.value.is_null()
36    }
37
38    #[inline(always)]
39    pub fn is_nan(&self) -> bool {
40        self.value.is_nan()
41    }
42
43    #[inline(always)]
44    pub fn value(&self) -> &AnyValue<'static> {
45        &self.value
46    }
47
48    pub fn as_any_value(&self) -> AnyValue {
49        self.value
50            .strict_cast(&self.dtype)
51            .unwrap_or_else(|| self.value.clone())
52    }
53
54    pub fn into_series(self, name: PlSmallStr) -> Series {
55        Series::from_any_values_and_dtype(name, &[self.as_any_value()], &self.dtype, true).unwrap()
56    }
57
58    /// Turn a scalar into a column with `length=1`.
59    pub fn into_column(self, name: PlSmallStr) -> Column {
60        Column::new_scalar(name, self, 1)
61    }
62
63    #[inline(always)]
64    pub fn dtype(&self) -> &DataType {
65        &self.dtype
66    }
67
68    #[inline(always)]
69    pub fn update(&mut self, value: AnyValue<'static>) {
70        self.value = value;
71    }
72}