Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion src/client/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use std::{
convert::TryFrom,
fmt::{self, Display, Formatter, Write},
hash::{Hash, Hasher},
net::{Ipv4Addr, Ipv6Addr},
net::{Ipv4Addr, Ipv6Addr, SocketAddr},
path::PathBuf,
str::FromStr,
time::Duration,
Expand Down Expand Up @@ -125,6 +125,15 @@ pub enum ServerAddress {
},
}

impl From<SocketAddr> for ServerAddress {
fn from(item: SocketAddr) -> Self {
ServerAddress::Tcp {
host: item.ip().to_string(),
port: Some(item.port()),
}
}
}

impl<'de> Deserialize<'de> for ServerAddress {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
Expand Down
39 changes: 38 additions & 1 deletion src/test/client.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
use std::{borrow::Cow, collections::HashMap, future::IntoFuture, net::Ipv6Addr, time::Duration};
use std::{
borrow::Cow,
collections::HashMap,
future::IntoFuture,
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
time::Duration,
};

use crate::bson::Document;
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -982,3 +988,34 @@ async fn ipv6_connect() {
.unwrap();
assert_eq!(result.get_f64("ok").unwrap(), 1.0);
}

#[test]
fn server_address_from_socket_addr_ipv4() {
let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 27017);
let server_address = ServerAddress::from(socket_addr);

match server_address {
ServerAddress::Tcp { host, port } => {
assert_eq!(host, "127.0.0.1", "Host was not correctly converted");
assert_eq!(port, Some(27017), "Port was not correctly converted");
}
_ => panic!("ServerAddress should have been Tcp variant"),
}
}

#[test]
fn server_address_from_socket_addr_ipv6() {
let socket_addr = SocketAddr::new(
IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1)),
27017,
);
let server_address = ServerAddress::from(socket_addr);

match server_address {
ServerAddress::Tcp { host, port } => {
assert_eq!(host, "2001:db8::1", "Host was not correctly converted");
assert_eq!(port, Some(27017), "Port was not correctly converted");
}
_ => panic!("ServerAddress should have been Tcp variant"),
}
}