use std::borrow::Cow;
use memchr::{memchr, memchr2};
use thiserror::Error;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Plus {
Space,
Literal,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BadEscape {
Error,
Keep,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Utf8 {
Error,
Replace,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Mode {
pub plus: Plus,
pub bad_escape: BadEscape,
pub utf8: Utf8,
}
impl Mode {
pub const FORM: Self = Self {
plus: Plus::Space,
bad_escape: BadEscape::Error,
utf8: Utf8::Replace,
};
pub const URI: Self = Self {
plus: Plus::Literal,
bad_escape: BadEscape::Error,
utf8: Utf8::Replace,
};
pub const LENIENT: Self = Self {
plus: Plus::Literal,
bad_escape: BadEscape::Keep,
utf8: Utf8::Replace,
};
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum PercentError {
#[error("a % at byte {at} has no two hex digits after it")]
BadEscape {
at: usize,
},
#[error("the decoded text is not UTF-8 from byte {valid_up_to}")]
Utf8 {
valid_up_to: usize,
},
}
pub fn decode(text: &str, mode: Mode) -> Result<Cow<'_, str>, PercentError> {
let bytes = text.as_bytes();
let mut out: Vec<u8> = Vec::new();
let mut copied = 0;
let mut at = 0;
while at < bytes.len() {
let rest = &bytes[at..];
let found = match mode.plus {
Plus::Space => memchr2(b'%', b'+', rest),
Plus::Literal => memchr(b'%', rest),
};
let Some(offset) = found else { break };
let i = at + offset;
if bytes[i] == b'+' {
if out.capacity() == 0 {
out.reserve(bytes.len());
}
out.extend_from_slice(&bytes[copied..i]);
out.push(b' ');
copied = i + 1;
at = i + 1;
continue;
}
let high = bytes.get(i + 1).copied().and_then(hex);
let low = bytes.get(i + 2).copied().and_then(hex);
match (high, low) {
(Some(high), Some(low)) => {
if out.capacity() == 0 {
out.reserve(bytes.len());
}
out.extend_from_slice(&bytes[copied..i]);
out.push(high << 4 | low);
copied = i + 3;
at = i + 3;
}
_ => match mode.bad_escape {
BadEscape::Error => return Err(PercentError::BadEscape { at: i }),
BadEscape::Keep => at = i + 1,
},
}
}
if copied == 0 {
return Ok(Cow::Borrowed(text));
}
out.extend_from_slice(&bytes[copied..]);
match String::from_utf8(out) {
Ok(decoded) => Ok(Cow::Owned(decoded)),
Err(bad) => match mode.utf8 {
Utf8::Error => Err(PercentError::Utf8 {
valid_up_to: bad.utf8_error().valid_up_to(),
}),
Utf8::Replace => Ok(Cow::Owned(
String::from_utf8_lossy(bad.as_bytes()).into_owned(),
)),
},
}
}
const fn hex(byte: u8) -> Option<u8> {
match byte {
b'0'..=b'9' => Some(byte - b'0'),
b'a'..=b'f' => Some(byte - b'a' + 10),
b'A'..=b'F' => Some(byte - b'A' + 10),
_ => None,
}
}