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
This commit is contained in:
Rohit Narurkar 2021-11-26 17:55:41 +05:30 committed by GitHub
parent 86522e2b9e
commit 0b68227c38
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 32 additions and 0 deletions

View File

@ -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

View File

@ -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<u8> {
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);
}
}