Skip to main content

af_move_type/
primitives.rs

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