diff --git a/Cargo.toml b/Cargo.toml index 38bee45..08bd361 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "publicsuffix" description = "A robust and reliable library for parsing domain names" -version = "1.1.0" +version = "1.2.0" license = "MIT/Apache-2.0" repository = "https://github.com/rushmorem/publicsuffix" documentation = "https://docs.rs/publicsuffix" diff --git a/README.md b/README.md index aab399f..16247a5 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ Add this crate to your `Cargo.toml`: ```toml [dependencies.publicsuffix] -version = "1.1" +version = "1.2" # This crate exposes the methods `List::fetch` and `List::from_url` as a # feature named "remote_list". This feature is on by default. If you have diff --git a/src/lib.rs b/src/lib.rs index ddba365..a2fa26f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -152,6 +152,12 @@ impl<'a> IntoUrl for &'a str { } } +impl<'a> IntoUrl for &'a String { + fn into_url(self) -> Result { + Ok(Url::parse(self)?) + } +} + impl IntoUrl for String { fn into_url(self) -> Result { Ok(Url::parse(&self)?) @@ -327,12 +333,31 @@ impl List { } /// Extracts Host from a URL - pub fn parse_url(&self, url: &str) -> Result { - match Url::parse(url)?.host_str() { + pub fn parse_url(&self, url: U) -> Result { + match url.into_url()?.host_str() { Some(host) => self.parse_host(host), None => Err(ErrorKind::NoHost.into()), } } + + /// Parses any arbitrary string + /// + /// Effectively this means that the string is either a URL or a host. + pub fn parse_str(&self, string: &str) -> Result { + if string.contains("//") { + if string.starts_with("//") { + // If a string starts with `//` it might be a protocol + // relative URL. Since we really do not care about the + // protocol anyway, let's just assume it's `https` to + // give it a fair chance with `Url::parse`. + self.parse_url(&format!("https:{}", string)) + } else { + self.parse_url(string) + } + } else { + self.parse_host(string) + } + } } impl Host { diff --git a/src/tests.rs b/src/tests.rs index c6ff8ae..0729d93 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -220,5 +220,20 @@ fn list_behaviour() { assert!(list.parse_url("https://127.38.53.247:8080/list/").unwrap().is_ip()); pass!() }); + + ctx.it("can be parsed from a standard URL using `parse_str`", || { + assert!(list.parse_str("https://127.38.53.247:8080/list/").unwrap().is_ip()); + pass!() + }); + + ctx.it("can be parsed from a protocol-relative URL using `parse_str`", || { + assert!(list.parse_str("//127.38.53.247:8080/list/").unwrap().is_ip()); + pass!() + }); + + ctx.it("can be parsed from a non-URL using `parse_str`", || { + assert!(list.parse_str("example.com").unwrap().is_domain()); + pass!() + }); }); }