Skip to content

Commit a5f2f36

Browse files
committed
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 rust-lang#39029 suggests better error messages to make it more discoverable). Rather than making people stumble over this, just implement `ToSocketAddrs` for `String`.
1 parent 9dedc81 commit a5f2f36

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

src/libstd/net/addr.rs

+20
Original file line numberDiff line numberDiff line change
@@ -760,6 +760,14 @@ impl<'a, T: ToSocketAddrs + ?Sized> ToSocketAddrs for &'a T {
760760
}
761761
}
762762

763+
#[stable(feature = "string_to_socket_addrs", since = "1.16.0")]
764+
impl ToSocketAddrs for String {
765+
type Iter = vec::IntoIter<SocketAddr>;
766+
fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
767+
(&**self).to_socket_addrs()
768+
}
769+
}
770+
763771
#[cfg(all(test, not(target_os = "emscripten")))]
764772
mod tests {
765773
use net::*;
@@ -797,6 +805,18 @@ mod tests {
797805
assert!(tsa("localhost:23924").unwrap().contains(&a));
798806
}
799807

808+
#[test]
809+
fn to_socket_addr_string() {
810+
let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
811+
assert_eq!(Ok(vec![a]), tsa(&*format!("{}:{}", "77.88.21.11", "24352")));
812+
assert_eq!(Ok(vec![a]), tsa(&format!("{}:{}", "77.88.21.11", "24352")));
813+
assert_eq!(Ok(vec![a]), tsa(format!("{}:{}", "77.88.21.11", "24352")));
814+
815+
let s = format!("{}:{}", "77.88.21.11", "24352");
816+
assert_eq!(Ok(vec![a]), tsa(s));
817+
// s has been moved into the tsa call
818+
}
819+
800820
// FIXME: figure out why this fails on openbsd and bitrig and fix it
801821
#[test]
802822
#[cfg(not(any(windows, target_os = "openbsd", target_os = "bitrig")))]

0 commit comments

Comments
 (0)