use core::cmp::Ordering;
use core::fmt::{self, Write as _};
use core::marker::PhantomData;
use crate::format::eq_str_display;
use crate::parser::char::{is_ascii_unreserved, is_unreserved, is_utf8_byte_continue};
use crate::parser::str::find_split_hole;
use crate::parser::trusted::take_xdigits2;
use crate::spec::Spec;
pub(crate) fn is_pct_case_normalized<S: Spec>(s: &str) -> bool {
eq_str_display(s, &DisplayPctCaseNormalize::<S>::new(s))
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct DisplayPctCaseNormalize<'a, S> {
segname: &'a str,
_spec: PhantomData<fn() -> S>,
}
impl<'a, S: Spec> DisplayPctCaseNormalize<'a, S> {
#[inline]
#[must_use]
pub(crate) fn new(source: &'a str) -> Self {
Self {
segname: source,
_spec: PhantomData,
}
}
}
impl<S: Spec> fmt::Display for DisplayPctCaseNormalize<'_, S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut rest = self.segname;
'outer_loop: while !rest.is_empty() {
let (prefix, after_percent) = match find_split_hole(rest, b'%') {
Some(v) => v,
None => return f.write_str(rest),
};
f.write_str(prefix)?;
let (first_decoded, after_triplet) = take_xdigits2(after_percent);
rest = after_triplet;
if first_decoded.is_ascii() {
if is_ascii_unreserved(first_decoded) {
f.write_char(char::from(first_decoded))?;
} else {
write!(f, "%{:02X}", first_decoded)?;
}
continue 'outer_loop;
}
let expected_char_len = match (first_decoded & 0xf0).cmp(&0b1110_0000) {
Ordering::Less => 2,
Ordering::Equal => 3,
Ordering::Greater => 4,
};
let c_buf = &mut [first_decoded, 0, 0, 0][..expected_char_len];
let before_pct_seqs = rest;
for (i, buf_dest) in c_buf[1..].iter_mut().enumerate() {
match take_first_char(rest) {
Some(('%', after_percent)) => {
let (byte, after_triplet) = take_xdigits2(after_percent);
if !is_utf8_byte_continue(byte) {
c_buf[..=i]
.iter()
.try_for_each(|b| write!(f, "%{:02X}", b))?;
continue 'outer_loop;
}
*buf_dest = byte;
rest = after_triplet;
}
Some((c, after_percent)) => {
c_buf[..=i]
.iter()
.try_for_each(|b| write!(f, "%{:02X}", b))?;
f.write_char(c)?;
rest = after_percent;
continue 'outer_loop;
}
None => {
c_buf[..=i]
.iter()
.try_for_each(|b| write!(f, "%{:02X}", b))?;
break 'outer_loop;
}
};
}
match core::str::from_utf8(&c_buf[..expected_char_len]) {
Ok(decoded_s) => {
let decoded_c = decoded_s
.chars()
.next()
.expect("[precondition] non-empty string must have characters");
if is_unreserved::<S>(decoded_c) {
f.write_char(decoded_c)?;
} else {
c_buf[0..expected_char_len]
.iter()
.try_for_each(|b| write!(f, "%{:02X}", b))?;
}
}
Err(e) => {
let undecodable_len = e.error_len().unwrap_or(expected_char_len);
debug_assert!(
undecodable_len > 0,
"[validity] decoding cannot fail without undecodable prefix bytes"
);
rest = &before_pct_seqs[(3 * undecodable_len)..];
c_buf[0..undecodable_len]
.iter()
.try_for_each(|b| write!(f, "%{:02X}", b))?;
}
}
}
Ok(())
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct DisplayNormalizedAsciiOnlyHost<'a> {
host_port: &'a str,
}
impl<'a> DisplayNormalizedAsciiOnlyHost<'a> {
#[inline]
#[must_use]
pub(crate) fn new(host_port: &'a str) -> Self {
Self { host_port }
}
}
impl fmt::Display for DisplayNormalizedAsciiOnlyHost<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut rest = self.host_port;
while !rest.is_empty() {
let (prefix, after_percent) = match find_split_hole(rest, b'%') {
Some(v) => v,
None => {
return rest
.chars()
.try_for_each(|c| f.write_char(c.to_ascii_lowercase()));
}
};
prefix
.chars()
.try_for_each(|c| f.write_char(c.to_ascii_lowercase()))?;
let (first_decoded, after_triplet) = take_xdigits2(after_percent);
rest = after_triplet;
assert!(
first_decoded.is_ascii(),
"[consistency] this function requires ASCII-only host as an argument"
);
if is_ascii_unreserved(first_decoded) {
f.write_char(char::from(first_decoded.to_ascii_lowercase()))?;
} else {
write!(f, "%{:02X}", first_decoded)?;
}
}
Ok(())
}
}
#[must_use]
fn take_first_char(s: &str) -> Option<(char, &str)> {
let mut chars = s.chars();
let c = chars.next()?;
let rest = chars.as_str();
Some((c, rest))
}
#[cfg(test)]
#[cfg(feature = "alloc")]
mod tests {
use super::*;
use crate::spec::{IriSpec, UriSpec};
#[test]
fn invalid_utf8() {
assert_eq!(
DisplayPctCaseNormalize::<UriSpec>::new("%80%cc%cc%cc").to_string(),
"%80%CC%CC%CC"
);
assert_eq!(
DisplayPctCaseNormalize::<IriSpec>::new("%80%cc%cc%cc").to_string(),
"%80%CC%CC%CC"
);
}
#[test]
fn iri_unreserved() {
assert_eq!(
DisplayPctCaseNormalize::<UriSpec>::new("%ce%b1").to_string(),
"%CE%B1"
);
assert_eq!(
DisplayPctCaseNormalize::<IriSpec>::new("%ce%b1").to_string(),
"\u{03B1}"
);
}
#[test]
fn iri_middle_decode() {
assert_eq!(
DisplayPctCaseNormalize::<UriSpec>::new("%ce%ce%b1%b1").to_string(),
"%CE%CE%B1%B1"
);
assert_eq!(
DisplayPctCaseNormalize::<IriSpec>::new("%ce%ce%b1%b1").to_string(),
"%CE\u{03B1}%B1"
);
}
#[test]
fn ascii_reserved() {
assert_eq!(
DisplayPctCaseNormalize::<UriSpec>::new("%3f").to_string(),
"%3F"
);
assert_eq!(
DisplayPctCaseNormalize::<IriSpec>::new("%3f").to_string(),
"%3F"
);
}
#[test]
fn ascii_forbidden() {
assert_eq!(
DisplayPctCaseNormalize::<UriSpec>::new("%3c%3e").to_string(),
"%3C%3E"
);
assert_eq!(
DisplayPctCaseNormalize::<IriSpec>::new("%3c%3e").to_string(),
"%3C%3E"
);
}
#[test]
fn ascii_unreserved() {
assert_eq!(
DisplayPctCaseNormalize::<UriSpec>::new("%7ea").to_string(),
"~a"
);
assert_eq!(
DisplayPctCaseNormalize::<IriSpec>::new("%7ea").to_string(),
"~a"
);
}
}