af_move_type/
vector.rs

1use af_sui_types::TypeTag;
2use derive_more::{Deref, DerefMut, From, Into};
3use derive_where::derive_where;
4use serde::{Deserialize, Serialize};
5
6use crate::{MoveType, ParseTypeTagError, StaticTypeTag, TypeTagError};
7
8#[derive(
9    Clone, Debug, Deref, DerefMut, Deserialize, From, Into, Serialize, PartialEq, Eq, Hash,
10)]
11#[serde(bound(deserialize = ""))]
12pub struct MoveVec<T: MoveType>(Vec<T>);
13
14impl<T: MoveType> MoveVec<T> {
15    pub fn into_inner(self) -> Vec<T> {
16        self.0
17    }
18}
19
20impl<T: MoveType> MoveType for MoveVec<T> {
21    type TypeTag = VecTypeTag<T>;
22}
23
24impl<T: StaticTypeTag> StaticTypeTag for MoveVec<T> {
25    fn type_() -> Self::TypeTag {
26        VecTypeTag(T::type_())
27    }
28}
29
30impl<T: MoveType> std::fmt::Display for MoveVec<T> {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        use tabled::Table;
33        use tabled::settings::style::Style;
34        use tabled::settings::{Rotate, Settings};
35
36        let mut table = Table::from_iter([self.iter().map(|e| e.to_string())]);
37        let settings = Settings::default()
38            .with(Rotate::Right)
39            .with(Style::rounded().remove_horizontals());
40        table.with(settings);
41        write!(f, "{table}")
42    }
43}
44
45impl<T: MoveType> std::fmt::Display for crate::MoveInstance<MoveVec<T>> {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        write!(f, "{}", self.value)
48    }
49}
50
51#[derive(Clone, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)]
52#[derive_where(PartialOrd, Ord)]
53pub struct VecTypeTag<T: MoveType>(T::TypeTag);
54
55impl<T: MoveType> From<VecTypeTag<T>> for TypeTag {
56    fn from(value: VecTypeTag<T>) -> Self {
57        Self::Vector(Box::new(value.0.into()))
58    }
59}
60
61impl<T: MoveType> TryFrom<TypeTag> for VecTypeTag<T> {
62    type Error = TypeTagError;
63
64    fn try_from(value: TypeTag) -> Result<Self, Self::Error> {
65        match value {
66            TypeTag::Vector(type_) => Ok(Self((*type_).try_into()?)),
67            _ => Err(TypeTagError::Variant {
68                expected: "Vector(_)".to_owned(),
69                got: value,
70            }),
71        }
72    }
73}
74
75impl<T: MoveType> std::str::FromStr for VecTypeTag<T> {
76    type Err = ParseTypeTagError;
77
78    fn from_str(s: &str) -> Result<Self, Self::Err> {
79        let tag: TypeTag = s.parse()?;
80        Ok(tag.try_into()?)
81    }
82}