Improving bip32 ChildNumber display implementation

This commit is contained in:
Dr Maxim Orlovsky 2021-02-06 23:41:49 +01:00
parent 80b47f1f5b
commit 017cd71ca7
No known key found for this signature in database
GPG Key ID: FFC0250947E5C6F7
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 {
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()));
}
}