lib.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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. For example, a forward slash
  9. //! indicates a path. In order for that character to exist outside of a path separator, that
  10. //! character would need to be encoded.
  11. //!
  12. //! Percent encoding replaces reserved characters with the `%` escape character followed by hexidecimal
  13. //! ASCII representaton. For non-ASCII character that are percent encoded, a UTF-8 byte sequence
  14. //! becomes percent encoded. A simple example can be seen when the space literal is replaced with
  15. //! `%20`.
  16. //!
  17. //! Percent encoding is further complicated by the fact that different parts of an URL have
  18. //! different encoding requirements. In order to support the variety of encoding requirements,
  19. //! `url::percent_encoding` includes different *encode sets*.
  20. //! See [URL Standard](https://url.spec.whatwg.org/#percent-encoded-bytes) for details.
  21. //!
  22. //! This module provides some `*_ENCODE_SET` constants.
  23. //! If a different set is required, it can be created with
  24. //! the [`define_encode_set!`](../macro.define_encode_set!.html) macro.
  25. //!
  26. //! # Examples
  27. //!
  28. //! ```
  29. //! use url::percent_encoding::{utf8_percent_encode, DEFAULT_ENCODE_SET};
  30. //!
  31. //! assert_eq!(utf8_percent_encode("foo bar?", DEFAULT_ENCODE_SET).to_string(), "foo%20bar%3F");
  32. //! ```
  33. use std::borrow::Cow;
  34. use std::fmt;
  35. use std::slice;
  36. use std::str;
  37. /// Represents a set of characters / bytes that should be percent-encoded.
  38. ///
  39. /// See [encode sets specification](http://url.spec.whatwg.org/#simple-encode-set).
  40. ///
  41. /// Different characters need to be encoded in different parts of an URL.
  42. /// For example, a literal `?` question mark in an URL’s path would indicate
  43. /// the start of the query string.
  44. /// A question mark meant to be part of the path therefore needs to be percent-encoded.
  45. /// In the query string however, a question mark does not have any special meaning
  46. /// and does not need to be percent-encoded.
  47. ///
  48. /// A few sets are defined in this module.
  49. /// Use the [`define_encode_set!`](../macro.define_encode_set!.html) macro to define different ones.
  50. pub trait EncodeSet: Clone {
  51. /// Called with UTF-8 bytes rather than code points.
  52. /// Should return true for all non-ASCII bytes.
  53. fn contains(&self, byte: u8) -> bool;
  54. }
  55. /// Define a new struct
  56. /// that implements the [`EncodeSet`](percent_encoding/trait.EncodeSet.html) trait,
  57. /// for use in [`percent_decode()`](percent_encoding/fn.percent_encode.html)
  58. /// and related functions.
  59. ///
  60. /// Parameters are characters to include in the set in addition to those of the base set.
  61. /// See [encode sets specification](http://url.spec.whatwg.org/#simple-encode-set).
  62. ///
  63. /// Example
  64. /// =======
  65. ///
  66. /// ```rust
  67. /// #[macro_use] extern crate percent_encoding;
  68. /// use percent_encoding::{utf8_percent_encode, SIMPLE_ENCODE_SET};
  69. /// define_encode_set! {
  70. /// /// This encode set is used in the URL parser for query strings.
  71. /// pub QUERY_ENCODE_SET = [SIMPLE_ENCODE_SET] | {' ', '"', '#', '<', '>'}
  72. /// }
  73. /// # fn main() {
  74. /// assert_eq!(utf8_percent_encode("foo bar", QUERY_ENCODE_SET).collect::<String>(), "foo%20bar");
  75. /// # }
  76. /// ```
  77. #[macro_export]
  78. macro_rules! define_encode_set {
  79. ($(#[$attr: meta])* pub $name: ident = [$base_set: expr] | {$($ch: pat),*}) => {
  80. $(#[$attr])*
  81. #[derive(Copy, Clone, Debug)]
  82. #[allow(non_camel_case_types)]
  83. pub struct $name;
  84. impl $crate::EncodeSet for $name {
  85. #[inline]
  86. fn contains(&self, byte: u8) -> bool {
  87. match byte as char {
  88. $(
  89. $ch => true,
  90. )*
  91. _ => $base_set.contains(byte)
  92. }
  93. }
  94. }
  95. }
  96. }
  97. /// This encode set is used for the path of cannot-be-a-base URLs.
  98. ///
  99. /// All ASCII charcters less than hexidecimal 20 and greater than 7E are encoded. This includes
  100. /// special charcters such as line feed, carriage return, NULL, etc.
  101. #[derive(Copy, Clone, Debug)]
  102. #[allow(non_camel_case_types)]
  103. pub struct SIMPLE_ENCODE_SET;
  104. impl EncodeSet for SIMPLE_ENCODE_SET {
  105. #[inline]
  106. fn contains(&self, byte: u8) -> bool {
  107. byte < 0x20 || byte > 0x7E
  108. }
  109. }
  110. define_encode_set! {
  111. /// This encode set is used in the URL parser for query strings.
  112. ///
  113. /// Aside from special chacters defined in the [`SIMPLE_ENCODE_SET`](struct.SIMPLE_ENCODE_SET.html),
  114. /// space, double quote ("), hash (#), and inequality qualifiers (<), (>) are encoded.
  115. pub QUERY_ENCODE_SET = [SIMPLE_ENCODE_SET] | {' ', '"', '#', '<', '>'}
  116. }
  117. define_encode_set! {
  118. /// This encode set is used for path components.
  119. ///
  120. /// Aside from special chacters defined in the [`SIMPLE_ENCODE_SET`](struct.SIMPLE_ENCODE_SET.html),
  121. /// space, double quote ("), hash (#), inequality qualifiers (<), (>), backtick (`),
  122. /// question mark (?), and curly brackets ({), (}) are encoded.
  123. pub DEFAULT_ENCODE_SET = [QUERY_ENCODE_SET] | {'`', '?', '{', '}'}
  124. }
  125. define_encode_set! {
  126. /// This encode set is used for on '/'-separated path segment
  127. ///
  128. /// Aside from special chacters defined in the [`SIMPLE_ENCODE_SET`](struct.SIMPLE_ENCODE_SET.html),
  129. /// space, double quote ("), hash (#), inequality qualifiers (<), (>), backtick (`),
  130. /// question mark (?), and curly brackets ({), (}), percent sign (%), forward slash (/) are
  131. /// encoded.
  132. ///
  133. /// # Note
  134. ///
  135. /// For [special URLs](https://url.spec.whatwg.org/#is-special), the backslash (\) character should
  136. /// additionally be escaped, but that is *not* included in this encode set.
  137. pub PATH_SEGMENT_ENCODE_SET = [DEFAULT_ENCODE_SET] | {'%', '/'}
  138. }
  139. define_encode_set! {
  140. /// This encode set is used for username and password.
  141. ///
  142. /// Aside from special chacters defined in the [`SIMPLE_ENCODE_SET`](struct.SIMPLE_ENCODE_SET.html),
  143. /// space, double quote ("), hash (#), inequality qualifiers (<), (>), backtick (`),
  144. /// question mark (?), and curly brackets ({), (}), forward slash (/), colon (:), semi-colon (;),
  145. /// equality (=), at (@), backslash (\\), square brackets ([), (]), caret (\^), and pipe (|) are
  146. /// encoded.
  147. pub USERINFO_ENCODE_SET = [DEFAULT_ENCODE_SET] | {
  148. '/', ':', ';', '=', '@', '[', '\\', ']', '^', '|'
  149. }
  150. }
  151. /// Return the percent-encoding of the given bytes.
  152. ///
  153. /// This is unconditional, unlike `percent_encode()` which uses an encode set.
  154. ///
  155. /// # Examples
  156. ///
  157. /// ```
  158. /// use url::percent_encoding::percent_encode_byte;
  159. ///
  160. /// assert_eq!("foo bar".bytes().map(percent_encode_byte).collect::<String>(),
  161. /// "%66%6F%6F%20%62%61%72");
  162. /// ```
  163. pub fn percent_encode_byte(byte: u8) -> &'static str {
  164. let index = usize::from(byte) * 3;
  165. &"\
  166. %00%01%02%03%04%05%06%07%08%09%0A%0B%0C%0D%0E%0F\
  167. %10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F\
  168. %20%21%22%23%24%25%26%27%28%29%2A%2B%2C%2D%2E%2F\
  169. %30%31%32%33%34%35%36%37%38%39%3A%3B%3C%3D%3E%3F\
  170. %40%41%42%43%44%45%46%47%48%49%4A%4B%4C%4D%4E%4F\
  171. %50%51%52%53%54%55%56%57%58%59%5A%5B%5C%5D%5E%5F\
  172. %60%61%62%63%64%65%66%67%68%69%6A%6B%6C%6D%6E%6F\
  173. %70%71%72%73%74%75%76%77%78%79%7A%7B%7C%7D%7E%7F\
  174. %80%81%82%83%84%85%86%87%88%89%8A%8B%8C%8D%8E%8F\
  175. %90%91%92%93%94%95%96%97%98%99%9A%9B%9C%9D%9E%9F\
  176. %A0%A1%A2%A3%A4%A5%A6%A7%A8%A9%AA%AB%AC%AD%AE%AF\
  177. %B0%B1%B2%B3%B4%B5%B6%B7%B8%B9%BA%BB%BC%BD%BE%BF\
  178. %C0%C1%C2%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF\
  179. %D0%D1%D2%D3%D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF\
  180. %E0%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF\
  181. %F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE%FF\
  182. "[index..index + 3]
  183. }
  184. /// Percent-encode the given bytes with the given encode set.
  185. ///
  186. /// The encode set define which bytes (in addition to non-ASCII and controls)
  187. /// need to be percent-encoded.
  188. /// The choice of this set depends on context.
  189. /// For example, `?` needs to be encoded in an URL path but not in a query string.
  190. ///
  191. /// The return value is an iterator of `&str` slices (so it has a `.collect::<String>()` method)
  192. /// that also implements `Display` and `Into<Cow<str>>`.
  193. /// The latter returns `Cow::Borrowed` when none of the bytes in `input`
  194. /// are in the given encode set.
  195. ///
  196. /// # Examples
  197. ///
  198. /// ```
  199. /// use url::percent_encoding::{percent_encode, DEFAULT_ENCODE_SET};
  200. ///
  201. /// assert_eq!(percent_encode(b"foo bar?", DEFAULT_ENCODE_SET).to_string(), "foo%20bar%3F");
  202. /// ```
  203. #[inline]
  204. pub fn percent_encode<E: EncodeSet>(input: &[u8], encode_set: E) -> PercentEncode<E> {
  205. PercentEncode {
  206. bytes: input,
  207. encode_set: encode_set,
  208. }
  209. }
  210. /// Percent-encode the UTF-8 encoding of the given string.
  211. ///
  212. /// See `percent_encode()` for how to use the return value.
  213. ///
  214. /// # Examples
  215. ///
  216. /// ```
  217. /// use url::percent_encoding::{utf8_percent_encode, DEFAULT_ENCODE_SET};
  218. ///
  219. /// assert_eq!(utf8_percent_encode("foo bar?", DEFAULT_ENCODE_SET).to_string(), "foo%20bar%3F");
  220. /// ```
  221. #[inline]
  222. pub fn utf8_percent_encode<E: EncodeSet>(input: &str, encode_set: E) -> PercentEncode<E> {
  223. percent_encode(input.as_bytes(), encode_set)
  224. }
  225. /// The return type of `percent_encode()` and `utf8_percent_encode()`.
  226. #[derive(Clone, Debug)]
  227. pub struct PercentEncode<'a, E: EncodeSet> {
  228. bytes: &'a [u8],
  229. encode_set: E,
  230. }
  231. impl<'a, E: EncodeSet> Iterator for PercentEncode<'a, E> {
  232. type Item = &'a str;
  233. fn next(&mut self) -> Option<&'a str> {
  234. if let Some((&first_byte, remaining)) = self.bytes.split_first() {
  235. if self.encode_set.contains(first_byte) {
  236. self.bytes = remaining;
  237. Some(percent_encode_byte(first_byte))
  238. } else {
  239. assert!(first_byte.is_ascii());
  240. for (i, &byte) in remaining.iter().enumerate() {
  241. if self.encode_set.contains(byte) {
  242. // 1 for first_byte + i for previous iterations of this loop
  243. let (unchanged_slice, remaining) = self.bytes.split_at(1 + i);
  244. self.bytes = remaining;
  245. return Some(unsafe { str::from_utf8_unchecked(unchanged_slice) });
  246. } else {
  247. assert!(byte.is_ascii());
  248. }
  249. }
  250. let unchanged_slice = self.bytes;
  251. self.bytes = &[][..];
  252. Some(unsafe { str::from_utf8_unchecked(unchanged_slice) })
  253. }
  254. } else {
  255. None
  256. }
  257. }
  258. fn size_hint(&self) -> (usize, Option<usize>) {
  259. if self.bytes.is_empty() {
  260. (0, Some(0))
  261. } else {
  262. (1, Some(self.bytes.len()))
  263. }
  264. }
  265. }
  266. impl<'a, E: EncodeSet> fmt::Display for PercentEncode<'a, E> {
  267. fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  268. for c in (*self).clone() {
  269. formatter.write_str(c)?
  270. }
  271. Ok(())
  272. }
  273. }
  274. impl<'a, E: EncodeSet> From<PercentEncode<'a, E>> for Cow<'a, str> {
  275. fn from(mut iter: PercentEncode<'a, E>) -> Self {
  276. match iter.next() {
  277. None => "".into(),
  278. Some(first) => match iter.next() {
  279. None => first.into(),
  280. Some(second) => {
  281. let mut string = first.to_owned();
  282. string.push_str(second);
  283. string.extend(iter);
  284. string.into()
  285. }
  286. },
  287. }
  288. }
  289. }
  290. /// Percent-decode the given bytes.
  291. ///
  292. /// The return value is an iterator of decoded `u8` bytes
  293. /// that also implements `Into<Cow<u8>>`
  294. /// (which returns `Cow::Borrowed` when `input` contains no percent-encoded sequence)
  295. /// and has `decode_utf8()` and `decode_utf8_lossy()` methods.
  296. ///
  297. /// # Examples
  298. ///
  299. /// ```
  300. /// use url::percent_encoding::percent_decode;
  301. ///
  302. /// assert_eq!(percent_decode(b"foo%20bar%3F").decode_utf8().unwrap(), "foo bar?");
  303. /// ```
  304. #[inline]
  305. pub fn percent_decode(input: &[u8]) -> PercentDecode {
  306. PercentDecode {
  307. bytes: input.iter(),
  308. }
  309. }
  310. /// The return type of `percent_decode()`.
  311. #[derive(Clone, Debug)]
  312. pub struct PercentDecode<'a> {
  313. bytes: slice::Iter<'a, u8>,
  314. }
  315. fn after_percent_sign(iter: &mut slice::Iter<u8>) -> Option<u8> {
  316. let initial_iter = iter.clone();
  317. let h = iter.next().and_then(|&b| (b as char).to_digit(16));
  318. let l = iter.next().and_then(|&b| (b as char).to_digit(16));
  319. if let (Some(h), Some(l)) = (h, l) {
  320. Some(h as u8 * 0x10 + l as u8)
  321. } else {
  322. *iter = initial_iter;
  323. None
  324. }
  325. }
  326. impl<'a> Iterator for PercentDecode<'a> {
  327. type Item = u8;
  328. fn next(&mut self) -> Option<u8> {
  329. self.bytes.next().map(|&byte| {
  330. if byte == b'%' {
  331. after_percent_sign(&mut self.bytes).unwrap_or(byte)
  332. } else {
  333. byte
  334. }
  335. })
  336. }
  337. fn size_hint(&self) -> (usize, Option<usize>) {
  338. let bytes = self.bytes.len();
  339. (bytes / 3, Some(bytes))
  340. }
  341. }
  342. impl<'a> From<PercentDecode<'a>> for Cow<'a, [u8]> {
  343. fn from(iter: PercentDecode<'a>) -> Self {
  344. match iter.if_any() {
  345. Some(vec) => Cow::Owned(vec),
  346. None => Cow::Borrowed(iter.bytes.as_slice()),
  347. }
  348. }
  349. }
  350. impl<'a> PercentDecode<'a> {
  351. /// If the percent-decoding is different from the input, return it as a new bytes vector.
  352. pub fn if_any(&self) -> Option<Vec<u8>> {
  353. let mut bytes_iter = self.bytes.clone();
  354. while bytes_iter.any(|&b| b == b'%') {
  355. if let Some(decoded_byte) = after_percent_sign(&mut bytes_iter) {
  356. let initial_bytes = self.bytes.as_slice();
  357. let unchanged_bytes_len = initial_bytes.len() - bytes_iter.len() - 3;
  358. let mut decoded = initial_bytes[..unchanged_bytes_len].to_owned();
  359. decoded.push(decoded_byte);
  360. decoded.extend(PercentDecode { bytes: bytes_iter });
  361. return Some(decoded);
  362. }
  363. }
  364. // Nothing to decode
  365. None
  366. }
  367. /// Decode the result of percent-decoding as UTF-8.
  368. ///
  369. /// This is return `Err` when the percent-decoded bytes are not well-formed in UTF-8.
  370. pub fn decode_utf8(self) -> Result<Cow<'a, str>, str::Utf8Error> {
  371. match self.clone().into() {
  372. Cow::Borrowed(bytes) => match str::from_utf8(bytes) {
  373. Ok(s) => Ok(s.into()),
  374. Err(e) => Err(e),
  375. },
  376. Cow::Owned(bytes) => match String::from_utf8(bytes) {
  377. Ok(s) => Ok(s.into()),
  378. Err(e) => Err(e.utf8_error()),
  379. },
  380. }
  381. }
  382. /// Decode the result of percent-decoding as UTF-8, lossily.
  383. ///
  384. /// Invalid UTF-8 percent-encoded byte sequences will be replaced � U+FFFD,
  385. /// the replacement character.
  386. pub fn decode_utf8_lossy(self) -> Cow<'a, str> {
  387. decode_utf8_lossy(self.clone().into())
  388. }
  389. }
  390. fn decode_utf8_lossy(input: Cow<[u8]>) -> Cow<str> {
  391. match input {
  392. Cow::Borrowed(bytes) => String::from_utf8_lossy(bytes),
  393. Cow::Owned(bytes) => {
  394. let raw_utf8: *const [u8];
  395. match String::from_utf8_lossy(&bytes) {
  396. Cow::Borrowed(utf8) => raw_utf8 = utf8.as_bytes(),
  397. Cow::Owned(s) => return s.into(),
  398. }
  399. // from_utf8_lossy returned a borrow of `bytes` unchanged.
  400. debug_assert!(raw_utf8 == &*bytes as *const [u8]);
  401. // Reuse the existing `Vec` allocation.
  402. unsafe { String::from_utf8_unchecked(bytes) }.into()
  403. }
  404. }
  405. }