• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
9 //! URLs use special chacters to indicate the parts of the request.
10 //! For example, a `?` question mark marks the end of a path and the start of a query string.
11 //! In order for that character to exist inside a path, it needs to be encoded differently.
12 //!
13 //! Percent encoding replaces reserved characters with the `%` escape character
14 //! followed by a byte value as two hexadecimal digits.
15 //! For example, an ASCII space is replaced with `%20`.
16 //!
17 //! When encoding, the set of characters that can (and should, for readability) be left alone
18 //! depends on the context.
19 //! The `?` question mark mentioned above is not a separator when used literally
20 //! inside of a query string, and therefore does not need to be encoded.
21 //! The [`AsciiSet`] parameter of [`percent_encode`] and [`utf8_percent_encode`]
22 //! lets callers configure this.
23 //!
24 //! This crate delibarately does not provide many different sets.
25 //! Users should consider in what context the encoded string will be used,
26 //! real relevant specifications, and define their own set.
27 //! This is done by using the `add` method of an existing set.
28 //!
29 //! # Examples
30 //!
31 //! ```
32 //! use percent_encoding::{utf8_percent_encode, AsciiSet, CONTROLS};
33 //!
34 //! /// https://url.spec.whatwg.org/#fragment-percent-encode-set
35 //! const FRAGMENT: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`');
36 //!
37 //! assert_eq!(utf8_percent_encode("foo <bar>", FRAGMENT).to_string(), "foo%20%3Cbar%3E");
38 //! ```
39 
40 use std::borrow::Cow;
41 use std::fmt;
42 use std::slice;
43 use std::str;
44 
45 /// Represents a set of characters or bytes in the ASCII range.
46 ///
47 /// This used in [`percent_encode`] and [`utf8_percent_encode`].
48 /// This is simlar to [percent-encode sets](https://url.spec.whatwg.org/#percent-encoded-bytes).
49 ///
50 /// Use the `add` method of an existing set to define a new set. For example:
51 ///
52 /// ```
53 /// use percent_encoding::{AsciiSet, CONTROLS};
54 ///
55 /// /// https://url.spec.whatwg.org/#fragment-percent-encode-set
56 /// const FRAGMENT: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`');
57 /// ```
58 pub struct AsciiSet {
59     mask: [Chunk; ASCII_RANGE_LEN / BITS_PER_CHUNK],
60 }
61 
62 type Chunk = u32;
63 
64 const ASCII_RANGE_LEN: usize = 0x80;
65 
66 const BITS_PER_CHUNK: usize = 8 * std::mem::size_of::<Chunk>();
67 
68 impl AsciiSet {
69     /// Called with UTF-8 bytes rather than code points.
70     /// Not used for non-ASCII bytes.
contains(&self, byte: u8) -> bool71     const fn contains(&self, byte: u8) -> bool {
72         let chunk = self.mask[byte as usize / BITS_PER_CHUNK];
73         let mask = 1 << (byte as usize % BITS_PER_CHUNK);
74         (chunk & mask) != 0
75     }
76 
should_percent_encode(&self, byte: u8) -> bool77     fn should_percent_encode(&self, byte: u8) -> bool {
78         !byte.is_ascii() || self.contains(byte)
79     }
80 
add(&self, byte: u8) -> Self81     pub const fn add(&self, byte: u8) -> Self {
82         let mut mask = self.mask;
83         mask[byte as usize / BITS_PER_CHUNK] |= 1 << (byte as usize % BITS_PER_CHUNK);
84         AsciiSet { mask }
85     }
86 
remove(&self, byte: u8) -> Self87     pub const fn remove(&self, byte: u8) -> Self {
88         let mut mask = self.mask;
89         mask[byte as usize / BITS_PER_CHUNK] &= !(1 << (byte as usize % BITS_PER_CHUNK));
90         AsciiSet { mask }
91     }
92 }
93 
94 /// The set of 0x00 to 0x1F (C0 controls), and 0x7F (DEL).
95 ///
96 /// Note that this includes the newline and tab characters, but not the space 0x20.
97 ///
98 /// <https://url.spec.whatwg.org/#c0-control-percent-encode-set>
99 pub const CONTROLS: &AsciiSet = &AsciiSet {
100     mask: [
101         !0_u32, // C0: 0x00 to 0x1F (32 bits set)
102         0,
103         0,
104         1 << (0x7F_u32 % 32), // DEL: 0x7F (one bit set)
105     ],
106 };
107 
108 macro_rules! static_assert {
109     ($( $bool: expr, )+) => {
110         fn _static_assert() {
111             $(
112                 let _ = std::mem::transmute::<[u8; $bool as usize], u8>;
113             )+
114         }
115     }
116 }
117 
118 static_assert! {
119     CONTROLS.contains(0x00),
120     CONTROLS.contains(0x1F),
121     !CONTROLS.contains(0x20),
122     !CONTROLS.contains(0x7E),
123     CONTROLS.contains(0x7F),
124 }
125 
126 /// Everything that is not an ASCII letter or digit.
127 ///
128 /// This is probably more eager than necessary in any context.
129 pub const NON_ALPHANUMERIC: &AsciiSet = &CONTROLS
130     .add(b' ')
131     .add(b'!')
132     .add(b'"')
133     .add(b'#')
134     .add(b'$')
135     .add(b'%')
136     .add(b'&')
137     .add(b'\'')
138     .add(b'(')
139     .add(b')')
140     .add(b'*')
141     .add(b'+')
142     .add(b',')
143     .add(b'-')
144     .add(b'.')
145     .add(b'/')
146     .add(b':')
147     .add(b';')
148     .add(b'<')
149     .add(b'=')
150     .add(b'>')
151     .add(b'?')
152     .add(b'@')
153     .add(b'[')
154     .add(b'\\')
155     .add(b']')
156     .add(b'^')
157     .add(b'_')
158     .add(b'`')
159     .add(b'{')
160     .add(b'|')
161     .add(b'}')
162     .add(b'~');
163 
164 /// Return the percent-encoding of the given byte.
165 ///
166 /// This is unconditional, unlike `percent_encode()` which has an `AsciiSet` parameter.
167 ///
168 /// # Examples
169 ///
170 /// ```
171 /// use percent_encoding::percent_encode_byte;
172 ///
173 /// assert_eq!("foo bar".bytes().map(percent_encode_byte).collect::<String>(),
174 ///            "%66%6F%6F%20%62%61%72");
175 /// ```
percent_encode_byte(byte: u8) -> &'static str176 pub fn percent_encode_byte(byte: u8) -> &'static str {
177     let index = usize::from(byte) * 3;
178     &"\
179       %00%01%02%03%04%05%06%07%08%09%0A%0B%0C%0D%0E%0F\
180       %10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F\
181       %20%21%22%23%24%25%26%27%28%29%2A%2B%2C%2D%2E%2F\
182       %30%31%32%33%34%35%36%37%38%39%3A%3B%3C%3D%3E%3F\
183       %40%41%42%43%44%45%46%47%48%49%4A%4B%4C%4D%4E%4F\
184       %50%51%52%53%54%55%56%57%58%59%5A%5B%5C%5D%5E%5F\
185       %60%61%62%63%64%65%66%67%68%69%6A%6B%6C%6D%6E%6F\
186       %70%71%72%73%74%75%76%77%78%79%7A%7B%7C%7D%7E%7F\
187       %80%81%82%83%84%85%86%87%88%89%8A%8B%8C%8D%8E%8F\
188       %90%91%92%93%94%95%96%97%98%99%9A%9B%9C%9D%9E%9F\
189       %A0%A1%A2%A3%A4%A5%A6%A7%A8%A9%AA%AB%AC%AD%AE%AF\
190       %B0%B1%B2%B3%B4%B5%B6%B7%B8%B9%BA%BB%BC%BD%BE%BF\
191       %C0%C1%C2%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF\
192       %D0%D1%D2%D3%D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF\
193       %E0%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF\
194       %F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE%FF\
195       "[index..index + 3]
196 }
197 
198 /// Percent-encode the given bytes with the given set.
199 ///
200 /// Non-ASCII bytes and bytes in `ascii_set` are encoded.
201 ///
202 /// The return type:
203 ///
204 /// * Implements `Iterator<Item = &str>` and therefore has a `.collect::<String>()` method,
205 /// * Implements `Display` and therefore has a `.to_string()` method,
206 /// * Implements `Into<Cow<str>>` borrowing `input` when none of its bytes are encoded.
207 ///
208 /// # Examples
209 ///
210 /// ```
211 /// use percent_encoding::{percent_encode, NON_ALPHANUMERIC};
212 ///
213 /// assert_eq!(percent_encode(b"foo bar?", NON_ALPHANUMERIC).to_string(), "foo%20bar%3F");
214 /// ```
215 #[inline]
percent_encode<'a>(input: &'a [u8], ascii_set: &'static AsciiSet) -> PercentEncode<'a>216 pub fn percent_encode<'a>(input: &'a [u8], ascii_set: &'static AsciiSet) -> PercentEncode<'a> {
217     PercentEncode {
218         bytes: input,
219         ascii_set,
220     }
221 }
222 
223 /// Percent-encode the UTF-8 encoding of the given string.
224 ///
225 /// See [`percent_encode`] regarding the return type.
226 ///
227 /// # Examples
228 ///
229 /// ```
230 /// use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
231 ///
232 /// assert_eq!(utf8_percent_encode("foo bar?", NON_ALPHANUMERIC).to_string(), "foo%20bar%3F");
233 /// ```
234 #[inline]
utf8_percent_encode<'a>(input: &'a str, ascii_set: &'static AsciiSet) -> PercentEncode<'a>235 pub fn utf8_percent_encode<'a>(input: &'a str, ascii_set: &'static AsciiSet) -> PercentEncode<'a> {
236     percent_encode(input.as_bytes(), ascii_set)
237 }
238 
239 /// The return type of [`percent_encode`] and [`utf8_percent_encode`].
240 #[derive(Clone)]
241 pub struct PercentEncode<'a> {
242     bytes: &'a [u8],
243     ascii_set: &'static AsciiSet,
244 }
245 
246 impl<'a> Iterator for PercentEncode<'a> {
247     type Item = &'a str;
248 
next(&mut self) -> Option<&'a str>249     fn next(&mut self) -> Option<&'a str> {
250         if let Some((&first_byte, remaining)) = self.bytes.split_first() {
251             if self.ascii_set.should_percent_encode(first_byte) {
252                 self.bytes = remaining;
253                 Some(percent_encode_byte(first_byte))
254             } else {
255                 for (i, &byte) in remaining.iter().enumerate() {
256                     if self.ascii_set.should_percent_encode(byte) {
257                         // 1 for first_byte + i for previous iterations of this loop
258                         let (unchanged_slice, remaining) = self.bytes.split_at(1 + i);
259                         self.bytes = remaining;
260                         return Some(unsafe { str::from_utf8_unchecked(unchanged_slice) });
261                     }
262                 }
263                 let unchanged_slice = self.bytes;
264                 self.bytes = &[][..];
265                 Some(unsafe { str::from_utf8_unchecked(unchanged_slice) })
266             }
267         } else {
268             None
269         }
270     }
271 
size_hint(&self) -> (usize, Option<usize>)272     fn size_hint(&self) -> (usize, Option<usize>) {
273         if self.bytes.is_empty() {
274             (0, Some(0))
275         } else {
276             (1, Some(self.bytes.len()))
277         }
278     }
279 }
280 
281 impl<'a> fmt::Display for PercentEncode<'a> {
fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result282     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
283         for c in (*self).clone() {
284             formatter.write_str(c)?
285         }
286         Ok(())
287     }
288 }
289 
290 impl<'a> From<PercentEncode<'a>> for Cow<'a, str> {
from(mut iter: PercentEncode<'a>) -> Self291     fn from(mut iter: PercentEncode<'a>) -> Self {
292         match iter.next() {
293             None => "".into(),
294             Some(first) => match iter.next() {
295                 None => first.into(),
296                 Some(second) => {
297                     let mut string = first.to_owned();
298                     string.push_str(second);
299                     string.extend(iter);
300                     string.into()
301                 }
302             },
303         }
304     }
305 }
306 
307 /// Percent-decode the given string.
308 ///
309 /// <https://url.spec.whatwg.org/#string-percent-decode>
310 ///
311 /// See [`percent_decode`] regarding the return type.
312 #[inline]
percent_decode_str(input: &str) -> PercentDecode313 pub fn percent_decode_str(input: &str) -> PercentDecode {
314     percent_decode(input.as_bytes())
315 }
316 
317 /// Percent-decode the given bytes.
318 ///
319 /// <https://url.spec.whatwg.org/#percent-decode>
320 ///
321 /// Any sequence of `%` followed by two hexadecimal digits is decoded.
322 /// The return type:
323 ///
324 /// * Implements `Into<Cow<u8>>` borrowing `input` when it contains no percent-encoded sequence,
325 /// * Implements `Iterator<Item = u8>` and therefore has a `.collect::<Vec<u8>>()` method,
326 /// * Has `decode_utf8()` and `decode_utf8_lossy()` methods.
327 ///
328 /// # Examples
329 ///
330 /// ```
331 /// use percent_encoding::percent_decode;
332 ///
333 /// assert_eq!(percent_decode(b"foo%20bar%3f").decode_utf8().unwrap(), "foo bar?");
334 /// ```
335 #[inline]
percent_decode(input: &[u8]) -> PercentDecode336 pub fn percent_decode(input: &[u8]) -> PercentDecode {
337     PercentDecode {
338         bytes: input.iter(),
339     }
340 }
341 
342 /// The return type of [`percent_decode`].
343 #[derive(Clone, Debug)]
344 pub struct PercentDecode<'a> {
345     bytes: slice::Iter<'a, u8>,
346 }
347 
after_percent_sign(iter: &mut slice::Iter<u8>) -> Option<u8>348 fn after_percent_sign(iter: &mut slice::Iter<u8>) -> Option<u8> {
349     let mut cloned_iter = iter.clone();
350     let h = char::from(*cloned_iter.next()?).to_digit(16)?;
351     let l = char::from(*cloned_iter.next()?).to_digit(16)?;
352     *iter = cloned_iter;
353     Some(h as u8 * 0x10 + l as u8)
354 }
355 
356 impl<'a> Iterator for PercentDecode<'a> {
357     type Item = u8;
358 
next(&mut self) -> Option<u8>359     fn next(&mut self) -> Option<u8> {
360         self.bytes.next().map(|&byte| {
361             if byte == b'%' {
362                 after_percent_sign(&mut self.bytes).unwrap_or(byte)
363             } else {
364                 byte
365             }
366         })
367     }
368 
size_hint(&self) -> (usize, Option<usize>)369     fn size_hint(&self) -> (usize, Option<usize>) {
370         let bytes = self.bytes.len();
371         (bytes / 3, Some(bytes))
372     }
373 }
374 
375 impl<'a> From<PercentDecode<'a>> for Cow<'a, [u8]> {
from(iter: PercentDecode<'a>) -> Self376     fn from(iter: PercentDecode<'a>) -> Self {
377         match iter.if_any() {
378             Some(vec) => Cow::Owned(vec),
379             None => Cow::Borrowed(iter.bytes.as_slice()),
380         }
381     }
382 }
383 
384 impl<'a> PercentDecode<'a> {
385     /// If the percent-decoding is different from the input, return it as a new bytes vector.
if_any(&self) -> Option<Vec<u8>>386     fn if_any(&self) -> Option<Vec<u8>> {
387         let mut bytes_iter = self.bytes.clone();
388         while bytes_iter.any(|&b| b == b'%') {
389             if let Some(decoded_byte) = after_percent_sign(&mut bytes_iter) {
390                 let initial_bytes = self.bytes.as_slice();
391                 let unchanged_bytes_len = initial_bytes.len() - bytes_iter.len() - 3;
392                 let mut decoded = initial_bytes[..unchanged_bytes_len].to_owned();
393                 decoded.push(decoded_byte);
394                 decoded.extend(PercentDecode { bytes: bytes_iter });
395                 return Some(decoded);
396             }
397         }
398         // Nothing to decode
399         None
400     }
401 
402     /// Decode the result of percent-decoding as UTF-8.
403     ///
404     /// This is return `Err` when the percent-decoded bytes are not well-formed in UTF-8.
decode_utf8(self) -> Result<Cow<'a, str>, str::Utf8Error>405     pub fn decode_utf8(self) -> Result<Cow<'a, str>, str::Utf8Error> {
406         match self.clone().into() {
407             Cow::Borrowed(bytes) => match str::from_utf8(bytes) {
408                 Ok(s) => Ok(s.into()),
409                 Err(e) => Err(e),
410             },
411             Cow::Owned(bytes) => match String::from_utf8(bytes) {
412                 Ok(s) => Ok(s.into()),
413                 Err(e) => Err(e.utf8_error()),
414             },
415         }
416     }
417 
418     /// Decode the result of percent-decoding as UTF-8, lossily.
419     ///
420     /// Invalid UTF-8 percent-encoded byte sequences will be replaced � U+FFFD,
421     /// the replacement character.
decode_utf8_lossy(self) -> Cow<'a, str>422     pub fn decode_utf8_lossy(self) -> Cow<'a, str> {
423         decode_utf8_lossy(self.clone().into())
424     }
425 }
426 
decode_utf8_lossy(input: Cow<[u8]>) -> Cow<str>427 fn decode_utf8_lossy(input: Cow<[u8]>) -> Cow<str> {
428     match input {
429         Cow::Borrowed(bytes) => String::from_utf8_lossy(bytes),
430         Cow::Owned(bytes) => {
431             let raw_utf8: *const [u8];
432             match String::from_utf8_lossy(&bytes) {
433                 Cow::Borrowed(utf8) => raw_utf8 = utf8.as_bytes(),
434                 Cow::Owned(s) => return s.into(),
435             }
436             // from_utf8_lossy returned a borrow of `bytes` unchanged.
437             debug_assert!(raw_utf8 == &*bytes as *const [u8]);
438             // Reuse the existing `Vec` allocation.
439             unsafe { String::from_utf8_unchecked(bytes) }.into()
440         }
441     }
442 }
443