diff --git a/CHANGELOG.md b/CHANGELOG.md index 471af9cb..6385b314 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ - Fix `format_units` to return a `String` of representing a decimal point float such that the decimal places don't get truncated. [597](https://github.com/gakonst/ethers-rs/pull/597) +- Implement hex display format for `ethers::core::Bytes` [#624](https://github.com/gakonst/ethers-rs/pull/624). ### Unreleased diff --git a/ethers-core/src/types/bytes.rs b/ethers-core/src/types/bytes.rs index f2179711..9ec30263 100644 --- a/ethers-core/src/types/bytes.rs +++ b/ethers-core/src/types/bytes.rs @@ -3,6 +3,8 @@ use serde::{ Deserialize, Deserializer, Serialize, Serializer, }; +use std::fmt::{Display, Formatter, LowerHex, Result as FmtResult}; + /// Wrapper type around Bytes to deserialize/serialize "0x" prefixed ethereum hex strings #[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, Ord, PartialOrd)] pub struct Bytes( @@ -10,6 +12,22 @@ pub struct Bytes( pub bytes::Bytes, ); +fn bytes_to_hex(b: &Bytes) -> String { + hex::encode(b.0.as_ref()) +} + +impl Display for Bytes { + fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { + write!(f, "0x{}", bytes_to_hex(self)) + } +} + +impl LowerHex for Bytes { + fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { + write!(f, "0x{}", bytes_to_hex(self)) + } +} + impl Bytes { pub fn to_vec(&self) -> Vec { self.as_ref().to_vec() @@ -67,3 +85,16 @@ where Err(Error::invalid_value(Unexpected::Str(&value), &"0x prefix")) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hex_formatting() { + let b = Bytes::from(vec![1, 35, 69, 103, 137, 171, 205, 239]); + let expected = String::from("0x0123456789abcdef"); + assert_eq!(format!("{:x}", b), expected); + assert_eq!(format!("{}", b), expected); + } +}