vortex_scalar/scalarvalue/
primitive.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
use paste::paste;
use vortex_dtype::half::f16;
use vortex_error::{vortex_err, VortexError};

use crate::scalarvalue::InnerScalarValue;
use crate::ScalarValue;

macro_rules! primitive_scalar {
    ($T:ty) => {
        impl TryFrom<&ScalarValue> for $T {
            type Error = VortexError;

            fn try_from(value: &ScalarValue) -> Result<Self, Self::Error> {
                <Option<$T>>::try_from(value)?
                    .ok_or_else(|| vortex_err!("Can't extract present value from null scalar"))
            }
        }

        impl TryFrom<&ScalarValue> for Option<$T> {
            type Error = VortexError;

            fn try_from(value: &ScalarValue) -> Result<Self, Self::Error> {
                paste! {
                    Ok(value.as_pvalue()?.and_then(|v| v.[<as_ $T>]()))
                }
            }
        }

        impl From<$T> for ScalarValue {
            fn from(value: $T) -> Self {
                ScalarValue(InnerScalarValue::Primitive(value.into()))
            }
        }
    };
}

primitive_scalar!(u8);
primitive_scalar!(u16);
primitive_scalar!(u32);
primitive_scalar!(u64);
primitive_scalar!(i8);
primitive_scalar!(i16);
primitive_scalar!(i32);
primitive_scalar!(i64);
primitive_scalar!(f16);
primitive_scalar!(f32);
primitive_scalar!(f64);

/// Read a scalar as usize. For usize only, we implicitly cast for better ergonomics.
impl TryFrom<&ScalarValue> for usize {
    type Error = VortexError;

    fn try_from(value: &ScalarValue) -> Result<Self, Self::Error> {
        let prim = value
            .as_pvalue()?
            .and_then(|v| v.as_u64())
            .ok_or_else(|| vortex_err!("cannot convert Null to usize"))?;
        Ok(usize::try_from(prim)?)
    }
}

/// Read a scalar as usize. For usize only, we implicitly cast for better ergonomics.
impl From<usize> for ScalarValue {
    fn from(value: usize) -> Self {
        ScalarValue(InnerScalarValue::Primitive((value as u64).into()))
    }
}