Crate uri_encode

Crate uri_encode 

Source
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_uri preserves URI structure characters, suitable for encoding complete URLs
  • encode_uri_component encodes more aggressively, suitable for path segments or query values
  • encode_query_param uses + 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.