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