safehtml 0.2.0

A high-performance, no_std Rust library for Type-Driven Security (XSS and injection prevention).
Documentation
//! Allocation-count regression tests: the alloc-path constructors promise
//! "one heap operation per produced value" (and zero for constants /
//! streaming), enforced here with a counting global allocator.
//!
//! Everything lives in a single `#[test]` because the test harness runs
//! tests on multiple threads and the counter is process-global; one test
//! means only our own allocations are counted.
#![cfg(feature = "alloc")]

use std::alloc::{GlobalAlloc, Layout, System};
use std::sync::atomic::{AtomicUsize, Ordering};

use safehtml::{
    SafeHtml, SafeHtmlBuilder, SafeUrl, SliceWriter, safe_html_cat, safe_html_format,
    safe_html_format_to,
};

/// Counts every allocation and reallocation (frees are not counted: the
/// interesting metric is how often we go to the heap, not peak usage).
struct CountingAlloc;

static HEAP_OPS: AtomicUsize = AtomicUsize::new(0);

unsafe impl GlobalAlloc for CountingAlloc {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        HEAP_OPS.fetch_add(1, Ordering::Relaxed);
        unsafe { System.alloc(layout) }
    }
    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        unsafe { System.dealloc(ptr, layout) }
    }
    unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
        HEAP_OPS.fetch_add(1, Ordering::Relaxed);
        unsafe { System.realloc(ptr, layout, new_size) }
    }
}

#[global_allocator]
static ALLOC: CountingAlloc = CountingAlloc;

fn heap_ops<T>(f: impl FnOnce() -> T) -> (usize, T) {
    let before = HEAP_OPS.load(Ordering::Relaxed);
    let value = f();
    (HEAP_OPS.load(Ordering::Relaxed) - before, value)
}

#[test]
fn allocation_counts() {
    // safe_html_cat!: size hints cover strings, safe types, and numbers,
    // so mixed concatenation is a single allocation.
    let (ops, html) =
        heap_ops(|| safe_html_cat!("hello ", SafeHtml::from_constant("<b>world</b>"), ' ', 42));
    assert_eq!(html.as_str(), "hello <b>world</b> 42");
    assert_eq!(ops, 1, "safe_html_cat! should allocate exactly once");

    // safe_html_format! (named): fmt.len() + hints, one allocation.
    // (Values that need escaping can still add one growth; these don't.)
    let (ops, html) = heap_ops(|| {
        safe_html_format!(
            r#"<input value="{v}" title="{t}">"#,
            v = "2026-07-18",
            t = "plain title"
        )
    });
    assert_eq!(
        html.as_str(),
        r#"<input value="2026-07-18" title="plain title">"#
    );
    assert_eq!(ops, 1, "safe_html_format! should allocate exactly once");

    // A brace-free literal compiles to a borrowed constant: zero.
    let (ops, html) = heap_ops(|| safe_html_format!("<hr class=x>"));
    assert_eq!(html.as_str(), "<hr class=x>");
    assert_eq!(ops, 0, "brace-free safe_html_format! should not allocate");

    // Streaming into a fixed buffer: zero.
    let mut buf = [0u8; 64];
    let (ops, ()) = heap_ops(|| {
        let mut w = SliceWriter::new(&mut buf);
        safe_html_format_to!(w, "<b>{v}</b>", v = "5 < 6").unwrap();
    });
    assert_eq!(
        ops, 0,
        "safe_html_format_to! into SliceWriter should not allocate"
    );

    // Builder with adequate capacity: the single with_capacity allocation
    // serves the whole render; finish() moves without copying.
    let (ops, html) = heap_ops(|| {
        let mut b = SafeHtmlBuilder::with_capacity(256);
        b.push(SafeHtml::from_constant("<ul>"));
        for i in 0..5 {
            safe_html_format!(b, "<li>row {i}</li>", i = i);
        }
        b.push(SafeHtml::from_constant("</ul>"));
        b.finish()
    });
    assert!(html.as_str().starts_with("<ul><li>row 0</li>"));
    assert_eq!(
        ops, 1,
        "a pre-sized builder render should allocate exactly once"
    );

    // += on a borrowed constant: promotion reserves for both sides, one
    // allocation instead of the former clone-then-regrow pair.
    let (ops, html) = heap_ops(|| {
        let mut h = SafeHtml::from_constant("<b>bold</b>");
        h += &SafeHtml::from_constant("<i>italic</i>");
        h
    });
    assert_eq!(html.as_str(), "<b>bold</b><i>italic</i>");
    assert_eq!(
        ops, 1,
        "AddAssign onto a borrowed constant should allocate once"
    );

    // push_query_param without a fragment appends in place: one reserve,
    // no temporary. (One op for sanitize's String::from, one for reserve.)
    let (ops, url) = heap_ops(|| {
        let mut url = SafeUrl::sanitize("https://example.com/search");
        url.push_query_param("q", "rust");
        url
    });
    assert_eq!(url.as_str(), "https://example.com/search?q=rust");
    assert_eq!(
        ops, 2,
        "sanitize + fragment-free push_query_param should be two heap ops total"
    );
}