lib.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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. #[macro_use]
  15. extern crate matches;
  16. use percent_encoding::{percent_decode, percent_encode_byte};
  17. use std::borrow::{Borrow, Cow};
  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 { input }
  29. }
  30. /// The return type of `parse()`.
  31. #[derive(Copy, Clone)]
  32. pub struct Parse<'a> {
  33. input: &'a [u8],
  34. }
  35. impl<'a> Iterator for Parse<'a> {
  36. type Item = (Cow<'a, str>, Cow<'a, str>);
  37. fn next(&mut self) -> Option<Self::Item> {
  38. loop {
  39. if self.input.is_empty() {
  40. return None;
  41. }
  42. let mut split2 = self.input.splitn(2, |&b| b == b'&');
  43. let sequence = split2.next().unwrap();
  44. self.input = split2.next().unwrap_or(&[][..]);
  45. if sequence.is_empty() {
  46. continue;
  47. }
  48. let mut split2 = sequence.splitn(2, |&b| b == b'=');
  49. let name = split2.next().unwrap();
  50. let value = split2.next().unwrap_or(&[][..]);
  51. return Some((decode(name), decode(value)));
  52. }
  53. }
  54. }
  55. fn decode(input: &[u8]) -> Cow<'_, str> {
  56. let replaced = replace_plus(input);
  57. decode_utf8_lossy(match percent_decode(&replaced).into() {
  58. Cow::Owned(vec) => Cow::Owned(vec),
  59. Cow::Borrowed(_) => replaced,
  60. })
  61. }
  62. /// Replace b'+' with b' '
  63. fn replace_plus(input: &[u8]) -> Cow<'_, [u8]> {
  64. match input.iter().position(|&b| b == b'+') {
  65. None => Cow::Borrowed(input),
  66. Some(first_position) => {
  67. let mut replaced = input.to_owned();
  68. replaced[first_position] = b' ';
  69. for byte in &mut replaced[first_position + 1..] {
  70. if *byte == b'+' {
  71. *byte = b' ';
  72. }
  73. }
  74. Cow::Owned(replaced)
  75. }
  76. }
  77. }
  78. impl<'a> Parse<'a> {
  79. /// Return a new iterator that yields pairs of `String` instead of pairs of `Cow<str>`.
  80. pub fn into_owned(self) -> ParseIntoOwned<'a> {
  81. ParseIntoOwned { inner: self }
  82. }
  83. }
  84. /// Like `Parse`, but yields pairs of `String` instead of pairs of `Cow<str>`.
  85. pub struct ParseIntoOwned<'a> {
  86. inner: Parse<'a>,
  87. }
  88. impl<'a> Iterator for ParseIntoOwned<'a> {
  89. type Item = (String, String);
  90. fn next(&mut self) -> Option<Self::Item> {
  91. self.inner
  92. .next()
  93. .map(|(k, v)| (k.into_owned(), v.into_owned()))
  94. }
  95. }
  96. /// The [`application/x-www-form-urlencoded` byte serializer](
  97. /// https://url.spec.whatwg.org/#concept-urlencoded-byte-serializer).
  98. ///
  99. /// Return an iterator of `&str` slices.
  100. pub fn byte_serialize(input: &[u8]) -> ByteSerialize<'_> {
  101. ByteSerialize { bytes: input }
  102. }
  103. /// Return value of `byte_serialize()`.
  104. #[derive(Debug)]
  105. pub struct ByteSerialize<'a> {
  106. bytes: &'a [u8],
  107. }
  108. fn byte_serialized_unchanged(byte: u8) -> bool {
  109. matches!(byte, b'*' | b'-' | b'.' | b'0' ..= b'9' | b'A' ..= b'Z' | b'_' | b'a' ..= b'z')
  110. }
  111. impl<'a> Iterator for ByteSerialize<'a> {
  112. type Item = &'a str;
  113. fn next(&mut self) -> Option<&'a str> {
  114. if let Some((&first, tail)) = self.bytes.split_first() {
  115. if !byte_serialized_unchanged(first) {
  116. self.bytes = tail;
  117. return Some(if first == b' ' {
  118. "+"
  119. } else {
  120. percent_encode_byte(first)
  121. });
  122. }
  123. let position = tail.iter().position(|&b| !byte_serialized_unchanged(b));
  124. let (unchanged_slice, remaining) = match position {
  125. // 1 for first_byte + i unchanged in tail
  126. Some(i) => self.bytes.split_at(1 + i),
  127. None => (self.bytes, &[][..]),
  128. };
  129. self.bytes = remaining;
  130. // This unsafe is appropriate because we have already checked these
  131. // bytes in byte_serialized_unchanged, which checks for a subset
  132. // of UTF-8. So we know these bytes are valid UTF-8, and doing
  133. // another UTF-8 check would be wasteful.
  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. if target.as_mut_string().len() < start_position {
  192. panic!(
  193. "invalid length {} for target of length {}",
  194. start_position,
  195. target.as_mut_string().len()
  196. );
  197. }
  198. Serializer {
  199. target: Some(target),
  200. start_position,
  201. encoding: None,
  202. }
  203. }
  204. /// Remove any existing name/value pair.
  205. ///
  206. /// Panics if called after `.finish()`.
  207. pub fn clear(&mut self) -> &mut Self {
  208. string(&mut self.target).truncate(self.start_position);
  209. self
  210. }
  211. /// Set the character encoding to be used for names and values before percent-encoding.
  212. pub fn encoding_override(&mut self, new: EncodingOverride<'a>) -> &mut Self {
  213. self.encoding = new;
  214. self
  215. }
  216. /// Serialize and append a name/value pair.
  217. ///
  218. /// Panics if called after `.finish()`.
  219. pub fn append_pair(&mut self, name: &str, value: &str) -> &mut Self {
  220. append_pair(
  221. string(&mut self.target),
  222. self.start_position,
  223. self.encoding,
  224. name,
  225. value,
  226. );
  227. self
  228. }
  229. /// Serialize and append a name of parameter without any value.
  230. ///
  231. /// Panics if called after `.finish()`.
  232. pub fn append_key_only(&mut self, name: &str) -> &mut Self {
  233. append_key_only(
  234. string(&mut self.target),
  235. self.start_position,
  236. self.encoding,
  237. name,
  238. );
  239. self
  240. }
  241. /// Serialize and append a number of name/value pairs.
  242. ///
  243. /// This simply calls `append_pair` repeatedly.
  244. /// This can be more convenient, so the user doesn’t need to introduce a block
  245. /// to limit the scope of `Serializer`’s borrow of its string.
  246. ///
  247. /// Panics if called after `.finish()`.
  248. pub fn extend_pairs<I, K, V>(&mut self, iter: I) -> &mut Self
  249. where
  250. I: IntoIterator,
  251. I::Item: Borrow<(K, V)>,
  252. K: AsRef<str>,
  253. V: AsRef<str>,
  254. {
  255. {
  256. let string = string(&mut self.target);
  257. for pair in iter {
  258. let &(ref k, ref v) = pair.borrow();
  259. append_pair(
  260. string,
  261. self.start_position,
  262. self.encoding,
  263. k.as_ref(),
  264. v.as_ref(),
  265. );
  266. }
  267. }
  268. self
  269. }
  270. /// Serialize and append a number of names without values.
  271. ///
  272. /// This simply calls `append_key_only` repeatedly.
  273. /// This can be more convenient, so the user doesn’t need to introduce a block
  274. /// to limit the scope of `Serializer`’s borrow of its string.
  275. ///
  276. /// Panics if called after `.finish()`.
  277. pub fn extend_keys_only<I, K>(&mut self, iter: I) -> &mut Self
  278. where
  279. I: IntoIterator,
  280. I::Item: Borrow<K>,
  281. K: AsRef<str>,
  282. {
  283. {
  284. let string = string(&mut self.target);
  285. for key in iter {
  286. let k = key.borrow().as_ref();
  287. append_key_only(string, self.start_position, self.encoding, k);
  288. }
  289. }
  290. self
  291. }
  292. /// If this serializer was constructed with a string, take and return that string.
  293. ///
  294. /// ```rust
  295. /// use form_urlencoded;
  296. /// let encoded: String = form_urlencoded::Serializer::new(String::new())
  297. /// .append_pair("foo", "bar & baz")
  298. /// .append_pair("saison", "Été+hiver")
  299. /// .finish();
  300. /// assert_eq!(encoded, "foo=bar+%26+baz&saison=%C3%89t%C3%A9%2Bhiver");
  301. /// ```
  302. ///
  303. /// Panics if called more than once.
  304. pub fn finish(&mut self) -> T::Finished {
  305. self.target
  306. .take()
  307. .expect("url::form_urlencoded::Serializer double finish")
  308. .finish()
  309. }
  310. }
  311. fn append_separator_if_needed(string: &mut String, start_position: usize) {
  312. if string.len() > start_position {
  313. string.push('&')
  314. }
  315. }
  316. fn string<T: Target>(target: &mut Option<T>) -> &mut String {
  317. target
  318. .as_mut()
  319. .expect("url::form_urlencoded::Serializer finished")
  320. .as_mut_string()
  321. }
  322. fn append_pair(
  323. string: &mut String,
  324. start_position: usize,
  325. encoding: EncodingOverride<'_>,
  326. name: &str,
  327. value: &str,
  328. ) {
  329. append_separator_if_needed(string, start_position);
  330. append_encoded(name, string, encoding);
  331. string.push('=');
  332. append_encoded(value, string, encoding);
  333. }
  334. fn append_key_only(
  335. string: &mut String,
  336. start_position: usize,
  337. encoding: EncodingOverride,
  338. name: &str,
  339. ) {
  340. append_separator_if_needed(string, start_position);
  341. append_encoded(name, string, encoding);
  342. }
  343. fn append_encoded(s: &str, string: &mut String, encoding: EncodingOverride<'_>) {
  344. string.extend(byte_serialize(&encode(encoding, s)))
  345. }
  346. pub(crate) fn encode<'a>(encoding_override: EncodingOverride<'_>, input: &'a str) -> Cow<'a, [u8]> {
  347. if let Some(o) = encoding_override {
  348. return o(input);
  349. }
  350. input.as_bytes().into()
  351. }
  352. pub(crate) fn decode_utf8_lossy(input: Cow<'_, [u8]>) -> Cow<'_, str> {
  353. // Note: This function is duplicated in `percent_encoding/lib.rs`.
  354. match input {
  355. Cow::Borrowed(bytes) => String::from_utf8_lossy(bytes),
  356. Cow::Owned(bytes) => {
  357. match String::from_utf8_lossy(&bytes) {
  358. Cow::Borrowed(utf8) => {
  359. // If from_utf8_lossy returns a Cow::Borrowed, then we can
  360. // be sure our original bytes were valid UTF-8. This is because
  361. // if the bytes were invalid UTF-8 from_utf8_lossy would have
  362. // to allocate a new owned string to back the Cow so it could
  363. // replace invalid bytes with a placeholder.
  364. // First we do a debug_assert to confirm our description above.
  365. let raw_utf8: *const [u8];
  366. raw_utf8 = utf8.as_bytes();
  367. debug_assert!(raw_utf8 == &*bytes as *const [u8]);
  368. // Given we know the original input bytes are valid UTF-8,
  369. // and we have ownership of those bytes, we re-use them and
  370. // return a Cow::Owned here.
  371. Cow::Owned(unsafe { String::from_utf8_unchecked(bytes) })
  372. }
  373. Cow::Owned(s) => Cow::Owned(s),
  374. }
  375. }
  376. }
  377. }
  378. pub type EncodingOverride<'a> = Option<&'a dyn Fn(&str) -> Cow<'_, [u8]>>;