ethers_types_rs/
bytes.rs

1#[macro_export]
2macro_rules! bytes_def {
3    ($name:ident) => {
4        /// 32 bytes $name
5        #[derive(Debug, Clone, PartialEq, Eq)]
6        pub struct $name(pub Vec<u8>);
7
8        impl Default for $name {
9            fn default() -> Self {
10                Self([0].to_vec())
11            }
12        }
13
14        impl std::fmt::Display for $name {
15            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
16                write!(f, "{}", self.to_string())
17            }
18        }
19
20        impl From<Vec<u8>> for $name {
21            fn from(value: Vec<u8>) -> Self {
22                Self(value)
23            }
24        }
25
26        impl From<&[u8]> for $name {
27            fn from(value: &[u8]) -> Self {
28                Self(value.to_owned())
29            }
30        }
31
32        impl TryFrom<&str> for $name {
33            type Error = $crate::anyhow::Error;
34
35            fn try_from(value: &str) -> Result<Self, Self::Error> {
36                let bytes = $crate::bytes::bytes_from_str(value)?;
37
38                Ok(Self(bytes))
39            }
40        }
41
42        impl TryFrom<String> for $name {
43            type Error = $crate::anyhow::Error;
44            fn try_from(value: String) -> Result<Self, Self::Error> {
45                Self::try_from(value.as_str())
46            }
47        }
48
49        impl<'a> AsRef<[u8]> for $name
50        where
51            Self: 'a,
52        {
53            fn as_ref(&self) -> &[u8] {
54                self.0.as_slice()
55            }
56        }
57
58        impl $crate::rlp::Encodable for $name {
59            fn rlp_append(&self, s: &mut $crate::rlp::RlpStream) {
60                let buff = &self.0;
61
62                if buff.len() == 0 {
63                    s.append_raw(&[0x80], 1);
64                } else {
65                    s.append(&buff.as_slice());
66                }
67            }
68        }
69
70        impl $crate::rlp::Decodable for $name {
71            fn decode(rlp: &$crate::rlp::Rlp) -> Result<Self, $crate::rlp::DecoderError> {
72                rlp.decoder()
73                    .decode_value(|bytes| Ok(bytes.to_vec().into()))
74            }
75        }
76
77        impl $name {
78            /// Convert `$name` instance to hex string.
79            pub fn to_string(&self) -> String {
80                $crate::bytes::bytes_to_string(self.0.as_slice())
81            }
82        }
83
84        impl serde::Serialize for $name {
85            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
86            where
87                S: serde::Serializer,
88            {
89                serializer.serialize_str(&self.to_string())
90            }
91        }
92
93        impl<'de> serde::Deserialize<'de> for $name {
94            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
95            where
96                D: serde::Deserializer<'de>,
97            {
98                use std::fmt::Formatter;
99
100                use serde::de;
101
102                struct Visitor;
103
104                impl<'de> de::Visitor<'de> for Visitor {
105                    type Value = $name;
106
107                    fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
108                        write!(formatter, "hex string for {}", stringify!($name))
109                    }
110
111                    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
112                    where
113                        E: de::Error,
114                    {
115                        Ok(v.try_into().map_err(serde::de::Error::custom)?)
116                    }
117
118                    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
119                    where
120                        E: de::Error,
121                    {
122                        Ok(v.try_into().map_err(serde::de::Error::custom)?)
123                    }
124
125                    fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
126                    where
127                        E: de::Error,
128                    {
129                        Ok($name(v.to_vec()))
130                    }
131
132                    fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
133                    where
134                        E: de::Error,
135                    {
136                        Ok($name(v))
137                    }
138
139                    fn visit_borrowed_bytes<E>(self, v: &'de [u8]) -> Result<Self::Value, E>
140                    where
141                        E: de::Error,
142                    {
143                        Ok($name(v.to_vec()))
144                    }
145                }
146
147                let hex = deserializer.deserialize_any(Visitor)?;
148
149                hex.try_into().map_err(serde::de::Error::custom)
150            }
151        }
152    };
153}
154
155/// Decode hex string to [`Vec<u8>`]
156///
157/// If `source` have the 0x prefix, skip over them.
158///
159#[allow(unused)]
160pub fn bytes_from_str<S>(source: S) -> anyhow::Result<Vec<u8>>
161where
162    S: AsRef<str>,
163{
164    let mut source = source.as_ref().trim_start_matches("0x").to_string();
165
166    if source.len() % 2 != 0 {
167        source = format!("0{}", source);
168    }
169
170    Ok(hex::decode(source)?)
171}
172
173/// Convert bytes to hex string with prefix `0x`
174#[allow(unused)]
175pub fn bytes_to_string<S>(source: S) -> String
176where
177    S: AsRef<[u8]>,
178{
179    let hex_str = hex::encode(source);
180
181    format!(
182        "0x{}",
183        if hex_str.len() == 2 {
184            hex_str.trim_start_matches("0")
185        } else {
186            hex_str.as_str()
187        }
188    )
189}