blockscout_display_bytes/
lib.rs

1#[cfg(feature = "ethers-core")]
2pub use ethers_core::types::Bytes;
3
4#[cfg(not(feature = "ethers-core"))]
5mod bytes;
6#[cfg(not(feature = "ethers-core"))]
7pub use crate::bytes::Bytes;
8
9pub mod serde_as;
10
11/// Allows to decode both "0x"-prefixed and non-prefixed hex strings
12pub fn decode_hex(value: &str) -> Result<Vec<u8>, hex::FromHexError> {
13    if let Some(value) = value.strip_prefix("0x") {
14        hex::decode(value)
15    } else {
16        hex::decode(value)
17    }
18}
19
20pub trait ToHex {
21    /// Encodes given value as "0x"-prefixed hex string using lowercase characters
22    fn to_hex(&self) -> String;
23
24    fn to_hex_upper(&self) -> String {
25        self.to_hex().to_uppercase()
26    }
27}
28
29impl<T: AsRef<[u8]>> ToHex for T {
30    fn to_hex(&self) -> String {
31        format!("0x{}", hex::encode(self))
32    }
33
34    fn to_hex_upper(&self) -> String {
35        format!("0x{}", hex::encode_upper(self))
36    }
37}