Skip to content

Commit

Permalink
Prefer implementing Display to From<T> for String (#7914)
Browse files Browse the repository at this point in the history
There’s still `impl From<AccountId> for String`.  It’s left
intentionally as it avoids string allocation when used compared
to using Display.
  • Loading branch information
mina86 authored and Nikolay Kurtov committed Nov 9, 2022
1 parent 163e529 commit afdf1f2
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 35 deletions.
16 changes: 0 additions & 16 deletions chain/client-primitives/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -600,22 +600,6 @@ pub enum TxStatusError {
TimeoutError,
}

impl From<TxStatusError> for String {
fn from(error: TxStatusError) -> Self {
match error {
TxStatusError::ChainError(err) => format!("Chain error: {}", err),
TxStatusError::MissingTransaction(tx_hash) => {
format!("Transaction {} doesn't exist", tx_hash)
}
TxStatusError::InternalError(debug_message) => {
format!("Internal error: {}", debug_message)
}
TxStatusError::TimeoutError => format!("Timeout error"),
TxStatusError::InvalidTx(e) => format!("Invalid transaction: {}", e),
}
}
}

impl Message for TxStatus {
type Result = Result<Option<FinalExecutionOutcomeViewEnum>, TxStatusError>;
}
Expand Down
27 changes: 8 additions & 19 deletions core/crypto/src/signature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,14 +255,18 @@ impl Hash for PublicKey {
}

impl Display for PublicKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
write!(f, "{}", String::from(self))
fn fmt(&self, fmt: &mut Formatter) -> std::fmt::Result {
let (key_type, key_data) = match self {
PublicKey::ED25519(public_key) => (KeyType::ED25519, &public_key.0[..]),
PublicKey::SECP256K1(public_key) => (KeyType::SECP256K1, &public_key.0[..]),
};
write!(fmt, "{}:{}", key_type, bs58::encode(key_data).into_string())
}
}

impl Debug for PublicKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
write!(f, "{}", String::from(self))
Display::fmt(self, f)
}
}

Expand Down Expand Up @@ -305,7 +309,7 @@ impl serde::Serialize for PublicKey {
where
S: serde::Serializer,
{
serializer.serialize_str(&String::from(self))
serializer.collect_str(self)
}
}

Expand All @@ -320,21 +324,6 @@ impl<'de> serde::Deserialize<'de> for PublicKey {
}
}

impl From<&PublicKey> for String {
fn from(public_key: &PublicKey) -> Self {
match public_key {
PublicKey::ED25519(public_key) => {
format!("{}:{}", KeyType::ED25519, bs58::encode(&public_key.0).into_string())
}
PublicKey::SECP256K1(public_key) => format!(
"{}:{}",
KeyType::SECP256K1,
bs58::encode(&public_key.0.to_vec()).into_string()
),
}
}
}

impl FromStr for PublicKey {
type Err = crate::errors::ParseKeyError;

Expand Down

0 comments on commit afdf1f2

Please sign in to comment.