From a4173705dbb6f79d6ee26bc5f61ba5ee6580390a Mon Sep 17 00:00:00 2001 From: Pierre Krieger Date: Wed, 17 Apr 2019 14:16:50 +0200 Subject: [PATCH] Add some TryFrom implementations (#1060) --- core/src/peer_id.rs | 18 +++++++++++++++++- misc/multihash/src/lib.rs | 10 +++++++++- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/core/src/peer_id.rs b/core/src/peer_id.rs index 1a7f2427..f7448049 100644 --- a/core/src/peer_id.rs +++ b/core/src/peer_id.rs @@ -22,7 +22,7 @@ use crate::PublicKey; use bs58; use quick_error::quick_error; use multihash; -use std::{fmt, str::FromStr}; +use std::{convert::TryFrom, fmt, str::FromStr}; /// Identifier of a peer of the network. /// @@ -143,6 +143,22 @@ impl From for PeerId { } } +impl TryFrom> for PeerId { + type Error = Vec; + + fn try_from(value: Vec) -> Result { + PeerId::from_bytes(value) + } +} + +impl TryFrom for PeerId { + type Error = multihash::Multihash; + + fn try_from(value: multihash::Multihash) -> Result { + PeerId::from_multihash(value) + } +} + impl PartialEq for PeerId { #[inline] fn eq(&self, other: &multihash::Multihash) -> bool { diff --git a/misc/multihash/src/lib.rs b/misc/multihash/src/lib.rs index 2244f2c2..e7ebe57a 100644 --- a/misc/multihash/src/lib.rs +++ b/misc/multihash/src/lib.rs @@ -9,7 +9,7 @@ mod errors; mod hashes; use sha2::Digest; -use std::fmt::Write; +use std::{convert::TryFrom, fmt::Write}; use unsigned_varint::{decode, encode}; pub use self::errors::{DecodeError, DecodeOwnedError, EncodeError}; @@ -165,6 +165,14 @@ impl<'a> PartialEq> for Multihash { } } +impl TryFrom> for Multihash { + type Error = DecodeOwnedError; + + fn try_from(value: Vec) -> Result { + Multihash::from_bytes(value) + } +} + /// Represents a valid multihash. #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub struct MultihashRef<'a> {