1use crate::prelude::*;
2use fixed_hash::construct_fixed_hash;
3use scale::{Decode, Encode};
4use serde::{Serialize, Serializer};
5use scale_info::TypeInfo;
6
7construct_fixed_hash! {
8#[derive(Encode, Decode, TypeInfo)]
11 pub struct H256(32);
12}
13
14construct_fixed_hash! {
15#[derive(Encode, Decode, TypeInfo)]
18 pub struct H160(20);
19}
20
21impl AsRef<H160> for H160 {
22 fn as_ref(&self) -> &H160 {
23 self
24 }
25}
26
27impl AsRef<H256> for H256 {
28 fn as_ref(&self) -> &H256 {
29 self
30 }
31}
32
33impl H256 {
34 pub fn to_hex_string(&self) -> String {
35 in_to_hex_string(&self.0)
36 }
37}
38
39fn in_to_hex_string(data: &[u8]) -> String {
40 use core::fmt::Write;
41 let mut s = String::with_capacity(data.len() * 2);
42 for v in data.iter() {
43 write!(s, "{:02x}", *v).unwrap();
44 }
45 s
46}
47
48pub type Address = H160;
55
56
57impl Address {
58 pub fn to_hex_string(&self) -> String {
59 in_to_hex_string(&self.0)
60 }
61}
62
63impl Serialize for Address {
64 fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where S: Serializer {
65 serializer.serialize_str(self.to_hex_string().as_str())
66 }
67}
68
69
70impl H160 {
71 pub const fn new(val: [u8; 20]) -> Self {
72 H160(val)
73 }
74}
75
76impl H256 {
77 pub const fn new(val: [u8; 32]) -> Self {
78 H256(val)
79 }
80}
81
82impl Serialize for H256 {
83 fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where S: Serializer {
84 serializer.serialize_str(self.to_hex_string().as_str())
85 }
86}
87
88pub enum LogLevel {
90 CRITICAL,
91 ERROR,
92 WARNING,
93 NOTICE,
94 INFO,
95 DEBUG,
96}
97
98impl LogLevel {
99 pub fn to_int(&self) -> u32 {
100 let res = match self {
101 LogLevel::CRITICAL => 0,
102 LogLevel::ERROR => 1,
103 LogLevel::WARNING => 2,
104 LogLevel::NOTICE => 3,
105 LogLevel::INFO => 4,
106 LogLevel::DEBUG => 5,
107 };
108 return res;
109 }
110}
111
112#[cfg(test)]
113mod tests {
114 use alloc::string::ToString;
115 use crate::types::{Address, H160, H256, in_to_hex_string};
116 use scale::Encode;
117
118
119 #[test]
120 fn test_to_hex_string() {
121 assert_eq!("e68891e4bbac616263".to_string(), in_to_hex_string("我们abc".as_bytes()))
122 }
123
124 #[test]
125 fn test_types() {
126 let h160 = H160::new([1; 20]);
127 let h_encode = h160.encode();
128 assert_eq!(h_encode.as_slice(), &[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]);
129
130 let address = Address::new([1; 20]);
131 let a_encode = address.encode();
132 assert_eq!(a_encode.as_slice(), &[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]);
133
134 let h256 = H256::new([1; 32]);
135 let h2_encode = h256.encode();
136 assert_eq!(h2_encode.as_slice(), &[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]);
137 }
138}
139