Skip to content
This repository has been archived by the owner on Oct 19, 2024. It is now read-only.

feat: implement hex display for Bytes #624

Merged
merged 4 commits into from
Nov 26, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
31 changes: 31 additions & 0 deletions ethers-core/src/types/bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,31 @@ 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(
#[serde(serialize_with = "serialize_bytes", deserialize_with = "deserialize_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()
Expand Down Expand Up @@ -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);
}
}