Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pola-rs
GitHub Repository: pola-rs/polars
Path: blob/main/crates/polars-arrow/src/scalar/primitive.rs
6939 views
1
use super::Scalar;
2
use crate::datatypes::ArrowDataType;
3
use crate::types::NativeType;
4
5
/// The implementation of [`Scalar`] for primitive, semantically equivalent to [`Option<T>`]
6
/// with [`ArrowDataType`].
7
#[derive(Debug, Clone, PartialEq, Eq)]
8
pub struct PrimitiveScalar<T: NativeType> {
9
value: Option<T>,
10
dtype: ArrowDataType,
11
}
12
13
impl<T: NativeType> PrimitiveScalar<T> {
14
/// Returns a new [`PrimitiveScalar`].
15
#[inline]
16
pub fn new(dtype: ArrowDataType, value: Option<T>) -> Self {
17
if !dtype.to_physical_type().eq_primitive(T::PRIMITIVE) {
18
panic!(
19
"Type {} does not support logical type {:?}",
20
std::any::type_name::<T>(),
21
dtype
22
)
23
}
24
Self { value, dtype }
25
}
26
27
/// Returns the optional value.
28
#[inline]
29
pub fn value(&self) -> &Option<T> {
30
&self.value
31
}
32
33
/// Returns a new `PrimitiveScalar` with the same value but different [`ArrowDataType`]
34
/// # Panic
35
/// This function panics if the `dtype` is not valid for self's physical type `T`.
36
pub fn to(self, dtype: ArrowDataType) -> Self {
37
Self::new(dtype, self.value)
38
}
39
}
40
41
impl<T: NativeType> From<Option<T>> for PrimitiveScalar<T> {
42
#[inline]
43
fn from(v: Option<T>) -> Self {
44
Self::new(T::PRIMITIVE.into(), v)
45
}
46
}
47
48
impl<T: NativeType> Scalar for PrimitiveScalar<T> {
49
#[inline]
50
fn as_any(&self) -> &dyn std::any::Any {
51
self
52
}
53
54
#[inline]
55
fn is_valid(&self) -> bool {
56
self.value.is_some()
57
}
58
59
#[inline]
60
fn dtype(&self) -> &ArrowDataType {
61
&self.dtype
62
}
63
}
64
65