safehtml 0.2.0

A high-performance, no_std Rust library for Type-Driven Security (XSS and injection prevention).
Documentation
//! [`SafeHtmlBuilder`]: incremental safe-HTML construction into a single
//! growable buffer. Requires the `alloc` feature.

use crate::SafeHtmlPart;
use crate::types::SafeHtml;
use alloc::string::String;

/// An incremental builder for [`SafeHtml`], holding one growable buffer for
/// an entire render.
///
/// Every input is routed through [`SafeHtmlPart`] (safe types verbatim,
/// strings and characters escaped, numbers formatted), so the buffer
/// satisfies the `SafeHtml` contract at all times and [`finish`](Self::finish)
/// wraps it without copying. This is the cheap alternative to concatenating
/// temporaries: `b += safe_html_cat!(...)` allocates and drops a `String`
/// per iteration, while `builder.push(...)` (or
/// `safe_html_format!(builder, ...)`) appends in place.
///
/// ```rust
/// use safehtml::{SafeHtml, SafeHtmlBuilder, safe_html_format};
///
/// let mut b = SafeHtmlBuilder::with_capacity(256);
/// b.push(SafeHtml::from_constant("<ul>"));
/// for name in ["a<b", "c&d"] {
///     safe_html_format!(b, "<li>{name}</li>", name = name);
/// }
/// b.push(SafeHtml::from_constant("</ul>"));
/// assert_eq!(
///     b.finish().as_str(),
///     "<ul><li>a&lt;b</li><li>c&amp;d</li></ul>"
/// );
/// ```
#[derive(Debug, Clone, Default)]
pub struct SafeHtmlBuilder {
    // Invariant: always satisfies the `SafeHtml` contract. All public
    // mutation goes through `SafeHtmlPart`; `__buf` is reserved for the
    // crate macros, which uphold the same invariant.
    html: String,
}

impl SafeHtmlBuilder {
    /// Creates an empty builder.
    pub const fn new() -> Self {
        SafeHtmlBuilder {
            html: String::new(),
        }
    }

    /// Creates an empty builder with at least `capacity` bytes
    /// pre-allocated. Renderers that know their approximate output size
    /// avoid reallocation entirely.
    pub fn with_capacity(capacity: usize) -> Self {
        SafeHtmlBuilder {
            html: String::with_capacity(capacity),
        }
    }

    /// Reserves capacity for at least `additional` more bytes.
    pub fn reserve(&mut self, additional: usize) {
        self.html.reserve(additional);
    }

    /// Appends a part: safe types verbatim, strings and characters
    /// HTML-escaped, numbers and booleans formatted. Returns `&mut self`
    /// for chaining.
    pub fn push(&mut self, part: impl SafeHtmlPart) -> &mut Self {
        self.html.reserve(part.size_hint());
        // Writing into a `String` cannot fail.
        let _ = part.write_to(&mut self.html);
        self
    }

    /// Number of bytes accumulated so far.
    pub fn len(&self) -> usize {
        self.html.len()
    }

    /// True if nothing has been appended yet.
    pub fn is_empty(&self) -> bool {
        self.html.is_empty()
    }

    /// The accumulated output so far.
    pub fn as_str(&self) -> &str {
        &self.html
    }

    /// Consumes the builder, wrapping the buffer as [`SafeHtml`] without
    /// copying.
    pub fn finish(self) -> SafeHtml {
        // SAFETY: the builder invariant guarantees the buffer satisfies the
        // `SafeHtml` contract.
        unsafe { SafeHtml::from_string_unchecked(self.html) }
    }

    /// Macro plumbing for `safe_html_format!(builder, ...)` (named form).
    /// Not public API: `fmt` is trusted as literal markup, which only the
    /// macro guarantees.
    #[doc(hidden)]
    pub fn __format_named(&mut self, fmt: &str, parts: &[(&str, &dyn crate::DynPart)]) {
        crate::format::format_named_into(&mut self.html, fmt, parts);
    }

    /// Positional-form sibling of [`__format_named`](Self::__format_named).
    #[doc(hidden)]
    pub fn __format_positional(&mut self, fmt: &str, parts: &[&dyn crate::DynPart]) {
        crate::format::format_positional_into(&mut self.html, fmt, parts);
    }
}

/// Continue building from existing safe HTML (reuses its buffer).
impl From<SafeHtml> for SafeHtmlBuilder {
    fn from(value: SafeHtml) -> Self {
        SafeHtmlBuilder {
            html: value.into_string(),
        }
    }
}

impl From<SafeHtmlBuilder> for SafeHtml {
    fn from(value: SafeHtmlBuilder) -> Self {
        value.finish()
    }
}

/// Appends every item as a part, e.g.
/// `builder.extend(rows.iter().map(render_row))`.
impl<P: SafeHtmlPart> Extend<P> for SafeHtmlBuilder {
    fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
        for part in iter {
            self.push(part);
        }
    }
}