lib.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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. //! URLs use special characters to indicate the parts of the request.
  9. //! For example, a `?` question mark marks the end of a path and the start of a query string.
  10. //! In order for that character to exist inside a path, it needs to be encoded differently.
  11. //!
  12. //! Percent encoding replaces reserved characters with the `%` escape character
  13. //! followed by a byte value as two hexadecimal digits.
  14. //! For example, an ASCII space is replaced with `%20`.
  15. //!
  16. //! When encoding, the set of characters that can (and should, for readability) be left alone
  17. //! depends on the context.
  18. //! The `?` question mark mentioned above is not a separator when used literally
  19. //! inside of a query string, and therefore does not need to be encoded.
  20. //! The [`AsciiSet`] parameter of [`percent_encode`] and [`utf8_percent_encode`]
  21. //! lets callers configure this.
  22. //!
  23. //! This crate deliberately does not provide many different sets.
  24. //! Users should consider in what context the encoded string will be used,
  25. //! read relevant specifications, and define their own set.
  26. //! This is done by using the `add` method of an existing set.
  27. //!
  28. //! # Examples
  29. //!
  30. //! ```
  31. //! use percent_encoding::{utf8_percent_encode, AsciiSet, CONTROLS};
  32. //!
  33. //! /// https://url.spec.whatwg.org/#fragment-percent-encode-set
  34. //! const FRAGMENT: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`');
  35. //!
  36. //! assert_eq!(utf8_percent_encode("foo <bar>", FRAGMENT).to_string(), "foo%20%3Cbar%3E");
  37. //! ```
  38. #![no_std]
  39. // For forwards compatibility
  40. #[cfg(feature = "std")]
  41. extern crate std as _;
  42. #[cfg(feature = "alloc")]
  43. extern crate alloc;
  44. #[cfg(feature = "alloc")]
  45. use alloc::{
  46. borrow::{Cow, ToOwned},
  47. string::String,
  48. vec::Vec,
  49. };
  50. use core::{fmt, slice, str};
  51. pub use self::ascii_set::{AsciiSet, CONTROLS, NON_ALPHANUMERIC};
  52. mod ascii_set;
  53. /// Return the percent-encoding of the given byte.
  54. ///
  55. /// This is unconditional, unlike `percent_encode()` which has an `AsciiSet` parameter.
  56. ///
  57. /// # Examples
  58. ///
  59. /// ```
  60. /// use percent_encoding::percent_encode_byte;
  61. ///
  62. /// assert_eq!("foo bar".bytes().map(percent_encode_byte).collect::<String>(),
  63. /// "%66%6F%6F%20%62%61%72");
  64. /// ```
  65. #[inline]
  66. pub fn percent_encode_byte(byte: u8) -> &'static str {
  67. static ENC_TABLE: &[u8; 768] = b"\
  68. %00%01%02%03%04%05%06%07%08%09%0A%0B%0C%0D%0E%0F\
  69. %10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F\
  70. %20%21%22%23%24%25%26%27%28%29%2A%2B%2C%2D%2E%2F\
  71. %30%31%32%33%34%35%36%37%38%39%3A%3B%3C%3D%3E%3F\
  72. %40%41%42%43%44%45%46%47%48%49%4A%4B%4C%4D%4E%4F\
  73. %50%51%52%53%54%55%56%57%58%59%5A%5B%5C%5D%5E%5F\
  74. %60%61%62%63%64%65%66%67%68%69%6A%6B%6C%6D%6E%6F\
  75. %70%71%72%73%74%75%76%77%78%79%7A%7B%7C%7D%7E%7F\
  76. %80%81%82%83%84%85%86%87%88%89%8A%8B%8C%8D%8E%8F\
  77. %90%91%92%93%94%95%96%97%98%99%9A%9B%9C%9D%9E%9F\
  78. %A0%A1%A2%A3%A4%A5%A6%A7%A8%A9%AA%AB%AC%AD%AE%AF\
  79. %B0%B1%B2%B3%B4%B5%B6%B7%B8%B9%BA%BB%BC%BD%BE%BF\
  80. %C0%C1%C2%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF\
  81. %D0%D1%D2%D3%D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF\
  82. %E0%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF\
  83. %F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE%FF\
  84. ";
  85. let index = usize::from(byte) * 3;
  86. // SAFETY: ENC_TABLE is ascii-only, so any subset of it should be
  87. // ascii-only too, which is valid utf8.
  88. unsafe { str::from_utf8_unchecked(&ENC_TABLE[index..index + 3]) }
  89. }
  90. /// Percent-encode the given bytes with the given set.
  91. ///
  92. /// Non-ASCII bytes and bytes in `ascii_set` are encoded.
  93. ///
  94. /// The return type:
  95. ///
  96. /// * Implements `Iterator<Item = &str>` and therefore has a `.collect::<String>()` method,
  97. /// * Implements `Display` and therefore has a `.to_string()` method,
  98. /// * Implements `Into<Cow<str>>` borrowing `input` when none of its bytes are encoded.
  99. ///
  100. /// # Examples
  101. ///
  102. /// ```
  103. /// use percent_encoding::{percent_encode, NON_ALPHANUMERIC};
  104. ///
  105. /// assert_eq!(percent_encode(b"foo bar?", NON_ALPHANUMERIC).to_string(), "foo%20bar%3F");
  106. /// ```
  107. #[inline]
  108. pub fn percent_encode<'a>(input: &'a [u8], ascii_set: &'static AsciiSet) -> PercentEncode<'a> {
  109. PercentEncode {
  110. bytes: input,
  111. ascii_set,
  112. }
  113. }
  114. /// Percent-encode the UTF-8 encoding of the given string.
  115. ///
  116. /// See [`percent_encode`] regarding the return type.
  117. ///
  118. /// # Examples
  119. ///
  120. /// ```
  121. /// use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
  122. ///
  123. /// assert_eq!(utf8_percent_encode("foo bar?", NON_ALPHANUMERIC).to_string(), "foo%20bar%3F");
  124. /// ```
  125. #[inline]
  126. pub fn utf8_percent_encode<'a>(input: &'a str, ascii_set: &'static AsciiSet) -> PercentEncode<'a> {
  127. percent_encode(input.as_bytes(), ascii_set)
  128. }
  129. /// The return type of [`percent_encode`] and [`utf8_percent_encode`].
  130. #[derive(Debug, Clone, PartialEq, Eq)]
  131. pub struct PercentEncode<'a> {
  132. bytes: &'a [u8],
  133. ascii_set: &'static AsciiSet,
  134. }
  135. impl<'a> Iterator for PercentEncode<'a> {
  136. type Item = &'a str;
  137. fn next(&mut self) -> Option<&'a str> {
  138. if let Some((&first_byte, remaining)) = self.bytes.split_first() {
  139. if self.ascii_set.should_percent_encode(first_byte) {
  140. self.bytes = remaining;
  141. Some(percent_encode_byte(first_byte))
  142. } else {
  143. // The unsafe blocks here are appropriate because the bytes are
  144. // confirmed as a subset of UTF-8 in should_percent_encode.
  145. for (i, &byte) in remaining.iter().enumerate() {
  146. if self.ascii_set.should_percent_encode(byte) {
  147. // 1 for first_byte + i for previous iterations of this loop
  148. let (unchanged_slice, remaining) = self.bytes.split_at(1 + i);
  149. self.bytes = remaining;
  150. return Some(unsafe { str::from_utf8_unchecked(unchanged_slice) });
  151. }
  152. }
  153. let unchanged_slice = self.bytes;
  154. self.bytes = &[][..];
  155. Some(unsafe { str::from_utf8_unchecked(unchanged_slice) })
  156. }
  157. } else {
  158. None
  159. }
  160. }
  161. fn size_hint(&self) -> (usize, Option<usize>) {
  162. if self.bytes.is_empty() {
  163. (0, Some(0))
  164. } else {
  165. (1, Some(self.bytes.len()))
  166. }
  167. }
  168. }
  169. impl fmt::Display for PercentEncode<'_> {
  170. fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
  171. for c in (*self).clone() {
  172. formatter.write_str(c)?
  173. }
  174. Ok(())
  175. }
  176. }
  177. #[cfg(feature = "alloc")]
  178. impl<'a> From<PercentEncode<'a>> for Cow<'a, str> {
  179. fn from(mut iter: PercentEncode<'a>) -> Self {
  180. match iter.next() {
  181. None => "".into(),
  182. Some(first) => match iter.next() {
  183. None => first.into(),
  184. Some(second) => {
  185. let mut string = first.to_owned();
  186. string.push_str(second);
  187. string.extend(iter);
  188. string.into()
  189. }
  190. },
  191. }
  192. }
  193. }
  194. /// Percent-decode the given string.
  195. ///
  196. /// <https://url.spec.whatwg.org/#string-percent-decode>
  197. ///
  198. /// See [`percent_decode`] regarding the return type.
  199. #[inline]
  200. pub fn percent_decode_str(input: &str) -> PercentDecode<'_> {
  201. percent_decode(input.as_bytes())
  202. }
  203. /// Percent-decode the given bytes.
  204. ///
  205. /// <https://url.spec.whatwg.org/#percent-decode>
  206. ///
  207. /// Any sequence of `%` followed by two hexadecimal digits is decoded.
  208. /// The return type:
  209. ///
  210. /// * Implements `Into<Cow<u8>>` borrowing `input` when it contains no percent-encoded sequence,
  211. /// * Implements `Iterator<Item = u8>` and therefore has a `.collect::<Vec<u8>>()` method,
  212. /// * Has `decode_utf8()` and `decode_utf8_lossy()` methods.
  213. ///
  214. /// # Examples
  215. ///
  216. /// ```
  217. /// use percent_encoding::percent_decode;
  218. ///
  219. /// assert_eq!(percent_decode(b"foo%20bar%3f").decode_utf8().unwrap(), "foo bar?");
  220. /// ```
  221. #[inline]
  222. pub fn percent_decode(input: &[u8]) -> PercentDecode<'_> {
  223. PercentDecode {
  224. bytes: input.iter(),
  225. }
  226. }
  227. /// The return type of [`percent_decode`].
  228. #[derive(Clone, Debug)]
  229. pub struct PercentDecode<'a> {
  230. bytes: slice::Iter<'a, u8>,
  231. }
  232. fn after_percent_sign(iter: &mut slice::Iter<'_, u8>) -> Option<u8> {
  233. let mut cloned_iter = iter.clone();
  234. let h = char::from(*cloned_iter.next()?).to_digit(16)?;
  235. let l = char::from(*cloned_iter.next()?).to_digit(16)?;
  236. *iter = cloned_iter;
  237. Some(h as u8 * 0x10 + l as u8)
  238. }
  239. impl Iterator for PercentDecode<'_> {
  240. type Item = u8;
  241. fn next(&mut self) -> Option<u8> {
  242. self.bytes.next().map(|&byte| {
  243. if byte == b'%' {
  244. after_percent_sign(&mut self.bytes).unwrap_or(byte)
  245. } else {
  246. byte
  247. }
  248. })
  249. }
  250. fn size_hint(&self) -> (usize, Option<usize>) {
  251. let bytes = self.bytes.len();
  252. ((bytes + 2) / 3, Some(bytes))
  253. }
  254. }
  255. #[cfg(feature = "alloc")]
  256. impl<'a> From<PercentDecode<'a>> for Cow<'a, [u8]> {
  257. fn from(iter: PercentDecode<'a>) -> Self {
  258. match iter.if_any() {
  259. Some(vec) => Cow::Owned(vec),
  260. None => Cow::Borrowed(iter.bytes.as_slice()),
  261. }
  262. }
  263. }
  264. impl<'a> PercentDecode<'a> {
  265. /// If the percent-decoding is different from the input, return it as a new bytes vector.
  266. #[cfg(feature = "alloc")]
  267. fn if_any(&self) -> Option<Vec<u8>> {
  268. let mut bytes_iter = self.bytes.clone();
  269. while bytes_iter.any(|&b| b == b'%') {
  270. if let Some(decoded_byte) = after_percent_sign(&mut bytes_iter) {
  271. let initial_bytes = self.bytes.as_slice();
  272. let unchanged_bytes_len = initial_bytes.len() - bytes_iter.len() - 3;
  273. let mut decoded = initial_bytes[..unchanged_bytes_len].to_owned();
  274. decoded.push(decoded_byte);
  275. decoded.extend(PercentDecode { bytes: bytes_iter });
  276. return Some(decoded);
  277. }
  278. }
  279. // Nothing to decode
  280. None
  281. }
  282. /// Decode the result of percent-decoding as UTF-8.
  283. ///
  284. /// This is return `Err` when the percent-decoded bytes are not well-formed in UTF-8.
  285. #[cfg(feature = "alloc")]
  286. pub fn decode_utf8(self) -> Result<Cow<'a, str>, str::Utf8Error> {
  287. match self.clone().into() {
  288. Cow::Borrowed(bytes) => match str::from_utf8(bytes) {
  289. Ok(s) => Ok(s.into()),
  290. Err(e) => Err(e),
  291. },
  292. Cow::Owned(bytes) => match String::from_utf8(bytes) {
  293. Ok(s) => Ok(s.into()),
  294. Err(e) => Err(e.utf8_error()),
  295. },
  296. }
  297. }
  298. /// Decode the result of percent-decoding as UTF-8, lossily.
  299. ///
  300. /// Invalid UTF-8 percent-encoded byte sequences will be replaced � U+FFFD,
  301. /// the replacement character.
  302. #[cfg(feature = "alloc")]
  303. pub fn decode_utf8_lossy(self) -> Cow<'a, str> {
  304. decode_utf8_lossy(self.clone().into())
  305. }
  306. }
  307. // std::ptr::addr_eq was stabilized in rust 1.76. Once we upgrade
  308. // the MSRV we can remove this lint override.
  309. #[cfg(feature = "alloc")]
  310. #[allow(ambiguous_wide_pointer_comparisons)]
  311. fn decode_utf8_lossy(input: Cow<'_, [u8]>) -> Cow<'_, str> {
  312. // Note: This function is duplicated in `form_urlencoded/src/query_encoding.rs`.
  313. match input {
  314. Cow::Borrowed(bytes) => String::from_utf8_lossy(bytes),
  315. Cow::Owned(bytes) => {
  316. match String::from_utf8_lossy(&bytes) {
  317. Cow::Borrowed(utf8) => {
  318. // If from_utf8_lossy returns a Cow::Borrowed, then we can
  319. // be sure our original bytes were valid UTF-8. This is because
  320. // if the bytes were invalid UTF-8 from_utf8_lossy would have
  321. // to allocate a new owned string to back the Cow so it could
  322. // replace invalid bytes with a placeholder.
  323. // First we do a debug_assert to confirm our description above.
  324. let raw_utf8: *const [u8] = utf8.as_bytes();
  325. debug_assert!(core::ptr::eq(raw_utf8, &*bytes));
  326. // Given we know the original input bytes are valid UTF-8,
  327. // and we have ownership of those bytes, we re-use them and
  328. // return a Cow::Owned here.
  329. Cow::Owned(unsafe { String::from_utf8_unchecked(bytes) })
  330. }
  331. Cow::Owned(s) => Cow::Owned(s),
  332. }
  333. }
  334. }
  335. }
  336. #[cfg(test)]
  337. mod tests {
  338. use super::*;
  339. #[test]
  340. fn percent_encode_byte() {
  341. for i in 0..=0xFF {
  342. let encoded = super::percent_encode_byte(i);
  343. assert_eq!(encoded, alloc::format!("%{:02X}", i));
  344. }
  345. }
  346. #[test]
  347. fn percent_encode_accepts_ascii_set_ref() {
  348. let encoded = percent_encode(b"foo bar?", &AsciiSet::EMPTY);
  349. assert_eq!(encoded.collect::<String>(), "foo bar?");
  350. }
  351. #[test]
  352. fn percent_encode_collect() {
  353. let encoded = percent_encode(b"foo bar?", NON_ALPHANUMERIC);
  354. assert_eq!(encoded.collect::<String>(), String::from("foo%20bar%3F"));
  355. let encoded = percent_encode(b"\x00\x01\x02\x03", CONTROLS);
  356. assert_eq!(encoded.collect::<String>(), String::from("%00%01%02%03"));
  357. }
  358. #[test]
  359. fn percent_encode_display() {
  360. let encoded = percent_encode(b"foo bar?", NON_ALPHANUMERIC);
  361. assert_eq!(alloc::format!("{}", encoded), "foo%20bar%3F");
  362. }
  363. #[test]
  364. fn percent_encode_cow() {
  365. let encoded = percent_encode(b"foo bar?", NON_ALPHANUMERIC);
  366. assert_eq!(Cow::from(encoded), "foo%20bar%3F");
  367. }
  368. #[test]
  369. fn utf8_percent_encode_accepts_ascii_set_ref() {
  370. let encoded = super::utf8_percent_encode("foo bar?", &AsciiSet::EMPTY);
  371. assert_eq!(encoded.collect::<String>(), "foo bar?");
  372. }
  373. #[test]
  374. fn utf8_percent_encode() {
  375. assert_eq!(
  376. super::utf8_percent_encode("foo bar?", NON_ALPHANUMERIC),
  377. percent_encode(b"foo bar?", NON_ALPHANUMERIC)
  378. );
  379. }
  380. #[test]
  381. fn percent_decode() {
  382. assert_eq!(
  383. super::percent_decode(b"foo%20bar%3f")
  384. .decode_utf8()
  385. .unwrap(),
  386. "foo bar?"
  387. );
  388. }
  389. #[test]
  390. fn percent_decode_str() {
  391. assert_eq!(
  392. super::percent_decode_str("foo%20bar%3f")
  393. .decode_utf8()
  394. .unwrap(),
  395. "foo bar?"
  396. );
  397. }
  398. #[test]
  399. fn percent_decode_collect() {
  400. let decoded = super::percent_decode(b"foo%20bar%3f");
  401. assert_eq!(decoded.collect::<Vec<u8>>(), b"foo bar?");
  402. }
  403. #[test]
  404. fn percent_decode_cow() {
  405. let decoded = super::percent_decode(b"foo%20bar%3f");
  406. assert_eq!(Cow::from(decoded), Cow::Owned::<[u8]>(b"foo bar?".to_vec()));
  407. let decoded = super::percent_decode(b"foo bar?");
  408. assert_eq!(Cow::from(decoded), Cow::Borrowed(b"foo bar?"));
  409. }
  410. #[test]
  411. fn percent_decode_invalid_utf8() {
  412. // Invalid UTF-8 sequence
  413. let decoded = super::percent_decode(b"%00%9F%92%96")
  414. .decode_utf8()
  415. .unwrap_err();
  416. assert_eq!(decoded.valid_up_to(), 1);
  417. assert_eq!(decoded.error_len(), Some(1));
  418. }
  419. #[test]
  420. fn percent_decode_utf8_lossy() {
  421. assert_eq!(
  422. super::percent_decode(b"%F0%9F%92%96").decode_utf8_lossy(),
  423. "💖"
  424. );
  425. }
  426. #[test]
  427. fn percent_decode_utf8_lossy_invalid_utf8() {
  428. assert_eq!(
  429. super::percent_decode(b"%00%9F%92%96").decode_utf8_lossy(),
  430. "\u{0}���"
  431. );
  432. }
  433. }