safehtml 0.2.0

A high-performance, no_std Rust library for Type-Driven Security (XSS and injection prevention).
Documentation
//! The [`SafeHtmlPart`] trait: values that can be interpolated into safe
//! HTML by the [`safe_html_cat!`](crate::safe_html_cat) and
//! [`safe_html_write!`](crate::safe_html_write) macros.
//!
//! Safe types ([`SafeHtmlStr`], [`SafeHtml`](crate::SafeHtml),
//! [`Identifier`](crate::Identifier)) pass through verbatim; raw strings and
//! characters are HTML-escaped; numbers and booleans are formatted (their
//! output is HTML-inert). The trait writes to any [`core::fmt::Write`], so
//! it works without `alloc`.

use crate::str_types::SafeHtmlStr;

/// A piece that can be written into a safe HTML output.
///
/// Implementations either emit their value verbatim (already-safe types) or
/// escape it (untrusted text). Used by
/// [`safe_html_cat!`](crate::safe_html_cat) and
/// [`safe_html_write!`](crate::safe_html_write).
pub trait SafeHtmlPart {
    /// Writes the escaped (or already-safe) representation of `self`.
    fn write_to<W: core::fmt::Write + ?Sized>(&self, w: &mut W) -> core::fmt::Result;

    /// A cheap estimate of how many bytes [`write_to`](Self::write_to) will
    /// produce, used to pre-reserve output buffers ([`safe_html_cat!`],
    /// [`safe_html_format!`], [`SafeHtmlBuilder::push`]) so that typical
    /// interpolations allocate exactly once.
    ///
    /// This is only a hint: it may be under (escaping expands text) or
    /// over (numeric widths), and buffers grow as needed regardless. It
    /// must be O(1). The default is `0`.
    ///
    /// [`safe_html_cat!`]: crate::safe_html_cat
    /// [`safe_html_format!`]: crate::safe_html_format
    /// [`SafeHtmlBuilder::push`]: crate::SafeHtmlBuilder::push
    fn size_hint(&self) -> usize {
        0
    }
}

/// Object-safe façade over [`SafeHtmlPart`]: the macros erase heterogeneous
/// parts to `&dyn DynPart` slices so the formatting engine stays a single
/// non-generic function.
#[doc(hidden)]
pub trait DynPart {
    fn dyn_write_to(&self, w: &mut dyn core::fmt::Write) -> core::fmt::Result;
    fn dyn_size_hint(&self) -> usize;
}

impl<T: SafeHtmlPart + ?Sized> DynPart for T {
    fn dyn_write_to(&self, w: &mut dyn core::fmt::Write) -> core::fmt::Result {
        self.write_to(w)
    }
    fn dyn_size_hint(&self) -> usize {
        self.size_hint()
    }
}

/// Backs `safe_html_cat!`: sums the size hints, allocates once, writes all
/// parts.
#[doc(hidden)]
#[cfg(feature = "alloc")]
pub fn cat_from_parts(parts: &[&dyn DynPart]) -> crate::types::SafeHtml {
    let mut cap = 0usize;
    for part in parts {
        cap = cap.saturating_add(part.dyn_size_hint());
    }
    let mut buf = alloc::string::String::with_capacity(cap);
    for part in parts {
        // Writing into a `String` cannot fail.
        let _ = part.dyn_write_to(&mut buf);
    }
    crate::__private::finish_safe_html(buf)
}

/// References to parts are parts: iterator adapters and loops routinely
/// yield `&&str`, `&String`, or `&SafeHtml`, and all interpolate the same
/// as the value itself.
impl<T: SafeHtmlPart + ?Sized> SafeHtmlPart for &T {
    fn write_to<W: core::fmt::Write + ?Sized>(&self, w: &mut W) -> core::fmt::Result {
        (**self).write_to(w)
    }

    fn size_hint(&self) -> usize {
        (**self).size_hint()
    }
}

/// `None` writes nothing; `Some(part)` writes the part. Collapses the
/// `match opt { Some(x) => ..., None => SafeHtml::empty() }` pattern when
/// interpolating optional content.
impl<T: SafeHtmlPart> SafeHtmlPart for Option<T> {
    fn write_to<W: core::fmt::Write + ?Sized>(&self, w: &mut W) -> core::fmt::Result {
        match self {
            Some(part) => part.write_to(w),
            None => Ok(()),
        }
    }

    fn size_hint(&self) -> usize {
        match self {
            Some(part) => part.size_hint(),
            None => 0,
        }
    }
}

/// A [`SafeHtmlPart`] adapter that HTML-escapes the [`Display`](core::fmt::Display)
/// output of a wrapped value on the fly. Created by [`disp`].
pub struct DisplayEscaped<T: core::fmt::Display>(T);

/// Wraps any [`Display`](core::fmt::Display) value as a [`SafeHtmlPart`]
/// whose formatted output is HTML-escaped as it streams — no intermediate
/// `String`.
///
/// This is the interpolation path for foreign types (e.g. a `Money` or
/// `Date` type from another crate) that cannot implement [`SafeHtmlPart`]
/// themselves due to the orphan rule: instead of
/// `my_date.to_string().as_str()` (allocate, then escape-copy), write
/// `disp(&my_date)`.
///
/// ```rust
/// use safehtml::{disp, safe_html_cat};
///
/// struct Tag(&'static str);
/// impl core::fmt::Display for Tag {
///     fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
///         write!(f, "<{}>", self.0)
///     }
/// }
///
/// let html = safe_html_cat!("tag: ", disp(&Tag("b")));
/// assert_eq!(html.as_str(), "tag: &lt;b&gt;");
/// ```
pub fn disp<T: core::fmt::Display>(value: T) -> DisplayEscaped<T> {
    DisplayEscaped(value)
}

impl<T: core::fmt::Display> SafeHtmlPart for DisplayEscaped<T> {
    fn write_to<W: core::fmt::Write + ?Sized>(&self, w: &mut W) -> core::fmt::Result {
        /// Escapes every chunk the wrapped `Display` impl writes. HTML
        /// escaping is per-character (stateless) and `write_str` chunks are
        /// always complete UTF-8, so chunk boundaries cannot split an
        /// escape decision.
        struct EscapingWriter<'a, W: core::fmt::Write + ?Sized>(&'a mut W);

        impl<W: core::fmt::Write + ?Sized> core::fmt::Write for EscapingWriter<'_, W> {
            fn write_str(&mut self, s: &str) -> core::fmt::Result {
                crate::escape_html_and_coerce_to(s, &mut *self.0)
            }
        }

        use core::fmt::Write as _;
        write!(EscapingWriter(w), "{}", self.0)
    }
}

impl SafeHtmlPart for str {
    fn write_to<W: core::fmt::Write + ?Sized>(&self, w: &mut W) -> core::fmt::Result {
        crate::escape_html_and_coerce_to(self, w)
    }

    fn size_hint(&self) -> usize {
        self.len()
    }
}

impl SafeHtmlPart for char {
    fn write_to<W: core::fmt::Write + ?Sized>(&self, w: &mut W) -> core::fmt::Result {
        let mut tmp = [0; 4];
        crate::escape_html_and_coerce_to(self.encode_utf8(&mut tmp), w)
    }

    fn size_hint(&self) -> usize {
        self.len_utf8()
    }
}

impl SafeHtmlPart for SafeHtmlStr {
    fn write_to<W: core::fmt::Write + ?Sized>(&self, w: &mut W) -> core::fmt::Result {
        w.write_str(self.as_str())
    }

    fn size_hint(&self) -> usize {
        self.as_str().len()
    }
}

impl SafeHtmlPart for crate::IdentifierStr {
    fn write_to<W: core::fmt::Write + ?Sized>(&self, w: &mut W) -> core::fmt::Result {
        // Identifier characters ([A-Za-z][A-Za-z0-9_-]*) are HTML-inert.
        w.write_str(self.as_str())
    }

    fn size_hint(&self) -> usize {
        self.as_str().len()
    }
}

macro_rules! impl_safe_html_part_for_display {
    ($($t:ty => $hint:expr),* $(,)?) => {
        $(
            impl SafeHtmlPart for $t {
                fn write_to<W: core::fmt::Write + ?Sized>(&self, w: &mut W) -> core::fmt::Result {
                    write!(w, "{}", self)
                }

                // Maximum `Display` width of the type, so numeric parts
                // never force a buffer regrowth.
                fn size_hint(&self) -> usize {
                    $hint
                }
            }
        )*
    };
}

impl_safe_html_part_for_display!(
    i8 => 4, i16 => 6, i32 => 11, i64 => 20, i128 => 40, isize => 20,
    u8 => 3, u16 => 5, u32 => 10, u64 => 20, u128 => 39, usize => 20,
    f32 => 16, f64 => 24, bool => 5,
);

#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
impl SafeHtmlPart for alloc::string::String {
    fn write_to<W: core::fmt::Write + ?Sized>(&self, w: &mut W) -> core::fmt::Result {
        crate::escape_html_and_coerce_to(self.as_str(), w)
    }

    fn size_hint(&self) -> usize {
        self.len()
    }
}

#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
impl SafeHtmlPart for crate::types::SafeHtml {
    fn write_to<W: core::fmt::Write + ?Sized>(&self, w: &mut W) -> core::fmt::Result {
        w.write_str(self.as_str())
    }

    fn size_hint(&self) -> usize {
        self.as_str().len()
    }
}

#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
impl SafeHtmlPart for crate::types::Identifier {
    fn write_to<W: core::fmt::Write + ?Sized>(&self, w: &mut W) -> core::fmt::Result {
        w.write_str(self.as_str())
    }

    fn size_hint(&self) -> usize {
        self.as_str().len()
    }
}

// URL types interpolate with HTML escaping applied: their contract is URL
// safety, not HTML safety, and a safe URL may still contain `&` or `'`
// which must be escaped in an HTML context. Escaping is semantics-preserving
// for URLs, so the result is a correct, safe href/src value.

impl SafeHtmlPart for crate::SafeUrlStr {
    fn write_to<W: core::fmt::Write + ?Sized>(&self, w: &mut W) -> core::fmt::Result {
        crate::escape_html_and_coerce_to(self.as_str(), w)
    }

    fn size_hint(&self) -> usize {
        self.as_str().len()
    }
}

impl SafeHtmlPart for crate::TrustedResourceUrlStr {
    fn write_to<W: core::fmt::Write + ?Sized>(&self, w: &mut W) -> core::fmt::Result {
        crate::escape_html_and_coerce_to(self.as_str(), w)
    }

    fn size_hint(&self) -> usize {
        self.as_str().len()
    }
}

#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
impl SafeHtmlPart for crate::types::SafeUrl {
    fn write_to<W: core::fmt::Write + ?Sized>(&self, w: &mut W) -> core::fmt::Result {
        crate::escape_html_and_coerce_to(self.as_str(), w)
    }

    fn size_hint(&self) -> usize {
        self.as_str().len()
    }
}

#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
impl SafeHtmlPart for crate::types::TrustedResourceUrl {
    fn write_to<W: core::fmt::Write + ?Sized>(&self, w: &mut W) -> core::fmt::Result {
        crate::escape_html_and_coerce_to(self.as_str(), w)
    }

    fn size_hint(&self) -> usize {
        self.as_str().len()
    }
}