Skip to content
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
19 changes: 19 additions & 0 deletions src/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,4 +144,23 @@ mod tests {
assert_eq!(url.to_string(), result.to_string());
}
}

#[test]
fn authorities() {
let data = [
("http://example.com/", "example.com"),
("http://noslash.com", "noslash.com"),
("http://@emptyuser.com/", "emptyuser.com"),
("http://:@emptypass.com/", ":@emptypass.com"),
("http://user@user.com/", "user@user.com"),
("http://user:pass@userpass.com/", "user:pass@userpass.com"),
("http://host.com:8080/path", "host.com:8080"),
("http://user:pass@host.com:8080/path", "user:pass@host.com:8080"),
];
for &(input, result) in data.iter() {
let url = Url::parse(input).unwrap();
let auth = url.authority().unwrap();
assert_eq!(auth.to_string(), result.to_string());
}
}
}
45 changes: 45 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,40 @@ pub struct RelativeSchemeData {
pub path: Vec<String>,
}

/// The Authority part of a URI.
pub struct Authority<'a> {
username: Option<&'a str>,
password: Option<&'a str>,
host: Option<&'a Host>,
port: Option<u16>
}

impl<'a> Show for Authority<'a> {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), FormatError> {
match self.username {
Some(ref u) => {
try!(UserInfoFormatter {
username: *u,
password: self.password
}.fmt(fmt));
},
None => ()
}
match self.host {
Some(ref h) => try!(h.fmt(fmt)),
None => ()
}
match self.port {
Some(ref p) => {
try!(':'.fmt(fmt));
try!(p.fmt(fmt));
},
None => ()
}
Ok(())
}
}

impl<S: hash::Writer> hash::Hash<S> for Url {
fn hash(&self, state: &mut S) {
self.serialize().hash(state)
Expand Down Expand Up @@ -554,6 +588,17 @@ impl Url {
}
}

/// If the URL is in a *relative scheme*, return its Authority.
#[inline]
pub fn authority<'a>(&'a self) -> Option<Authority<'a>> {
self.relative_scheme_data().and(Some(Authority {
username: self.username(),
password: self.password(),
host: self.host(),
port: self.port()
}))
}

/// If the URL is in a *relative scheme*, return its username.
#[inline]
pub fn username<'a>(&'a self) -> Option<&'a str> {
Expand Down