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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
//! HTML escaping and Unicode interchange coercion (zero-allocation core),
//! plus JSON-for-`<script>` escaping and the [`HtmlEscaped`] display adapter.

/// Checks if a character is "interchange-invalid" according to Unicode and HTML
/// preprocessing specs.
///
/// This function identifies codepoints that can trigger parser inconsistencies
/// or upstream bugs:
/// - **C0 control characters**: ASCII values `0x00..=0x1F` except allowed
///   whitespace:
///   - Horizontal Tab (`0x09`)
///   - Line Feed (`0x0A`)
///   - Form Feed (`0x0C`)
///   - Carriage Return (`0x0D`)
/// - **C1 controls and DEL**: `0x7F..=0x9F`
/// - **Unicode Non-characters**:
///   - Range `U+FDD0..=U+FDEF` (32 codepoints)
///   - Plane non-characters ending in `0xFFFE` or `0xFFFF` (e.g., `U+FFFE`,
///     `U+FFFF`, `U+10FFFF`)
///
/// By identifying these characters early, the library ensures that no malformed
/// unicode reaches client-side rendering engines.
#[inline]
pub fn is_interchange_invalid(c: char) -> bool {
    let u = c as u32;
    // C0 controls check (excluding HT, LF, FF, CR)
    if u <= 0x1F {
        return u != 0x09 && u != 0x0A && u != 0x0C && u != 0x0D;
    }
    // DEL and C1 controls check
    if matches!(u, 0x7F..=0x9F) {
        return true;
    }
    // Unicode non-character blocks check
    if matches!(u, 0xFDD0..=0xFDEF) {
        return true;
    }
    let masked = u & 0xFFFF;
    masked == 0xFFFE || masked == 0xFFFF
}

/// Builds a 256-entry byte-classification table for the linear scanners.
///
/// Flagged bytes are the ones a scanner must stop at:
/// - C0 controls except allowed whitespace (HT, LF, FF, CR), plus DEL (`0x7F`)
/// - the five HTML-special characters (`&`, `<`, `>`, `"`, `'`) when
///   `include_html_specials` is set
/// - all non-ASCII bytes (`0x80..=0xFF`), which require full character
///   decoding to check for interchange-invalid codepoints
const fn build_scan_table(include_html_specials: bool) -> [bool; 256] {
    let mut table = [false; 256];
    let mut b = 0usize;
    while b < 256 {
        table[b] = match b {
            0x09 | 0x0A | 0x0C | 0x0D => false, // allowed whitespace
            0x00..=0x1F | 0x7F => true,         // C0 controls and DEL
            0x22 | 0x26 | 0x27 | 0x3C | 0x3E => include_html_specials, // " & ' < >
            0x80..=0xFF => true,                // non-ASCII: decode required
            _ => false,
        };
        b += 1;
    }
    table
}

static HTML_SCAN: [bool; 256] = build_scan_table(true);
static INTERCHANGE_SCAN: [bool; 256] = build_scan_table(false);

/// Bytes that must be replaced when embedding JSON in an HTML `<script>` block:
/// `<`, `>`, `&`, and `0xE2` (the UTF-8 lead byte of U+2028/U+2029).
const fn build_json_scan_table() -> [bool; 256] {
    let mut table = [false; 256];
    table[0x3C] = true; // <
    table[0x3E] = true; // >
    table[0x26] = true; // &
    table[0xE2] = true; // lead byte of U+2028 / U+2029
    table
}

static JSON_SCAN: [bool; 256] = build_json_scan_table();

// -----------------------------------------------------------------------------
// Chunked scanning: SWAR by default, `core::simd` with the `simd` feature
//
// The scanners below skip clean input a chunk at a time instead of byte by
// byte. Two interchangeable chunk-predicate implementations exist:
//
// - Default (stable): SWAR (SIMD Within A Register) on `usize` words —
//   portable to every target width (8 bytes per step on 64-bit, 4 on 32-bit
//   embedded targets, 2 on 16-bit), safe stable Rust, no intrinsics.
// - `simd` feature (nightly): `core::simd` portable vectors, 16 bytes per
//   step, compiled to native SIMD on x86_64/AArch64/etc.
//
// Either way the chunk predicates are a *conservative prefilter*: they may
// report a chunk as "interesting" when it is not (e.g. a word containing
// allowed whitespace like `\n`), but they must never miss a byte flagged in
// the corresponding scan table. Whenever a chunk is flagged, classification
// falls back to the authoritative 256-entry table for that chunk, so the
// tables remain the single source of truth and the escape/coerce paths cannot
// diverge. The `prefilters_cover_tables` unit test verifies the never-miss
// property for every byte value and every lane position.
// -----------------------------------------------------------------------------

/// SWAR chunk predicates: branchless byte-class tests on `usize` words.
#[cfg(not(feature = "simd"))]
mod chunkscan {
    /// Bytes scanned per step: one machine word.
    pub const CHUNK: usize = core::mem::size_of::<usize>();

    /// Broadcasts a byte into every lane of a `usize` word.
    const fn repeat_byte(b: u8) -> usize {
        usize::from_ne_bytes([b; CHUNK])
    }

    const LSB: usize = repeat_byte(0x01);
    const MSB: usize = repeat_byte(0x80);

    /// Per-lane mask with the high bit set in every zero lane of `x`
    /// (exact; no false positives).
    #[inline(always)]
    const fn zero_byte_mask(x: usize) -> usize {
        x.wrapping_sub(LSB) & !x & MSB
    }

    /// Per-lane mask marking lanes equal to `B`.
    #[inline(always)]
    const fn eq_mask<const B: u8>(w: usize) -> usize {
        zero_byte_mask(w ^ repeat_byte(B))
    }

    /// Per-lane mask marking lanes less than `N`. Requires `N <= 0x80`.
    #[inline(always)]
    const fn lt_mask<const N: u8>(w: usize) -> usize {
        w.wrapping_sub(repeat_byte(N)) & !w & MSB
    }

    /// Prefilter for (a superset of) [`super::HTML_SCAN`]: C0 controls, DEL,
    /// non-ASCII, and the five HTML-special characters.
    #[inline(always)]
    pub fn html_may_flag(chunk: &[u8; CHUNK]) -> bool {
        let w = usize::from_ne_bytes(*chunk);
        (lt_mask::<0x20>(w)
            | (w & MSB)
            | eq_mask::<0x7F>(w)
            | eq_mask::<b'&'>(w)
            | eq_mask::<b'<'>(w)
            | eq_mask::<b'>'>(w)
            | eq_mask::<b'"'>(w)
            | eq_mask::<b'\''>(w))
            != 0
    }

    /// Prefilter for (a superset of) [`super::INTERCHANGE_SCAN`]: C0
    /// controls, DEL, and non-ASCII.
    #[inline(always)]
    pub fn interchange_may_flag(chunk: &[u8; CHUNK]) -> bool {
        let w = usize::from_ne_bytes(*chunk);
        (lt_mask::<0x20>(w) | (w & MSB) | eq_mask::<0x7F>(w)) != 0
    }

    /// Prefilter matching [`super::JSON_SCAN`] exactly: `<`, `>`, `&`, `0xE2`.
    #[inline(always)]
    pub fn json_may_flag(chunk: &[u8; CHUNK]) -> bool {
        let w = usize::from_ne_bytes(*chunk);
        (eq_mask::<b'<'>(w) | eq_mask::<b'>'>(w) | eq_mask::<b'&'>(w) | eq_mask::<0xE2>(w)) != 0
    }
}

/// `core::simd` chunk predicates: 16-byte portable vectors (nightly).
#[cfg(feature = "simd")]
mod chunkscan {
    use core::simd::Simd;
    use core::simd::cmp::{SimdPartialEq, SimdPartialOrd};

    /// Bytes scanned per step.
    pub const CHUNK: usize = 16;

    type V = Simd<u8, CHUNK>;

    /// Prefilter for (a superset of) [`super::HTML_SCAN`]: C0 controls, DEL,
    /// non-ASCII (`>= 0x7F` covers both), and the HTML-special characters.
    #[inline(always)]
    pub fn html_may_flag(chunk: &[u8; CHUNK]) -> bool {
        let v = V::from_array(*chunk);
        (v.simd_lt(V::splat(0x20))
            | v.simd_ge(V::splat(0x7F))
            | v.simd_eq(V::splat(b'&'))
            | v.simd_eq(V::splat(b'<'))
            | v.simd_eq(V::splat(b'>'))
            | v.simd_eq(V::splat(b'"'))
            | v.simd_eq(V::splat(b'\'')))
        .any()
    }

    /// Prefilter for (a superset of) [`super::INTERCHANGE_SCAN`]: C0
    /// controls, DEL, and non-ASCII.
    #[inline(always)]
    pub fn interchange_may_flag(chunk: &[u8; CHUNK]) -> bool {
        let v = V::from_array(*chunk);
        (v.simd_lt(V::splat(0x20)) | v.simd_ge(V::splat(0x7F))).any()
    }

    /// Prefilter matching [`super::JSON_SCAN`] exactly: `<`, `>`, `&`, `0xE2`.
    #[inline(always)]
    pub fn json_may_flag(chunk: &[u8; CHUNK]) -> bool {
        let v = V::from_array(*chunk);
        (v.simd_eq(V::splat(b'<'))
            | v.simd_eq(V::splat(b'>'))
            | v.simd_eq(V::splat(b'&'))
            | v.simd_eq(V::splat(0xE2)))
        .any()
    }
}

/// Returns the absolute index of the first byte at or after `from` that is
/// flagged in `table`, skipping clean input a chunk at a time.
///
/// `chunk_may_flag` is the conservative prefilter paired with `table`; when
/// it fires, the bytes of that chunk are re-checked against the authoritative
/// table (false positives are skipped, never reported).
#[inline(always)]
fn find_flagged_chunked<const N: usize>(
    bytes: &[u8],
    from: usize,
    table: &[bool; 256],
    chunk_may_flag: impl Fn(&[u8; N]) -> bool,
) -> Option<usize> {
    // Dense-region fast path: scanning usually resumes immediately after a
    // replaced byte, and in escape-heavy or multi-byte text the next flagged
    // byte is that very position. One table probe returns straight away
    // there, where the chunk predicates below would cost far more.
    match bytes.get(from) {
        Some(&b) if table[b as usize] => return Some(from),
        Some(_) => {}
        None => return None,
    }
    let mut i = from + 1;
    while let Some(chunk) = bytes.get(i..i + N) {
        let Ok(arr) = <&[u8; N]>::try_from(chunk) else {
            break;
        };
        if chunk_may_flag(arr) {
            if let Some(p) = chunk.iter().position(|&b| table[b as usize]) {
                return Some(i + p);
            }
        }
        i += N;
    }
    // Tail shorter than one chunk.
    bytes
        .get(i..)?
        .iter()
        .position(|&b| table[b as usize])
        .map(|p| i + p)
}

/// [`find_flagged_chunked`] specialized for [`HTML_SCAN`].
#[inline]
fn find_html_flagged(bytes: &[u8], from: usize) -> Option<usize> {
    find_flagged_chunked::<{ chunkscan::CHUNK }>(bytes, from, &HTML_SCAN, chunkscan::html_may_flag)
}

/// [`find_flagged_chunked`] specialized for [`INTERCHANGE_SCAN`].
#[inline]
fn find_interchange_flagged(bytes: &[u8], from: usize) -> Option<usize> {
    find_flagged_chunked::<{ chunkscan::CHUNK }>(
        bytes,
        from,
        &INTERCHANGE_SCAN,
        chunkscan::interchange_may_flag,
    )
}

/// [`find_flagged_chunked`] specialized for [`JSON_SCAN`].
#[inline]
fn find_json_flagged(bytes: &[u8], from: usize) -> Option<usize> {
    find_flagged_chunked::<{ chunkscan::CHUNK }>(bytes, from, &JSON_SCAN, chunkscan::json_may_flag)
}

/// Coerces a string to interchange-valid UTF-8, replacing invalid characters.
///
/// Any character identified as interchange-invalid by
/// [`is_interchange_invalid`] is replaced with the Unicode replacement
/// character (`\u{FFFD}`). The output is written directly to the provided
/// [`core::fmt::Write`] writer.
///
/// Optimized to bulk-skip runs of valid ASCII via a table-driven scan and
/// write safe substrings in bulk to reduce function calls to the writer.
pub fn coerce_to_interchange_valid_to<W: core::fmt::Write>(
    text: &str,
    mut w: W,
) -> core::fmt::Result {
    let bytes = text.as_bytes();
    let mut last = 0;
    let mut idx = 0;

    while let Some(i) = find_interchange_flagged(bytes, idx) {
        idx = i;
        match bytes.get(idx) {
            Some(&b) if b < 0x80 => {
                // Every flagged ASCII byte is an interchange-invalid control.
                if idx > last {
                    w.write_str(text.get(last..idx).unwrap_or(""))?;
                }
                w.write_char('\u{FFFD}')?;
                idx += 1;
                last = idx;
            }
            Some(_) => {
                // Non-ASCII: decode the full character. The scanner only stops
                // at char boundaries here because every byte of a multi-byte
                // character is flagged, so the first one hit is the lead byte.
                let Some(c) = text.get(idx..).and_then(|s| s.chars().next()) else {
                    break;
                };
                if is_interchange_invalid(c) {
                    if idx > last {
                        w.write_str(text.get(last..idx).unwrap_or(""))?;
                    }
                    w.write_char('\u{FFFD}')?;
                    idx += c.len_utf8();
                    last = idx;
                } else {
                    idx += c.len_utf8();
                }
            }
            None => break,
        }
    }

    if last < bytes.len() {
        w.write_str(text.get(last..).unwrap_or(""))?;
    }
    Ok(())
}

/// Coerces a string to interchange-valid UTF-8 and HTML-escapes
/// security-sensitive characters.
///
/// Characters escaped:
/// - `&` -> `&amp;`
/// - `<` -> `&lt;`
/// - `>` -> `&gt;`
/// - `"` -> `&#34;`
/// - `'` -> `&#39;`
///
/// Invalid Unicode codepoints (including C0 controls, DEL, C1 controls, and
/// Unicode non-characters) are simultaneously coerced to `\u{FFFD}` in a
/// single pass. Optimized to write safe substrings in bulk to reduce function
/// calls to the writer.
pub fn escape_html_and_coerce_to<W: core::fmt::Write>(text: &str, mut w: W) -> core::fmt::Result {
    let bytes = text.as_bytes();
    let mut last = 0;
    let mut idx = 0;

    while let Some(i) = find_html_flagged(bytes, idx) {
        idx = i;
        match bytes.get(idx) {
            Some(&b) if b < 0x80 => {
                let rep = match b {
                    b'&' => "&amp;",
                    b'<' => "&lt;",
                    b'>' => "&gt;",
                    b'"' => "&#34;",
                    b'\'' => "&#39;",
                    // Every other flagged ASCII byte is an interchange-invalid
                    // control character (C0 minus allowed whitespace, or DEL).
                    _ => "\u{FFFD}",
                };
                if idx > last {
                    w.write_str(text.get(last..idx).unwrap_or(""))?;
                }
                w.write_str(rep)?;
                idx += 1;
                last = idx;
            }
            Some(_) => {
                // Non-ASCII: decode the full character to check validity.
                let Some(c) = text.get(idx..).and_then(|s| s.chars().next()) else {
                    break;
                };
                if is_interchange_invalid(c) {
                    if idx > last {
                        w.write_str(text.get(last..idx).unwrap_or(""))?;
                    }
                    w.write_str("\u{FFFD}")?;
                    idx += c.len_utf8();
                    last = idx;
                } else {
                    idx += c.len_utf8();
                }
            }
            None => break,
        }
    }

    if last < bytes.len() {
        w.write_str(text.get(last..).unwrap_or(""))?;
    }
    Ok(())
}

/// Coerces raw bytes (which may contain invalid UTF-8 sequences) to
/// interchange-valid UTF-8, writing the result to a writer.
///
/// Invalid byte sequences and invalid Unicode codepoints are replaced with
/// `\u{FFFD}`, matching the semantics of [`core::str::Utf8Chunks`] /
/// `String::from_utf8_lossy` (one replacement per maximal invalid sequence).
pub fn coerce_bytes_to_interchange_valid_to<W: core::fmt::Write>(
    bytes: &[u8],
    mut w: W,
) -> core::fmt::Result {
    for chunk in bytes.utf8_chunks() {
        coerce_to_interchange_valid_to(chunk.valid(), &mut w)?;
        if !chunk.invalid().is_empty() {
            w.write_char('\u{FFFD}')?;
        }
    }
    Ok(())
}

/// Coerces raw bytes (which may contain invalid UTF-8 sequences) to
/// interchange-valid UTF-8, escaping security-sensitive HTML characters,
/// writing the result to a writer.
///
/// Invalid byte sequences and invalid Unicode codepoints are replaced with
/// `\u{FFFD}`.
pub fn escape_html_bytes_and_coerce_to<W: core::fmt::Write>(
    bytes: &[u8],
    mut w: W,
) -> core::fmt::Result {
    for chunk in bytes.utf8_chunks() {
        escape_html_and_coerce_to(chunk.valid(), &mut w)?;
        if !chunk.invalid().is_empty() {
            w.write_char('\u{FFFD}')?;
        }
    }
    Ok(())
}

/// Coerces raw bytes to interchange-valid UTF-8.
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn coerce_bytes_to_interchange_valid(bytes: &[u8]) -> alloc::string::String {
    let mut s = alloc::string::String::with_capacity(bytes.len());
    let _ = coerce_bytes_to_interchange_valid_to(bytes, &mut s);
    s
}

/// Coerces raw bytes to interchange-valid UTF-8 and escapes security-sensitive
/// HTML characters.
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn escape_html_bytes(bytes: &[u8]) -> alloc::string::String {
    let mut s = alloc::string::String::with_capacity(bytes.len());
    let _ = escape_html_bytes_and_coerce_to(bytes, &mut s);
    s
}

/// Escapes a JSON string to be safely embedded within an inline `<script>` HTML
/// tag.
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn escape_json_for_script(json: &str) -> alloc::string::String {
    let mut s = alloc::string::String::with_capacity(json.len());
    let _ = escape_json_for_script_to(json, &mut s);
    s
}

/// Escapes a string to be HTML-safe while preserving existing valid character
/// references.
///
/// A valid character reference is identified by the format `&[A-Za-z0-9#]+;`
/// (e.g. `&nbsp;`, `&#39;`). Any sequence matching this format is written
/// directly without escaping. Standalone ampersands and malformed entity
/// syntaxes are escaped to `&amp;`.
///
/// Note that entity *names* are not validated against the HTML spec: any
/// entity-shaped sequence (e.g. `&madeup;`) is preserved as-is. Browsers
/// render unknown references literally, so this is harmless, but callers that
/// require strict output should use [`escape_html_and_coerce_to`] instead.
pub fn escape_allow_character_references_to<W: core::fmt::Write>(
    mut text: &str,
    mut w: W,
) -> core::fmt::Result {
    while let Some(amp_idx) = text.find('&') {
        // First escape and write everything before the ampersand
        escape_html_and_coerce_to(text.get(..amp_idx).unwrap_or(""), &mut w)?;
        text = text.get(amp_idx..).unwrap_or(""); // Now text starts with '&'

        // Scan ahead to check if this starts a valid character reference.
        // It must consist of alphanumeric characters or '#' followed by a semicolon ';'
        let chars = text.chars().skip(1);
        let mut len = 1; // Count '&'
        let mut has_allowed = false;
        let mut terminated = false;

        for c in chars {
            if c.is_ascii_alphanumeric() || c == '#' {
                len += c.len_utf8();
                has_allowed = true;
            } else if c == ';' {
                len += 1;
                terminated = true;
                break;
            } else {
                break;
            }
        }

        if terminated && has_allowed {
            // It's a valid character reference prefix like &nbsp;. Write it as-is.
            w.write_str(text.get(..len).unwrap_or(""))?;
            text = text.get(len..).unwrap_or("");
        } else {
            // Not a valid reference. Escape the '&' and the scanned characters.
            escape_html_and_coerce_to(text.get(..len).unwrap_or(""), &mut w)?;
            text = text.get(len..).unwrap_or("");
        }
    }
    // Escape and write any remaining text
    escape_html_and_coerce_to(text, &mut w)?;
    Ok(())
}

/// Escapes a JSON string to be safely embedded within an inline `<script>` HTML
/// tag.
///
/// Standard JSON may contain `<`, `>`, and `&`, which can break out of a
/// `<script>` tag in HTML (e.g., `</script>`). This function replaces them with
/// their Unicode escape sequences (`<`, `>`, `&`) which are
/// perfectly valid in JavaScript/JSON.
///
/// Additionally, the Unicode line separators U+2028 and U+2029 are escaped to
/// ``/``. They are valid in JSON but were historically invalid
/// inside JavaScript string literals (pre-ES2019 engines), so escaping them
/// makes the output safe for every consumer.
pub fn escape_json_for_script_to<W: core::fmt::Write>(json: &str, mut w: W) -> core::fmt::Result {
    let bytes = json.as_bytes();
    let mut last = 0;
    let mut idx = 0;

    while let Some(i) = find_json_flagged(bytes, idx) {
        idx = i;
        let (rep, skip) = match bytes.get(idx) {
            Some(b'<') => ("\\u003c", 1),
            Some(b'>') => ("\\u003e", 1),
            Some(b'&') => ("\\u0026", 1),
            Some(0xE2) => match bytes.get(idx..idx + 3) {
                Some([0xE2, 0x80, 0xA8]) => ("\\u2028", 3),
                Some([0xE2, 0x80, 0xA9]) => ("\\u2029", 3),
                _ => {
                    // Some other character starting with 0xE2; not special.
                    idx += 1;
                    continue;
                }
            },
            _ => break,
        };
        if idx > last {
            w.write_str(json.get(last..idx).unwrap_or(""))?;
        }
        w.write_str(rep)?;
        idx += skip;
        last = idx;
    }

    if last < bytes.len() {
        w.write_str(json.get(last..).unwrap_or(""))?;
    }
    Ok(())
}

/// A zero-allocation [`core::fmt::Display`] adapter that HTML-escapes the
/// wrapped string as it is formatted.
///
/// This allows interpolating untrusted text directly into any formatting
/// context — including `no_std` fixed buffers — without an intermediate
/// allocation:
///
/// ```rust
/// use safehtml::html_escaped;
/// # #[cfg(feature = "alloc")] {
/// let s = safehtml::alloc::format!("<p>{}</p>", html_escaped("<script>"));
/// assert_eq!(s, "<p>&lt;script&gt;</p>");
/// # }
/// ```
#[derive(Debug, Clone, Copy)]
pub struct HtmlEscaped<'a>(&'a str);

/// Wraps `text` in an [`HtmlEscaped`] display adapter; formatting it produces
/// the HTML-escaped, interchange-coerced representation.
pub fn html_escaped(text: &str) -> HtmlEscaped<'_> {
    HtmlEscaped(text)
}

impl core::fmt::Display for HtmlEscaped<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        escape_html_and_coerce_to(self.0, f)
    }
}

// -----------------------------------------------------------------------------
// Context-specific escapers: JS string literals and unquoted HTML attributes
// -----------------------------------------------------------------------------

/// Lowercase hex digits for `\u00XX` escape sequences.
const HEX_LOWER: &[u8; 16] = b"0123456789abcdef";

/// Returns the absolute index of the first byte at or after `from` flagged in
/// `table`, using a plain linear scan (for the low-volume context escapers).
#[inline]
fn linear_find_flagged(bytes: &[u8], from: usize, table: &[bool; 256]) -> Option<usize> {
    bytes
        .get(from..)?
        .iter()
        .position(|&b| table[b as usize])
        .map(|p| from + p)
}

/// Bytes that must be escaped inside a JavaScript string literal: backslash,
/// both quotes, backtick, angle brackets (blocks `</script>` breakout), C0
/// controls, DEL, and `0xE2` (the UTF-8 lead byte of U+2028/U+2029).
const fn build_js_string_scan_table() -> [bool; 256] {
    let mut table = [false; 256];
    let mut b = 0usize;
    while b < 256 {
        table[b] = matches!(
            b,
            0x00..=0x1F | 0x7F | 0x22 | 0x27 | 0x3C | 0x3E | 0x5C | 0x60
        );
        b += 1;
    }
    table[0xE2] = true; // lead byte of U+2028 / U+2029
    table
}

static JS_STRING_SCAN: [bool; 256] = build_js_string_scan_table();

/// Writes `\u00XX` for a single byte without the `core::fmt` machinery.
#[inline]
fn write_js_hex_escape<W: core::fmt::Write>(w: &mut W, b: u8) -> core::fmt::Result {
    w.write_str("\\u00")?;
    w.write_char(HEX_LOWER[(b >> 4) as usize] as char)?;
    w.write_char(HEX_LOWER[(b & 0x0F) as usize] as char)
}

/// Escapes untrusted text for embedding inside a JavaScript string literal
/// (single-quoted, double-quoted, or template literal) in an inline
/// `<script>` block.
///
/// Escaped: `\` -> `\\`, `\n`/`\r`/`\t` -> their short escapes, both
/// quotes, backtick, `<`, `>`, remaining C0 controls, and DEL as `\u00XX`,
/// and the line separators U+2028/U+2029 as `\u2028`/`\u2029`. Escaping
/// `<` and `>` blocks `</script>` and `<!--` breakouts, so the output cannot
/// terminate the surrounding script element.
///
/// This complements [`escape_json_for_script_to`]: use that for serialized
/// JSON documents, and this for plain text placed inside a string literal.
pub fn escape_js_string_to<W: core::fmt::Write>(text: &str, mut w: W) -> core::fmt::Result {
    let bytes = text.as_bytes();
    let mut last = 0;
    let mut idx = 0;

    while let Some(i) = linear_find_flagged(bytes, idx, &JS_STRING_SCAN) {
        idx = i;
        match bytes.get(idx) {
            Some(&b) if b < 0x80 => {
                if idx > last {
                    w.write_str(text.get(last..idx).unwrap_or(""))?;
                }
                match b {
                    b'\\' => w.write_str("\\\\")?,
                    b'\n' => w.write_str("\\n")?,
                    b'\r' => w.write_str("\\r")?,
                    b'\t' => w.write_str("\\t")?,
                    _ => write_js_hex_escape(&mut w, b)?,
                }
                idx += 1;
                last = idx;
            }
            Some(_) => match bytes.get(idx..idx + 3) {
                Some([0xE2, 0x80, 0xA8]) | Some([0xE2, 0x80, 0xA9]) => {
                    if idx > last {
                        w.write_str(text.get(last..idx).unwrap_or(""))?;
                    }
                    let Some(&third) = bytes.get(idx + 2) else {
                        break;
                    };
                    w.write_str(if third == 0xA8 { "\\u2028" } else { "\\u2029" })?;
                    idx += 3;
                    last = idx;
                }
                _ => {
                    // Some other character starting with 0xE2; not special.
                    idx += 1;
                }
            },
            None => break,
        }
    }

    if last < bytes.len() {
        w.write_str(text.get(last..).unwrap_or(""))?;
    }
    Ok(())
}

/// Allocating convenience form of [`escape_js_string_to`].
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn escape_js_string(text: &str) -> alloc::string::String {
    let mut s = alloc::string::String::with_capacity(text.len());
    let _ = escape_js_string_to(text, &mut s);
    s
}

/// A zero-allocation [`core::fmt::Display`] adapter that JS-string-escapes
/// the wrapped text as it is formatted (see [`escape_js_string_to`]).
#[derive(Debug, Clone, Copy)]
pub struct JsStringEscaped<'a>(&'a str);

/// Wraps `text` in a [`JsStringEscaped`] display adapter.
pub fn js_string_escaped(text: &str) -> JsStringEscaped<'_> {
    JsStringEscaped(text)
}

impl core::fmt::Display for JsStringEscaped<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        escape_js_string_to(self.0, f)
    }
}

/// Bytes that must be escaped in an *unquoted* HTML attribute value: the
/// HTML/interchange set plus the characters that terminate an unquoted value
/// or enable attribute injection (ASCII whitespace, `=`, and backtick).
const fn build_unquoted_attr_scan_table() -> [bool; 256] {
    let mut table = build_scan_table(true);
    table[0x09] = true; // \t
    table[0x0A] = true; // \n
    table[0x0C] = true; // form feed
    table[0x0D] = true; // \r
    table[0x20] = true; // space
    table[0x3D] = true; // =
    table[0x60] = true; // ` (legacy IE attribute delimiter)
    table
}

static UNQUOTED_ATTR_SCAN: [bool; 256] = build_unquoted_attr_scan_table();

/// Escapes text for use as an **unquoted** HTML attribute value, coercing
/// interchange-invalid characters in the same pass.
///
/// [`escape_html_and_coerce_to`] is only safe inside quoted attributes; an
/// unquoted value is additionally terminated by ASCII whitespace and can be
/// broken out of with `=` or the legacy backtick delimiter. This escaper
/// covers the standard five HTML specials plus space, tab, LF, FF, CR, `=`,
/// and `` ` `` (as numeric character references).
///
/// Prefer quoted attributes with [`escape_html_and_coerce_to`] where
/// possible; note an *empty* unquoted value still renders as a malformed
/// attribute and should be avoided by the caller.
pub fn escape_html_unquoted_attribute_to<W: core::fmt::Write>(
    text: &str,
    mut w: W,
) -> core::fmt::Result {
    let bytes = text.as_bytes();
    let mut last = 0;
    let mut idx = 0;

    while let Some(i) = linear_find_flagged(bytes, idx, &UNQUOTED_ATTR_SCAN) {
        idx = i;
        match bytes.get(idx) {
            Some(&b) if b < 0x80 => {
                let rep = match b {
                    b'&' => "&amp;",
                    b'<' => "&lt;",
                    b'>' => "&gt;",
                    b'"' => "&#34;",
                    b'\'' => "&#39;",
                    b' ' => "&#32;",
                    b'\t' => "&#9;",
                    b'\n' => "&#10;",
                    0x0C => "&#12;",
                    b'\r' => "&#13;",
                    b'=' => "&#61;",
                    b'`' => "&#96;",
                    // Every other flagged ASCII byte is an interchange-invalid
                    // control character.
                    _ => "\u{FFFD}",
                };
                if idx > last {
                    w.write_str(text.get(last..idx).unwrap_or(""))?;
                }
                w.write_str(rep)?;
                idx += 1;
                last = idx;
            }
            Some(_) => {
                // Non-ASCII: decode the full character to check validity.
                let Some(c) = text.get(idx..).and_then(|s| s.chars().next()) else {
                    break;
                };
                if is_interchange_invalid(c) {
                    if idx > last {
                        w.write_str(text.get(last..idx).unwrap_or(""))?;
                    }
                    w.write_str("\u{FFFD}")?;
                    idx += c.len_utf8();
                    last = idx;
                } else {
                    idx += c.len_utf8();
                }
            }
            None => break,
        }
    }

    if last < bytes.len() {
        w.write_str(text.get(last..).unwrap_or(""))?;
    }
    Ok(())
}

/// Allocating convenience form of [`escape_html_unquoted_attribute_to`].
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn escape_html_unquoted_attribute(text: &str) -> alloc::string::String {
    let mut s = alloc::string::String::with_capacity(text.len());
    let _ = escape_html_unquoted_attribute_to(text, &mut s);
    s
}

#[cfg(test)]
mod tests {
    use super::*;

    const CHUNK: usize = chunkscan::CHUNK;
    type ChunkPredicate = fn(&[u8; CHUNK]) -> bool;
    type Finder = fn(&[u8], usize) -> Option<usize>;

    /// Verifies the prefilter safety invariant: for every byte flagged in a
    /// scan table, the paired chunk prefilter (SWAR or SIMD, whichever is
    /// active) must fire no matter which lane the byte occupies. (False
    /// positives are allowed; misses are not.)
    #[test]
    fn prefilters_cover_tables() {
        let pairs: [(&[bool; 256], ChunkPredicate, &str); 3] = [
            (&HTML_SCAN, chunkscan::html_may_flag, "html"),
            (
                &INTERCHANGE_SCAN,
                chunkscan::interchange_may_flag,
                "interchange",
            ),
            (&JSON_SCAN, chunkscan::json_may_flag, "json"),
        ];
        for (table, prefilter, name) in pairs {
            for b in 0..=255u8 {
                if !table[b as usize] {
                    continue;
                }
                for lane in 0..CHUNK {
                    // 'A' is unflagged in every table, so only `b` matters.
                    let mut chunk = [b'A'; CHUNK];
                    chunk[lane] = b;
                    assert!(
                        prefilter(&chunk),
                        "{name} prefilter missed flagged byte {b:#04x} in lane {lane}"
                    );
                }
            }
        }
    }

    /// Rebuilding the tables at runtime must reproduce the compile-time
    /// statics, and the HTML/interchange tables must agree with
    /// [`is_interchange_invalid`] for every ASCII byte.
    #[test]
    fn scan_tables_rebuild_and_match_char_classification() {
        assert_eq!(build_scan_table(true), HTML_SCAN);
        assert_eq!(build_scan_table(false), INTERCHANGE_SCAN);
        assert_eq!(build_json_scan_table(), JSON_SCAN);
        assert_eq!(build_js_string_scan_table(), JS_STRING_SCAN);
        assert_eq!(build_unquoted_attr_scan_table(), UNQUOTED_ATTR_SCAN);
        // The unquoted-attribute set is a strict superset of the HTML set.
        for b in 0..256 {
            assert!(!HTML_SCAN[b] || UNQUOTED_ATTR_SCAN[b]);
        }

        for b in 0..=0x7Fu8 {
            let c = b as char;
            let is_special = matches!(c, '&' | '<' | '>' | '"' | '\'');
            assert_eq!(
                INTERCHANGE_SCAN[b as usize],
                is_interchange_invalid(c),
                "interchange table disagrees at {b:#04x}"
            );
            assert_eq!(
                HTML_SCAN[b as usize],
                is_interchange_invalid(c) || is_special,
                "html table disagrees at {b:#04x}"
            );
        }
        // Every non-ASCII byte requires character decoding.
        for b in 0x80..=0xFFu8 {
            assert!(HTML_SCAN[b as usize] && INTERCHANGE_SCAN[b as usize]);
        }
        for b in 0..=0xFFu8 {
            assert_eq!(
                JSON_SCAN[b as usize],
                matches!(b, b'<' | b'>' | b'&' | 0xE2),
                "json table disagrees at {b:#04x}"
            );
        }
    }

    /// The word scanner must agree with a plain byte-at-a-time table scan for
    /// every starting offset, including offsets that split words.
    #[test]
    fn swar_scan_matches_naive_scan() {
        let sample = b"plain text, <b>&amp;</b> \x00 ctl \xE2\x80\xA8 unicode \xC3\xBC tail<";
        let tables: [(&[bool; 256], Finder); 3] = [
            (&HTML_SCAN, find_html_flagged),
            (&INTERCHANGE_SCAN, find_interchange_flagged),
            (&JSON_SCAN, find_json_flagged),
        ];
        for (table, finder) in tables {
            for from in 0..=sample.len() + 2 {
                let naive = sample
                    .get(from..)
                    .and_then(|t| t.iter().position(|&b| table[b as usize]).map(|p| from + p));
                assert_eq!(finder(sample, from), naive, "mismatch at offset {from}");
            }
        }
    }
}