lib.rs 13 KB

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