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