headless_lms_utils/
url_encoding.rs

1use bytes::Bytes;
2use percent_encoding::{NON_ALPHANUMERIC, percent_decode_str, utf8_percent_encode};
3
4/// URL-encodes a string value for use in HTTP headers or other contexts requiring ASCII-compatibility.
5/// Percent-encodes all non-alphanumeric characters (including spaces, punctuation, ASCII special
6/// characters, non-ASCII characters, and control characters) to preserve the original information
7/// while making the value ASCII-safe for use in HTTP headers or other contexts requiring ASCII-compatibility.
8pub fn url_encode(value: &str) -> Bytes {
9    utf8_percent_encode(value, NON_ALPHANUMERIC)
10        .to_string()
11        .into()
12}
13
14/// URL-decodes a percent-encoded string back to its original UTF-8 representation.
15/// Decodes percent-encoded values back to their original UTF-8 strings.
16pub fn url_decode(encoded: &str) -> anyhow::Result<String> {
17    percent_decode_str(encoded)
18        .decode_utf8()
19        .map_err(|e| anyhow::anyhow!("Failed to decode URL-encoded value: {}", e))
20        .map(|s| s.to_string())
21}