#![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,
};
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() {
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");
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");
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");
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"
);
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"
);
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"
);
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"
);
}