form_urlencoded.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. // Copyright 2013-2016 The rust-url developers.
  2. //
  3. // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
  4. // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
  5. // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
  6. // option. This file may not be copied, modified, or distributed
  7. // except according to those terms.
  8. //! Parser and serializer for the [`application/x-www-form-urlencoded` syntax](
  9. //! http://url.spec.whatwg.org/#application/x-www-form-urlencoded),
  10. //! as used by HTML forms.
  11. //!
  12. //! Converts between a string (such as an URL’s query string)
  13. //! and a sequence of (name, value) pairs.
  14. use encoding::EncodingOverride;
  15. use percent_encoding::{percent_encode_byte, percent_decode};
  16. use std::borrow::{Borrow, Cow};
  17. use std::fmt;
  18. use std::str;
  19. /// Convert a byte string in the `application/x-www-form-urlencoded` syntax
  20. /// into a iterator of (name, value) pairs.
  21. ///
  22. /// Use `parse(input.as_bytes())` to parse a `&str` string.
  23. ///
  24. /// The names and values are percent-decoded. For instance, `%23first=%25try%25` will be
  25. /// converted to `[("#first", "%try%")]`.
  26. #[inline]
  27. pub fn parse(input: &[u8]) -> Parse {
  28. Parse {
  29. input: input,
  30. encoding: EncodingOverride::utf8(),
  31. }
  32. }
  33. /// Convert a byte string in the `application/x-www-form-urlencoded` syntax
  34. /// into a iterator of (name, value) pairs.
  35. ///
  36. /// Use `parse(input.as_bytes())` to parse a `&str` string.
  37. ///
  38. /// This function is only available if the `query_encoding`
  39. /// [feature](http://doc.crates.io/manifest.html#the-features-section]) is enabled.
  40. ///
  41. /// Arguments:
  42. ///
  43. /// * `encoding_override`: The character encoding each name and values is decoded as
  44. /// after percent-decoding. Defaults to UTF-8.
  45. /// `EncodingRef` is defined in [rust-encoding](https://github.com/lifthrasiir/rust-encoding).
  46. /// * `use_charset`: The *use _charset_ flag*. If in doubt, set to `false`.
  47. #[cfg(feature = "query_encoding")]
  48. pub fn parse_with_encoding<'a>(input: &'a [u8],
  49. encoding_override: Option<::encoding::EncodingRef>,
  50. use_charset: bool)
  51. -> Result<Parse<'a>, ()> {
  52. use std::ascii::AsciiExt;
  53. let mut encoding = EncodingOverride::from_opt_encoding(encoding_override);
  54. if !(encoding.is_utf8() || input.is_ascii()) {
  55. return Err(())
  56. }
  57. if use_charset {
  58. for sequence in input.split(|&b| b == b'&') {
  59. // No '+' in "_charset_" to replace with ' '.
  60. if sequence.starts_with(b"_charset_=") {
  61. let value = &sequence[b"_charset_=".len()..];
  62. // Skip replacing '+' with ' ' in value since no encoding label contains either:
  63. // https://encoding.spec.whatwg.org/#names-and-labels
  64. if let Some(e) = EncodingOverride::lookup(value) {
  65. encoding = e;
  66. break
  67. }
  68. }
  69. }
  70. }
  71. Ok(Parse {
  72. input: input,
  73. encoding: encoding,
  74. })
  75. }
  76. /// The return type of `parse()`.
  77. #[derive(Copy, Clone, Debug)]
  78. pub struct Parse<'a> {
  79. input: &'a [u8],
  80. encoding: EncodingOverride,
  81. }
  82. impl<'a> Iterator for Parse<'a> {
  83. type Item = (Cow<'a, str>, Cow<'a, str>);
  84. fn next(&mut self) -> Option<Self::Item> {
  85. loop {
  86. if self.input.is_empty() {
  87. return None
  88. }
  89. let mut split2 = self.input.splitn(2, |&b| b == b'&');
  90. let sequence = split2.next().unwrap();
  91. self.input = split2.next().unwrap_or(&[][..]);
  92. if sequence.is_empty() {
  93. continue
  94. }
  95. let mut split2 = sequence.splitn(2, |&b| b == b'=');
  96. let name = split2.next().unwrap();
  97. let value = split2.next().unwrap_or(&[][..]);
  98. return Some((
  99. decode(name, self.encoding),
  100. decode(value, self.encoding),
  101. ))
  102. }
  103. }
  104. }
  105. fn decode(input: &[u8], encoding: EncodingOverride) -> Cow<str> {
  106. let replaced = replace_plus(input);
  107. encoding.decode(match percent_decode(&replaced).if_any() {
  108. Some(vec) => Cow::Owned(vec),
  109. None => replaced,
  110. })
  111. }
  112. /// Replace b'+' with b' '
  113. fn replace_plus(input: &[u8]) -> Cow<[u8]> {
  114. match input.iter().position(|&b| b == b'+') {
  115. None => Cow::Borrowed(input),
  116. Some(first_position) => {
  117. let mut replaced = input.to_owned();
  118. replaced[first_position] = b' ';
  119. for byte in &mut replaced[first_position + 1..] {
  120. if *byte == b'+' {
  121. *byte = b' ';
  122. }
  123. }
  124. Cow::Owned(replaced)
  125. }
  126. }
  127. }
  128. impl<'a> Parse<'a> {
  129. /// Return a new iterator that yields pairs of `String` instead of pairs of `Cow<str>`.
  130. pub fn into_owned(self) -> ParseIntoOwned<'a> {
  131. ParseIntoOwned { inner: self }
  132. }
  133. }
  134. /// Like `Parse`, but yields pairs of `String` instead of pairs of `Cow<str>`.
  135. #[derive(Debug)]
  136. pub struct ParseIntoOwned<'a> {
  137. inner: Parse<'a>
  138. }
  139. impl<'a> Iterator for ParseIntoOwned<'a> {
  140. type Item = (String, String);
  141. fn next(&mut self) -> Option<Self::Item> {
  142. self.inner.next().map(|(k, v)| (k.into_owned(), v.into_owned()))
  143. }
  144. }
  145. /// The [`application/x-www-form-urlencoded` byte serializer](
  146. /// https://url.spec.whatwg.org/#concept-urlencoded-byte-serializer).
  147. ///
  148. /// Return an iterator of `&str` slices.
  149. pub fn byte_serialize(input: &[u8]) -> ByteSerialize {
  150. ByteSerialize {
  151. bytes: input,
  152. }
  153. }
  154. /// Return value of `byte_serialize()`.
  155. #[derive(Debug)]
  156. pub struct ByteSerialize<'a> {
  157. bytes: &'a [u8],
  158. }
  159. fn byte_serialized_unchanged(byte: u8) -> bool {
  160. matches!(byte, b'*' | b'-' | b'.' | b'0' ... b'9' | b'A' ... b'Z' | b'_' | b'a' ... b'z')
  161. }
  162. impl<'a> Iterator for ByteSerialize<'a> {
  163. type Item = &'a str;
  164. fn next(&mut self) -> Option<&'a str> {
  165. if let Some((&first, tail)) = self.bytes.split_first() {
  166. if !byte_serialized_unchanged(first) {
  167. self.bytes = tail;
  168. return Some(if first == b' ' { "+" } else { percent_encode_byte(first) })
  169. }
  170. let position = tail.iter().position(|&b| !byte_serialized_unchanged(b));
  171. let (unchanged_slice, remaining) = match position {
  172. // 1 for first_byte + i unchanged in tail
  173. Some(i) => self.bytes.split_at(1 + i),
  174. None => (self.bytes, &[][..]),
  175. };
  176. self.bytes = remaining;
  177. Some(unsafe { str::from_utf8_unchecked(unchanged_slice) })
  178. } else {
  179. None
  180. }
  181. }
  182. fn size_hint(&self) -> (usize, Option<usize>) {
  183. if self.bytes.is_empty() {
  184. (0, Some(0))
  185. } else {
  186. (1, Some(self.bytes.len()))
  187. }
  188. }
  189. }
  190. /// The [`application/x-www-form-urlencoded` serializer](
  191. /// https://url.spec.whatwg.org/#concept-urlencoded-serializer).
  192. #[derive(Debug)]
  193. pub struct Serializer<T: Target> {
  194. target: Option<T>,
  195. start_position: usize,
  196. encoding: EncodingOverride,
  197. custom_encoding: Option<SilentDebug<Box<FnMut(&str) -> Cow<[u8]>>>>,
  198. }
  199. struct SilentDebug<T>(T);
  200. impl<T> fmt::Debug for SilentDebug<T> {
  201. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  202. f.write_str("…")
  203. }
  204. }
  205. pub trait Target {
  206. fn as_mut_string(&mut self) -> &mut String;
  207. fn finish(self) -> Self::Finished;
  208. type Finished;
  209. }
  210. impl Target for String {
  211. fn as_mut_string(&mut self) -> &mut String { self }
  212. fn finish(self) -> Self { self }
  213. type Finished = Self;
  214. }
  215. impl<'a> Target for &'a mut String {
  216. fn as_mut_string(&mut self) -> &mut String { &mut **self }
  217. fn finish(self) -> Self { self }
  218. type Finished = Self;
  219. }
  220. // `as_mut_string` string here exposes the internal serialization of an `Url`,
  221. // which should not be exposed to users.
  222. // We achieve that by not giving users direct access to `UrlQuery`:
  223. // * Its fields are private
  224. // (and so can not be constructed with struct literal syntax outside of this crate),
  225. // * It has no constructor
  226. // * It is only visible (on the type level) to users in the return type of
  227. // `Url::query_pairs_mut` which is `Serializer<UrlQuery>`
  228. // * `Serializer` keeps its target in a private field
  229. // * Unlike in other `Target` impls, `UrlQuery::finished` does not return `Self`.
  230. impl<'a> Target for ::UrlQuery<'a> {
  231. fn as_mut_string(&mut self) -> &mut String {
  232. &mut self.url.as_mut().unwrap().serialization
  233. }
  234. fn finish(mut self) -> &'a mut ::Url {
  235. let url = self.url.take().unwrap();
  236. url.restore_already_parsed_fragment(self.fragment.take());
  237. url
  238. }
  239. type Finished = &'a mut ::Url;
  240. }
  241. impl<T: Target> Serializer<T> {
  242. /// Create a new `application/x-www-form-urlencoded` serializer for the given target.
  243. ///
  244. /// If the target is non-empty,
  245. /// its content is assumed to already be in `application/x-www-form-urlencoded` syntax.
  246. pub fn new(target: T) -> Self {
  247. Self::for_suffix(target, 0)
  248. }
  249. /// Create a new `application/x-www-form-urlencoded` serializer
  250. /// for a suffix of the given target.
  251. ///
  252. /// If that suffix is non-empty,
  253. /// its content is assumed to already be in `application/x-www-form-urlencoded` syntax.
  254. pub fn for_suffix(mut target: T, start_position: usize) -> Self {
  255. &target.as_mut_string()[start_position..]; // Panic if out of bounds
  256. Serializer {
  257. target: Some(target),
  258. start_position: start_position,
  259. encoding: EncodingOverride::utf8(),
  260. custom_encoding: None,
  261. }
  262. }
  263. /// Remove any existing name/value pair.
  264. ///
  265. /// Panics if called after `.finish()`.
  266. pub fn clear(&mut self) -> &mut Self {
  267. string(&mut self.target).truncate(self.start_position);
  268. self
  269. }
  270. /// Set the character encoding to be used for names and values before percent-encoding.
  271. #[cfg(feature = "query_encoding")]
  272. pub fn encoding_override(&mut self, new: Option<::encoding::EncodingRef>) -> &mut Self {
  273. self.encoding = EncodingOverride::from_opt_encoding(new).to_output_encoding();
  274. self
  275. }
  276. /// Set the character encoding to be used for names and values before percent-encoding.
  277. pub fn custom_encoding_override<F>(&mut self, encode: F) -> &mut Self
  278. where F: FnMut(&str) -> Cow<[u8]> + 'static
  279. {
  280. self.custom_encoding = Some(SilentDebug(Box::new(encode)));
  281. self
  282. }
  283. /// Serialize and append a name/value pair.
  284. ///
  285. /// Panics if called after `.finish()`.
  286. pub fn append_pair(&mut self, name: &str, value: &str) -> &mut Self {
  287. append_pair(string(&mut self.target), self.start_position, self.encoding,
  288. &mut self.custom_encoding, name, value);
  289. self
  290. }
  291. /// Serialize and append a number of name/value pairs.
  292. ///
  293. /// This simply calls `append_pair` repeatedly.
  294. /// This can be more convenient, so the user doesn’t need to introduce a block
  295. /// to limit the scope of `Serializer`’s borrow of its string.
  296. ///
  297. /// Panics if called after `.finish()`.
  298. pub fn extend_pairs<I, K, V>(&mut self, iter: I) -> &mut Self
  299. where I: IntoIterator, I::Item: Borrow<(K, V)>, K: AsRef<str>, V: AsRef<str> {
  300. {
  301. let string = string(&mut self.target);
  302. for pair in iter {
  303. let &(ref k, ref v) = pair.borrow();
  304. append_pair(string, self.start_position, self.encoding,
  305. &mut self.custom_encoding, k.as_ref(), v.as_ref());
  306. }
  307. }
  308. self
  309. }
  310. /// Add a name/value pair whose name is `_charset_`
  311. /// and whose value is the character encoding’s name.
  312. /// (See the `encoding_override()` method.)
  313. ///
  314. /// Panics if called after `.finish()`.
  315. #[cfg(feature = "query_encoding")]
  316. pub fn append_charset(&mut self) -> &mut Self {
  317. assert!(self.custom_encoding.is_none(),
  318. "Cannot use both custom_encoding_override() and append_charset()");
  319. {
  320. let string = string(&mut self.target);
  321. append_separator_if_needed(string, self.start_position);
  322. string.push_str("_charset_=");
  323. string.push_str(self.encoding.name());
  324. }
  325. self
  326. }
  327. /// If this serializer was constructed with a string, take and return that string.
  328. ///
  329. /// ```rust
  330. /// use url::form_urlencoded;
  331. /// let encoded: String = form_urlencoded::Serializer::new(String::new())
  332. /// .append_pair("foo", "bar & baz")
  333. /// .append_pair("saison", "Été+hiver")
  334. /// .finish();
  335. /// assert_eq!(encoded, "foo=bar+%26+baz&saison=%C3%89t%C3%A9%2Bhiver");
  336. /// ```
  337. ///
  338. /// Panics if called more than once.
  339. pub fn finish(&mut self) -> T::Finished {
  340. self.target.take().expect("url::form_urlencoded::Serializer double finish").finish()
  341. }
  342. }
  343. fn append_separator_if_needed(string: &mut String, start_position: usize) {
  344. if string.len() > start_position {
  345. string.push('&')
  346. }
  347. }
  348. fn string<T: Target>(target: &mut Option<T>) -> &mut String {
  349. target.as_mut().expect("url::form_urlencoded::Serializer finished").as_mut_string()
  350. }
  351. fn append_pair(string: &mut String, start_position: usize, encoding: EncodingOverride,
  352. custom_encoding: &mut Option<SilentDebug<Box<FnMut(&str) -> Cow<[u8]>>>>,
  353. name: &str, value: &str) {
  354. append_separator_if_needed(string, start_position);
  355. append_encoded(name, string, encoding, custom_encoding);
  356. string.push('=');
  357. append_encoded(value, string, encoding, custom_encoding);
  358. }
  359. fn append_encoded(s: &str, string: &mut String, encoding: EncodingOverride,
  360. custom_encoding: &mut Option<SilentDebug<Box<FnMut(&str) -> Cow<[u8]>>>>) {
  361. let bytes = if let Some(SilentDebug(ref mut custom)) = *custom_encoding {
  362. custom(s)
  363. } else {
  364. encoding.encode(s.into())
  365. };
  366. string.extend(byte_serialize(&bytes));
  367. }