percent_encoding.rs 12 KB

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