vortex_scalar/scalar_value/
primitive.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use paste::paste;
5use vortex_dtype::half::f16;
6use vortex_error::{VortexError, vortex_err};
7
8use crate::scalar_value::InnerScalarValue;
9use crate::{PValue, ScalarValue};
10
11macro_rules! primitive_scalar {
12    ($T:ty) => {
13        impl TryFrom<&ScalarValue> for $T {
14            type Error = VortexError;
15
16            fn try_from(value: &ScalarValue) -> Result<Self, Self::Error> {
17                <Option<$T>>::try_from(value)?
18                    .ok_or_else(|| vortex_err!("Can't extract present value from null scalar"))
19            }
20        }
21
22        impl TryFrom<&ScalarValue> for Option<$T> {
23            type Error = VortexError;
24
25            fn try_from(value: &ScalarValue) -> Result<Self, Self::Error> {
26                paste! {
27                    Ok(value.as_pvalue()?.and_then(|v| v.[<as_ $T>]()))
28                }
29            }
30        }
31
32        impl From<$T> for ScalarValue {
33            fn from(value: $T) -> Self {
34                ScalarValue(InnerScalarValue::Primitive(value.into()))
35            }
36        }
37    };
38}
39
40primitive_scalar!(u8);
41primitive_scalar!(u16);
42primitive_scalar!(u32);
43primitive_scalar!(u64);
44primitive_scalar!(i8);
45primitive_scalar!(i16);
46primitive_scalar!(i32);
47primitive_scalar!(i64);
48primitive_scalar!(f16);
49primitive_scalar!(f32);
50primitive_scalar!(f64);
51
52/// Read a scalar as usize. For usize only, we implicitly cast for better ergonomics.
53impl TryFrom<&ScalarValue> for usize {
54    type Error = VortexError;
55
56    fn try_from(value: &ScalarValue) -> Result<Self, Self::Error> {
57        let prim = value
58            .as_pvalue()?
59            .and_then(|v| v.as_u64())
60            .ok_or_else(|| vortex_err!("cannot convert Null to usize"))?;
61        Ok(usize::try_from(prim)?)
62    }
63}
64
65impl From<PValue> for ScalarValue {
66    fn from(value: PValue) -> Self {
67        ScalarValue(InnerScalarValue::Primitive(value))
68    }
69}
70
71/// Read a scalar as usize. For usize only, we implicitly cast for better ergonomics.
72impl From<usize> for ScalarValue {
73    fn from(value: usize) -> Self {
74        ScalarValue(InnerScalarValue::Primitive((value as u64).into()))
75    }
76}