Skip to content

Commit

Permalink
Add ToServerAddrs impl for array/vector of strings
Browse files Browse the repository at this point in the history
Quality-of-life improvement for connect() function.
With this changes it's straightforward to pass Vec<String> or [&str] directly
into connnect() function.
This is useful when passing list of NATS servers directly from
configuration file or command-line argument.
  • Loading branch information
mmalek authored Mar 13, 2024
1 parent ce2280b commit 177c4c7
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions async-nats/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1492,6 +1492,24 @@ impl ToServerAddrs for String {
}
}

impl<T: AsRef<str>> ToServerAddrs for [T] {
type Iter = std::vec::IntoIter<ServerAddr>;
fn to_server_addrs(&self) -> io::Result<Self::Iter> {
self.iter()
.map(AsRef::as_ref)
.map(str::parse)
.collect::<io::Result<_>>()
.map(Vec::into_iter)
}
}

impl<T: AsRef<str>> ToServerAddrs for Vec<T> {
type Iter = std::vec::IntoIter<ServerAddr>;
fn to_server_addrs(&self) -> io::Result<Self::Iter> {
self.as_slice().to_server_addrs()
}
}

impl<'a> ToServerAddrs for &'a [ServerAddr] {
type Iter = iter::Cloned<slice::Iter<'a, ServerAddr>>;

Expand Down Expand Up @@ -1554,4 +1572,40 @@ mod tests {
let address = ServerAddr::from_str("nats://example.com").unwrap();
assert_eq!(address.host(), "example.com")
}

#[test]
fn to_server_addrs_vec_str() {
let vec = vec!["nats://127.0.0.1", "nats://[::]"];
let mut addrs_iter = vec.to_server_addrs().unwrap();
assert_eq!(addrs_iter.next().unwrap().host(), "127.0.0.1");
assert_eq!(addrs_iter.next().unwrap().host(), "::");
assert_eq!(addrs_iter.next(), None);
}

#[test]
fn to_server_addrs_arr_str() {
let arr = ["nats://127.0.0.1", "nats://[::]"];
let mut addrs_iter = arr.to_server_addrs().unwrap();
assert_eq!(addrs_iter.next().unwrap().host(), "127.0.0.1");
assert_eq!(addrs_iter.next().unwrap().host(), "::");
assert_eq!(addrs_iter.next(), None);
}

#[test]
fn to_server_addrs_vec_string() {
let vec = vec!["nats://127.0.0.1".to_string(), "nats://[::]".to_string()];
let mut addrs_iter = vec.to_server_addrs().unwrap();
assert_eq!(addrs_iter.next().unwrap().host(), "127.0.0.1");
assert_eq!(addrs_iter.next().unwrap().host(), "::");
assert_eq!(addrs_iter.next(), None);
}

#[test]
fn to_server_addrs_arr_string() {
let arr = ["nats://127.0.0.1".to_string(), "nats://[::]".to_string()];
let mut addrs_iter = arr.to_server_addrs().unwrap();
assert_eq!(addrs_iter.next().unwrap().host(), "127.0.0.1");
assert_eq!(addrs_iter.next().unwrap().host(), "::");
assert_eq!(addrs_iter.next(), None);
}
}

0 comments on commit 177c4c7

Please sign in to comment.