| @@ -143,6 +143,31 @@ pub fn chars(s: &str) -> Vec<&str> { |
| 143 | 143 | .collect() |
| 144 | 144 | } |
| 145 | 145 | |
| 146 | +/// The characters of `s` from `start` up to `end` (excluded); both are |
| 147 | +/// clamped to `0..=s.chars().count()`, and the slice is empty when |
| 148 | +/// `end <= start`. One pass over the bytes, stopping at `end`. |
| 149 | +pub fn char_slice(s: &str, start: i64, end: i64) -> &str { |
| 150 | + if end <= start { |
| 151 | + return ""; |
| 152 | + } |
| 153 | + let (start, end) = (start.max(0) as usize, end.max(0) as usize); |
| 154 | + // `from` stays `usize::MAX` when `start` is past the last character. |
| 155 | + let (mut from, mut to) = (usize::MAX, s.len()); |
| 156 | + for (i, (byte, _)) in s.char_indices().enumerate() { |
| 157 | + if i == start { |
| 158 | + from = byte; |
| 159 | + } |
| 160 | + if i == end { |
| 161 | + to = byte; |
| 162 | + break; |
| 163 | + } |
| 164 | + } |
| 165 | + if from == usize::MAX || from >= to { |
| 166 | + return ""; |
| 167 | + } |
| 168 | + &s[from..to] |
| 169 | +} |
| 170 | + |
| 146 | 171 | /// A float read from text (the platform's `f64` parser), or why not. |
| 147 | 172 | pub fn parse_float(s: &str) -> Result<f64, String> { |
| 148 | 173 | s.parse::<f64>().map_err(|_| format!("not a float: {s:?}")) |
| @@ -337,6 +362,56 @@ pub fn url_decode(s: &str) -> String { |
| 337 | 362 | String::from_utf8_lossy(&buf).into_owned() |
| 338 | 363 | } |
| 339 | 364 | |
| 365 | +/// Whether `b` is unreserved (RFC 3986): the one set of bytes |
| 366 | +/// `url_encode` leaves as they are. |
| 367 | +fn url_unreserved(b: u8) -> bool { |
| 368 | + matches!(b, b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~') |
| 369 | +} |
| 370 | + |
| 371 | +/// Whether `url_encode` changes `s`: it holds a byte that is not |
| 372 | +/// unreserved. |
| 373 | +pub fn url_needs_encode(s: &str) -> bool { |
| 374 | + s.bytes().any(|b| !url_unreserved(b)) |
| 375 | +} |
| 376 | + |
| 377 | +/// Percent-encode `s` into `out`, which has room for `3 * s.len()` bytes |
| 378 | +/// (every byte may become `%XX`); the encoded length is returned. |
| 379 | +pub fn url_encode_into(s: &str, out: &mut [u8]) -> usize { |
| 380 | + const HEX: &[u8; 16] = b"0123456789ABCDEF"; |
| 381 | + debug_assert!(out.len() >= 3 * s.len()); |
| 382 | + let mut n = 0; |
| 383 | + for &b in s.as_bytes() { |
| 384 | + if url_unreserved(b) { |
| 385 | + out[n] = b; |
| 386 | + n += 1; |
| 387 | + } else { |
| 388 | + out[n..n + 3].copy_from_slice(&[ |
| 389 | + b'%', |
| 390 | + HEX[usize::from(b >> 4)], |
| 391 | + HEX[usize::from(b & 15)], |
| 392 | + ]); |
| 393 | + n += 3; |
| 394 | + } |
| 395 | + } |
| 396 | + n |
| 397 | +} |
| 398 | + |
| 399 | +/// Percent-encode `s` for a URL path or query (RFC 3986): every byte |
| 400 | +/// outside the unreserved set becomes `%XX` (uppercase hex); a space is |
| 401 | +/// `%20`, not `+` (`url_decode` maps both back to a space, and a `+` |
| 402 | +/// decodes as a space only in a query or form). `url_decode` inverts it: |
| 403 | +/// `url_decode(url_encode(s)) == s`. |
| 404 | +pub fn url_encode(s: &str) -> String { |
| 405 | + if !url_needs_encode(s) { |
| 406 | + return s.to_owned(); |
| 407 | + } |
| 408 | + let mut buf = vec![0; 3 * s.len()]; |
| 409 | + let n = url_encode_into(s, &mut buf); |
| 410 | + buf.truncate(n); |
| 411 | + // Unreserved bytes and `%XX` triplets are all ASCII. |
| 412 | + String::from_utf8(buf).expect("louise: percent-encoded bytes are ASCII") |
| 413 | +} |
| 414 | + |
| 340 | 415 | /// The fields of an `application/x-www-form-urlencoded` body or query |
| 341 | 416 | /// string (`std/http.form`): pairs split on `&`, each on its first `=`, |
| 342 | 417 | /// both sides percent-decoded with `+` a space (as [`url_decode`], so a |
| @@ -530,6 +605,66 @@ mod tests { |
| 530 | 605 | assert_eq!(url_decode("é"), "é"); |
| 531 | 606 | } |
| 532 | 607 | |
| 608 | + #[test] |
| 609 | + fn url_encoding_escapes_everything_but_the_unreserved() { |
| 610 | + // Clean inputs (only unreserved bytes) come back unchanged. |
| 611 | + assert!(!url_needs_encode("")); |
| 612 | + assert!(!url_needs_encode("plain-text_1.0~x")); |
| 613 | + assert_eq!(url_encode(""), ""); |
| 614 | + assert_eq!(url_encode("abcXYZ019-_.~"), "abcXYZ019-_.~"); |
| 615 | + // Everything else becomes `%XX`, uppercase; a space is `%20`. |
| 616 | + assert!(url_needs_encode("a b")); |
| 617 | + assert_eq!(url_encode("a b"), "a%20b"); |
| 618 | + assert_eq!(url_encode("=&?/#%+"), "%3D%26%3F%2F%23%25%2B"); |
| 619 | + assert_eq!(url_encode("\0"), "%00"); |
| 620 | + // Unicode is UTF-8, each byte escaped. |
| 621 | + assert_eq!(url_encode("é"), "%C3%A9"); |
| 622 | + assert_eq!(url_encode("☃"), "%E2%98%83"); |
| 623 | + // Encoding is not idempotent: `%` becomes `%25`. |
| 624 | + assert_eq!(url_encode("%41"), "%2541"); |
| 625 | + assert_eq!(url_encode("100%"), "100%25"); |
| 626 | + // `url_decode` inverts it, arbitrary unicode included. |
| 627 | + for s in [ |
| 628 | + "", |
| 629 | + "a", |
| 630 | + "A Z", |
| 631 | + "a+b", |
| 632 | + "100%", |
| 633 | + "%41", |
| 634 | + "=", |
| 635 | + "&", |
| 636 | + "x=y", |
| 637 | + "é", |
| 638 | + "☃", |
| 639 | + "a/b?c", |
| 640 | + " ", |
| 641 | + "+", |
| 642 | + "%", |
| 643 | + "\t", |
| 644 | + "ünïcodé", |
| 645 | + ] { |
| 646 | + assert_eq!(url_decode(&url_encode(s)), s, "round-trip {s:?}"); |
| 647 | + } |
| 648 | + } |
| 649 | + |
| 650 | + #[test] |
| 651 | + fn char_slices_clamp_to_the_character_bounds() { |
| 652 | + assert_eq!(char_slice("hello", 1, 4), "ell"); |
| 653 | + assert_eq!(char_slice("hello", 0, 5), "hello"); |
| 654 | + // Multibyte characters are indexed, not their bytes. |
| 655 | + assert_eq!(char_slice("héllo", 1, 3), "él"); |
| 656 | + assert_eq!(char_slice("日本語", 1, 2), "本"); |
| 657 | + // Both bounds clamp to `0..=length`; `end <= start` is empty. |
| 658 | + assert_eq!(char_slice("héllo", 0, i64::MAX), "héllo"); |
| 659 | + assert_eq!(char_slice("héllo", -3, 2), "hé"); |
| 660 | + assert_eq!(char_slice("héllo", 3, 100), "lo"); |
| 661 | + assert_eq!(char_slice("héllo", 5, 5), ""); |
| 662 | + assert_eq!(char_slice("héllo", 4, 2), ""); |
| 663 | + assert_eq!(char_slice("héllo", 7, 9), ""); |
| 664 | + assert_eq!(char_slice("héllo", -2, -1), ""); |
| 665 | + assert_eq!(char_slice("", 0, 1), ""); |
| 666 | + } |
| 667 | + |
| 533 | 668 | /// `query_params` against what `std/http.form` did before it: split |
| 534 | 669 | /// on `&`, drop empty pairs, split each on `=`, decode both sides |
| 535 | 670 | /// (the value re-joined on `=`). |