Skip to main content

urly/
quoting.rs

1//! Percent-encoding inspired by Python's yarl.
2//!
3//! * [`quote`] encodes a literal value: every character that isn't allowed in the
4//!   component, including `%`, is percent-encoded.
5//! * [`requote`] normalizes an already-encoded value: valid `%XX` escapes are kept
6//!   (uppercased, or decoded when they encode an unreserved character `A-Z a-z
7//!   0-9 - . _ ~`), any other
8//!   disallowed character is percent-encoded.
9//! * [`unquote`] decodes a value. Escapes that don't form valid UTF-8 are kept as is.
10//!
11//! All functions borrow the input if it doesn't need to change.
12//!
13//! ```
14//! use urly::quoting::{Component, quote, requote, unquote};
15//!
16//! assert_eq!(quote("a b/100%", Component::Path), "a%20b/100%25");
17//! assert_eq!(requote("a b/100%25%7e", Component::Path), "a%20b/100%25~");
18//! assert_eq!(quote("a b&c=d", Component::QueryPart), "a+b%26c%3Dd");
19//! assert_eq!(unquote("a+b%26c", Component::QueryPart), "a b&c");
20//! assert_eq!(quote("a=b; c", Component::Opaque), "a%3Db%3B%20c");
21//! ```
22use std::borrow::Cow;
23
24use crate::chars::{ALLOWED, HEX_UPPER, NONE, QS, Set, UNRESERVED, pct_at, push_pct};
25
26/// The URL component a value belongs to; it selects the characters that are
27/// left unencoded.
28#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
29pub enum Component {
30    /// User name or password. `:` and `@` are encoded.
31    UserInfo,
32    /// Path. `/` is kept.
33    Path,
34    /// Whole query string. `&`, `=`, `+` and `;` are kept; space is encoded as `+`.
35    Query,
36    /// Query key or value. `&`, `=`, `+` and `;` are encoded; space is encoded as `+`.
37    QueryPart,
38    /// Fragment.
39    Fragment,
40    /// A standalone value outside of a URL, such as a cookie name or value.
41    /// Only unreserved characters (`A-Z a-z 0-9 - . _ ~`) are kept.
42    Opaque,
43}
44
45struct Quoter {
46    safe: Set,
47    qs: bool,
48}
49
50static USERINFO: Quoter = Quoter {
51    safe: ALLOWED.union(QS),
52    qs: false,
53};
54static PATH: Quoter = Quoter {
55    safe: ALLOWED.union(QS).union(Set::new(b"@:/+")),
56    qs: false,
57};
58static QUERY: Quoter = Quoter {
59    safe: ALLOWED.union(Set::new(b"?/:@=+&;")),
60    qs: true,
61};
62// a literal `+` in a query would be decoded as space
63static QUERY_LITERAL: Quoter = Quoter {
64    safe: QUERY.safe.without(b'+'),
65    qs: true,
66};
67static QUERY_PART: Quoter = Quoter {
68    safe: ALLOWED.union(Set::new(b"?/:@")),
69    qs: true,
70};
71static FRAGMENT: Quoter = Quoter {
72    safe: ALLOWED.union(QS).union(Set::new(b"?/:@")),
73    qs: false,
74};
75static OPAQUE: Quoter = Quoter {
76    safe: UNRESERVED,
77    qs: false,
78};
79
80const PATH_SAFE: Set = Set::new(b"/%");
81
82impl Component {
83    fn quoter(self, requote: bool) -> &'static Quoter {
84        match self {
85            Component::UserInfo => &USERINFO,
86            Component::Path => &PATH,
87            Component::Query if requote => &QUERY,
88            Component::Query => &QUERY_LITERAL,
89            Component::QueryPart => &QUERY_PART,
90            Component::Fragment => &FRAGMENT,
91            Component::Opaque => &OPAQUE,
92        }
93    }
94}
95
96/// Percent-encodes a literal value.
97pub fn quote(src: &str, component: Component) -> Cow<'_, str> {
98    quote_with::<false>(src, component)
99}
100
101/// Normalizes the percent-encoding of an already-encoded value.
102pub fn requote(src: &str, component: Component) -> Cow<'_, str> {
103    quote_with::<true>(src, component)
104}
105
106/// Decodes a percent-encoded value.
107///
108/// For [`Component::QueryPart`] `+` is decoded as space. For [`Component::Query`]
109/// `+` is decoded as space too, but escapes of `&`, `=`, `+` and `;` are kept, so
110/// the result can still be split into pairs.
111pub fn unquote(src: &str, component: Component) -> Cow<'_, str> {
112    match component {
113        Component::Query => unquote_with::<true>(src, &QS),
114        Component::QueryPart => unquote_with::<true>(src, &NONE),
115        _ => unquote_with::<false>(src, &NONE),
116    }
117}
118
119fn quote_with<const REQUOTE: bool>(src: &str, component: Component) -> Cow<'_, str> {
120    let q = component.quoter(REQUOTE);
121    let bytes = src.as_bytes();
122    let is_safe = |b: u8| q.safe.contains(b);
123
124    // fast path, find the first byte that has to change
125    let mut i = 0;
126    while i < bytes.len() {
127        let b = bytes[i];
128        if is_safe(b) {
129            i += 1;
130            continue;
131        }
132        if REQUOTE
133            && let Some(v) = pct_at(bytes, i)
134            && !bytes[i + 1].is_ascii_lowercase()
135            && !bytes[i + 2].is_ascii_lowercase()
136            && !UNRESERVED.contains(v)
137        {
138            i += 3;
139            continue;
140        }
141        break;
142    }
143    if i == bytes.len() {
144        return Cow::Borrowed(src);
145    }
146
147    let mut out = String::with_capacity(bytes.len() + 16);
148    out.push_str(&src[..i]);
149    if bytes.len() - i < 32 {
150        quote_into::<REQUOTE, false>(&mut out, src, i, q);
151    } else {
152        quote_into::<REQUOTE, true>(&mut out, src, i, q);
153    }
154    Cow::Owned(out)
155}
156
157#[inline(always)]
158fn quote_into<const REQUOTE: bool, const BULK: bool>(
159    out: &mut String,
160    src: &str,
161    mut i: usize,
162    q: &Quoter,
163) {
164    let bytes = src.as_bytes();
165    while i < bytes.len() {
166        let b = bytes[i];
167        if q.safe.contains(b) {
168            if BULK {
169                let mut end = i + 1;
170                while end < bytes.len() && q.safe.contains(bytes[end]) {
171                    end += 1;
172                }
173                if end - i >= 8 {
174                    out.push_str(&src[i..end]);
175                    i = end;
176                    continue;
177                }
178                return quote_into::<REQUOTE, false>(out, src, i, q);
179            }
180            out.push(b as char);
181            i += 1;
182        } else if REQUOTE && let Some(v) = pct_at(bytes, i) {
183            if !UNRESERVED.contains(v) {
184                push_pct(out, v);
185            } else {
186                out.push(v as char);
187            }
188            i += 3;
189        } else if q.qs && b == b' ' {
190            out.push('+');
191            i += 1;
192        } else {
193            push_pct(out, b);
194            i += 1;
195        }
196    }
197}
198
199/// Decodes `src`, keeping escapes of `ignore` characters encoded.
200pub(crate) fn unquote_with<'a, const PLUS: bool>(src: &'a str, ignore: &Set) -> Cow<'a, str> {
201    let bytes = src.as_bytes();
202    let Some(start) = bytes
203        .iter()
204        .position(|b| *b == b'%' || (PLUS && *b == b'+'))
205    else {
206        return Cow::Borrowed(src);
207    };
208
209    // fast path, decode everything and validate once
210    let mut buf = Vec::with_capacity(bytes.len());
211    buf.extend_from_slice(&bytes[..start]);
212    unquote_into::<PLUS, true>(&mut buf, bytes, start, ignore);
213    if simdutf8::basic::from_utf8(&buf[start..]).is_ok() {
214        // SAFETY: the unchanged prefix is valid UTF-8 ending at an ASCII escape
215        // boundary, and the decoded suffix is validated above.
216        return Cow::Owned(unsafe { String::from_utf8_unchecked(buf) });
217    }
218    let mut out = String::with_capacity(bytes.len());
219    out.push_str(&src[..start]);
220    // Literal UTF-8 cannot complete an escaped partial sequence: it never starts
221    // with a continuation byte. Repairing the decoded buffer preserves run boundaries.
222    for chunk in buf[start..].utf8_chunks() {
223        out.push_str(chunk.valid());
224        for &b in chunk.invalid() {
225            push_pct(&mut out, b);
226        }
227    }
228    Cow::Owned(out)
229}
230
231// Specialize short-run tails so dense escapes do not pay a per-byte bulk-copy branch.
232#[inline(always)]
233fn unquote_into<const PLUS: bool, const BULK: bool>(
234    buf: &mut Vec<u8>,
235    bytes: &[u8],
236    mut i: usize,
237    ignore: &Set,
238) {
239    while i < bytes.len() {
240        let b = bytes[i];
241        if let Some(v) = pct_at(bytes, i) {
242            if ignore.contains(v) {
243                buf.extend_from_slice(&[
244                    b'%',
245                    HEX_UPPER[usize::from(v >> 4)],
246                    HEX_UPPER[usize::from(v & 15)],
247                ]);
248            } else {
249                buf.push(v);
250            }
251            i += 3;
252        } else {
253            if BULK && b != b'%' && !(PLUS && b == b'+') {
254                let mut end = i + 1;
255                while end < bytes.len() && bytes[end] != b'%' && !(PLUS && bytes[end] == b'+') {
256                    end += 1;
257                }
258                if end - i >= 8 {
259                    buf.extend_from_slice(&bytes[i..end]);
260                    i = end;
261                    continue;
262                }
263                return unquote_into::<PLUS, false>(buf, bytes, i, ignore);
264            }
265            buf.push(if PLUS && b == b'+' { b' ' } else { b });
266            i += 1;
267        }
268    }
269}
270
271/// Decodes a path, keeping `%2F` and `%25` encoded.
272pub(crate) fn unquote_path_safe(src: &str) -> Cow<'_, str> {
273    unquote_with::<false>(src, &PATH_SAFE)
274}
275
276#[cfg(test)]
277mod tests {
278    use super::*;
279
280    /// STATEMENT: Specialized quote modes preserve component rules across short and long safe runs.
281    ///
282    /// HOW:
283    /// - Surround Unicode, spaces, delimiters and percent escapes with varying ASCII spans.
284    /// - Check literal and normalized output, and borrowing for unchanged canonical inputs.
285    #[test]
286    fn quoting_modes_and_spans() {
287        for len in [0, 1, 7, 8, 15, 16, 31, 32, 63, 64, 127] {
288            let prefix = "a".repeat(len);
289            let suffix = "z".repeat(len);
290            for (component, input, quoted, requoted) in [
291                (
292                    Component::Path,
293                    "a b/\u{fc}",
294                    "a%20b/%C3%BC",
295                    "a%20b/%C3%BC",
296                ),
297                (
298                    Component::Path,
299                    "%7e%41%2f%2b",
300                    "%257e%2541%252f%252b",
301                    "~A%2F%2B",
302                ),
303                (Component::Path, "%zz%4", "%25zz%254", "%25zz%254"),
304                (Component::Query, "a+b=c d", "a%2Bb=c+d", "a+b=c+d"),
305                (
306                    Component::QueryPart,
307                    "a+b=c&d;e",
308                    "a%2Bb%3Dc%26d%3Be",
309                    "a%2Bb%3Dc%26d%3Be",
310                ),
311                (Component::UserInfo, "u:p@x", "u%3Ap%40x", "u%3Ap%40x"),
312                (
313                    Component::Fragment,
314                    "x#\u{1f642}",
315                    "x%23%F0%9F%99%82",
316                    "x%23%F0%9F%99%82",
317                ),
318                (Component::Opaque, "=?#\0", "%3D%3F%23%00", "%3D%3F%23%00"),
319            ] {
320                let src = format!("{prefix}{input}{suffix}");
321                assert_eq!(quote(&src, component), format!("{prefix}{quoted}{suffix}"));
322                assert_eq!(
323                    requote(&src, component),
324                    format!("{prefix}{requoted}{suffix}")
325                );
326            }
327            let src = format!("{prefix}%2F%20{suffix}");
328            assert!(matches!(requote(&src, Component::Path), Cow::Borrowed(_)));
329            let src = format!("{prefix}-{suffix}");
330            assert!(matches!(quote(&src, Component::Opaque), Cow::Borrowed(_)));
331            let src = format!(" {prefix}\u{fc}{suffix} ");
332            assert_eq!(
333                quote(&src, Component::Path),
334                format!("%20{prefix}%C3%BC{suffix}%20")
335            );
336        }
337    }
338
339    /// STATEMENT: Specialized decoding handles every escaped byte without changing literal UTF-8.
340    ///
341    /// HOW:
342    /// - Surround each lowercase byte escape with literal Unicode and a literal plus.
343    /// - Check path, query and query-part plus handling and protected-escape normalization.
344    /// - Check the safe-path decoder preserves slash and percent escapes.
345    #[test]
346    fn unquote_bytes_and_modes() {
347        for byte in 0..=255u8 {
348            let src = format!("\u{e9}+%{byte:02x}\u{1f642}");
349            let encoded = format!("%{byte:02X}");
350            let decoded = if byte.is_ascii() {
351                char::from(byte).to_string()
352            } else {
353                encoded.clone()
354            };
355            for component in [Component::Path, Component::Query, Component::QueryPart] {
356                let plus = if component == Component::Path { "+" } else { " " };
357                let value = if component == Component::Query && b"&=+;".contains(&byte) {
358                    &encoded
359                } else {
360                    &decoded
361                };
362                assert_eq!(
363                    unquote(&src, component),
364                    format!("\u{e9}{plus}{value}\u{1f642}")
365                );
366            }
367            let value = if b"/%".contains(&byte) { &encoded } else { &decoded };
368            assert_eq!(unquote_path_safe(&src), format!("\u{e9}+{value}\u{1f642}"));
369        }
370    }
371
372    /// STATEMENT: Repairing decoded bytes preserves escaped-run boundaries and literal percent text.
373    ///
374    /// HOW:
375    /// - Mix valid escaped Unicode, invalid/truncated UTF-8, raw Unicode and malformed escapes.
376    /// - Check invalid bytes are re-encoded once, without reinterpreting decoded percent signs.
377    /// - Exercise long valid prefixes and ignored query/path escapes alongside invalid bytes.
378    #[test]
379    fn unquote_invalid_runs() {
380        for len in [0, 1, 15, 16, 63, 64, 127] {
381            let prefix = "a".repeat(len);
382            for (input, expected) in [
383                ("%ff%C3%BCx%C3", "%FF\u{fc}x%C3"),
384                ("%E2%28%A1", "%E2(%A1"),
385                ("%C0%AF", "%C0%AF"),
386                ("%ED%A0%80", "%ED%A0%80"),
387                ("%F4%90%80%80", "%F4%90%80%80"),
388                ("%F0%9F%92", "%F0%9F%92"),
389                ("%E2%82%AC%E2%82", "\u{20ac}%E2%82"),
390                ("%e2\u{20ac}%82%ac", "%E2\u{20ac}%82%AC"),
391                ("%ff%25ff", "%FF%ff"),
392                ("\u{e9}%ff%25ff", "\u{e9}%FF%ff"),
393                ("%ff%25C3%25BC", "%FF%C3%BC"),
394                ("%ff%zz%4", "%FF%zz%4"),
395                (
396                    "%ff\u{e9}\u{20ac}\u{1f600}%20",
397                    "%FF\u{e9}\u{20ac}\u{1f600} ",
398                ),
399            ] {
400                let src = format!("{prefix}{input}");
401                assert_eq!(
402                    unquote(&src, Component::Path),
403                    format!("{prefix}{expected}")
404                );
405            }
406            let src = format!("{prefix}%ff+%26%3d%2b%3b");
407            assert_eq!(
408                unquote(&src, Component::Query),
409                format!("{prefix}%FF %26%3D%2B%3B")
410            );
411            assert_eq!(
412                unquote(&src, Component::QueryPart),
413                format!("{prefix}%FF &=+;")
414            );
415            let src = format!("{prefix}%ff%2f%25%C3%BC");
416            assert_eq!(unquote_path_safe(&src), format!("{prefix}%FF%2F%25\u{fc}"));
417        }
418    }
419
420    /// STATEMENT: Scalar span copying preserves malformed escapes and borrows unchanged inputs.
421    ///
422    /// HOW:
423    /// - Separate escapes, plus signs and malformed percent text with safe runs of varying lengths.
424    /// - Check path/query decoding and borrowing when no transformation is needed.
425    #[test]
426    fn unquote_spans() {
427        for len in [0, 1, 7, 8, 15, 16, 31, 32, 63, 64, 127] {
428            let span = "x".repeat(len);
429            let src = format!("%41{span}+{span}%20{span}%zz{span}%");
430            assert_eq!(
431                unquote(&src, Component::Path),
432                format!("A{span}+{span} {span}%zz{span}%")
433            );
434            assert_eq!(
435                unquote(&src, Component::QueryPart),
436                format!("A{span} {span} {span}%zz{span}%")
437            );
438            let src = format!("\u{fc}{span}");
439            assert!(matches!(unquote(&src, Component::Path), Cow::Borrowed(_)));
440            assert!(matches!(
441                unquote(&src, Component::QueryPart),
442                Cow::Borrowed(_)
443            ));
444        }
445    }
446
447    /// STATEMENT: Literal quoting uses the safe set and space rules of each component.
448    ///
449    /// HOW:
450    /// - Check representative delimiters, Unicode and percent signs in every component.
451    /// - Confirm already-safe opaque values are borrowed.
452    #[test]
453    fn quote_rules() {
454        assert_eq!(quote("", Component::Path), "");
455        assert_eq!(quote("/a b/ü", Component::Path), "/a%20b/%C3%BC");
456        assert_eq!(quote("%41", Component::Path), "%2541");
457        assert_eq!(quote("u:p@x", Component::UserInfo), "u%3Ap%40x");
458        assert_eq!(
459            quote("a+b=c&d;e", Component::QueryPart),
460            "a%2Bb%3Dc%26d%3Be"
461        );
462        assert_eq!(quote("a=b&c d", Component::Query), "a=b&c+d");
463        assert_eq!(quote("x#y", Component::Fragment), "x%23y");
464        assert_eq!(
465            quote("a=b; c,\"%~", Component::Opaque),
466            "a%3Db%3B%20c%2C%22%25~"
467        );
468        assert!(matches!(
469            quote("a-b_c.1~", Component::Opaque),
470            Cow::Borrowed(_)
471        ));
472    }
473
474    /// STATEMENT: Requoting normalizes escapes without decoding protected component delimiters.
475    ///
476    /// HOW:
477    /// - Check canonical borrowing, lowercase escapes, malformed escapes and query spaces.
478    #[test]
479    fn requote_rules() {
480        assert!(matches!(
481            requote("/a%2Fb%20c", Component::Path),
482            Cow::Borrowed(_)
483        ));
484        assert_eq!(requote("%7e%41%2f%2b", Component::Path), "~A%2F%2B");
485        assert_eq!(requote("100%", Component::Path), "100%25");
486        assert_eq!(requote("%zz%4", Component::Path), "%25zz%254");
487        assert_eq!(requote("a=%3d&b", Component::Query), "a=%3D&b");
488        assert_eq!(requote("a b", Component::Query), "a+b");
489        assert_eq!(requote("%C3%BC", Component::Fragment), "%C3%BC");
490    }
491
492    /// STATEMENT: Unquoting preserves invalid UTF-8 and component-specific protected escapes.
493    ///
494    /// HOW:
495    /// - Decode Unicode and plus signs, checking path, query and safe-path results.
496    /// - Confirm unchanged text is borrowed and malformed escapes remain literal.
497    #[test]
498    fn unquote_rules() {
499        assert!(matches!(unquote("abc", Component::Path), Cow::Borrowed(_)));
500        assert_eq!(unquote("%C3%BC%20x", Component::Path), "ü x");
501        assert_eq!(unquote("a+b", Component::Path), "a+b");
502        assert_eq!(unquote("a+b%2B", Component::QueryPart), "a b+");
503        assert_eq!(unquote("a+b%26c%3D", Component::Query), "a b%26c%3D");
504        assert_eq!(unquote("%FF%C3%BCx%C3", Component::Path), "%FFüx%C3");
505        assert_eq!(unquote("100%", Component::Path), "100%");
506        assert_eq!(unquote_path_safe("a%2Fb%25c%20"), "a%2Fb%25c ");
507        assert_eq!(unquote("ü%20", Component::Fragment), "ü ");
508    }
509}