Expand description
§encodeurl — encode a URL to a percent-encoded form, preserving existing escapes
Encodes all the non-URL code points in a string while leaving already-encoded
sequences intact: %20 stays %20, but a stray % (e.g. %foo) becomes %25foo.
This is the “encode a URL you were given, without double-encoding it” operation.
A faithful Rust port of the widely-used encodeurl
npm package (v2), used by Express, send, and serve-static. Safe (never panics),
zero dependencies, and #![no_std] (needs only alloc).
use encodeurl::encode_url;
assert_eq!(encode_url("http://example.com/foo bar"), "http://example.com/foo%20bar");
assert_eq!(encode_url("/path?q=café"), "/path?q=caf%C3%A9");
assert_eq!(encode_url("%20already%20encoded"), "%20already%20encoded"); // kept as-is
assert_eq!(encode_url("100%done"), "100%25done"); // stray % is escapedThe return type is Cow, so an input that needs no changes is returned without any
allocation:
use std::borrow::Cow;
use encodeurl::encode_url;
assert!(matches!(encode_url("/already/clean?x=1"), Cow::Borrowed(_)));§What is and isn’t encoded
The characters left unencoded are the URL-significant set
! # $ % & ' ( ) * + , - . / 0-9 : ; = ? @ A-Z [ \ ] ^ _ a-z | ~. Everything else —
spaces, quotes, angle brackets, braces, backticks, control characters, and all
non-ASCII — is percent-encoded using UTF-8 (uppercase hex), exactly as JavaScript’s
encodeURI would. A % is left
alone only when it begins a valid two-hex-digit escape; otherwise it is encoded to
%25.
Functions§
- encode_
url - Encode a URL to a percent-encoded form, excluding already-encoded sequences.