lib.rs 16 KB

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