form_urlencoded.rs 12 KB

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