Skip to content

Commit f60bfb8

Browse files
authored
Merge pull request #104 from alexanderwiederin/tx-display
Feat(core): Add Debug and Display implementations for Txid types
2 parents 3f1a50d + f27ab77 commit f60bfb8

File tree

1 file changed

+63
-3
lines changed

1 file changed

+63
-3
lines changed

src/core/transaction.rs

Lines changed: 63 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
use std::{ffi::c_void, marker::PhantomData};
1+
use std::{
2+
ffi::c_void,
3+
fmt::{self, Debug, Display, Formatter},
4+
marker::PhantomData,
5+
};
26

37
use libbitcoinkernel_sys::{
48
btck_Transaction, btck_TransactionInput, btck_TransactionOutPoint, btck_TransactionOutput,
@@ -653,7 +657,6 @@ pub trait TxidExt: AsPtr<btck_Txid> {
653657
}
654658
}
655659

656-
#[derive(Debug)]
657660
pub struct Txid {
658661
inner: *mut btck_Txid,
659662
}
@@ -709,7 +712,22 @@ impl PartialEq<TxidRef<'_>> for Txid {
709712

710713
impl Eq for Txid {}
711714

712-
#[derive(Debug)]
715+
impl Debug for Txid {
716+
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
717+
write!(f, "Txid({:?})", self.to_bytes())
718+
}
719+
}
720+
721+
impl Display for Txid {
722+
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
723+
let bytes = self.to_bytes();
724+
for byte in bytes.iter().rev() {
725+
write!(f, "{:02x}", byte)?;
726+
}
727+
Ok(())
728+
}
729+
}
730+
713731
pub struct TxidRef<'a> {
714732
inner: *const btck_Txid,
715733
marker: PhantomData<&'a ()>,
@@ -765,6 +783,22 @@ impl PartialEq<Txid> for TxidRef<'_> {
765783
}
766784
}
767785

786+
impl<'a> Debug for TxidRef<'a> {
787+
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
788+
write!(f, "Txid({:?})", self.to_bytes())
789+
}
790+
}
791+
792+
impl<'a> Display for TxidRef<'a> {
793+
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
794+
let bytes = self.to_bytes();
795+
for byte in bytes.iter().rev() {
796+
write!(f, "{:02x}", byte)?;
797+
}
798+
Ok(())
799+
}
800+
}
801+
768802
#[cfg(test)]
769803
mod tests {
770804
use super::*;
@@ -1322,4 +1356,30 @@ mod tests {
13221356

13231357
assert_eq!(iter_count, count);
13241358
}
1359+
1360+
#[test]
1361+
fn test_txid_display() {
1362+
let (tx, _) = get_test_transactions();
1363+
let txid = tx.txid().to_owned();
1364+
1365+
let display = format!("{}", txid);
1366+
1367+
assert_eq!(
1368+
display,
1369+
"f3ac0618ad042336fbec1f88a4e965481b46cd3381a807591c78c75fdbae7d67"
1370+
);
1371+
}
1372+
1373+
#[test]
1374+
fn test_txid_ref_display() {
1375+
let (tx, _) = get_test_transactions();
1376+
let txid = tx.txid();
1377+
1378+
let display = format!("{}", txid);
1379+
1380+
assert_eq!(
1381+
display,
1382+
"f3ac0618ad042336fbec1f88a4e965481b46cd3381a807591c78c75fdbae7d67"
1383+
);
1384+
}
13251385
}

0 commit comments

Comments
 (0)