Expand description
URI percent-encoding functions.
This crate provides functions for percent-encoding strings according to RFC 3986,
with APIs that mirror JavaScript’s encodeURI() and encodeURIComponent() functions.
§Overview
URI encoding (also called percent-encoding) replaces unsafe ASCII characters with
a % followed by two hexadecimal digits representing the character’s byte value.
For example, a space becomes %20.
Different contexts require different encoding rules:
encode_uripreserves URI structure characters, suitable for encoding complete URLsencode_uri_componentencodes more aggressively, suitable for path segments or query valuesencode_query_paramuses+for spaces (application/x-www-form-urlencoded style)
§Examples
use uri_encode::{encode_uri, encode_uri_component, encode_query_param};
// Encoding a complete URL preserves its structure
let url = "https://example.com/path?q=hello world";
assert_eq!(encode_uri(url), "https://example.com/path?q=hello%20world");
// Encoding a component is more aggressive
let component = "hello world&foo=bar";
assert_eq!(encode_uri_component(component), "hello%20world%26foo%3dbar");
// Query parameters use + for spaces
let param = "hello world";
assert_eq!(encode_query_param(param), "hello+world");§Character Sets
The following characters are never encoded by any function (unreserved characters per RFC 3986):
- Alphanumeric:
A-Z,a-z,0-9 - Special:
-,_,.,!,~,*,',(,)
Additionally, encode_uri and encode_query_param preserve these reserved characters:
;,,,/,?,:,@,&,=,+,$,#
§No Unsafe Code
This crate uses #![forbid(unsafe_code)] and has zero dependencies.
Functions§
- encode_
query_ param - Encodes a query parameter name or value using
+for spaces. - encode_
uri - Encodes a complete URI, preserving its structural characters.
- encode_
uri_ component - Encodes a URI component, such as a path segment or query value.