safehtml 0.1.0

A high-performance, no_std Rust library for Type-Driven Security (XSS and injection prevention).
Documentation
//! HTML identifiers: validated names for `id`, `name`, and similar
//! attributes, mirroring Go safehtml's `Identifier`.

/// Validates an HTML identifier: one ASCII letter followed by any number of
/// ASCII alphanumerics, `-`, or `_`.
///
/// `const`, so it can validate constants at compile time (used by
/// [`IdentifierStr::from_constant`] and
/// [`Identifier::from_constant`](crate::Identifier::from_constant)).
pub const fn is_safe_identifier(s: &str) -> bool {
    let bytes = s.as_bytes();
    let [first, rest @ ..] = bytes else {
        return false;
    };
    if !first.is_ascii_alphabetic() {
        return false;
    }
    let mut i = 0;
    while i < rest.len() {
        let b = rest[i];
        if !(b.is_ascii_alphanumeric() || b == b'-' || b == b'_') {
            return false;
        }
        i += 1;
    }
    true
}

/// A borrowed, validated HTML identifier (`[A-Za-z][A-Za-z0-9_-]*`), safe to
/// interpolate into `id`/`name`/`class` attributes and CSS selectors without
/// escaping. The `no_std` counterpart of
/// [`Identifier`](crate::Identifier), mirroring Go safehtml's `Identifier`.
///
/// Unlike the other borrowed safe types there is no `EMPTY`: an empty
/// identifier is not valid.
///
/// ```rust
/// use safehtml::IdentifierStr;
///
/// // Validated at compile time — an invalid constant fails the build.
/// const MENU: &IdentifierStr = IdentifierStr::from_constant("nav-menu");
/// assert_eq!(MENU.as_str(), "nav-menu");
///
/// // Runtime values are validated, borrowing on success.
/// assert!(IdentifierStr::try_from_str("user_42").is_some());
/// assert!(IdentifierStr::try_from_str("42user").is_none());
/// assert!(IdentifierStr::try_from_str("x onclick=").is_none());
/// ```
#[must_use]
#[repr(transparent)]
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct IdentifierStr(str);

impl IdentifierStr {
    /// Wraps a compile-time constant identifier, validating it in `const`
    /// context.
    ///
    /// # Panics
    ///
    /// Panics at compile time (in `const` context) if `val` is not a valid
    /// identifier.
    pub const fn from_constant(val: &'static str) -> &'static IdentifierStr {
        assert!(
            is_safe_identifier(val),
            "IdentifierStr::from_constant requires [A-Za-z][A-Za-z0-9_-]*"
        );
        // SAFETY: just validated.
        unsafe { IdentifierStr::from_str_unchecked(val) }
    }

    /// Validates `value` at runtime, borrowing it on success. Zero
    /// allocation.
    pub fn try_from_str(value: &str) -> Option<&IdentifierStr> {
        if is_safe_identifier(value) {
            // SAFETY: just validated.
            Some(unsafe { IdentifierStr::from_str_unchecked(value) })
        } else {
            None
        }
    }

    /// Wraps a raw string without validation.
    ///
    /// Part of the `from_string_unchecked` constructor family.
    ///
    /// # Safety
    ///
    /// The caller must ensure `val` matches `[A-Za-z][A-Za-z0-9_-]*`.
    pub const unsafe fn from_str_unchecked(val: &str) -> &IdentifierStr {
        // SAFETY: `IdentifierStr` is `repr(transparent)` over `str`, so the
        // pointer cast preserves layout and provenance.
        unsafe { &*(val as *const str as *const IdentifierStr) }
    }

    /// Returns the underlying string.
    pub const fn as_str(&self) -> &str {
        &self.0
    }
}

impl core::ops::Deref for IdentifierStr {
    type Target = str;
    fn deref(&self) -> &str {
        &self.0
    }
}

impl AsRef<str> for IdentifierStr {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl core::fmt::Display for IdentifierStr {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(&self.0)
    }
}

#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
impl core::borrow::Borrow<IdentifierStr> for crate::types::Identifier {
    fn borrow(&self) -> &IdentifierStr {
        self
    }
}

#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
impl alloc::borrow::ToOwned for IdentifierStr {
    type Owned = crate::types::Identifier;
    fn to_owned(&self) -> crate::types::Identifier {
        // SAFETY: this value already satisfies the identifier contract.
        unsafe {
            crate::types::Identifier::from_string_unchecked(alloc::string::String::from(&self.0))
        }
    }
}

#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
impl From<&IdentifierStr> for crate::types::Identifier {
    fn from(value: &IdentifierStr) -> Self {
        alloc::borrow::ToOwned::to_owned(value)
    }
}

#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
impl PartialEq<IdentifierStr> for crate::types::Identifier {
    fn eq(&self, other: &IdentifierStr) -> bool {
        self.as_str() == other.as_str()
    }
}

#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
impl PartialEq<crate::types::Identifier> for &IdentifierStr {
    fn eq(&self, other: &crate::types::Identifier) -> bool {
        self.as_str() == other.as_str()
    }
}