ethabi_next/param_type/
deserialize.rs

1// Copyright 2015-2020 Parity Technologies
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9use super::{ParamType, Reader};
10use serde::{
11	de::{Error as SerdeError, Visitor},
12	Deserialize, Deserializer,
13};
14use std::fmt;
15
16impl<'a> Deserialize<'a> for ParamType {
17	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
18	where
19		D: Deserializer<'a>,
20	{
21		deserializer.deserialize_identifier(ParamTypeVisitor)
22	}
23}
24
25struct ParamTypeVisitor;
26
27impl<'a> Visitor<'a> for ParamTypeVisitor {
28	type Value = ParamType;
29
30	fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
31		write!(formatter, "a correct name of abi-encodable parameter type")
32	}
33
34	fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
35	where
36		E: SerdeError,
37	{
38		Reader::read(value).map_err(|e| SerdeError::custom(format!("{:?}", e).as_str()))
39	}
40
41	fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
42	where
43		E: SerdeError,
44	{
45		self.visit_str(value.as_str())
46	}
47}
48
49#[cfg(test)]
50mod tests {
51	use crate::ParamType;
52
53	#[test]
54	fn param_type_deserialization() {
55		let s = r#"["address", "bytes", "bytes32", "bool", "string", "int", "uint", "address[]", "uint[3]", "bool[][5]", "tuple[]"]"#;
56		let deserialized: Vec<ParamType> = serde_json::from_str(s).unwrap();
57		assert_eq!(
58			deserialized,
59			vec![
60				ParamType::Address,
61				ParamType::Bytes,
62				ParamType::FixedBytes(32),
63				ParamType::Bool,
64				ParamType::String,
65				ParamType::Int(256),
66				ParamType::Uint(256),
67				ParamType::Array(Box::new(ParamType::Address)),
68				ParamType::FixedArray(Box::new(ParamType::Uint(256)), 3),
69				ParamType::FixedArray(Box::new(ParamType::Array(Box::new(ParamType::Bool))), 5),
70				ParamType::Array(Box::new(ParamType::Tuple(vec![]))),
71			]
72		);
73	}
74}