1pub use primitive_types::{U256, U512};
21
22#[cfg(test)]
23mod tests {
24 use super::*;
25 use codec::{Decode, Encode};
26
27 macro_rules! test {
28 ($name: ident, $test_name: ident) => {
29 #[test]
30 fn $test_name() {
31 let tests = vec![
32 ($name::from(0), "0x0"),
33 ($name::from(1), "0x1"),
34 ($name::from(2), "0x2"),
35 ($name::from(10), "0xa"),
36 ($name::from(15), "0xf"),
37 ($name::from(16), "0x10"),
38 ($name::from(1_000), "0x3e8"),
39 ($name::from(100_000), "0x186a0"),
40 ($name::from(u64::MAX), "0xffffffffffffffff"),
41 ($name::from(u64::MAX) + $name::from(1), "0x10000000000000000"),
42 ];
43
44 for (number, expected) in tests {
45 assert_eq!(
46 format!("{:?}", expected),
47 serde_json::to_string_pretty(&number).expect("Json pretty print failed")
48 );
49 assert_eq!(number, serde_json::from_str(&format!("{:?}", expected)).unwrap());
50 }
51
52 assert!(serde_json::from_str::<$name>("\"0x\"").unwrap_err().is_data());
54 assert!(serde_json::from_str::<$name>("\"0xg\"").unwrap_err().is_data());
55 assert!(serde_json::from_str::<$name>("\"\"").unwrap_err().is_data());
56 }
57 };
58 }
59
60 test!(U256, test_u256);
61
62 #[test]
63 fn test_u256_codec() {
64 let res1 = vec![
65 120, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
66 0, 0, 0, 0,
67 ];
68 let res2 = vec![
69 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
70 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
71 0xff, 0xff, 0xff, 0xff,
72 ];
73
74 assert_eq!(U256::from(120).encode(), res1);
75 assert_eq!(U256::max_value().encode(), res2);
76 assert_eq!(U256::decode(&mut &res1[..]), Ok(U256::from(120)));
77 assert_eq!(U256::decode(&mut &res2[..]), Ok(U256::max_value()));
78 }
79
80 #[test]
81 fn test_large_values() {
82 assert_eq!(
83 serde_json::to_string_pretty(&!U256::zero()).expect("Json pretty print failed"),
84 "\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\""
85 );
86 assert!(serde_json::from_str::<U256>(
87 "\"0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\""
88 )
89 .unwrap_err()
90 .is_data());
91 }
92}