Skip to content

Commit c8657b1

Browse files
author
Andrew Witten
authored
RUST-892 implement FromStr for ServerAddress (#458)
Implements FromStr for ServerAddress. Allows for calling "a:1234".parse::<ServerAddress>();
1 parent 660cdf7 commit c8657b1

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

src/client/options/mod.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,13 @@ impl Hash for ServerAddress {
168168
}
169169
}
170170

171+
impl FromStr for ServerAddress {
172+
type Err = crate::error::Error;
173+
fn from_str(address: &str) -> Result<Self> {
174+
ServerAddress::parse(address)
175+
}
176+
}
177+
171178
impl ServerAddress {
172179
/// Parses an address string into a `StreamAddress`.
173180
pub fn parse(address: impl AsRef<str>) -> Result<Self> {
@@ -1994,6 +2001,23 @@ mod tests {
19942001
}
19952002
}
19962003

2004+
#[test]
2005+
fn test_parse_address_with_from_str() {
2006+
let x = "localhost:27017".parse::<ServerAddress>().unwrap();
2007+
let ServerAddress::Tcp { host, port } = x;
2008+
assert_eq!(host, "localhost");
2009+
assert_eq!(port, Some(27017));
2010+
2011+
// Port defaults to 27017 (so this doesn't fail)
2012+
let x = "localhost".parse::<ServerAddress>().unwrap();
2013+
let ServerAddress::Tcp { host, port } = x;
2014+
assert_eq!(host, "localhost");
2015+
assert_eq!(port, None);
2016+
2017+
let x = "localhost:not a number".parse::<ServerAddress>();
2018+
assert!(x.is_err());
2019+
}
2020+
19972021
#[cfg_attr(feature = "tokio-runtime", tokio::test)]
19982022
#[cfg_attr(feature = "async-std-runtime", async_std::test)]
19992023
async fn fails_without_scheme() {

0 commit comments

Comments
 (0)