1use rustc_hex::{FromHex, ToHex};
2use serde::de::{Error, Visitor};
3use serde::{Deserialize, Deserializer, Serialize, Serializer};
4use std::fmt;
5
6#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
8pub struct Bytes(pub Vec<u8>);
9
10impl<T: Into<Vec<u8>>> From<T> for Bytes {
11 fn from(data: T) -> Self {
12 Bytes(data.into())
13 }
14}
15
16impl Serialize for Bytes {
17 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
18 where
19 S: Serializer,
20 {
21 let mut serialized = "0x".to_owned();
22 serialized.push_str(self.0.to_hex::<String>().as_ref());
23 serializer.serialize_str(serialized.as_ref())
24 }
25}
26
27impl<'a> Deserialize<'a> for Bytes {
28 fn deserialize<D>(deserializer: D) -> Result<Bytes, D::Error>
29 where
30 D: Deserializer<'a>,
31 {
32 deserializer.deserialize_identifier(BytesVisitor)
33 }
34}
35
36struct BytesVisitor;
37
38impl<'a> Visitor<'a> for BytesVisitor {
39 type Value = Bytes;
40
41 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
42 write!(formatter, "a 0x-prefixed hex-encoded vector of bytes")
43 }
44
45 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
46 where
47 E: Error,
48 {
49 if value.len() >= 2 && &value[0..2] == "0x" && value.len() & 1 == 0 {
50 Ok(Bytes(
51 FromHex::from_hex(&value[2..]).map_err(|_| Error::custom("invalid hex"))?,
52 ))
53 } else {
54 Err(Error::custom("invalid format"))
55 }
56 }
57
58 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
59 where
60 E: Error,
61 {
62 self.visit_str(value.as_ref())
63 }
64}