grippo 0.2.4

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/uri/percent.rs
// Purpose:   Percent-decoding with plus, bad-escape and UTF-8 modes
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Percent-decoding in one pass, with a mode for each reading in use.
//!
//! `%XX` takes exactly two hex digits. Text with nothing to decode comes
//! back borrowed.

use std::borrow::Cow;

use memchr::{memchr, memchr2};
use thiserror::Error;

/// What `+` decodes to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Plus {
    /// A space, as in a form body or `java.net.URLDecoder`.
    Space,
    /// Itself, as in RFC 3986.
    Literal,
}

/// What a `%` without two hex digits after it does.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BadEscape {
    /// The decode fails with [`PercentError::BadEscape`].
    Error,
    /// The `%` stays as written and decoding goes on after it.
    Keep,
}

/// What decoded bytes that aren't UTF-8 do.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Utf8 {
    /// The decode fails with [`PercentError::Utf8`].
    Error,
    /// Each bad sequence becomes U+FFFD.
    Replace,
}

/// How [`decode`] reads `+`, a bad escape and bytes that aren't UTF-8.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Mode {
    /// What `+` decodes to.
    pub plus: Plus,
    /// What a `%` without two hex digits does.
    pub bad_escape: BadEscape,
    /// What decoded bytes that aren't UTF-8 do.
    pub utf8: Utf8,
}

impl Mode {
    /// `java.net.URLDecoder` with UTF-8 on JDK 25: `+` is a space, a bad
    /// escape fails and bad bytes become U+FFFD.
    pub const FORM: Self = Self {
        plus: Plus::Space,
        bad_escape: BadEscape::Error,
        utf8: Utf8::Replace,
    };

    /// `java.net.URI`'s decoding getters: `+` stays, a bad escape fails and
    /// bad bytes become U+FFFD.
    pub const URI: Self = Self {
        plus: Plus::Literal,
        bad_escape: BadEscape::Error,
        utf8: Utf8::Replace,
    };

    /// Never fails: `+` stays, a bad escape stays as written and bad bytes
    /// become U+FFFD.
    pub const LENIENT: Self = Self {
        plus: Plus::Literal,
        bad_escape: BadEscape::Keep,
        utf8: Utf8::Replace,
    };
}

/// Why [`decode`] failed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum PercentError {
    /// A `%` at byte `at` of the text has fewer than two hex digits after it.
    #[error("a % at byte {at} has no two hex digits after it")]
    BadEscape {
        /// The byte offset of the `%` in the text.
        at: usize,
    },
    /// The decoded bytes stop being UTF-8 at byte `valid_up_to` of the decoded text.
    #[error("the decoded text is not UTF-8 from byte {valid_up_to}")]
    Utf8 {
        /// How many decoded bytes are UTF-8 before the first bad one.
        valid_up_to: usize,
    },
}

/// `text` with its escapes decoded, read by `mode`.
///
/// Borrows when nothing changes: no `%` with two hex digits, and no `+`
/// under [`Plus::Space`].
///
/// # Errors
///
/// [`PercentError::BadEscape`] under [`BadEscape::Error`], and
/// [`PercentError::Utf8`] under [`Utf8::Error`].
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(),
            )),
        },
    }
}

/// The value of one ASCII hex digit.
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,
    }
}