Skip to content

Commit

Permalink
sc-network-types: implement From<IpAddr> for Multiaddr (#4855)
Browse files Browse the repository at this point in the history
Add `From` implementation used by downstream project.

Ref.
#4198 (comment)

CC @nazar-pc
  • Loading branch information
dmitry-markin authored Jun 21, 2024
1 parent a477bd0 commit 3b3a1d2
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
22 changes: 22 additions & 0 deletions substrate/client/network/types/src/multiaddr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ use litep2p::types::multiaddr::{
};
use std::{
fmt::{self, Debug, Display},
net::{IpAddr, Ipv4Addr, Ipv6Addr},
str::FromStr,
};

Expand Down Expand Up @@ -102,6 +103,27 @@ impl From<Multiaddr> for LiteP2pMultiaddr {
}
}

impl From<IpAddr> for Multiaddr {
fn from(v: IpAddr) -> Multiaddr {
match v {
IpAddr::V4(a) => a.into(),
IpAddr::V6(a) => a.into(),
}
}
}

impl From<Ipv4Addr> for Multiaddr {
fn from(v: Ipv4Addr) -> Multiaddr {
Protocol::Ip4(v).into()
}
}

impl From<Ipv6Addr> for Multiaddr {
fn from(v: Ipv6Addr) -> Multiaddr {
Protocol::Ip6(v).into()
}
}

impl TryFrom<Vec<u8>> for Multiaddr {
type Error = ParseError;

Expand Down
26 changes: 25 additions & 1 deletion substrate/client/network/types/src/multiaddr/protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use crate::multihash::Multihash;
use litep2p::types::multiaddr::Protocol as LiteP2pProtocol;
use std::{
borrow::Cow,
net::{Ipv4Addr, Ipv6Addr},
net::{IpAddr, Ipv4Addr, Ipv6Addr},
};

/// [`Protocol`] describes all possible multiaddress protocols.
Expand Down Expand Up @@ -60,6 +60,30 @@ pub enum Protocol<'a> {
Wss(Cow<'a, str>),
}

impl<'a> From<IpAddr> for Protocol<'a> {
#[inline]
fn from(addr: IpAddr) -> Self {
match addr {
IpAddr::V4(addr) => Protocol::Ip4(addr),
IpAddr::V6(addr) => Protocol::Ip6(addr),
}
}
}

impl<'a> From<Ipv4Addr> for Protocol<'a> {
#[inline]
fn from(addr: Ipv4Addr) -> Self {
Protocol::Ip4(addr)
}
}

impl<'a> From<Ipv6Addr> for Protocol<'a> {
#[inline]
fn from(addr: Ipv6Addr) -> Self {
Protocol::Ip6(addr)
}
}

impl<'a> From<LiteP2pProtocol<'a>> for Protocol<'a> {
fn from(protocol: LiteP2pProtocol<'a>) -> Self {
match protocol {
Expand Down

0 comments on commit 3b3a1d2

Please sign in to comment.