Skip to main content

tpack_core/native/
primitives.rs

1use crate::{Decimal, Result, Schema, TpackValue, TypeDescriptor};
2
3use super::helpers::{deserialize_via_from_value, type_mismatch};
4use super::{FromTpackValue, TpackDeserialize, TpackSerialize};
5
6macro_rules! impl_scalar {
7    ($ty:ty, $variant:ident, $desc:ident, $name:literal) => {
8        impl TpackSerialize for $ty {
9            fn schema() -> Schema {
10                Schema::new(TypeDescriptor::$desc)
11            }
12
13            fn to_value(&self) -> TpackValue<'_> {
14                TpackValue::$variant(*self)
15            }
16        }
17
18        impl<'de> TpackDeserialize<'de> for $ty {
19            fn schema() -> Schema {
20                <Self as TpackSerialize>::schema()
21            }
22
23            fn from_value(value: TpackValue<'de>) -> Result<Self> {
24                deserialize_via_from_value(value)
25            }
26        }
27
28        impl<'de> FromTpackValue<'de> for $ty {
29            fn from_value(value: TpackValue<'de>) -> Result<Self> {
30                match value {
31                    TpackValue::$variant(value) => Ok(value),
32                    _ => Err(type_mismatch($name)),
33                }
34            }
35        }
36    };
37}
38
39impl_scalar!(bool, Bool, Bool, "Bool");
40impl_scalar!(i8, I8, I8, "I8");
41impl_scalar!(i16, I16, I16, "I16");
42impl_scalar!(i32, I32, I32, "I32");
43impl_scalar!(i64, I64, I64, "I64");
44impl_scalar!(u8, U8, U8, "U8");
45impl_scalar!(u16, U16, U16, "U16");
46impl_scalar!(u32, U32, U32, "U32");
47impl_scalar!(u64, U64, U64, "U64");
48impl_scalar!(f32, F32, F32, "F32");
49impl_scalar!(f64, F64, F64, "F64");
50impl_scalar!(Decimal, Decimal, Decimal, "Decimal");