From 017cd71ca7330aa557626a7083dbd517bf8b983f Mon Sep 17 00:00:00 2001 From: Dr Maxim Orlovsky Date: Sat, 6 Feb 2021 23:41:49 +0100 Subject: [PATCH] Improving bip32 ChildNumber display implementation --- src/util/bip32.rs | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/src/util/bip32.rs b/src/util/bip32.rs index 46727377..9e30ba6d 100644 --- a/src/util/bip32.rs +++ b/src/util/bip32.rs @@ -169,8 +169,12 @@ impl From for u32 { impl fmt::Display for ChildNumber { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - ChildNumber::Hardened { index } => write!(f, "{}'", index), - ChildNumber::Normal { index } => write!(f, "{}", index), + ChildNumber::Hardened { index } => { + fmt::Display::fmt(&index, f)?; + let alt = f.alternate(); + f.write_str(if alt { "'" } else { "h" }) + }, + ChildNumber::Normal { index } => fmt::Display::fmt(&index, f), } } } @@ -1083,5 +1087,15 @@ mod tests { cc.to_string() ); } + + #[test] + fn fmt_child_number() { + assert_eq!("000005'", &format!("{:#06}", ChildNumber::from_hardened_idx(5).unwrap())); + assert_eq!("5'", &format!("{:#}", ChildNumber::from_hardened_idx(5).unwrap())); + assert_eq!("000005h", &format!("{:06}", ChildNumber::from_hardened_idx(5).unwrap())); + assert_eq!("5h", &format!("{}", ChildNumber::from_hardened_idx(5).unwrap())); + assert_eq!("42", &format!("{}", ChildNumber::from_normal_idx(42).unwrap())); + assert_eq!("000042", &format!("{:06}", ChildNumber::from_normal_idx(42).unwrap())); + } }