Skip to content

Commit 061c490

Browse files
RUST-2104 Implement From<std::net::SocketAddr> for ServerAddress (#1396)
1 parent 7bf0a7b commit 061c490

File tree

2 files changed

+48
-2
lines changed

2 files changed

+48
-2
lines changed

src/client/options.rs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ use std::{
1111
convert::TryFrom,
1212
fmt::{self, Display, Formatter, Write},
1313
hash::{Hash, Hasher},
14-
net::{Ipv4Addr, Ipv6Addr},
14+
net::{Ipv4Addr, Ipv6Addr, SocketAddr},
1515
path::PathBuf,
1616
str::FromStr,
1717
time::Duration,
@@ -125,6 +125,15 @@ pub enum ServerAddress {
125125
},
126126
}
127127

128+
impl From<SocketAddr> for ServerAddress {
129+
fn from(item: SocketAddr) -> Self {
130+
ServerAddress::Tcp {
131+
host: item.ip().to_string(),
132+
port: Some(item.port()),
133+
}
134+
}
135+
}
136+
128137
impl<'de> Deserialize<'de> for ServerAddress {
129138
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
130139
where

src/test/client.rs

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,10 @@
1-
use std::{borrow::Cow, collections::HashMap, future::IntoFuture, net::Ipv6Addr, time::Duration};
1+
use std::{
2+
borrow::Cow,
3+
collections::HashMap,
4+
future::IntoFuture,
5+
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
6+
time::Duration,
7+
};
28

39
use crate::bson::Document;
410
use serde::{Deserialize, Serialize};
@@ -982,3 +988,34 @@ async fn ipv6_connect() {
982988
.unwrap();
983989
assert_eq!(result.get_f64("ok").unwrap(), 1.0);
984990
}
991+
992+
#[test]
993+
fn server_address_from_socket_addr_ipv4() {
994+
let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 27017);
995+
let server_address = ServerAddress::from(socket_addr);
996+
997+
match server_address {
998+
ServerAddress::Tcp { host, port } => {
999+
assert_eq!(host, "127.0.0.1", "Host was not correctly converted");
1000+
assert_eq!(port, Some(27017), "Port was not correctly converted");
1001+
}
1002+
_ => panic!("ServerAddress should have been Tcp variant"),
1003+
}
1004+
}
1005+
1006+
#[test]
1007+
fn server_address_from_socket_addr_ipv6() {
1008+
let socket_addr = SocketAddr::new(
1009+
IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1)),
1010+
27017,
1011+
);
1012+
let server_address = ServerAddress::from(socket_addr);
1013+
1014+
match server_address {
1015+
ServerAddress::Tcp { host, port } => {
1016+
assert_eq!(host, "2001:db8::1", "Host was not correctly converted");
1017+
assert_eq!(port, Some(27017), "Port was not correctly converted");
1018+
}
1019+
_ => panic!("ServerAddress should have been Tcp variant"),
1020+
}
1021+
}

0 commit comments

Comments
 (0)