outmove_common/types/
value.rs

1// Copyright (c) The Diem Core Contributors
2// SPDX-License-Identifier: Apache-2.0
3
4use super::account_address::AccountAddress;
5use anyhow::Result as AResult;
6use serde::{
7    de::Error as DeError,
8    ser::{SerializeSeq, SerializeTuple},
9    Deserialize, Serialize,
10};
11use std::fmt::{self, Debug};
12
13#[derive(Debug, PartialEq, Eq, Clone)]
14pub struct MoveStruct(Vec<MoveValue>);
15
16#[derive(Debug, PartialEq, Eq, Clone)]
17pub enum MoveValue {
18    U8(u8),
19    U64(u64),
20    U128(u128),
21    Bool(bool),
22    Address(AccountAddress),
23    Vector(Vec<MoveValue>),
24    Struct(MoveStruct),
25    Signer(AccountAddress),
26}
27
28#[derive(Debug, Clone, Serialize, Deserialize)]
29pub struct MoveStructLayout(Vec<MoveTypeLayout>);
30
31#[derive(Debug, Clone, Serialize, Deserialize)]
32pub enum MoveTypeLayout {
33    Bool,
34    U8,
35    U64,
36    U128,
37    Address,
38    Vector(Box<MoveTypeLayout>),
39    Struct(MoveStructLayout),
40    Signer,
41}
42
43impl MoveValue {
44    pub fn simple_deserialize(blob: &[u8], ty: &MoveTypeLayout) -> AResult<Self> {
45        Ok(bcs::from_bytes_seed(ty, blob)?)
46    }
47
48    pub fn simple_serialize(&self) -> Option<Vec<u8>> {
49        bcs::to_bytes(self).ok()
50    }
51
52    pub fn vector_u8(v: Vec<u8>) -> Self {
53        MoveValue::Vector(v.into_iter().map(MoveValue::U8).collect())
54    }
55}
56
57pub fn serialize_values<'a, I>(vals: I) -> Vec<Vec<u8>>
58where
59    I: IntoIterator<Item = &'a MoveValue>,
60{
61    vals.into_iter()
62        .map(|val| {
63            val.simple_serialize()
64                .expect("serialization should succeed")
65        })
66        .collect()
67}
68
69impl MoveStruct {
70    pub fn new(value: Vec<MoveValue>) -> Self {
71        MoveStruct(value)
72    }
73
74    pub fn simple_deserialize(blob: &[u8], ty: &MoveStructLayout) -> AResult<Self> {
75        Ok(bcs::from_bytes_seed(ty, blob)?)
76    }
77
78    pub fn fields(&self) -> &[MoveValue] {
79        &self.0
80    }
81
82    pub fn into_inner(self) -> Vec<MoveValue> {
83        self.0
84    }
85}
86
87impl MoveStructLayout {
88    pub fn new(types: Vec<MoveTypeLayout>) -> Self {
89        MoveStructLayout(types)
90    }
91    pub fn fields(&self) -> &[MoveTypeLayout] {
92        &self.0
93    }
94}
95
96impl<'d> serde::de::DeserializeSeed<'d> for &MoveTypeLayout {
97    type Value = MoveValue;
98
99    fn deserialize<D: serde::de::Deserializer<'d>>(
100        self,
101        deserializer: D,
102    ) -> Result<Self::Value, D::Error> {
103        match self {
104            MoveTypeLayout::Bool => bool::deserialize(deserializer).map(MoveValue::Bool),
105            MoveTypeLayout::U8 => u8::deserialize(deserializer).map(MoveValue::U8),
106            MoveTypeLayout::U64 => u64::deserialize(deserializer).map(MoveValue::U64),
107            MoveTypeLayout::U128 => u128::deserialize(deserializer).map(MoveValue::U128),
108            MoveTypeLayout::Address => {
109                AccountAddress::deserialize(deserializer).map(MoveValue::Address)
110            }
111            MoveTypeLayout::Signer => {
112                AccountAddress::deserialize(deserializer).map(MoveValue::Signer)
113            }
114            MoveTypeLayout::Struct(ty) => Ok(MoveValue::Struct(ty.deserialize(deserializer)?)),
115            MoveTypeLayout::Vector(layout) => Ok(MoveValue::Vector(
116                deserializer.deserialize_seq(VectorElementVisitor(layout))?,
117            )),
118        }
119    }
120}
121
122struct VectorElementVisitor<'a>(&'a MoveTypeLayout);
123
124impl<'d, 'a> serde::de::Visitor<'d> for VectorElementVisitor<'a> {
125    type Value = Vec<MoveValue>;
126
127    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
128        formatter.write_str("Vector")
129    }
130
131    fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
132    where
133        A: serde::de::SeqAccess<'d>,
134    {
135        let mut vals = Vec::new();
136        while let Some(elem) = seq.next_element_seed(self.0)? {
137            vals.push(elem)
138        }
139        Ok(vals)
140    }
141}
142
143struct StructFieldVisitor<'a>(&'a [MoveTypeLayout]);
144
145impl<'d, 'a> serde::de::Visitor<'d> for StructFieldVisitor<'a> {
146    type Value = Vec<MoveValue>;
147
148    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
149        formatter.write_str("Struct")
150    }
151
152    fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
153    where
154        A: serde::de::SeqAccess<'d>,
155    {
156        let mut val = Vec::new();
157        for (i, field_type) in self.0.iter().enumerate() {
158            match seq.next_element_seed(field_type)? {
159                Some(elem) => val.push(elem),
160                None => return Err(A::Error::invalid_length(i, &self)),
161            }
162        }
163        Ok(val)
164    }
165}
166
167impl<'d> serde::de::DeserializeSeed<'d> for &MoveStructLayout {
168    type Value = MoveStruct;
169
170    fn deserialize<D: serde::de::Deserializer<'d>>(
171        self,
172        deserializer: D,
173    ) -> Result<Self::Value, D::Error> {
174        let layout = &self.0;
175        let fields = deserializer.deserialize_tuple(layout.len(), StructFieldVisitor(layout))?;
176        Ok(MoveStruct(fields))
177    }
178}
179
180impl serde::Serialize for MoveValue {
181    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
182        match self {
183            MoveValue::Struct(s) => s.serialize(serializer),
184            MoveValue::Bool(b) => serializer.serialize_bool(*b),
185            MoveValue::U8(i) => serializer.serialize_u8(*i),
186            MoveValue::U64(i) => serializer.serialize_u64(*i),
187            MoveValue::U128(i) => serializer.serialize_u128(*i),
188            MoveValue::Address(a) => a.serialize(serializer),
189            MoveValue::Signer(a) => a.serialize(serializer),
190            MoveValue::Vector(v) => {
191                let mut t = serializer.serialize_seq(Some(v.len()))?;
192                for val in v {
193                    t.serialize_element(val)?;
194                }
195                t.end()
196            }
197        }
198    }
199}
200
201impl serde::Serialize for MoveStruct {
202    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
203        let mut t = serializer.serialize_tuple(self.0.len())?;
204        for v in self.0.iter() {
205            t.serialize_element(v)?;
206        }
207        t.end()
208    }
209}