diff options
| author | Brian Campbell <lambda@continuation.org> | 2017-01-13 16:28:50 -0500 |
|---|---|---|
| committer | Brian Campbell <lambda@continuation.org> | 2017-01-13 19:13:10 -0500 |
| commit | a5f2f36ebdad455cbff8d6cb1b2647698299020a (patch) | |
| tree | b7ed0c301930881aea54e9ace9d5beba6f239ead /src/libstd | |
| parent | 9dedc815d97752f24a1073258d005d64c643ad80 (diff) | |
| download | rust-a5f2f36ebdad455cbff8d6cb1b2647698299020a.tar.gz rust-a5f2f36ebdad455cbff8d6cb1b2647698299020a.zip | |
impl ToSocketAddrs for String
`ToSocketAddrs` is implemented for a number of different types,
including `(IpAddr, u16)`, `&str`, and various others, for the
convenience of being able to run things like
`TcpListener::bind("10.11.12.13:1415")`. However, because this is a
generic parameter with a trait bound, if you have a `String` you cannot
pass it in, either directly as `TcpListener::bind(string)`, or the
`TcpListener::bind(&string)` as you might expect due to deref coercion;
you have to use `TcpListener::bind(&*string)`, which is noisy and hard
to discover (though #39029 suggests better error messages to make it
more discoverable).
Rather than making people stumble over this, just implement
`ToSocketAddrs` for `String`.
Diffstat (limited to 'src/libstd')
| -rw-r--r-- | src/libstd/net/addr.rs | 20 |
1 files changed, 20 insertions, 0 deletions
diff --git a/src/libstd/net/addr.rs b/src/libstd/net/addr.rs index f5348934310..d186a53311d 100644 --- a/src/libstd/net/addr.rs +++ b/src/libstd/net/addr.rs @@ -760,6 +760,14 @@ impl<'a, T: ToSocketAddrs + ?Sized> ToSocketAddrs for &'a T { } } +#[stable(feature = "string_to_socket_addrs", since = "1.16.0")] +impl ToSocketAddrs for String { + type Iter = vec::IntoIter<SocketAddr>; + fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> { + (&**self).to_socket_addrs() + } +} + #[cfg(all(test, not(target_os = "emscripten")))] mod tests { use net::*; @@ -797,6 +805,18 @@ mod tests { assert!(tsa("localhost:23924").unwrap().contains(&a)); } + #[test] + fn to_socket_addr_string() { + let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352); + assert_eq!(Ok(vec![a]), tsa(&*format!("{}:{}", "77.88.21.11", "24352"))); + assert_eq!(Ok(vec![a]), tsa(&format!("{}:{}", "77.88.21.11", "24352"))); + assert_eq!(Ok(vec![a]), tsa(format!("{}:{}", "77.88.21.11", "24352"))); + + let s = format!("{}:{}", "77.88.21.11", "24352"); + assert_eq!(Ok(vec![a]), tsa(s)); + // s has been moved into the tsa call + } + // FIXME: figure out why this fails on openbsd and bitrig and fix it #[test] #[cfg(not(any(windows, target_os = "openbsd", target_os = "bitrig")))] |
