Add some TryFrom implementations (#1060)

This commit is contained in:
Pierre Krieger
2019-04-17 14:16:50 +02:00
committed by GitHub
parent 3ec9c37e17
commit a4173705db
2 changed files with 26 additions and 2 deletions

View File

@ -22,7 +22,7 @@ use crate::PublicKey;
use bs58; use bs58;
use quick_error::quick_error; use quick_error::quick_error;
use multihash; use multihash;
use std::{fmt, str::FromStr}; use std::{convert::TryFrom, fmt, str::FromStr};
/// Identifier of a peer of the network. /// Identifier of a peer of the network.
/// ///
@ -143,6 +143,22 @@ impl From<PublicKey> for PeerId {
} }
} }
impl TryFrom<Vec<u8>> for PeerId {
type Error = Vec<u8>;
fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
PeerId::from_bytes(value)
}
}
impl TryFrom<multihash::Multihash> for PeerId {
type Error = multihash::Multihash;
fn try_from(value: multihash::Multihash) -> Result<Self, Self::Error> {
PeerId::from_multihash(value)
}
}
impl PartialEq<multihash::Multihash> for PeerId { impl PartialEq<multihash::Multihash> for PeerId {
#[inline] #[inline]
fn eq(&self, other: &multihash::Multihash) -> bool { fn eq(&self, other: &multihash::Multihash) -> bool {

View File

@ -9,7 +9,7 @@ mod errors;
mod hashes; mod hashes;
use sha2::Digest; use sha2::Digest;
use std::fmt::Write; use std::{convert::TryFrom, fmt::Write};
use unsigned_varint::{decode, encode}; use unsigned_varint::{decode, encode};
pub use self::errors::{DecodeError, DecodeOwnedError, EncodeError}; pub use self::errors::{DecodeError, DecodeOwnedError, EncodeError};
@ -165,6 +165,14 @@ impl<'a> PartialEq<MultihashRef<'a>> for Multihash {
} }
} }
impl TryFrom<Vec<u8>> for Multihash {
type Error = DecodeOwnedError;
fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
Multihash::from_bytes(value)
}
}
/// Represents a valid multihash. /// Represents a valid multihash.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct MultihashRef<'a> { pub struct MultihashRef<'a> {