1use std::borrow::Cow;
23
24use crate::chars::{ALLOWED, HEX_UPPER, NONE, QS, Set, UNRESERVED, pct_at, push_pct};
25
26#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
29pub enum Component {
30 UserInfo,
32 Path,
34 Query,
36 QueryPart,
38 Fragment,
40 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};
62static 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
96pub fn quote(src: &str, component: Component) -> Cow<'_, str> {
98 quote_with::<false>(src, component)
99}
100
101pub fn requote(src: &str, component: Component) -> Cow<'_, str> {
103 quote_with::<true>(src, component)
104}
105
106pub 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 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
199pub(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 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 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 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#[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
271pub(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 #[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 #[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 #[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 #[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 #[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 #[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 #[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}