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