use std::borrow::Cow;
#[must_use]
pub fn percent_encode(input: &str) -> Cow<'_, str> {
if input.bytes().all(is_unreserved) {
return Cow::Borrowed(input);
}
let mut out = String::with_capacity(input.len() + 8);
for byte in input.bytes() {
if is_unreserved(byte) {
out.push(char::from(byte));
} else {
out.push('%');
out.push(char::from(HEX[usize::from(byte >> 4)]));
out.push(char::from(HEX[usize::from(byte & 0x0f)]));
}
}
Cow::Owned(out)
}
const HEX: &[u8; 16] = b"0123456789ABCDEF";
fn is_unreserved(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~')
}
#[cfg(test)]
#[path = "percent_encode.test.rs"]
mod tests;
#[cfg(test)]
#[path = "percent_encode.spec.rs"]
mod spec;