moverox_traits/
primitives.rs

1use std::str::FromStr;
2
3use moverox_types::{Address, TypeTag, U256};
4
5use crate::{
6    ConstTypeTag,
7    MoveDatatypeTag,
8    MoveType,
9    MoveTypeTag,
10    ParseTypeTagError,
11    TypeTagError,
12};
13
14macro_rules! impl_primitive_type_tags {
15    ($($typ:ty: ($type_tag:ident, $variant:ident)),*) => {
16        $(
17            #[derive(
18                Clone,
19                Debug,
20                PartialEq,
21                Eq,
22                Hash,
23                PartialOrd,
24                Ord,
25            )]
26            #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
27            pub struct $type_tag;
28
29            impl MoveTypeTag for $type_tag {
30                fn as_datatype_tag(&self) -> Option<&dyn MoveDatatypeTag> {
31                    None
32                }
33
34                fn from_type_tag(value: &TypeTag) -> Result<Self, TypeTagError> {
35                    match value {
36                        TypeTag::$variant => Ok(Self),
37                        _ => Err(TypeTagError::Variant {
38                            expected: stringify!($variant).to_owned(),
39                            got: crate::type_tag_variant_name(value) }
40                        )
41                    }
42                }
43
44                fn to_type_tag(&self) -> TypeTag {
45                    TypeTag::$variant
46                }
47            }
48
49            impl std::fmt::Display for $type_tag {
50                fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51                    let stag = MoveTypeTag::to_type_tag(self);
52                    write!(f, "{}", stag)
53                }
54            }
55
56            impl FromStr for $type_tag {
57                type Err = ParseTypeTagError;
58
59                fn from_str(s: &str) -> Result<Self, Self::Err> {
60                    let tag: TypeTag = s.parse().map_err(ParseTypeTagError::from_str)?;
61                    Ok(MoveTypeTag::from_type_tag(&tag)?)
62                }
63            }
64
65            impl MoveType for $typ {
66                type TypeTag = $type_tag;
67            }
68
69            impl ConstTypeTag for $typ {
70                const TYPE_TAG: $type_tag = $type_tag;
71            }
72        )*
73    };
74}
75
76impl_primitive_type_tags! {
77    Address: (AddressTypeTag, Address),
78    bool: (BoolTypeTag, Bool),
79    u8: (U8TypeTag, U8),
80    u16: (U16TypeTag, U16),
81    u32: (U32TypeTag, U32),
82    u64: (U64TypeTag, U64),
83    u128: (U128TypeTag, U128),
84    U256: (U256TypeTag, U256)
85}