From 18047ea4b87073db62e2dcd62a3dd14462ea522c Mon Sep 17 00:00:00 2001 From: Bakyt Niiazaliev Date: Fri, 13 Jun 2025 17:30:48 +0700 Subject: [PATCH] feat: add encode_percent function for percent-encoding strings --- src/py_module.rs | 5 ++++- src/urlparse.rs | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/py_module.rs b/src/py_module.rs index 0c7dae9f..574cfaef 100644 --- a/src/py_module.rs +++ b/src/py_module.rs @@ -3,5 +3,8 @@ use pyo3::prelude::*; #[pymodule] mod _httpx { #[pymodule_export] - use crate::{urlparse::normalize_path, urls::QueryParams}; + use crate::{ + urlparse::{encode_percent, normalize_path}, + urls::QueryParams, + }; } diff --git a/src/urlparse.rs b/src/urlparse.rs index 6fb0d945..e27fe384 100644 --- a/src/urlparse.rs +++ b/src/urlparse.rs @@ -23,3 +23,21 @@ pub fn normalize_path(path: &str) -> String { normalized_components.join("/") } + +const UNRESERVED_CHARS: &[u8] = + b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"; + +#[pyfunction] +pub fn encode_percent(string: &str, safe: &str) -> String { + let safe = safe.as_bytes(); + string + .bytes() + .map(|b| { + if UNRESERVED_CHARS.contains(&b) || safe.contains(&b) { + (b as char).to_string() + } else { + format!("%{:02X}", b) + } + }) + .collect::() +}