Skip to content

url: add TryFrom<&[u8]> for Url and TryFrom tests #638

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
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
9 changes: 9 additions & 0 deletions url/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2339,6 +2339,15 @@ impl<'a> TryFrom<&'a str> for Url {
}
}

impl<'a> TryFrom<&'a [u8]> for Url {
type Error = ParseError;

fn try_from(bytes: &'a [u8]) -> Result<Self, Self::Error> {
let s = std::str::from_utf8(bytes).map_err(|_| ParseError::InvalidUtf8)?;
Url::parse(s)
}
}

/// Display the serialization of this URL.
impl fmt::Display for Url {
#[inline]
Expand Down
1 change: 1 addition & 0 deletions url/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ simple_enum_error! {
InvalidIpv4Address => "invalid IPv4 address",
InvalidIpv6Address => "invalid IPv6 address",
InvalidDomainCharacter => "invalid domain character",
InvalidUtf8 => "invalid UTF-8",
RelativeUrlWithoutBase => "relative URL without a base",
RelativeUrlWithCannotBeABaseBase => "relative URL with a cannot-be-a-base base",
SetHostOnCannotBeABaseUrl => "a cannot-be-a-base URL doesn’t have a host to set",
Expand Down
18 changes: 17 additions & 1 deletion url/tests/unit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@

use std::borrow::Cow;
use std::cell::{Cell, RefCell};
use std::convert::TryFrom;
use std::net::{Ipv4Addr, Ipv6Addr};
use std::path::{Path, PathBuf};
use url::{form_urlencoded, Host, Url};
use url::{form_urlencoded, Host, ParseError, Url};

#[test]
fn size() {
Expand Down Expand Up @@ -169,6 +170,21 @@ fn from_str() {
assert!("http://testing.com/this".parse::<Url>().is_ok());
}

#[test]
fn try_from_str() {
assert!(Url::try_from("http://testing.com/this").is_ok());
}

#[test]
fn try_from_slice() {
assert!(Url::try_from(&b"http://testing.com/this"[..]).is_ok());
}

#[test]
fn try_from_slice_invalid_utf8() {
assert!(Url::try_from(&[0, 159, 146, 150][..]) == Err(ParseError::InvalidUtf8));
}

#[test]
fn parse_with_params() {
let url = Url::parse_with_params(
Expand Down