1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Copyright 2015-2020 Parity Technologies
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use super::{ParamType, Reader};
use serde::{
	de::{Error as SerdeError, Visitor},
	Deserialize, Deserializer,
};
use std::fmt;

impl<'a> Deserialize<'a> for ParamType {
	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
	where
		D: Deserializer<'a>,
	{
		deserializer.deserialize_identifier(ParamTypeVisitor)
	}
}

struct ParamTypeVisitor;

impl<'a> Visitor<'a> for ParamTypeVisitor {
	type Value = ParamType;

	fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
		write!(formatter, "a correct name of abi-encodable parameter type")
	}

	fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
	where
		E: SerdeError,
	{
		Reader::read(value).map_err(|e| SerdeError::custom(format!("{:?}", e).as_str()))
	}

	fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
	where
		E: SerdeError,
	{
		self.visit_str(value.as_str())
	}
}

#[cfg(test)]
mod tests {
	use crate::ParamType;

	#[test]
	fn param_type_deserialization() {
		let s = r#"["address", "bytes", "bytes32", "bool", "string", "int", "uint", "address[]", "uint[3]", "bool[][5]", "tuple[]"]"#;
		let deserialized: Vec<ParamType> = serde_json::from_str(s).unwrap();
		assert_eq!(
			deserialized,
			vec![
				ParamType::Address,
				ParamType::Bytes,
				ParamType::FixedBytes(32),
				ParamType::Bool,
				ParamType::String,
				ParamType::Int(256),
				ParamType::Uint(256),
				ParamType::Array(Box::new(ParamType::Address)),
				ParamType::FixedArray(Box::new(ParamType::Uint(256)), 3),
				ParamType::FixedArray(Box::new(ParamType::Array(Box::new(ParamType::Bool))), 5),
				ParamType::Array(Box::new(ParamType::Tuple(vec![]))),
			]
		);
	}
}