percent_encoding/
lib.rs

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.  For example, a forward slash
10//! indicates a path.  In order for that charcter to exist outside of a path separator, that
11//! charcter would need to be encoded.
12//!
13//! Percent encoding replaces reserved charcters with the `%` escape charcter followed by hexidecimal
14//! ASCII representaton.  For non-ASCII charcters that are percent encoded, a UTF-8 byte sequence
15//! becomes percent encoded.  A simple example can be seen when the space literal is replaced with
16//! `%20`.
17//!
18//! Percent encoding is further complicated by the fact that different parts of an URL have
19//! different encoding requirements.  In order to support the variety of encoding requirements,
20//! `url::percent_encoding` includes different *encode sets*.
21//! See [URL Standard](https://url.spec.whatwg.org/#percent-encoded-bytes) for details.
22//!
23//! This module provides some `*_ENCODE_SET` constants.
24//! If a different set is required, it can be created with
25//! the [`define_encode_set!`](../macro.define_encode_set!.html) macro.
26//!
27//! # Examples
28//!
29//! ```
30//! use url::percent_encoding::{utf8_percent_encode, DEFAULT_ENCODE_SET};
31//!
32//! assert_eq!(utf8_percent_encode("foo bar?", DEFAULT_ENCODE_SET).to_string(), "foo%20bar%3F");
33//! ```
34
35use std::ascii::AsciiExt;
36use std::borrow::Cow;
37use std::fmt;
38use std::slice;
39use std::str;
40
41/// Represents a set of characters / bytes that should be percent-encoded.
42///
43/// See [encode sets specification](http://url.spec.whatwg.org/#simple-encode-set).
44///
45/// Different characters need to be encoded in different parts of an URL.
46/// For example, a literal `?` question mark in an URL’s path would indicate
47/// the start of the query string.
48/// A question mark meant to be part of the path therefore needs to be percent-encoded.
49/// In the query string however, a question mark does not have any special meaning
50/// and does not need to be percent-encoded.
51///
52/// A few sets are defined in this module.
53/// Use the [`define_encode_set!`](../macro.define_encode_set!.html) macro to define different ones.
54pub trait EncodeSet: Clone {
55    /// Called with UTF-8 bytes rather than code points.
56    /// Should return true for all non-ASCII bytes.
57    fn contains(&self, byte: u8) -> bool;
58}
59
60/// Define a new struct
61/// that implements the [`EncodeSet`](percent_encoding/trait.EncodeSet.html) trait,
62/// for use in [`percent_decode()`](percent_encoding/fn.percent_encode.html)
63/// and related functions.
64///
65/// Parameters are characters to include in the set in addition to those of the base set.
66/// See [encode sets specification](http://url.spec.whatwg.org/#simple-encode-set).
67///
68/// Example
69/// =======
70///
71/// ```rust
72/// #[macro_use] extern crate percent_encoding;
73/// use percent_encoding::{utf8_percent_encode, SIMPLE_ENCODE_SET};
74/// define_encode_set! {
75///     /// This encode set is used in the URL parser for query strings.
76///     pub QUERY_ENCODE_SET = [SIMPLE_ENCODE_SET] | {' ', '"', '#', '<', '>'}
77/// }
78/// # fn main() {
79/// assert_eq!(utf8_percent_encode("foo bar", QUERY_ENCODE_SET).collect::<String>(), "foo%20bar");
80/// # }
81/// ```
82#[macro_export]
83macro_rules! define_encode_set {
84    ($(#[$attr: meta])* pub $name: ident = [$base_set: expr] | {$($ch: pat),*}) => {
85        $(#[$attr])*
86        #[derive(Copy, Clone, Debug)]
87        #[allow(non_camel_case_types)]
88        pub struct $name;
89
90        impl $crate::EncodeSet for $name {
91            #[inline]
92            fn contains(&self, byte: u8) -> bool {
93                match byte as char {
94                    $(
95                        $ch => true,
96                    )*
97                    _ => $base_set.contains(byte)
98                }
99            }
100        }
101    }
102}
103
104/// This encode set is used for the path of cannot-be-a-base URLs.
105///
106/// All ASCII charcters less than hexidecimal 20 and greater than 7E are encoded.  This includes
107/// special charcters such as line feed, carriage return, NULL, etc.
108#[derive(Copy, Clone, Debug)]
109#[allow(non_camel_case_types)]
110pub struct SIMPLE_ENCODE_SET;
111
112impl EncodeSet for SIMPLE_ENCODE_SET {
113    #[inline]
114    fn contains(&self, byte: u8) -> bool {
115        byte < 0x20 || byte > 0x7E
116    }
117}
118
119define_encode_set! {
120    /// This encode set is used in the URL parser for query strings.
121    ///
122    /// Aside from special chacters defined in the [`SIMPLE_ENCODE_SET`](struct.SIMPLE_ENCODE_SET.html),
123    /// space, double quote ("), hash (#), and inequality qualifiers (<), (>) are encoded.
124    pub QUERY_ENCODE_SET = [SIMPLE_ENCODE_SET] | {' ', '"', '#', '<', '>'}
125}
126
127define_encode_set! {
128    /// This encode set is used for path components.
129    ///
130    /// Aside from special chacters defined in the [`SIMPLE_ENCODE_SET`](struct.SIMPLE_ENCODE_SET.html),
131    /// space, double quote ("), hash (#), inequality qualifiers (<), (>), backtick (`),
132    /// question mark (?), and curly brackets ({), (}) are encoded.
133    pub DEFAULT_ENCODE_SET = [QUERY_ENCODE_SET] | {'`', '?', '{', '}'}
134}
135
136define_encode_set! {
137    /// This encode set is used for on '/'-separated path segment
138    ///
139    /// Aside from special chacters defined in the [`SIMPLE_ENCODE_SET`](struct.SIMPLE_ENCODE_SET.html),
140    /// space, double quote ("), hash (#), inequality qualifiers (<), (>), backtick (`),
141    /// question mark (?), and curly brackets ({), (}), percent sign (%), forward slash (/) are
142    /// encoded.
143    pub PATH_SEGMENT_ENCODE_SET = [DEFAULT_ENCODE_SET] | {'%', '/'}
144}
145
146define_encode_set! {
147    /// This encode set is used for username and password.
148    ///
149    /// Aside from special chacters defined in the [`SIMPLE_ENCODE_SET`](struct.SIMPLE_ENCODE_SET.html),
150    /// space, double quote ("), hash (#), inequality qualifiers (<), (>), backtick (`),
151    /// question mark (?), and curly brackets ({), (}), forward slash (/), colon (:), semi-colon (;),
152    /// equality (=), at (@), backslash (\\), square brackets ([), (]), caret (\^), and pipe (|) are
153    /// encoded.
154    pub USERINFO_ENCODE_SET = [DEFAULT_ENCODE_SET] | {
155        '/', ':', ';', '=', '@', '[', '\\', ']', '^', '|'
156    }
157}
158
159/// Return the percent-encoding of the given bytes.
160///
161/// This is unconditional, unlike `percent_encode()` which uses an encode set.
162///
163/// # Examples
164///
165/// ```
166/// use url::percent_encoding::percent_encode_byte;
167///
168/// assert_eq!("foo bar".bytes().map(percent_encode_byte).collect::<String>(),
169///            "%66%6F%6F%20%62%61%72");
170/// ```
171pub fn percent_encode_byte(byte: u8) -> &'static str {
172    let index = usize::from(byte) * 3;
173    &"\
174        %00%01%02%03%04%05%06%07%08%09%0A%0B%0C%0D%0E%0F\
175        %10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F\
176        %20%21%22%23%24%25%26%27%28%29%2A%2B%2C%2D%2E%2F\
177        %30%31%32%33%34%35%36%37%38%39%3A%3B%3C%3D%3E%3F\
178        %40%41%42%43%44%45%46%47%48%49%4A%4B%4C%4D%4E%4F\
179        %50%51%52%53%54%55%56%57%58%59%5A%5B%5C%5D%5E%5F\
180        %60%61%62%63%64%65%66%67%68%69%6A%6B%6C%6D%6E%6F\
181        %70%71%72%73%74%75%76%77%78%79%7A%7B%7C%7D%7E%7F\
182        %80%81%82%83%84%85%86%87%88%89%8A%8B%8C%8D%8E%8F\
183        %90%91%92%93%94%95%96%97%98%99%9A%9B%9C%9D%9E%9F\
184        %A0%A1%A2%A3%A4%A5%A6%A7%A8%A9%AA%AB%AC%AD%AE%AF\
185        %B0%B1%B2%B3%B4%B5%B6%B7%B8%B9%BA%BB%BC%BD%BE%BF\
186        %C0%C1%C2%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF\
187        %D0%D1%D2%D3%D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF\
188        %E0%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF\
189        %F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE%FF\
190    "[index..index + 3]
191}
192
193/// Percent-encode the given bytes with the given encode set.
194///
195/// The encode set define which bytes (in addition to non-ASCII and controls)
196/// need to be percent-encoded.
197/// The choice of this set depends on context.
198/// For example, `?` needs to be encoded in an URL path but not in a query string.
199///
200/// The return value is an iterator of `&str` slices (so it has a `.collect::<String>()` method)
201/// that also implements `Display` and `Into<Cow<str>>`.
202/// The latter returns `Cow::Borrowed` when none of the bytes in `input`
203/// are in the given encode set.
204///
205/// # Examples
206///
207/// ```
208/// use url::percent_encoding::{percent_encode, DEFAULT_ENCODE_SET};
209///
210/// assert_eq!(percent_encode(b"foo bar?", DEFAULT_ENCODE_SET).to_string(), "foo%20bar%3F");
211/// ```
212#[inline]
213pub fn percent_encode<E: EncodeSet>(input: &[u8], encode_set: E) -> PercentEncode<E> {
214    PercentEncode {
215        bytes: input,
216        encode_set: encode_set,
217    }
218}
219
220/// Percent-encode the UTF-8 encoding of the given string.
221///
222/// See `percent_encode()` for how to use the return value.
223///
224/// # Examples
225///
226/// ```
227/// use url::percent_encoding::{utf8_percent_encode, DEFAULT_ENCODE_SET};
228///
229/// assert_eq!(utf8_percent_encode("foo bar?", DEFAULT_ENCODE_SET).to_string(), "foo%20bar%3F");
230/// ```
231#[inline]
232pub fn utf8_percent_encode<E: EncodeSet>(input: &str, encode_set: E) -> PercentEncode<E> {
233    percent_encode(input.as_bytes(), encode_set)
234}
235
236/// The return type of `percent_encode()` and `utf8_percent_encode()`.
237#[derive(Clone, Debug)]
238pub struct PercentEncode<'a, E: EncodeSet> {
239    bytes: &'a [u8],
240    encode_set: E,
241}
242
243impl<'a, E: EncodeSet> Iterator for PercentEncode<'a, E> {
244    type Item = &'a str;
245
246    fn next(&mut self) -> Option<&'a str> {
247        if let Some((&first_byte, remaining)) = self.bytes.split_first() {
248            if self.encode_set.contains(first_byte) {
249                self.bytes = remaining;
250                Some(percent_encode_byte(first_byte))
251            } else {
252                assert!(first_byte.is_ascii());
253                for (i, &byte) in remaining.iter().enumerate() {
254                    if self.encode_set.contains(byte) {
255                        // 1 for first_byte + i for previous iterations of this loop
256                        let (unchanged_slice, remaining) = self.bytes.split_at(1 + i);
257                        self.bytes = remaining;
258                        return Some(unsafe { str::from_utf8_unchecked(unchanged_slice) })
259                    } else {
260                        assert!(byte.is_ascii());
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
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
281impl<'a, E: EncodeSet> fmt::Display for PercentEncode<'a, E> {
282    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
290impl<'a, E: EncodeSet> From<PercentEncode<'a, E>> for Cow<'a, str> {
291    fn from(mut iter: PercentEncode<'a, E>) -> Self {
292        match iter.next() {
293            None => "".into(),
294            Some(first) => {
295                match iter.next() {
296                    None => first.into(),
297                    Some(second) => {
298                        let mut string = first.to_owned();
299                        string.push_str(second);
300                        string.extend(iter);
301                        string.into()
302                    }
303                }
304            }
305        }
306    }
307}
308
309/// Percent-decode the given bytes.
310///
311/// The return value is an iterator of decoded `u8` bytes
312/// that also implements `Into<Cow<u8>>`
313/// (which returns `Cow::Borrowed` when `input` contains no percent-encoded sequence)
314/// and has `decode_utf8()` and `decode_utf8_lossy()` methods.
315///
316/// # Examples
317///
318/// ```
319/// use url::percent_encoding::percent_decode;
320///
321/// assert_eq!(percent_decode(b"foo%20bar%3F").decode_utf8().unwrap(), "foo bar?");
322/// ```
323#[inline]
324pub fn percent_decode(input: &[u8]) -> PercentDecode {
325    PercentDecode {
326        bytes: input.iter()
327    }
328}
329
330/// The return type of `percent_decode()`.
331#[derive(Clone, Debug)]
332pub struct PercentDecode<'a> {
333    bytes: slice::Iter<'a, u8>,
334}
335
336fn after_percent_sign(iter: &mut slice::Iter<u8>) -> Option<u8> {
337    let initial_iter = iter.clone();
338    let h = iter.next().and_then(|&b| (b as char).to_digit(16));
339    let l = iter.next().and_then(|&b| (b as char).to_digit(16));
340    if let (Some(h), Some(l)) = (h, l) {
341        Some(h as u8 * 0x10 + l as u8)
342    } else {
343        *iter = initial_iter;
344        None
345    }
346}
347
348impl<'a> Iterator for PercentDecode<'a> {
349    type Item = u8;
350
351    fn next(&mut self) -> Option<u8> {
352        self.bytes.next().map(|&byte| {
353            if byte == b'%' {
354                after_percent_sign(&mut self.bytes).unwrap_or(byte)
355            } else {
356                byte
357            }
358        })
359    }
360
361    fn size_hint(&self) -> (usize, Option<usize>) {
362        let bytes = self.bytes.len();
363        (bytes / 3, Some(bytes))
364    }
365}
366
367impl<'a> From<PercentDecode<'a>> for Cow<'a, [u8]> {
368    fn from(iter: PercentDecode<'a>) -> Self {
369        match iter.if_any() {
370            Some(vec) => Cow::Owned(vec),
371            None => Cow::Borrowed(iter.bytes.as_slice()),
372        }
373    }
374}
375
376impl<'a> PercentDecode<'a> {
377    /// If the percent-decoding is different from the input, return it as a new bytes vector.
378    pub fn if_any(&self) -> Option<Vec<u8>> {
379        let mut bytes_iter = self.bytes.clone();
380        while bytes_iter.any(|&b| b == b'%') {
381            if let Some(decoded_byte) = after_percent_sign(&mut bytes_iter) {
382                let initial_bytes = self.bytes.as_slice();
383                let unchanged_bytes_len = initial_bytes.len() - bytes_iter.len() - 3;
384                let mut decoded = initial_bytes[..unchanged_bytes_len].to_owned();
385                decoded.push(decoded_byte);
386                decoded.extend(PercentDecode {
387                    bytes: bytes_iter
388                });
389                return Some(decoded)
390            }
391        }
392        // Nothing to decode
393        None
394    }
395
396    /// Decode the result of percent-decoding as UTF-8.
397    ///
398    /// This is return `Err` when the percent-decoded bytes are not well-formed in UTF-8.
399    pub fn decode_utf8(self) -> Result<Cow<'a, str>, str::Utf8Error> {
400        match self.clone().into() {
401            Cow::Borrowed(bytes) => {
402                match str::from_utf8(bytes) {
403                    Ok(s) => Ok(s.into()),
404                    Err(e) => Err(e),
405                }
406            }
407            Cow::Owned(bytes) => {
408                match String::from_utf8(bytes) {
409                    Ok(s) => Ok(s.into()),
410                    Err(e) => Err(e.utf8_error()),
411                }
412            }
413        }
414    }
415
416    /// Decode the result of percent-decoding as UTF-8, lossily.
417    ///
418    /// Invalid UTF-8 percent-encoded byte sequences will be replaced � U+FFFD,
419    /// the replacement character.
420    pub fn decode_utf8_lossy(self) -> Cow<'a, str> {
421        decode_utf8_lossy(self.clone().into())
422    }
423}
424
425fn decode_utf8_lossy(input: Cow<[u8]>) -> Cow<str> {
426    match input {
427        Cow::Borrowed(bytes) => String::from_utf8_lossy(bytes),
428        Cow::Owned(bytes) => {
429            let raw_utf8: *const [u8];
430            match String::from_utf8_lossy(&bytes) {
431                Cow::Borrowed(utf8) => raw_utf8 = utf8.as_bytes(),
432                Cow::Owned(s) => return s.into(),
433            }
434            // from_utf8_lossy returned a borrow of `bytes` unchanged.
435            debug_assert!(raw_utf8 == &*bytes as *const [u8]);
436            // Reuse the existing `Vec` allocation.
437            unsafe { String::from_utf8_unchecked(bytes) }.into()
438        }
439    }
440}
441
442