use crate::error::{Error, Result};
use std::collections::HashMap;
pub fn encode(input: &str) -> String {
percent_encoding::utf8_percent_encode(input, percent_encoding::NON_ALPHANUMERIC).to_string()
}
pub fn encode_with_safe(input: &str, safe_chars: &str) -> String {
let _ = safe_chars; encode(input)
}
pub fn decode(input: &str) -> Result<String> {
percent_encoding::percent_decode_str(input)
.decode_utf8()
.map(|s| s.to_string())
.map_err(|e| Error::template(format!("URL decode error: {}", e)))
}
pub fn btoa(input: &str) -> String {
base64::Engine::encode(&base64::engine::general_purpose::STANDARD, input.as_bytes())
}
pub fn btoa_bytes(input: &[u8]) -> String {
base64::Engine::encode(&base64::engine::general_purpose::STANDARD, input)
}
pub fn atob(input: &str) -> Result<String> {
let bytes = base64::Engine::decode(&base64::engine::general_purpose::STANDARD, input)
.map_err(|e| Error::template(format!("Base64 decode error: {}", e)))?;
String::from_utf8(bytes).map_err(|e| Error::template(format!("UTF-8 decode error: {}", e)))
}
pub fn base64_decode_bytes(input: &str) -> Result<Vec<u8>> {
base64::Engine::decode(&base64::engine::general_purpose::STANDARD, input)
.map_err(|e| Error::template(format!("Base64 decode error: {}", e)))
}
pub fn base64_url_encode(input: &str) -> String {
base64::Engine::encode(
&base64::engine::general_purpose::URL_SAFE_NO_PAD,
input.as_bytes(),
)
}
pub fn base64_url_decode(input: &str) -> Result<String> {
let bytes = base64::Engine::decode(&base64::engine::general_purpose::URL_SAFE_NO_PAD, input)
.map_err(|e| Error::template(format!("Base64 URL decode error: {}", e)))?;
String::from_utf8(bytes).map_err(|e| Error::template(format!("UTF-8 decode error: {}", e)))
}
pub fn html_encode(input: &str) -> String {
input
.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace("\"", """)
.replace("'", "'")
.replace("/", "/")
}
pub fn html_decode(input: &str) -> String {
let mut result = input.to_string();
let entities = [
("&", "&"),
("<", "<"),
(">", ">"),
(""", "\""),
("'", "'"),
("'", "'"),
("/", "/"),
("/", "/"),
(" ", " "),
];
for (entity, character) in &entities {
result = result.replace(entity, character);
}
result
}
pub fn json_encode(input: &str) -> String {
input
.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\n", "\\n")
.replace("\r", "\\r")
.replace("\t", "\\t")
.replace("\u{08}", "\\b")
.replace("\u{0C}", "\\f")
}
pub fn hex_encode(input: &[u8]) -> String {
input.iter().map(|b| format!("{:02x}", b)).collect()
}
pub fn hex_decode(input: &str) -> Result<Vec<u8>> {
if input.len() % 2 != 0 {
return Err(Error::template(
"Hex string must have even length".to_string(),
));
}
let mut result = Vec::new();
for chunk in input.as_bytes().chunks(2) {
let hex_str = std::str::from_utf8(chunk)
.map_err(|e| Error::template(format!("Invalid UTF-8 in hex string: {}", e)))?;
let byte = u8::from_str_radix(hex_str, 16)
.map_err(|e| Error::template(format!("Invalid hex character: {}", e)))?;
result.push(byte);
}
Ok(result)
}
pub fn query_encode(params: &HashMap<&str, &str>) -> String {
params
.iter()
.map(|(key, value)| format!("{}={}", encode(key), encode(value)))
.collect::<Vec<_>>()
.join("&")
}
pub fn query_decode(query: &str) -> Result<HashMap<String, String>> {
let mut params = HashMap::new();
for pair in query.split('&') {
if pair.is_empty() {
continue;
}
let parts: Vec<&str> = pair.splitn(2, '=').collect();
if parts.len() != 2 {
return Err(Error::template(format!(
"Invalid query parameter: {}",
pair
)));
}
let key = decode(parts[0])?;
let value = decode(parts[1])?;
params.insert(key, value);
}
Ok(params)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_url_encoding() {
assert_eq!(encode("hello world"), "hello%20world");
assert_eq!(encode("a+b=c"), "a%2Bb%3Dc");
assert_eq!(encode("café"), "caf%C3%A9");
let decoded = decode("hello%20world").unwrap();
assert_eq!(decoded, "hello world");
let decoded = decode("caf%C3%A9").unwrap();
assert_eq!(decoded, "café");
}
#[test]
fn test_base64_encoding() {
assert_eq!(btoa("hello"), "aGVsbG8=");
assert_eq!(btoa(""), "");
let decoded = atob("aGVsbG8=").unwrap();
assert_eq!(decoded, "hello");
let decoded = atob("").unwrap();
assert_eq!(decoded, "");
}
#[test]
fn test_base64_url_encoding() {
let encoded = btoa("hello world");
let decoded = atob(&encoded).unwrap();
assert_eq!(decoded, "hello world");
}
#[test]
fn test_html_encoding() {
let encoded = html_encode("<script>alert('xss')</script>");
assert_eq!(
encoded,
"<script>alert('xss')</script>"
);
let decoded = html_decode("<div>Hello</div>");
assert_eq!(decoded, "<div>Hello</div>");
}
#[test]
fn test_json_encoding() {
let encoded = json_encode("Hello \"World\"\nNew line");
assert_eq!(encoded, "Hello \\\"World\\\"\\nNew line");
}
#[test]
fn test_hex_encoding() {
let hex = hex_encode(&[255, 0, 128]);
assert_eq!(hex, "ff0080");
let bytes = hex_decode("ff0080").unwrap();
assert_eq!(bytes, vec![255, 0, 128]);
assert!(hex_decode("ff008").is_err()); assert!(hex_decode("gg0080").is_err()); }
#[test]
fn test_query_encoding() {
let mut params = HashMap::new();
params.insert("name", "John Doe");
params.insert("age", "30");
let query = query_encode(¶ms);
assert!(query.contains("name=John%20Doe"));
assert!(query.contains("age=30"));
assert!(query.contains("&"));
let decoded = query_decode(&query).unwrap();
assert_eq!(decoded.get("name").unwrap(), "John Doe");
assert_eq!(decoded.get("age").unwrap(), "30");
}
#[test]
fn test_base64_bytes() {
let bytes = vec![104, 101, 108, 108, 111];
let encoded = btoa_bytes(&bytes);
assert_eq!(encoded, "aGVsbG8=");
let decoded = base64_decode_bytes(&encoded).unwrap();
assert_eq!(decoded, bytes);
}
}