Skip to content

Commit 1d67bb9

Browse files
authored
Rollup merge of rust-lang#39372 - seanmonstar:more-addr-froms, r=alexcrichton
A few ergonomic From impls for SocketAddr/IpAddr My main motivation is removing things like this: `"127.0.0.1:3000".parse().unwrap()`. Instead, this now works: `SocketAddr::from(([127, 0, 0, 1], 3000))` or even `([127, 0, 0, 1], 3000).into())` when passing to a function.
2 parents 1997791 + cd603e4 commit 1d67bb9

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

src/libstd/net/addr.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -456,6 +456,13 @@ impl From<SocketAddrV6> for SocketAddr {
456456
}
457457
}
458458

459+
#[stable(feature = "addr_from_into_ip", since = "1.17.0")]
460+
impl<I: Into<IpAddr>> From<(I, u16)> for SocketAddr {
461+
fn from(pieces: (I, u16)) -> SocketAddr {
462+
SocketAddr::new(pieces.0.into(), pieces.1)
463+
}
464+
}
465+
459466
impl<'a> IntoInner<(*const c::sockaddr, c::socklen_t)> for &'a SocketAddr {
460467
fn into_inner(self) -> (*const c::sockaddr, c::socklen_t) {
461468
match *self {

src/libstd/net/ip.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -656,6 +656,13 @@ impl From<[u8; 4]> for Ipv4Addr {
656656
}
657657
}
658658

659+
#[stable(feature = "ip_from_slice", since = "1.17.0")]
660+
impl From<[u8; 4]> for IpAddr {
661+
fn from(octets: [u8; 4]) -> IpAddr {
662+
IpAddr::V4(Ipv4Addr::from(octets))
663+
}
664+
}
665+
659666
impl Ipv6Addr {
660667
/// Creates a new IPv6 address from eight 16-bit segments.
661668
///
@@ -1186,6 +1193,21 @@ impl From<[u16; 8]> for Ipv6Addr {
11861193
}
11871194
}
11881195

1196+
1197+
#[stable(feature = "ip_from_slice", since = "1.17.0")]
1198+
impl From<[u8; 16]> for IpAddr {
1199+
fn from(octets: [u8; 16]) -> IpAddr {
1200+
IpAddr::V6(Ipv6Addr::from(octets))
1201+
}
1202+
}
1203+
1204+
#[stable(feature = "ip_from_slice", since = "1.17.0")]
1205+
impl From<[u16; 8]> for IpAddr {
1206+
fn from(segments: [u16; 8]) -> IpAddr {
1207+
IpAddr::V6(Ipv6Addr::from(segments))
1208+
}
1209+
}
1210+
11891211
// Tests for this module
11901212
#[cfg(all(test, not(target_os = "emscripten")))]
11911213
mod tests {

0 commit comments

Comments
 (0)