Skip to content

Commit 8be5a58

Browse files
authored
Add String and &String convert for PathAndQuery (#450)
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.
1 parent be05ed2 commit 8be5a58

2 files changed

Lines changed: 59 additions & 0 deletions

File tree

src/uri/builder.rs

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,3 +152,46 @@ impl Default for Builder {
152152
}
153153
}
154154
}
155+
156+
#[cfg(test)]
157+
mod tests {
158+
use super::*;
159+
160+
#[test]
161+
fn build_from_str() {
162+
let uri = Builder::new()
163+
.scheme(Scheme::HTTP)
164+
.authority("hyper.rs")
165+
.path_and_query("/foo?a=1")
166+
.build()
167+
.unwrap();
168+
assert_eq!(uri.scheme_str(), Some("http"));
169+
assert_eq!(uri.authority().unwrap().host(), "hyper.rs");
170+
assert_eq!(uri.path(), "/foo");
171+
assert_eq!(uri.query(), Some("a=1"));
172+
}
173+
174+
#[test]
175+
fn build_from_string() {
176+
for i in 1..10 {
177+
let uri = Builder::new()
178+
.path_and_query(format!("/foo?a={}", i))
179+
.build()
180+
.unwrap();
181+
let expected_query = format!("a={}", i);
182+
assert_eq!(uri.path(), "/foo");
183+
assert_eq!(uri.query(), Some(expected_query.as_str()));
184+
}
185+
}
186+
187+
#[test]
188+
fn build_from_string_ref() {
189+
for i in 1..10 {
190+
let p_a_q = format!("/foo?a={}", i);
191+
let uri = Builder::new().path_and_query(&p_a_q).build().unwrap();
192+
let expected_query = format!("a={}", i);
193+
assert_eq!(uri.path(), "/foo");
194+
assert_eq!(uri.query(), Some(expected_query.as_str()));
195+
}
196+
}
197+
}

src/uri/path.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,22 @@ impl<'a> TryFrom<&'a str> for PathAndQuery {
279279
}
280280
}
281281

282+
impl TryFrom<String> for PathAndQuery {
283+
type Error = InvalidUri;
284+
#[inline]
285+
fn try_from(s: String) -> Result<Self, Self::Error> {
286+
TryFrom::try_from(s.as_bytes())
287+
}
288+
}
289+
290+
impl TryFrom<&String> for PathAndQuery {
291+
type Error = InvalidUri;
292+
#[inline]
293+
fn try_from(s: &String) -> Result<Self, Self::Error> {
294+
TryFrom::try_from(s.as_bytes())
295+
}
296+
}
297+
282298
impl FromStr for PathAndQuery {
283299
type Err = InvalidUri;
284300
#[inline]

0 commit comments

Comments
 (0)