const fn build_allowed_table(extra: &[u8]) -> [bool; 256] {
let mut table = [false; 256];
let mut b = 0usize;
while b < 256 {
let c = b as u8;
table[b] = c.is_ascii_alphanumeric() || matches!(c, b'-' | b'.' | b'_' | b'~');
b += 1;
}
let mut i = 0;
while i < extra.len() {
table[extra[i] as usize] = true;
i += 1;
}
table
}
static URL_COMPONENT_ALLOWED: [bool; 256] = build_allowed_table(&[]);
static CSS_URL_ALLOWED: [bool; 256] = build_allowed_table(b"/:?#[]@!$&*+=%");
const HEX_UPPER: &[u8; 16] = b"0123456789ABCDEF";
#[inline]
fn write_pct_encoded<W: core::fmt::Write>(w: &mut W, b: u8) -> core::fmt::Result {
w.write_char('%')?;
w.write_char(HEX_UPPER[(b >> 4) as usize] as char)?;
w.write_char(HEX_UPPER[(b & 0x0F) as usize] as char)
}
fn percent_encode_with_table<W: core::fmt::Write>(
text: &str,
table: &[bool; 256],
mut w: W,
) -> core::fmt::Result {
let bytes = text.as_bytes();
let mut last = 0;
for (idx, &b) in bytes.iter().enumerate() {
if !table[b as usize] {
if idx > last {
w.write_str(text.get(last..idx).unwrap_or(""))?;
}
write_pct_encoded(&mut w, b)?;
last = idx + 1;
}
}
if last < bytes.len() {
w.write_str(text.get(last..).unwrap_or(""))?;
}
Ok(())
}
pub fn percent_escape_css_url_to<W: core::fmt::Write>(url: &str, w: W) -> core::fmt::Result {
percent_encode_with_table(url, &CSS_URL_ALLOWED, w)
}
pub fn url_encode_component_to<W: core::fmt::Write>(text: &str, w: W) -> core::fmt::Result {
percent_encode_with_table(text, &URL_COMPONENT_ALLOWED, w)
}
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn url_encode_component(text: &str) -> alloc::string::String {
let mut s = alloc::string::String::with_capacity(text.len());
let _ = url_encode_component_to(text, &mut s);
s
}
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn percent_escape_css_url(url: &str) -> alloc::string::String {
let mut s = alloc::string::String::with_capacity(url.len());
let _ = percent_escape_css_url_to(url, &mut s);
s
}
#[derive(Clone, Copy)]
pub struct EncodeSet {
table: [bool; 256],
}
impl EncodeSet {
pub const UNRESERVED: EncodeSet = EncodeSet {
table: build_allowed_table(&[]),
};
pub const CSS_URL: EncodeSet = EncodeSet {
table: build_allowed_table(b"/:?#[]@!$&*+=%"),
};
#[must_use]
pub const fn allow(mut self, b: u8) -> EncodeSet {
assert!(b.is_ascii(), "EncodeSet may only allow ASCII bytes");
self.table[b as usize] = true;
self
}
#[must_use]
pub const fn allow_all(mut self, bytes: &[u8]) -> EncodeSet {
let mut i = 0;
while i < bytes.len() {
assert!(bytes[i].is_ascii(), "EncodeSet may only allow ASCII bytes");
self.table[bytes[i] as usize] = true;
i += 1;
}
self
}
#[must_use]
pub const fn disallow(mut self, b: u8) -> EncodeSet {
self.table[b as usize] = false;
self
}
pub const fn is_allowed(&self, b: u8) -> bool {
self.table[b as usize]
}
}
pub fn percent_encode_to<W: core::fmt::Write>(
text: &str,
set: &EncodeSet,
w: W,
) -> core::fmt::Result {
percent_encode_with_table(text, &set.table, w)
}
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn percent_encode(text: &str, set: &EncodeSet) -> alloc::string::String {
let mut s = alloc::string::String::with_capacity(text.len());
let _ = percent_encode_to(text, set, &mut s);
s
}
#[derive(Debug, Clone)]
pub struct PercentDecode<'a> {
bytes: &'a [u8],
}
pub fn percent_decode(input: &str) -> PercentDecode<'_> {
PercentDecode {
bytes: input.as_bytes(),
}
}
#[inline]
const fn hex_value(b: u8) -> Option<u8> {
match b {
b'0'..=b'9' => Some(b - b'0'),
b'a'..=b'f' => Some(b - b'a' + 10),
b'A'..=b'F' => Some(b - b'A' + 10),
_ => None,
}
}
impl Iterator for PercentDecode<'_> {
type Item = u8;
fn next(&mut self) -> Option<u8> {
let (&first, rest) = self.bytes.split_first()?;
if first == b'%'
&& let (Some(&h), Some(&l)) = (rest.first(), rest.get(1))
&& let (Some(hi), Some(lo)) = (hex_value(h), hex_value(l))
{
self.bytes = rest.get(2..).unwrap_or(&[]);
return Some(hi << 4 | lo);
}
self.bytes = rest;
Some(first)
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.bytes.len().div_ceil(3), Some(self.bytes.len()))
}
}
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn percent_decode_bytes(input: &str) -> alloc::vec::Vec<u8> {
percent_decode(input).collect()
}
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn percent_decode_utf8_lossy(input: &str) -> alloc::string::String {
let bytes = percent_decode_bytes(input);
match alloc::string::String::from_utf8_lossy(&bytes) {
alloc::borrow::Cow::Borrowed(_) => {
alloc::string::String::from_utf8(bytes).unwrap_or_default()
}
alloc::borrow::Cow::Owned(s) => s,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn allowed_tables_rebuild_and_match_spec() {
assert_eq!(build_allowed_table(&[]), URL_COMPONENT_ALLOWED);
assert_eq!(build_allowed_table(b"/:?#[]@!$&*+=%"), CSS_URL_ALLOWED);
for b in 0..=0xFFu8 {
let unreserved = b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~');
assert_eq!(
URL_COMPONENT_ALLOWED[b as usize], unreserved,
"url-component table disagrees at {b:#04x}"
);
let css_extra = b"/:?#[]@!$&*+=%".contains(&b);
assert_eq!(
CSS_URL_ALLOWED[b as usize],
unreserved || css_extra,
"css-url table disagrees at {b:#04x}"
);
}
}
}