ethabi_next/param_type/
writer.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 crate::ParamType;
10
11/// Output formatter for param type.
12pub struct Writer;
13
14impl Writer {
15	/// Returns string which is a formatted represenation of param.
16	pub fn write(param: &ParamType) -> String {
17		match *param {
18			ParamType::Address => "address".to_owned(),
19			ParamType::Bytes => "bytes".to_owned(),
20			ParamType::FixedBytes(len) => format!("bytes{}", len),
21			ParamType::Int(len) => format!("int{}", len),
22			ParamType::Uint(len) => format!("uint{}", len),
23			ParamType::Bool => "bool".to_owned(),
24			ParamType::String => "string".to_owned(),
25			ParamType::FixedArray(ref param, len) => format!("{}[{}]", Writer::write(param), len),
26			ParamType::Array(ref param) => format!("{}[]", Writer::write(param)),
27			ParamType::Tuple(ref params) => {
28				format!("({})", params.iter().map(|ref t| format!("{}", t)).collect::<Vec<String>>().join(","))
29			}
30		}
31	}
32}
33
34#[cfg(test)]
35mod tests {
36	use super::Writer;
37	use crate::ParamType;
38
39	#[test]
40	fn test_write_param() {
41		assert_eq!(Writer::write(&ParamType::Address), "address".to_owned());
42		assert_eq!(Writer::write(&ParamType::Bytes), "bytes".to_owned());
43		assert_eq!(Writer::write(&ParamType::FixedBytes(32)), "bytes32".to_owned());
44		assert_eq!(Writer::write(&ParamType::Uint(256)), "uint256".to_owned());
45		assert_eq!(Writer::write(&ParamType::Int(64)), "int64".to_owned());
46		assert_eq!(Writer::write(&ParamType::Bool), "bool".to_owned());
47		assert_eq!(Writer::write(&ParamType::String), "string".to_owned());
48		assert_eq!(Writer::write(&ParamType::Array(Box::new(ParamType::Bool))), "bool[]".to_owned());
49		assert_eq!(Writer::write(&ParamType::FixedArray(Box::new(ParamType::String), 2)), "string[2]".to_owned());
50		assert_eq!(
51			Writer::write(&ParamType::FixedArray(Box::new(ParamType::Array(Box::new(ParamType::Bool))), 2)),
52			"bool[][2]".to_owned()
53		);
54		assert_eq!(
55			Writer::write(&ParamType::Array(Box::new(ParamType::Tuple(vec![
56				ParamType::Array(Box::new(ParamType::Tuple(vec![ParamType::Int(256), ParamType::Uint(256)]))),
57				ParamType::FixedBytes(32),
58			])))),
59			"((int256,uint256)[],bytes32)[]".to_owned()
60		);
61	}
62}