From 092934c420e2f3fb6c947b4cc9252ea5d3b7eeee Mon Sep 17 00:00:00 2001 From: Kyle Bishop Date: Sun, 15 Jan 2017 12:48:58 +0700 Subject: [PATCH] add Url::parse_with_params() --- Cargo.toml | 2 +- src/lib.rs | 31 ++++++++++++++++++++++++++++++- tests/unit.rs | 8 ++++++++ 3 files changed, 39 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 4ae9905c..c2c1e009 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "url" -version = "1.2.5" +version = "1.3.0" authors = ["The rust-url developers"] description = "URL library for Rust, based on the WHATWG URL Standard" diff --git a/src/lib.rs b/src/lib.rs index 2c3b0a9b..0f9178c3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -125,6 +125,7 @@ use host::HostInternal; use parser::{Parser, Context, SchemeType, to_u32}; use percent_encoding::{PATH_SEGMENT_ENCODE_SET, USERINFO_ENCODE_SET, percent_encode, percent_decode, utf8_percent_encode}; +use std::borrow::Borrow; use std::cmp; #[cfg(feature = "serde")] use std::error::Error; use std::fmt::{self, Write}; @@ -242,6 +243,34 @@ impl Url { Url::options().parse(input) } + /// Parse an absolute URL from a string and add params to its query string. + /// + /// Existing params are not removed. + /// + /// # Examples + /// + /// ```rust + /// use url::Url; + /// + /// let url = Url::parse_with_params("https://example.net?dont=clobberme", + /// &[("lang", "rust"), ("browser", "servo")]); + /// ``` + #[inline] + pub fn parse_with_params(input: &str, iter: I) -> Result + where I: IntoIterator, + I::Item: Borrow<(K, V)>, + K: AsRef, + V: AsRef + { + let mut url = Url::options().parse(input); + + if let Ok(ref mut url) = url { + url.query_pairs_mut().extend_pairs(iter); + } + + url + } + /// Parse a string as an URL, with this URL as the base URL. /// /// # Examples @@ -1369,7 +1398,7 @@ impl Url { /// assert_eq!(url.as_str(), "foo://example.net/"); /// assert!(result.is_ok()); /// ``` - /// + /// /// /// Cannot change URL’s scheme from `https` to `foõ`: /// diff --git a/tests/unit.rs b/tests/unit.rs index 81aa04d3..9c22dd7f 100644 --- a/tests/unit.rs +++ b/tests/unit.rs @@ -111,6 +111,14 @@ fn from_str() { assert!("http://testing.com/this".parse::().is_ok()); } +#[test] +fn parse_with_params() { + let url = Url::parse_with_params("http://testing.com/this?dont=clobberme", + &[("lang", "rust")]).unwrap(); + + assert_eq!(url.as_str(), "http://testing.com/this?dont=clobberme&lang=rust"); +} + #[test] fn issue_124() { let url: Url = "file:a".parse().unwrap();