Skip to content

Commit

Permalink
Add String and &String convert for PathAndQuery (#450)
Browse files Browse the repository at this point in the history
When building a URI, it is not possible to provide neither String nor
&String, which is useful when adding a path_and_query from a string
built using format!.

This commit adds implementation of From<String> and From<&String> for
PathAndQuery.
  • Loading branch information
mkindahl authored Dec 8, 2020
1 parent be05ed2 commit 8be5a58
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
43 changes: 43 additions & 0 deletions src/uri/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,3 +152,46 @@ impl Default for Builder {
}
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn build_from_str() {
let uri = Builder::new()
.scheme(Scheme::HTTP)
.authority("hyper.rs")
.path_and_query("/foo?a=1")
.build()
.unwrap();
assert_eq!(uri.scheme_str(), Some("http"));
assert_eq!(uri.authority().unwrap().host(), "hyper.rs");
assert_eq!(uri.path(), "/foo");
assert_eq!(uri.query(), Some("a=1"));
}

#[test]
fn build_from_string() {
for i in 1..10 {
let uri = Builder::new()
.path_and_query(format!("/foo?a={}", i))
.build()
.unwrap();
let expected_query = format!("a={}", i);
assert_eq!(uri.path(), "/foo");
assert_eq!(uri.query(), Some(expected_query.as_str()));
}
}

#[test]
fn build_from_string_ref() {
for i in 1..10 {
let p_a_q = format!("/foo?a={}", i);
let uri = Builder::new().path_and_query(&p_a_q).build().unwrap();
let expected_query = format!("a={}", i);
assert_eq!(uri.path(), "/foo");
assert_eq!(uri.query(), Some(expected_query.as_str()));
}
}
}
16 changes: 16 additions & 0 deletions src/uri/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,22 @@ impl<'a> TryFrom<&'a str> for PathAndQuery {
}
}

impl TryFrom<String> for PathAndQuery {
type Error = InvalidUri;
#[inline]
fn try_from(s: String) -> Result<Self, Self::Error> {
TryFrom::try_from(s.as_bytes())
}
}

impl TryFrom<&String> for PathAndQuery {
type Error = InvalidUri;
#[inline]
fn try_from(s: &String) -> Result<Self, Self::Error> {
TryFrom::try_from(s.as_bytes())
}
}

impl FromStr for PathAndQuery {
type Err = InvalidUri;
#[inline]
Expand Down

0 comments on commit 8be5a58

Please sign in to comment.