lib.rs 9.6 KB

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