Simplify `PublicKey` serialization code

There were a bunch of `if self.serialized` expressions repeated in the
code. This change simplifies it by putting the `if` in a function that
calls a closure with a slice containing the serialized bytes.
This commit is contained in:
Martin Habovstiak 2022-09-08 10:04:20 +02:00
parent ed9012c25c
commit b9a512330a
1 changed files with 16 additions and 23 deletions

View File

@ -109,13 +109,17 @@ impl PublicKey {
} }
} }
fn with_serialized<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
if self.compressed {
f(&self.inner.serialize())
} else {
f(&self.inner.serialize_uncompressed())
}
}
/// Returns bitcoin 160-bit hash of the public key /// Returns bitcoin 160-bit hash of the public key
pub fn pubkey_hash(&self) -> PubkeyHash { pub fn pubkey_hash(&self) -> PubkeyHash {
if self.compressed { self.with_serialized(PubkeyHash::hash)
PubkeyHash::hash(&self.inner.serialize())
} else {
PubkeyHash::hash(&self.inner.serialize_uncompressed())
}
} }
/// Returns bitcoin 160-bit hash of the public key for witness program /// Returns bitcoin 160-bit hash of the public key for witness program
@ -133,11 +137,7 @@ impl PublicKey {
/// Write the public key into a writer /// Write the public key into a writer
pub fn write_into<W: io::Write>(&self, mut writer: W) -> Result<(), io::Error> { pub fn write_into<W: io::Write>(&self, mut writer: W) -> Result<(), io::Error> {
if self.compressed { self.with_serialized(|bytes| writer.write_all(bytes))
writer.write_all(&self.inner.serialize())
} else {
writer.write_all(&self.inner.serialize_uncompressed())
}
} }
/// Read the public key from a reader /// Read the public key from a reader
@ -272,16 +272,13 @@ pub struct SortKey(u8, [u8; 32], [u8; 32]);
impl fmt::Display for PublicKey { impl fmt::Display for PublicKey {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.compressed { // TODO: fast hex encoding
for ch in &self.inner.serialize()[..] { self.with_serialized(|bytes| {
for ch in bytes {
write!(f, "{:02x}", ch)?; write!(f, "{:02x}", ch)?;
} }
} else { Ok(())
for ch in &self.inner.serialize_uncompressed()[..] { })
write!(f, "{:02x}", ch)?;
}
}
Ok(())
} }
} }
@ -479,11 +476,7 @@ impl serde::Serialize for PublicKey {
if s.is_human_readable() { if s.is_human_readable() {
s.collect_str(self) s.collect_str(self)
} else { } else {
if self.compressed { self.with_serialized(|bytes| s.serialize_bytes(bytes))
s.serialize_bytes(&self.inner.serialize()[..])
} else {
s.serialize_bytes(&self.inner.serialize_uncompressed()[..])
}
} }
} }
} }