safehtml 0.2.0

A high-performance, no_std Rust library for Type-Driven Security (XSS and injection prevention).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! Tests for `safe_html_format!`/`safe_html_format_to!`, `SafeHtmlBuilder`,
//! `disp`, and the `Option<T: SafeHtmlPart>` impl.
//!
//! This file deliberately sets `#![forbid(unsafe_code)]`: the macros must
//! be usable from consumer crates that forbid `unsafe` (the expansion's
//! `unsafe` lives inside the `safehtml` crate).
#![forbid(unsafe_code)]
#![cfg(feature = "alloc")]

use safehtml::{
    Identifier, SafeHtml, SafeHtmlBuilder, SafeHtmlStr, SliceWriter, disp, safe_html_cat,
    safe_html_format, safe_html_format_to, safe_html_write,
};

// --- safe_html_cat! / safe_html_write! under forbid(unsafe_code) ---

#[test]
fn cat_works_under_forbid_unsafe_code() {
    let html = safe_html_cat!(SafeHtml::from_constant("<b>"), "a & b", 42);
    assert_eq!(html.as_str(), "<b>a &amp; b42");
}

// --- safe_html_format!: named form ---

#[test]
fn format_named_escapes_arguments() {
    let date = "2026-07-18";
    let title = "Bob & <Alice> \"quoted\"";
    let html = safe_html_format!(
        r#"<input name="date" value="{date}" title="{t}">"#,
        date = date,
        t = title,
    );
    assert_eq!(
        html.as_str(),
        r#"<input name="date" value="2026-07-18" title="Bob &amp; &lt;Alice&gt; &#34;quoted&#34;">"#
    );
}

#[test]
fn format_named_safe_types_pass_verbatim() {
    let inner = safe_html_cat!("x < y");
    let id = Identifier::from_constant("row-1");
    let html = safe_html_format!("<td id=\"{id}\">{body}</td>", id = id, body = inner);
    assert_eq!(html.as_str(), "<td id=\"row-1\">x &lt; y</td>");
}

#[test]
fn format_named_numbers_and_bools() {
    let html = safe_html_format!("{a},{b},{c}", a = -5i32, b = 2.5f64, c = true);
    assert_eq!(html.as_str(), "-5,2.5,true");
}

#[test]
fn format_named_repeated_placeholder() {
    let html = safe_html_format!("{x} and {x}", x = "a<b");
    assert_eq!(html.as_str(), "a&lt;b and a&lt;b");
}

#[test]
fn format_named_argument_shadowing_local() {
    // The common `name = name` shape: argument named after the local.
    let name = "x&y";
    let html = safe_html_format!("<i>{name}</i>", name = name);
    assert_eq!(html.as_str(), "<i>x&amp;y</i>");
}

#[test]
fn format_raw_identifier_argument() {
    // `r#type = v` matches `{type}`: the r# prefix is stripped for
    // placeholder matching (compile-time check and runtime lookup).
    let html = safe_html_format!("<x kind=\"{type}\">{fn}</x>", r#type = "a&b", r#fn = 1);
    assert_eq!(html.as_str(), "<x kind=\"a&amp;b\">1</x>");
}

#[test]
fn format_literal_braces() {
    let html = safe_html_format!("a {{b}} {v} {{{{", v = 1);
    assert_eq!(html.as_str(), "a {b} 1 {{");
}

#[test]
fn format_no_arguments() {
    let html = safe_html_format!("<hr> {{literal}}");
    assert_eq!(html.as_str(), "<hr> {literal}");
}

#[test]
fn format_placeholder_at_boundaries() {
    let html = safe_html_format!("{a}mid{b}", a = "<", b = ">");
    assert_eq!(html.as_str(), "&lt;mid&gt;");
    let adjacent = safe_html_format!("{a}{b}", a = "1<", b = "2>");
    assert_eq!(adjacent.as_str(), "1&lt;2&gt;");
}

#[test]
fn format_unicode_literal_text() {
    let html = safe_html_format!("héllo → {v} ✓", v = "å<b");
    assert_eq!(html.as_str(), "héllo → å&lt;b ✓");
}

#[test]
fn format_argument_evaluated_once() {
    let mut calls = 0;
    let mut value = || {
        calls += 1;
        "v"
    };
    let html = safe_html_format!("{x}/{x}", x = value());
    assert_eq!(html.as_str(), "v/v");
    assert_eq!(calls, 1);
}

// --- safe_html_format!: positional form ---

#[test]
fn format_positional() {
    let html = safe_html_format!("<b>{}</b><i>{}</i>", "a<b", 7);
    assert_eq!(html.as_str(), "<b>a&lt;b</b><i>7</i>");
}

// --- safe_html_format_to!: streaming, no_std path ---

#[test]
fn format_to_slice_writer() {
    let mut buf = [0u8; 64];
    let mut w = SliceWriter::new(&mut buf);
    safe_html_format_to!(w, "<b>{msg}</b>", msg = "5 < 6").unwrap();
    assert_eq!(w.as_str(), "<b>5 &lt; 6</b>");
}

#[test]
fn format_to_positional_and_safe_types() {
    let mut out = String::new();
    safe_html_format_to!(
        out,
        "{}: {}",
        SafeHtmlStr::from_constant("<b>ok</b>"),
        "x&y"
    )
    .unwrap();
    assert_eq!(out, "<b>ok</b>: x&amp;y");
}

#[test]
fn format_to_capacity_error() {
    let mut buf = [0u8; 4];
    let mut w = SliceWriter::new(&mut buf);
    assert!(safe_html_format_to!(w, "{v} is too long", v = "value").is_err());
}

// --- SafeHtmlBuilder ---

#[test]
fn builder_push_chain_and_finish() {
    let mut b = SafeHtmlBuilder::new();
    b.push(SafeHtml::from_constant("<p>"))
        .push("a & b")
        .push(42)
        .push(SafeHtml::from_constant("</p>"));
    assert_eq!(b.as_str(), "<p>a &amp; b42</p>");
    assert_eq!(b.len(), "<p>a &amp; b42</p>".len());
    assert!(!b.is_empty());
    assert_eq!(b.finish().as_str(), "<p>a &amp; b42</p>");
}

#[test]
fn builder_with_capacity_does_not_reallocate() {
    let mut b = SafeHtmlBuilder::with_capacity(1024);
    for i in 0..10 {
        safe_html_format!(b, "<li>{i}</li>", i = i);
    }
    let html = b.finish();
    assert!(html.as_str().starts_with("<li>0</li>"));
    assert!(html.as_str().ends_with("<li>9</li>"));
}

#[test]
fn builder_format_named_and_positional() {
    let mut b = SafeHtmlBuilder::new();
    safe_html_format!(b, "<b>{v}</b>", v = "a<b");
    safe_html_format!(b, "<i>{}</i>", "c&d");
    safe_html_format!(b, "<hr>");
    assert_eq!(b.finish().as_str(), "<b>a&lt;b</b><i>c&amp;d</i><hr>");
}

#[test]
fn builder_from_safe_html_and_back() {
    let start = safe_html_cat!(SafeHtml::from_constant("<ul>"));
    let mut b = SafeHtmlBuilder::from(start);
    b.push(SafeHtml::from_constant("</ul>"));
    let html: SafeHtml = b.into();
    assert_eq!(html.as_str(), "<ul></ul>");
}

#[test]
fn builder_extend() {
    let mut b = SafeHtmlBuilder::new();
    b.extend(["a<b", "c&d"]);
    assert_eq!(b.as_str(), "a&lt;bc&amp;d");
    b.extend([safe_html_cat!("<i>"), SafeHtml::from_constant("<i>")]);
    assert_eq!(b.as_str(), "a&lt;bc&amp;d&lt;i&gt;<i>");
}

#[test]
fn builder_default_is_empty() {
    let b = SafeHtmlBuilder::default();
    assert!(b.is_empty());
    assert_eq!(b.finish().as_str(), "");
}

// --- references to parts are parts ---

#[test]
fn reference_parts_interpolate_like_values() {
    let owned = String::from("a&b");
    let safe = safe_html_cat!("c<d");
    let html = safe_html_cat!(&owned, &&owned, &safe, &&safe);
    assert_eq!(html.as_str(), "a&amp;ba&amp;bc&lt;dc&lt;d");

    // The `iter().enumerate()` shape that yields `&&str`.
    let mut b = SafeHtmlBuilder::new();
    for (i, name) in ["x<y"].iter().enumerate() {
        safe_html_format!(b, "{i}:{name}", i = i, name = name);
    }
    assert_eq!(b.finish().as_str(), "0:x&lt;y");
}

// --- Option<T: SafeHtmlPart> ---

#[test]
fn option_part_some_and_none() {
    let flash: Option<SafeHtml> = Some(safe_html_cat!("hi & bye"));
    let html = safe_html_cat!(flash, Option::<SafeHtml>::None, Some("x<y"), 1);
    assert_eq!(html.as_str(), "hi &amp; byex&lt;y1");
}

#[test]
fn option_part_in_format_and_write() {
    let none: Option<&str> = None;
    let html = safe_html_format!("[{a}][{b}]", a = Some("v&w"), b = none);
    assert_eq!(html.as_str(), "[v&amp;w][]");

    let mut buf = [0u8; 32];
    let mut w = SliceWriter::new(&mut buf);
    safe_html_write!(w, Some("a<b"), Option::<&str>::None).unwrap();
    assert_eq!(w.as_str(), "a&lt;b");
}

// --- disp: streaming Display escaping ---

struct Money(i64);

impl core::fmt::Display for Money {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        // Deliberately writes in multiple chunks with HTML specials.
        write!(f, "<{}", self.0 / 100)?;
        write!(f, ".{:02}>", self.0 % 100)
    }
}

#[test]
fn disp_escapes_display_output() {
    let html = safe_html_cat!("cost: ", disp(&Money(1234)));
    assert_eq!(html.as_str(), "cost: &lt;12.34&gt;");
}

#[test]
fn disp_in_format_macro() {
    let html = safe_html_format!("<td>{m}</td>", m = disp(Money(99)));
    assert_eq!(html.as_str(), "<td>&lt;0.99&gt;</td>");
}

#[test]
fn disp_zero_alloc_streaming() {
    let mut buf = [0u8; 32];
    let mut w = SliceWriter::new(&mut buf);
    safe_html_write!(w, disp(&Money(5))).unwrap();
    assert_eq!(w.as_str(), "&lt;0.05&gt;");
}

// --- double-escape hazard is real (documents the behavior) ---

#[test]
fn pre_escaped_string_double_escapes() {
    // A legacy helper returning an already-escaped String must NOT be
    // passed as a part; this locks in the documented (wrong-looking but
    // type-correct) behavior.
    let pre_escaped = String::from("a &amp; b");
    let html = safe_html_cat!(pre_escaped);
    assert_eq!(html.as_str(), "a &amp;amp; b");
}

// --- const checker diagnostics (runtime-invoked for testability) ---
//
// In macro use these run in `const` context, so each panic below is a
// compile error at the call site. `should_panic` exercises the same code
// paths at runtime through the doc-hidden `__private` API.

#[test]
#[should_panic(expected = "no matching")]
fn checker_rejects_unknown_placeholder() {
    safehtml::__private::check_named_format("{missing}", &["present"]);
}

#[test]
#[should_panic(expected = "never used")]
fn checker_rejects_unused_argument() {
    safehtml::__private::check_named_format("no placeholders", &["extra"]);
}

#[test]
#[should_panic(expected = "unclosed placeholder")]
fn checker_rejects_unclosed_brace() {
    safehtml::__private::check_named_format("a {name", &["name"]);
}

#[test]
#[should_panic(expected = "unclosed placeholder")]
fn checker_rejects_nested_open_brace() {
    safehtml::__private::check_named_format("a {na{me}", &["name"]);
}

#[test]
#[should_panic(expected = "unmatched closing brace")]
fn checker_rejects_lone_closing_brace() {
    safehtml::__private::check_named_format("a } b", &[]);
}

#[test]
#[should_panic(expected = "format specs")]
fn checker_rejects_format_specs() {
    safehtml::__private::check_named_format("{name:>8}", &["name"]);
}

#[test]
#[should_panic(expected = "empty placeholder is not allowed")]
fn checker_rejects_empty_placeholder_in_named_form() {
    safehtml::__private::check_named_format("{} and {name}", &["name"]);
}

#[test]
#[should_panic(expected = "duplicate named argument")]
fn checker_rejects_duplicate_names() {
    safehtml::__private::check_named_format("{a}", &["a", "a"]);
}

#[test]
#[should_panic(expected = "must equal the number of arguments")]
fn checker_rejects_positional_count_mismatch() {
    safehtml::__private::check_positional_format("{} {}", 3);
}

#[test]
#[should_panic(expected = "only empty placeholders")]
fn checker_rejects_named_placeholder_in_positional_form() {
    safehtml::__private::check_positional_format("{name}", 1);
}

#[test]
fn checker_accepts_valid_forms() {
    safehtml::__private::check_named_format("{{}} {a} {b} {a}", &["a", "b"]);
    // Different-length names exercise the length-mismatch comparisons.
    safehtml::__private::check_named_format("{long_name} {x}", &["x", "long_name"]);
    safehtml::__private::check_positional_format("{} {{x}} {}", 2);
    safehtml::__private::check_named_format("{type}", &["r#type"]);
    safehtml::__private::unit("x");
    assert!(safehtml::__private::has_brace("a{b"));
    assert!(safehtml::__private::has_brace("a}b"));
    assert!(!safehtml::__private::has_brace("plain"));
}

#[test]
fn builder_reserve() {
    let mut b = SafeHtmlBuilder::new();
    b.reserve(128);
    b.push("a");
    assert_eq!(b.as_str(), "a");
}

// --- runtime scanners: defensive paths for direct (non-macro) calls ---
//
// Through the macros these inputs are compile errors; called directly, the
// scanners must degrade gracefully rather than panic or emit unsafely.

#[test]
fn scanner_named_defensive_paths() {
    let mut out = String::new();
    // Unknown placeholder writes nothing; lone '}' and unclosed '{' emit
    // literal text; '{{'/'}}' emit single braces.
    safehtml::__private::format_named_to("{missing}|}|{{|}}|{open", &[], &mut out).unwrap();
    assert_eq!(out, "|}|{|}|");
}

#[test]
fn scanner_positional_defensive_paths() {
    let mut out = String::new();
    // "X" escapes to itself, so this part writes a literal X.
    let extra: &dyn safehtml::__private::DynPart = &"X";
    // Named placeholders are skipped in the positional scanner; a '{}'
    // beyond the provided parts writes nothing; braces still unescape.
    safehtml::__private::format_positional_to("{name}|{}|{}|{{|}}|}", &[extra], &mut out).unwrap();
    assert_eq!(out, "|X||{|}|}");
}