From 0b68227c38a681cc23554779a64b47c2f1ffad5c Mon Sep 17 00:00:00 2001 From: Rohit Narurkar Date: Fri, 26 Nov 2021 17:55:41 +0530 Subject: [PATCH] feat: implement hex display for Bytes (#624) * feat: implement hex display for Bytes * chore: add changelog * feat: impl Display, same as LowerHex * fix: prepend 0x for hex display --- CHANGELOG.md | 1 + ethers-core/src/types/bytes.rs | 31 +++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) 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); + } +}