Skip to content

Commit

Permalink
feat(client): add FromStr impl for Name
Browse files Browse the repository at this point in the history
  • Loading branch information
faern authored and seanmonstar committed Jan 10, 2019
1 parent ec7b93c commit 607c4da
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/client/connect/dns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@
//! - The [`Resolve`](Resolve) trait and related types to build a custom
//! resolver for use with the `HttpConnector`.
use std::{fmt, io, vec};
use std::error::Error;
use std::net::{
IpAddr, Ipv4Addr, Ipv6Addr,
SocketAddr, ToSocketAddrs,
SocketAddrV4, SocketAddrV6,
};
use std::str::FromStr;
use std::sync::Arc;

use futures::{Async, Future, Poll};
Expand Down Expand Up @@ -72,6 +74,32 @@ impl fmt::Debug for Name {
}
}

impl FromStr for Name {
type Err = InvalidNameError;

fn from_str(host: &str) -> Result<Self, Self::Err> {
// Possibly add validation later
Ok(Name::new(host.to_owned()))
}
}

/// Error indicating a given string was not a valid domain name.
#[derive(Debug)]
pub struct InvalidNameError(());

impl fmt::Display for InvalidNameError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.description().fmt(f)
}
}

impl Error for InvalidNameError {
fn description(&self) -> &str {
"Not a valid domain name"
}
}


impl GaiResolver {
/// Construct a new `GaiResolver`.
///
Expand Down Expand Up @@ -317,4 +345,10 @@ mod tests {
assert!(preferred.next().unwrap().is_ipv6());
assert!(fallback.next().unwrap().is_ipv4());
}

#[test]
fn test_name_from_str() {
let name = Name::from_str("test.example.com").expect("Should be a valid domain");
assert_eq!(name.as_str(), "test.example.com");
}
}

0 comments on commit 607c4da

Please sign in to comment.