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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
//! Compile-time-checked safe HTML template formatting: the engine behind
//! [`safe_html_format!`](crate::safe_html_format) and
//! [`safe_html_format_to!`](crate::safe_html_format_to).
//!
//! The format string is a string literal and therefore carries the same
//! trust as [`SafeHtml::from_constant`](crate::types::SafeHtml::from_constant):
//! it is reviewed alongside the code. Every interpolated argument is routed
//! through [`SafeHtmlPart`](crate::SafeHtmlPart) (safe types verbatim,
//! strings escaped, numbers formatted), type-erased to
//! [`DynPart`](crate::DynPart) slices so the interpolation engine is a
//! single non-generic function.
//!
//! Placeholders are validated at compile time by `const fn` checkers
//! invoked from the macros via `const _: () = ...;`. In particular, a
//! `{name}` placeholder without a matching `name = value` argument is a
//! compile error. This is deliberate: `format_args!`-style implicit capture
//! of same-named locals would interpolate them *unescaped*, which is
//! exactly the XSS hazard these macros exist to prevent.
//!
//! Only two placeholder forms exist: `{name}` (named form) and `{}`
//! (positional form). Format specs (`{x:>8}`) are not supported —
//! pre-format such values into an argument instead. `{{` and `}}` emit
//! literal braces, as in [`format!`].
//!
//! Allocation behavior: the [`SafeHtml`](crate::types::SafeHtml)- and
//! builder-producing entry points pre-reserve `fmt.len()` plus the sum of
//! the parts' [`size_hint`](crate::SafeHtmlPart::size_hint)s, so a typical
//! interpolation allocates exactly once (or not at all when appending to a
//! builder with spare capacity). A no-placeholder literal without braces
//! compiles to a borrowed `SafeHtml::from_constant` — zero allocation.

use crate::DynPart;

/// The bytes an argument name matches placeholders with: a raw identifier
/// (`r#type`) sheds its `r#` prefix, so `r#type = ...` pairs with `{type}`.
const fn arg_name_bytes(name: &str) -> &[u8] {
    let bytes = name.as_bytes();
    if bytes.len() > 2 && bytes[0] == b'r' && bytes[1] == b'#' {
        bytes.split_at(2).1
    } else {
        bytes
    }
}

/// Const byte-slice equality.
const fn bytes_eq(a: &[u8], b: &[u8]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    let mut i = 0;
    while i < a.len() {
        if a[i] != b[i] {
            return false;
        }
        i += 1;
    }
    true
}

/// Const comparison of `bytes[start..end]` against `name`.
const fn placeholder_matches(bytes: &[u8], start: usize, end: usize, name: &[u8]) -> bool {
    if end - start != name.len() {
        return false;
    }
    let mut i = 0;
    while i < name.len() {
        if bytes[start + i] != name[i] {
            return false;
        }
        i += 1;
    }
    true
}

/// Const check for any brace at all: a brace-free literal needs no
/// interpolation or unescaping, so the macros emit a borrowed
/// `SafeHtml::from_constant` for it.
pub const fn has_brace(fmt: &str) -> bool {
    let bytes = fmt.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'{' || bytes[i] == b'}' {
            return true;
        }
        i += 1;
    }
    false
}

/// Compile-time validation for the named form: every `{name}` placeholder
/// must match one of `names`, every name must be used, and braces must be
/// well-formed. Panicking here is a compile error at the macro call site.
pub const fn check_named_format(fmt: &str, names: &[&str]) {
    assert!(
        names.len() <= 128,
        "safe_html_format!: at most 128 named arguments are supported"
    );
    let mut i = 0;
    while i < names.len() {
        let mut j = i + 1;
        while j < names.len() {
            assert!(
                !bytes_eq(arg_name_bytes(names[i]), arg_name_bytes(names[j])),
                "safe_html_format!: duplicate named argument"
            );
            j += 1;
        }
        i += 1;
    }
    let bytes = fmt.as_bytes();
    let mut used: u128 = 0;
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'{' {
            if i + 1 < bytes.len() && bytes[i + 1] == b'{' {
                i += 2;
                continue;
            }
            let start = i + 1;
            let mut end = start;
            while end < bytes.len() && bytes[end] != b'}' && bytes[end] != b'{' {
                end += 1;
            }
            assert!(
                end < bytes.len() && bytes[end] == b'}',
                "safe_html_format!: unclosed placeholder; double the brace to emit a literal brace"
            );
            assert!(
                end > start,
                "safe_html_format!: an empty placeholder is not allowed with named arguments; name it to match a `name = value` argument"
            );
            let mut k = start;
            while k < end {
                assert!(
                    bytes[k] != b':',
                    "safe_html_format!: format specs are not supported in placeholders; pre-format the value into the argument instead"
                );
                k += 1;
            }
            let mut m = 0;
            let mut found = false;
            while m < names.len() {
                if placeholder_matches(bytes, start, end, arg_name_bytes(names[m])) {
                    used |= 1u128 << m;
                    found = true;
                    break;
                }
                m += 1;
            }
            assert!(
                found,
                "safe_html_format!: placeholder has no matching `name = value` argument; implicit capture of locals is not supported because every value must be routed through escaping"
            );
            i = end + 1;
        } else if bytes[i] == b'}' {
            assert!(
                i + 1 < bytes.len() && bytes[i + 1] == b'}',
                "safe_html_format!: unmatched closing brace; double the brace to emit a literal brace"
            );
            i += 2;
        } else {
            i += 1;
        }
    }
    assert!(
        used.count_ones() as usize == names.len(),
        "safe_html_format!: a named argument is never used in the format string"
    );
}

/// Compile-time validation for the positional form: the number of `{}`
/// placeholders must equal `count`, named placeholders are rejected, and
/// braces must be well-formed.
pub const fn check_positional_format(fmt: &str, count: usize) {
    let bytes = fmt.as_bytes();
    let mut seen = 0usize;
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'{' {
            if i + 1 < bytes.len() && bytes[i + 1] == b'{' {
                i += 2;
                continue;
            }
            assert!(
                i + 1 < bytes.len() && bytes[i + 1] == b'}',
                "safe_html_format!: only empty placeholders are allowed with positional arguments; use `name = value` arguments for named placeholders"
            );
            seen += 1;
            i += 2;
        } else if bytes[i] == b'}' {
            assert!(
                i + 1 < bytes.len() && bytes[i + 1] == b'}',
                "safe_html_format!: unmatched closing brace; double the brace to emit a literal brace"
            );
            i += 2;
        } else {
            i += 1;
        }
    }
    assert!(
        seen == count,
        "safe_html_format!: the number of empty placeholders must equal the number of arguments"
    );
}

/// Runtime counterpart of [`arg_name_bytes`]: the name a `(name, part)`
/// pair matches placeholders with, raw-identifier prefix stripped.
fn arg_name(name: &str) -> &str {
    match name.as_bytes() {
        [b'r', b'#', _, ..] => name.get(2..).unwrap_or(name),
        _ => name,
    }
}

/// Runtime interpolation for the named form. `fmt` has already passed
/// [`check_named_format`] when called from the macros, so the defensive
/// branches (unknown name, malformed braces) are unreachable there and
/// degrade to writing nothing / literal text on direct misuse.
pub fn format_named_to(
    fmt: &str,
    parts: &[(&str, &dyn DynPart)],
    w: &mut dyn core::fmt::Write,
) -> core::fmt::Result {
    let bytes = fmt.as_bytes();
    let mut start = 0;
    let mut i = 0;
    while i < bytes.len() {
        let b = bytes[i];
        if b != b'{' && b != b'}' {
            i += 1;
            continue;
        }
        if let Some(run) = fmt.get(start..i)
            && !run.is_empty()
        {
            w.write_str(run)?;
        }
        if i + 1 < bytes.len() && bytes[i + 1] == b {
            w.write_char(b as char)?;
            i += 2;
        } else if b == b'{' {
            let mut end = i + 1;
            while end < bytes.len() && bytes[end] != b'}' {
                end += 1;
            }
            let name = fmt.get(i + 1..end).unwrap_or("");
            if let Some((_, part)) = parts.iter().find(|(n, _)| arg_name(n) == name) {
                part.dyn_write_to(w)?;
            }
            i = end.saturating_add(1);
        } else {
            w.write_char('}')?;
            i += 1;
        }
        start = i;
    }
    if let Some(tail) = fmt.get(start..)
        && !tail.is_empty()
    {
        w.write_str(tail)?;
    }
    Ok(())
}

/// Runtime interpolation for the positional form: each `{}` consumes the
/// next part in order. `fmt` has already passed [`check_positional_format`]
/// when called from the macros.
pub fn format_positional_to(
    fmt: &str,
    parts: &[&dyn DynPart],
    w: &mut dyn core::fmt::Write,
) -> core::fmt::Result {
    let bytes = fmt.as_bytes();
    let mut start = 0;
    let mut i = 0;
    let mut next = 0usize;
    while i < bytes.len() {
        let b = bytes[i];
        if b != b'{' && b != b'}' {
            i += 1;
            continue;
        }
        if let Some(run) = fmt.get(start..i)
            && !run.is_empty()
        {
            w.write_str(run)?;
        }
        if i + 1 < bytes.len() && bytes[i + 1] == b {
            w.write_char(b as char)?;
            i += 2;
        } else if b == b'{' {
            let mut end = i + 1;
            while end < bytes.len() && bytes[end] != b'}' {
                end += 1;
            }
            if end == i + 1 {
                if let Some(part) = parts.get(next) {
                    part.dyn_write_to(w)?;
                }
                next += 1;
            }
            i = end.saturating_add(1);
        } else {
            w.write_char('}')?;
            i += 1;
        }
        start = i;
    }
    if let Some(tail) = fmt.get(start..)
        && !tail.is_empty()
    {
        w.write_str(tail)?;
    }
    Ok(())
}

/// Reserves `fmt.len()` plus the parts' size hints, then interpolates the
/// named form into `buf`. Backs `safe_html_format!(builder, ...)`.
#[cfg(feature = "alloc")]
pub fn format_named_into(
    buf: &mut alloc::string::String,
    fmt: &str,
    parts: &[(&str, &dyn DynPart)],
) {
    let mut cap = fmt.len();
    for (_, part) in parts {
        cap = cap.saturating_add(part.dyn_size_hint());
    }
    buf.reserve(cap);
    // Writing into a `String` cannot fail.
    let _ = format_named_to(fmt, parts, buf);
}

/// Positional-form sibling of [`format_named_into`].
#[cfg(feature = "alloc")]
pub fn format_positional_into(buf: &mut alloc::string::String, fmt: &str, parts: &[&dyn DynPart]) {
    let mut cap = fmt.len();
    for part in parts {
        cap = cap.saturating_add(part.dyn_size_hint());
    }
    buf.reserve(cap);
    let _ = format_positional_to(fmt, parts, buf);
}

/// Single-allocation named interpolation returning `SafeHtml`. Backs
/// `safe_html_format!`.
#[cfg(feature = "alloc")]
pub fn format_named(fmt: &str, parts: &[(&str, &dyn DynPart)]) -> crate::types::SafeHtml {
    let mut buf = alloc::string::String::new();
    format_named_into(&mut buf, fmt, parts);
    crate::__private::finish_safe_html(buf)
}

/// Positional-form sibling of [`format_named`].
#[cfg(feature = "alloc")]
pub fn format_positional(fmt: &str, parts: &[&dyn DynPart]) -> crate::types::SafeHtml {
    let mut buf = alloc::string::String::new();
    format_positional_into(&mut buf, fmt, parts);
    crate::__private::finish_safe_html(buf)
}

/// Builds a [`SafeHtml`](crate::types::SafeHtml) from a trusted template
/// literal with escaped interpolations, or appends the same to a
/// [`SafeHtmlBuilder`](crate::SafeHtmlBuilder).
///
/// The format string must be a string literal; like
/// [`SafeHtml::from_constant`](crate::types::SafeHtml::from_constant), its
/// literal text is trusted as-is. Every interpolated argument goes through
/// [`SafeHtmlPart`](crate::SafeHtmlPart): safe types ([`SafeHtml`](crate::types::SafeHtml),
/// [`SafeHtmlStr`](crate::SafeHtmlStr), [`Identifier`](crate::types::Identifier))
/// pass verbatim, strings and characters are HTML-escaped, numbers and
/// booleans are formatted. Other [`Display`](core::fmt::Display) types can
/// be interpolated with [`disp`](crate::disp), which escapes their output
/// on the fly. Arguments are evaluated exactly once; the output buffer is
/// pre-reserved from the parts' size hints, so a typical interpolation
/// allocates once (a brace-free literal with no arguments allocates never).
///
/// Placeholders are checked at compile time: a `{name}` placeholder
/// **must** have a matching `name = value` argument (locals are never
/// captured implicitly — an implicit capture would bypass escaping), every
/// argument must be used, and either all placeholders are named or all are
/// positional `{}`. Format specs (`{x:>8}`) are not supported; pre-format
/// such values into an argument. `{{` and `}}` emit literal braces. A
/// raw-identifier argument matches its unprefixed placeholder:
/// `r#type = v` pairs with `{type}`.
///
/// ```rust
/// use safehtml::safe_html_format;
///
/// let title = "Bob & <Alice>";
/// let html = safe_html_format!(
///     r#"<input name="date" value="{date}" title="{t}">"#,
///     date = "2026-07-18",
///     t = title,
/// );
/// assert_eq!(
///     html.as_str(),
///     r#"<input name="date" value="2026-07-18" title="Bob &amp; &lt;Alice&gt;">"#
/// );
/// ```
///
/// With a [`SafeHtmlBuilder`](crate::SafeHtmlBuilder) as first argument the
/// output is appended in place (no temporary allocation), which is the
/// natural shape for rendering loops:
///
/// ```rust
/// use safehtml::{SafeHtmlBuilder, safe_html_format};
///
/// let mut b = SafeHtmlBuilder::with_capacity(256);
/// for (i, name) in ["a<b", "c&d"].iter().enumerate() {
///     safe_html_format!(b, "<li id=\"row-{i}\">{name}</li>", i = i, name = name);
/// }
/// assert_eq!(
///     b.finish().as_str(),
///     "<li id=\"row-0\">a&lt;b</li><li id=\"row-1\">c&amp;d</li>"
/// );
/// ```
///
/// Positional form: `safe_html_format!("<b>{}</b>", user_input)`.
///
/// See also [`safe_html_format_to!`](crate::safe_html_format_to), the
/// `no_std` sibling that streams into any [`core::fmt::Write`].
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
#[macro_export]
macro_rules! safe_html_format {
    ($fmt:literal $(,)?) => {{
        const _: () = $crate::__private::check_named_format($fmt, &[]);
        const HAS_BRACE: bool = $crate::__private::has_brace($fmt);
        if HAS_BRACE {
            $crate::__private::format_named($fmt, &[])
        } else {
            $crate::SafeHtml::from_constant($fmt)
        }
    }};
    ($fmt:literal, $($name:ident = $val:expr),+ $(,)?) => {{
        const _: () = $crate::__private::check_named_format($fmt, &[$(stringify!($name)),+]);
        $crate::__private::format_named(
            $fmt,
            &[$((stringify!($name), &$val as &dyn $crate::__private::DynPart)),+],
        )
    }};
    ($fmt:literal, $($val:expr),+ $(,)?) => {{
        const _: () = $crate::__private::check_positional_format(
            $fmt,
            <[()]>::len(&[$($crate::__private::unit(stringify!($val))),+]),
        );
        $crate::__private::format_positional(
            $fmt,
            &[$(&$val as &dyn $crate::__private::DynPart),+],
        )
    }};
    ($builder:expr, $fmt:literal $(,)?) => {{
        const _: () = $crate::__private::check_named_format($fmt, &[]);
        ($builder).__format_named($fmt, &[]);
    }};
    ($builder:expr, $fmt:literal, $($name:ident = $val:expr),+ $(,)?) => {{
        const _: () = $crate::__private::check_named_format($fmt, &[$(stringify!($name)),+]);
        ($builder).__format_named(
            $fmt,
            &[$((stringify!($name), &$val as &dyn $crate::__private::DynPart)),+],
        );
    }};
    ($builder:expr, $fmt:literal, $($val:expr),+ $(,)?) => {{
        const _: () = $crate::__private::check_positional_format(
            $fmt,
            <[()]>::len(&[$($crate::__private::unit(stringify!($val))),+]),
        );
        ($builder).__format_positional(
            $fmt,
            &[$(&$val as &dyn $crate::__private::DynPart),+],
        );
    }};
}

/// Streams a trusted template literal with escaped interpolations into any
/// [`core::fmt::Write`] — the `no_std`, zero-allocation sibling of
/// [`safe_html_format!`](crate::safe_html_format).
///
/// The first argument is the writer; the format string and arguments follow
/// the same rules as [`safe_html_format!`](crate::safe_html_format)
/// (compile-time-checked placeholders, arguments routed through
/// [`SafeHtmlPart`](crate::SafeHtmlPart)). Evaluates to
/// [`core::fmt::Result`], so a full [`SliceWriter`](crate::SliceWriter)
/// surfaces as `Err`.
///
/// The caller vouches for the destination: whatever is written is safe
/// HTML, but a raw writer (e.g. a `String`) does not itself carry the
/// [`SafeHtml`](crate::types::SafeHtml) contract. Use
/// [`SafeHtmlBuilder`](crate::SafeHtmlBuilder) (with
/// `safe_html_format!(builder, ...)`) to keep the contract in the type.
///
/// ```rust
/// use safehtml::{SliceWriter, safe_html_format_to};
///
/// 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>");
/// ```
#[macro_export]
macro_rules! safe_html_format_to {
    ($w:expr, $fmt:literal $(,)?) => {{
        const _: () = $crate::__private::check_named_format($fmt, &[]);
        $crate::__private::format_named_to($fmt, &[], &mut $w)
    }};
    ($w:expr, $fmt:literal, $($name:ident = $val:expr),+ $(,)?) => {{
        const _: () = $crate::__private::check_named_format($fmt, &[$(stringify!($name)),+]);
        $crate::__private::format_named_to(
            $fmt,
            &[$((stringify!($name), &$val as &dyn $crate::__private::DynPart)),+],
            &mut $w,
        )
    }};
    ($w:expr, $fmt:literal, $($val:expr),+ $(,)?) => {{
        const _: () = $crate::__private::check_positional_format(
            $fmt,
            <[()]>::len(&[$($crate::__private::unit(stringify!($val))),+]),
        );
        $crate::__private::format_positional_to(
            $fmt,
            &[$(&$val as &dyn $crate::__private::DynPart),+],
            &mut $w,
        )
    }};
}

/// Discards a value; used by the macros to count repetition elements in
/// `const` context.
pub const fn unit(_: &str) {}