Merge pull request #567 from LNP-BP/bip32/child-number-display

Improving bip32 ChildNumber display implementation
This commit is contained in:
Andrew Poelstra 2021-03-12 21:01:56 +00:00 committed by GitHub
commit bee5e8a090
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 16 additions and 2 deletions

View File

@ -169,8 +169,12 @@ impl From<ChildNumber> for u32 {
impl fmt::Display for ChildNumber { impl fmt::Display for ChildNumber {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self { match *self {
ChildNumber::Hardened { index } => write!(f, "{}'", index), ChildNumber::Hardened { index } => {
ChildNumber::Normal { index } => write!(f, "{}", 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() 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()));
}
} }