lib.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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 chacters 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 delibarately does not provide many different sets.
  24. //! Users should consider in what context the encoded string will be used,
  25. //! real 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. use std::borrow::Cow;
  39. use std::fmt;
  40. use std::slice;
  41. use std::str;
  42. /// Represents a set of characters or bytes in the ASCII range.
  43. ///
  44. /// This used in [`percent_encode`] and [`utf8_percent_encode`].
  45. /// This is simlar to [percent-encode sets](https://url.spec.whatwg.org/#percent-encoded-bytes).
  46. ///
  47. /// Use the `add` method of an existing set to define a new set. For example:
  48. ///
  49. /// ```
  50. /// use percent_encoding::{AsciiSet, CONTROLS};
  51. ///
  52. /// /// https://url.spec.whatwg.org/#fragment-percent-encode-set
  53. /// const FRAGMENT: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`');
  54. /// ```
  55. pub struct AsciiSet {
  56. mask: [Chunk; ASCII_RANGE_LEN / BITS_PER_CHUNK],
  57. }
  58. type Chunk = u32;
  59. const ASCII_RANGE_LEN: usize = 0x80;
  60. const BITS_PER_CHUNK: usize = 8 * std::mem::size_of::<Chunk>();
  61. impl AsciiSet {
  62. /// Called with UTF-8 bytes rather than code points.
  63. /// Not used for non-ASCII bytes.
  64. const fn contains(&self, byte: u8) -> bool {
  65. let chunk = self.mask[byte as usize / BITS_PER_CHUNK];
  66. let mask = 1 << (byte as usize % BITS_PER_CHUNK);
  67. (chunk & mask) != 0
  68. }
  69. fn should_percent_encode(&self, byte: u8) -> bool {
  70. !byte.is_ascii() || self.contains(byte)
  71. }
  72. pub const fn add(&self, byte: u8) -> Self {
  73. let mut mask = self.mask;
  74. mask[byte as usize / BITS_PER_CHUNK] |= 1 << (byte as usize % BITS_PER_CHUNK);
  75. AsciiSet { mask }
  76. }
  77. pub const fn remove(&self, byte: u8) -> Self {
  78. let mut mask = self.mask;
  79. mask[byte as usize / BITS_PER_CHUNK] &= !(1 << (byte as usize % BITS_PER_CHUNK));
  80. AsciiSet { mask }
  81. }
  82. }
  83. /// The set of 0x00 to 0x1F (C0 controls), and 0x7F (DEL).
  84. ///
  85. /// Note that this includes the newline and tab characters, but not the space 0x20.
  86. ///
  87. /// <https://url.spec.whatwg.org/#c0-control-percent-encode-set>
  88. pub const CONTROLS: &AsciiSet = &AsciiSet {
  89. mask: [
  90. !0_u32, // C0: 0x00 to 0x1F (32 bits set)
  91. 0,
  92. 0,
  93. 1 << (0x7F_u32 % 32), // DEL: 0x7F (one bit set)
  94. ],
  95. };
  96. macro_rules! static_assert {
  97. ($( $bool: expr, )+) => {
  98. fn _static_assert() {
  99. $(
  100. let _ = std::mem::transmute::<[u8; $bool as usize], u8>;
  101. )+
  102. }
  103. }
  104. }
  105. static_assert! {
  106. CONTROLS.contains(0x00),
  107. CONTROLS.contains(0x1F),
  108. !CONTROLS.contains(0x20),
  109. !CONTROLS.contains(0x7E),
  110. CONTROLS.contains(0x7F),
  111. }
  112. /// Everything that is not an ASCII letter or digit.
  113. ///
  114. /// This is probably more eager than necessary in any context.
  115. pub const NON_ALPHANUMERIC: &AsciiSet = &CONTROLS
  116. .add(b' ')
  117. .add(b'!')
  118. .add(b'"')
  119. .add(b'#')
  120. .add(b'$')
  121. .add(b'%')
  122. .add(b'&')
  123. .add(b'\'')
  124. .add(b'(')
  125. .add(b')')
  126. .add(b'*')
  127. .add(b'+')
  128. .add(b',')
  129. .add(b'-')
  130. .add(b'.')
  131. .add(b'/')
  132. .add(b':')
  133. .add(b';')
  134. .add(b'<')
  135. .add(b'=')
  136. .add(b'>')
  137. .add(b'?')
  138. .add(b'@')
  139. .add(b'[')
  140. .add(b'\\')
  141. .add(b']')
  142. .add(b'^')
  143. .add(b'_')
  144. .add(b'`')
  145. .add(b'{')
  146. .add(b'|')
  147. .add(b'}')
  148. .add(b'~');
  149. /// Return the percent-encoding of the given byte.
  150. ///
  151. /// This is unconditional, unlike `percent_encode()` which has an `AsciiSet` parameter.
  152. ///
  153. /// # Examples
  154. ///
  155. /// ```
  156. /// use percent_encoding::percent_encode_byte;
  157. ///
  158. /// assert_eq!("foo bar".bytes().map(percent_encode_byte).collect::<String>(),
  159. /// "%66%6F%6F%20%62%61%72");
  160. /// ```
  161. pub fn percent_encode_byte(byte: u8) -> &'static str {
  162. let index = usize::from(byte) * 3;
  163. &"\
  164. %00%01%02%03%04%05%06%07%08%09%0A%0B%0C%0D%0E%0F\
  165. %10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F\
  166. %20%21%22%23%24%25%26%27%28%29%2A%2B%2C%2D%2E%2F\
  167. %30%31%32%33%34%35%36%37%38%39%3A%3B%3C%3D%3E%3F\
  168. %40%41%42%43%44%45%46%47%48%49%4A%4B%4C%4D%4E%4F\
  169. %50%51%52%53%54%55%56%57%58%59%5A%5B%5C%5D%5E%5F\
  170. %60%61%62%63%64%65%66%67%68%69%6A%6B%6C%6D%6E%6F\
  171. %70%71%72%73%74%75%76%77%78%79%7A%7B%7C%7D%7E%7F\
  172. %80%81%82%83%84%85%86%87%88%89%8A%8B%8C%8D%8E%8F\
  173. %90%91%92%93%94%95%96%97%98%99%9A%9B%9C%9D%9E%9F\
  174. %A0%A1%A2%A3%A4%A5%A6%A7%A8%A9%AA%AB%AC%AD%AE%AF\
  175. %B0%B1%B2%B3%B4%B5%B6%B7%B8%B9%BA%BB%BC%BD%BE%BF\
  176. %C0%C1%C2%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF\
  177. %D0%D1%D2%D3%D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF\
  178. %E0%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF\
  179. %F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE%FF\
  180. "[index..index + 3]
  181. }
  182. /// Percent-encode the given bytes with the given set.
  183. ///
  184. /// Non-ASCII bytes and bytes in `ascii_set` are encoded.
  185. ///
  186. /// The return type:
  187. ///
  188. /// * Implements `Iterator<Item = &str>` and therefore has a `.collect::<String>()` method,
  189. /// * Implements `Display` and therefore has a `.to_string()` method,
  190. /// * Implements `Into<Cow<str>>` borrowing `input` when none of its bytes are encoded.
  191. ///
  192. /// # Examples
  193. ///
  194. /// ```
  195. /// use percent_encoding::{percent_encode, NON_ALPHANUMERIC};
  196. ///
  197. /// assert_eq!(percent_encode(b"foo bar?", NON_ALPHANUMERIC).to_string(), "foo%20bar%3F");
  198. /// ```
  199. #[inline]
  200. pub fn percent_encode<'a>(input: &'a [u8], ascii_set: &'static AsciiSet) -> PercentEncode<'a> {
  201. PercentEncode {
  202. bytes: input,
  203. ascii_set,
  204. }
  205. }
  206. /// Percent-encode the UTF-8 encoding of the given string.
  207. ///
  208. /// See [`percent_encode`] regarding the return type.
  209. ///
  210. /// # Examples
  211. ///
  212. /// ```
  213. /// use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
  214. ///
  215. /// assert_eq!(utf8_percent_encode("foo bar?", NON_ALPHANUMERIC).to_string(), "foo%20bar%3F");
  216. /// ```
  217. #[inline]
  218. pub fn utf8_percent_encode<'a>(input: &'a str, ascii_set: &'static AsciiSet) -> PercentEncode<'a> {
  219. percent_encode(input.as_bytes(), ascii_set)
  220. }
  221. /// The return type of [`percent_encode`] and [`utf8_percent_encode`].
  222. #[derive(Clone)]
  223. pub struct PercentEncode<'a> {
  224. bytes: &'a [u8],
  225. ascii_set: &'static AsciiSet,
  226. }
  227. impl<'a> Iterator for PercentEncode<'a> {
  228. type Item = &'a str;
  229. fn next(&mut self) -> Option<&'a str> {
  230. if let Some((&first_byte, remaining)) = self.bytes.split_first() {
  231. if self.ascii_set.should_percent_encode(first_byte) {
  232. self.bytes = remaining;
  233. Some(percent_encode_byte(first_byte))
  234. } else {
  235. for (i, &byte) in remaining.iter().enumerate() {
  236. if self.ascii_set.should_percent_encode(byte) {
  237. // 1 for first_byte + i for previous iterations of this loop
  238. let (unchanged_slice, remaining) = self.bytes.split_at(1 + i);
  239. self.bytes = remaining;
  240. return Some(unsafe { str::from_utf8_unchecked(unchanged_slice) });
  241. }
  242. }
  243. let unchanged_slice = self.bytes;
  244. self.bytes = &[][..];
  245. Some(unsafe { str::from_utf8_unchecked(unchanged_slice) })
  246. }
  247. } else {
  248. None
  249. }
  250. }
  251. fn size_hint(&self) -> (usize, Option<usize>) {
  252. if self.bytes.is_empty() {
  253. (0, Some(0))
  254. } else {
  255. (1, Some(self.bytes.len()))
  256. }
  257. }
  258. }
  259. impl<'a> fmt::Display for PercentEncode<'a> {
  260. fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  261. for c in (*self).clone() {
  262. formatter.write_str(c)?
  263. }
  264. Ok(())
  265. }
  266. }
  267. impl<'a> From<PercentEncode<'a>> for Cow<'a, str> {
  268. fn from(mut iter: PercentEncode<'a>) -> Self {
  269. match iter.next() {
  270. None => "".into(),
  271. Some(first) => match iter.next() {
  272. None => first.into(),
  273. Some(second) => {
  274. let mut string = first.to_owned();
  275. string.push_str(second);
  276. string.extend(iter);
  277. string.into()
  278. }
  279. },
  280. }
  281. }
  282. }
  283. /// Percent-decode the given string.
  284. ///
  285. /// <https://url.spec.whatwg.org/#string-percent-decode>
  286. ///
  287. /// See [`percent_decode`] regarding the return type.
  288. #[inline]
  289. pub fn percent_decode_str(input: &str) -> PercentDecode {
  290. percent_decode(input.as_bytes())
  291. }
  292. /// Percent-decode the given bytes.
  293. ///
  294. /// <https://url.spec.whatwg.org/#percent-decode>
  295. ///
  296. /// Any sequence of `%` followed by two hexadecimal digits is decoded.
  297. /// The return type:
  298. ///
  299. /// * Implements `Into<Cow<u8>>` borrowing `input` when it contains no percent-encoded sequence,
  300. /// * Implements `Iterator<Item = u8>` and therefore has a `.collect::<Vec<u8>>()` method,
  301. /// * Has `decode_utf8()` and `decode_utf8_lossy()` methods.
  302. ///
  303. /// # Examples
  304. ///
  305. /// ```
  306. /// use percent_encoding::percent_decode;
  307. ///
  308. /// assert_eq!(percent_decode(b"foo%20bar%3f").decode_utf8().unwrap(), "foo bar?");
  309. /// ```
  310. #[inline]
  311. pub fn percent_decode(input: &[u8]) -> PercentDecode {
  312. PercentDecode {
  313. bytes: input.iter(),
  314. }
  315. }
  316. /// The return type of [`percent_decode`].
  317. #[derive(Clone, Debug)]
  318. pub struct PercentDecode<'a> {
  319. bytes: slice::Iter<'a, u8>,
  320. }
  321. fn after_percent_sign(iter: &mut slice::Iter<u8>) -> Option<u8> {
  322. let mut cloned_iter = iter.clone();
  323. let h = char::from(*cloned_iter.next()?).to_digit(16)?;
  324. let l = char::from(*cloned_iter.next()?).to_digit(16)?;
  325. *iter = cloned_iter;
  326. Some(h as u8 * 0x10 + l as u8)
  327. }
  328. impl<'a> Iterator for PercentDecode<'a> {
  329. type Item = u8;
  330. fn next(&mut self) -> Option<u8> {
  331. self.bytes.next().map(|&byte| {
  332. if byte == b'%' {
  333. after_percent_sign(&mut self.bytes).unwrap_or(byte)
  334. } else {
  335. byte
  336. }
  337. })
  338. }
  339. fn size_hint(&self) -> (usize, Option<usize>) {
  340. let bytes = self.bytes.len();
  341. (bytes / 3, Some(bytes))
  342. }
  343. }
  344. impl<'a> From<PercentDecode<'a>> for Cow<'a, [u8]> {
  345. fn from(iter: PercentDecode<'a>) -> Self {
  346. match iter.if_any() {
  347. Some(vec) => Cow::Owned(vec),
  348. None => Cow::Borrowed(iter.bytes.as_slice()),
  349. }
  350. }
  351. }
  352. impl<'a> PercentDecode<'a> {
  353. /// If the percent-decoding is different from the input, return it as a new bytes vector.
  354. fn if_any(&self) -> Option<Vec<u8>> {
  355. let mut bytes_iter = self.bytes.clone();
  356. while bytes_iter.any(|&b| b == b'%') {
  357. if let Some(decoded_byte) = after_percent_sign(&mut bytes_iter) {
  358. let initial_bytes = self.bytes.as_slice();
  359. let unchanged_bytes_len = initial_bytes.len() - bytes_iter.len() - 3;
  360. let mut decoded = initial_bytes[..unchanged_bytes_len].to_owned();
  361. decoded.push(decoded_byte);
  362. decoded.extend(PercentDecode { bytes: bytes_iter });
  363. return Some(decoded);
  364. }
  365. }
  366. // Nothing to decode
  367. None
  368. }
  369. /// Decode the result of percent-decoding as UTF-8.
  370. ///
  371. /// This is return `Err` when the percent-decoded bytes are not well-formed in UTF-8.
  372. pub fn decode_utf8(self) -> Result<Cow<'a, str>, str::Utf8Error> {
  373. match self.clone().into() {
  374. Cow::Borrowed(bytes) => match str::from_utf8(bytes) {
  375. Ok(s) => Ok(s.into()),
  376. Err(e) => Err(e),
  377. },
  378. Cow::Owned(bytes) => match String::from_utf8(bytes) {
  379. Ok(s) => Ok(s.into()),
  380. Err(e) => Err(e.utf8_error()),
  381. },
  382. }
  383. }
  384. /// Decode the result of percent-decoding as UTF-8, lossily.
  385. ///
  386. /// Invalid UTF-8 percent-encoded byte sequences will be replaced � U+FFFD,
  387. /// the replacement character.
  388. pub fn decode_utf8_lossy(self) -> Cow<'a, str> {
  389. decode_utf8_lossy(self.clone().into())
  390. }
  391. }
  392. fn decode_utf8_lossy(input: Cow<[u8]>) -> Cow<str> {
  393. match input {
  394. Cow::Borrowed(bytes) => String::from_utf8_lossy(bytes),
  395. Cow::Owned(bytes) => {
  396. let raw_utf8: *const [u8];
  397. match String::from_utf8_lossy(&bytes) {
  398. Cow::Borrowed(utf8) => raw_utf8 = utf8.as_bytes(),
  399. Cow::Owned(s) => return s.into(),
  400. }
  401. // from_utf8_lossy returned a borrow of `bytes` unchanged.
  402. debug_assert!(raw_utf8 == &*bytes as *const [u8]);
  403. // Reuse the existing `Vec` allocation.
  404. unsafe { String::from_utf8_unchecked(bytes) }.into()
  405. }
  406. }
  407. }