percent_encoding.rs 12 KB

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