Skip to content

Commit

Permalink
Add LowerHex and UpperHex impls for Id and some tests
Browse files Browse the repository at this point in the history
  • Loading branch information
TheQuantumPhysicist committed Feb 5, 2024
1 parent 91e32c6 commit fd79164
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 4 deletions.
64 changes: 62 additions & 2 deletions common/src/primitives/id/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

mod with_id;

use std::fmt::{Debug, Display};
use std::fmt::{Debug, Display, LowerHex, UpperHex};

use generic_array::{typenum, GenericArray};
use ref_cast::RefCast;
Expand Down Expand Up @@ -126,7 +126,36 @@ impl<T> Copy for Id<T> {}

impl<T> Display for Id<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:x}", self.hash)
let s = self.hash.to_string();
write!(
f,
"{}",
self.hash.to_string().strip_prefix("0x").unwrap_or(&s)
)
}
}

impl<T> LowerHex for Id<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if f.alternate() {
write!(f, "0x")?;
}
for i in &self.hash.0[..] {
write!(f, "{:02x}", i)?;
}
Ok(())
}
}

impl<T> UpperHex for Id<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if f.alternate() {
write!(f, "0X")?;
}
for i in &self.hash.0[..] {
write!(f, "{:02X}", i)?;
}
Ok(())
}
}

Expand Down Expand Up @@ -253,6 +282,37 @@ mod tests {
}
}

#[test]
fn basic_str() {
let h1: Id<TestType1> =
H256::from_str("000000006a625f06636b8bb6ac7b960a8d03705d1ace08b1a19da3fdcc99ddbd")
.unwrap()
.into();

assert_eq!(
format!("{:x}", h1),
"000000006a625f06636b8bb6ac7b960a8d03705d1ace08b1a19da3fdcc99ddbd".to_string()
);
assert_eq!(
format!("{:#x}", h1),
"0x000000006a625f06636b8bb6ac7b960a8d03705d1ace08b1a19da3fdcc99ddbd".to_string()
);
assert_eq!(
format!("{:X}", h1),
"000000006A625F06636B8BB6AC7B960A8D03705D1ACE08B1A19DA3FDCC99DDBD".to_string()
);
assert_eq!(
format!("{:#X}", h1),
"0X000000006A625F06636B8BB6AC7B960A8D03705D1ACE08B1A19DA3FDCC99DDBD".to_string()
);
assert_eq!(format!("{}", h1), "0000…ddbd".to_string());
assert_eq!(
format!("{:?}", h1),
"Id<TestType1>{000000006a625f06636b8bb6ac7b960a8d03705d1ace08b1a19da3fdcc99ddbd}"
.to_string()
);
}

#[rstest]
#[trace]
#[case(Seed::from_entropy())]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ use iced::{
Alignment, Element, Length,
};
use iced_aw::Grid;
use serialization::hex::HexEncode;

use crate::{
backend::messages::AccountInfo,
Expand Down Expand Up @@ -54,7 +53,7 @@ pub fn view_transactions(
|| "-".to_owned(),
|timestamp| print_block_timestamp(*timestamp),
);
let full_tx_id_str = format!("{}", tx.txid.hex_encode());
let full_tx_id_str = format!("{:x}", tx.txid);
transaction_list = transaction_list
.push(field(format!("{}", current_transaction_list.skip + index)))
.push(
Expand Down

0 comments on commit fd79164

Please sign in to comment.