ferromark 0.1.2

Ultra-high-performance Markdown to HTML compiler
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
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
//! HTML output writer with optimized buffer management.
//!
//! Uses md4c's growth strategy: 1.5x + 128-byte alignment.

use crate::Range;
use crate::escape;
use memchr::memchr;

/// Decode HTML entities with CommonMark compliance.
/// - Replaces null bytes (from �) with U+FFFD replacement character
/// - Handles multi-codepoint entities that html_escape doesn't support
fn decode_entities_commonmark(input: &str) -> std::borrow::Cow<'_, str> {
    let decoded = html_escape::decode_html_entities(input);

    // Check if we need to fix null bytes or missing multi-codepoint entities
    let needs_fixup = decoded.contains('\0') ||
        // Check for known multi-codepoint entities that html_escape misses
        input.contains("&ngE;");

    if !needs_fixup {
        return decoded;
    }

    // Need to fix up the result
    let mut result = decoded.into_owned();

    // Replace null bytes with U+FFFD
    if result.contains('\0') {
        result = result.replace('\0', "\u{FFFD}");
    }

    // Fix multi-codepoint entities
    // &ngE; should be ≧ + combining stroke (U+2267 + U+0338)
    if input.contains("&ngE;") {
        result = result.replace('', "\u{2267}\u{0338}");
    }

    std::borrow::Cow::Owned(result)
}

/// HTML output writer with pre-allocated, reusable buffer.
///
/// # Example
/// ```
/// use ferromark::HtmlWriter;
///
/// let mut writer = HtmlWriter::with_capacity_for(1000);
/// writer.write_str("<p>");
/// writer.write_escaped_text(b"Hello <World>");
/// writer.write_str("</p>");
///
/// let html = writer.into_string();
/// assert_eq!(html, "<p>Hello &lt;World&gt;</p>");
/// ```
pub struct HtmlWriter {
    out: Vec<u8>,
}

impl HtmlWriter {
    /// Create a new writer with default capacity.
    #[inline]
    pub fn new() -> Self {
        Self {
            out: Vec::with_capacity(1024),
        }
    }

    /// Create with pre-allocated capacity based on expected input size.
    ///
    /// Typical HTML is ~1.25x input size; we reserve extra for safety.
    #[inline]
    pub fn with_capacity_for(input_len: usize) -> Self {
        let capacity = input_len + input_len / 4;
        Self {
            out: Vec::with_capacity(capacity),
        }
    }

    /// Create with explicit capacity.
    #[inline]
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            out: Vec::with_capacity(capacity),
        }
    }

    /// Grow buffer using md4c's strategy: 1.5x + 128-byte alignment.
    #[cold]
    #[inline(never)]
    #[allow(dead_code)]
    fn grow(&mut self, needed: usize) {
        let new_cap = ((self.out.len() + needed) * 3 / 2 + 128) & !127;
        self.out
            .reserve(new_cap.saturating_sub(self.out.capacity()));
    }

    /// Ensure capacity for additional bytes.
    #[inline]
    #[allow(dead_code)]
    fn ensure_capacity(&mut self, additional: usize) {
        if self.out.len() + additional > self.out.capacity() {
            self.grow(additional);
        }
    }

    /// Write raw bytes without escaping.
    #[inline]
    pub fn write_bytes(&mut self, bytes: &[u8]) {
        self.out.extend_from_slice(bytes);
    }

    /// Write a static string (compile-time known).
    #[inline]
    pub fn write_str(&mut self, s: &'static str) {
        self.out.extend_from_slice(s.as_bytes());
    }

    /// Write a dynamic string without escaping.
    #[inline]
    pub fn write_string(&mut self, s: &str) {
        self.out.extend_from_slice(s.as_bytes());
    }

    /// Write a single byte.
    #[inline]
    pub fn write_byte(&mut self, b: u8) {
        self.out.push(b);
    }

    /// Write text with HTML escaping (for text content).
    #[inline]
    pub fn write_escaped_text(&mut self, text: &[u8]) {
        escape::escape_text_into(&mut self.out, text);
    }

    /// Write text with entity decoding and HTML escaping (for inline text content).
    /// First decodes HTML entities, then escapes for output.
    #[inline]
    pub fn write_text_with_entities(&mut self, text: &[u8]) {
        if memchr(b'&', text).is_none() {
            escape::escape_text_into(&mut self.out, text);
            return;
        }
        // First decode HTML entities
        let text_str = core::str::from_utf8(text).unwrap_or("");
        let decoded = decode_entities_commonmark(text_str);
        // Then HTML-escape the result
        escape::escape_text_into(&mut self.out, decoded.as_bytes());
    }

    /// Write text with HTML escaping from a range.
    #[inline]
    pub fn write_escaped_range(&mut self, input: &[u8], range: Range) {
        escape::escape_text_into(&mut self.out, range.slice(input));
    }

    /// Write attribute value with full escaping (including quotes).
    #[inline]
    pub fn write_escaped_attr(&mut self, attr: &[u8]) {
        escape::escape_full_into(&mut self.out, attr);
    }

    /// Write URL/title with backslash escape processing and HTML attribute escaping.
    /// Backslash-escaped punctuation characters have the backslash removed.
    #[inline]
    pub fn write_escaped_link_attr(&mut self, attr: &[u8]) {
        let mut pos = 0;
        while pos < attr.len() {
            if attr[pos] == b'\\' && pos + 1 < attr.len() && is_link_escapable(attr[pos + 1]) {
                // Skip backslash, write escaped char (with HTML escaping)
                pos += 1;
                escape::escape_full_into(&mut self.out, &attr[pos..pos + 1]);
                pos += 1;
            } else {
                // Find next backslash or end
                let start = pos;
                while pos < attr.len()
                    && !(attr[pos] == b'\\'
                        && pos + 1 < attr.len()
                        && is_link_escapable(attr[pos + 1]))
                {
                    pos += 1;
                }
                escape::escape_full_into(&mut self.out, &attr[start..pos]);
            }
        }
    }

    /// Write link title with entity decoding, backslash escape processing, and HTML escaping.
    #[inline]
    pub fn write_link_title(&mut self, title: &[u8]) {
        if memchr(b'&', title).is_none() {
            self.write_escaped_link_attr(title);
            return;
        }

        // First decode entities
        let title_str = core::str::from_utf8(title).unwrap_or("");
        let decoded = decode_entities_commonmark(title_str);
        let decoded_bytes = decoded.as_bytes();

        if memchr(b'\\', decoded_bytes).is_none() {
            escape::escape_full_into(&mut self.out, decoded_bytes);
            return;
        }

        // Then process backslash escapes and HTML-escape
        let mut pos = 0;
        while pos < decoded_bytes.len() {
            if decoded_bytes[pos] == b'\\'
                && pos + 1 < decoded_bytes.len()
                && is_link_escapable(decoded_bytes[pos + 1])
            {
                // Skip backslash, write escaped char (with HTML escaping)
                pos += 1;
                escape::escape_full_into(&mut self.out, &decoded_bytes[pos..pos + 1]);
                pos += 1;
            } else {
                // Find next backslash or end
                let start = pos;
                while pos < decoded_bytes.len()
                    && !(decoded_bytes[pos] == b'\\'
                        && pos + 1 < decoded_bytes.len()
                        && is_link_escapable(decoded_bytes[pos + 1]))
                {
                    pos += 1;
                }
                escape::escape_full_into(&mut self.out, &decoded_bytes[start..pos]);
            }
        }
    }

    /// Write autolink URL with percent-encoding and HTML escaping.
    /// Used for autolink hrefs per CommonMark spec.
    #[inline]
    pub fn write_url_encoded(&mut self, url: &[u8]) {
        escape::url_encode_then_html_escape(&mut self.out, url);
    }

    /// Write link destination with backslash escape processing and URL encoding.
    /// Used for link destinations in `[text](url)` syntax.
    #[inline]
    pub fn write_link_url(&mut self, url: &[u8]) {
        escape::url_escape_link_destination(&mut self.out, url);
    }

    /// Write a newline.
    #[inline]
    pub fn newline(&mut self) {
        self.out.push(b'\n');
    }

    /// Current output length.
    #[inline]
    pub fn len(&self) -> usize {
        self.out.len()
    }

    /// Check if output is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.out.is_empty()
    }

    /// Clear output for reuse (keeps capacity).
    #[inline]
    pub fn clear(&mut self) {
        self.out.clear();
    }

    /// Get output as byte slice.
    #[inline]
    pub fn as_bytes(&self) -> &[u8] {
        &self.out
    }

    /// Get output as str (assumes valid UTF-8).
    #[inline]
    pub fn as_str(&self) -> &str {
        // SAFETY: We only write valid UTF-8 (ASCII tags + escaped content)
        unsafe { std::str::from_utf8_unchecked(&self.out) }
    }

    /// Take ownership of output buffer.
    #[inline]
    pub fn into_vec(self) -> Vec<u8> {
        self.out
    }

    /// Take ownership as String.
    #[inline]
    pub fn into_string(self) -> String {
        // SAFETY: We only write valid UTF-8
        unsafe { String::from_utf8_unchecked(self.out) }
    }

    /// Get mutable reference to internal buffer.
    ///
    /// Use with caution - allows bypassing escaping.
    #[inline]
    pub fn buffer_mut(&mut self) -> &mut Vec<u8> {
        &mut self.out
    }

    // --- HTML Tag Helpers ---

    /// Write opening tag: `<tagname>`
    #[inline]
    pub fn open_tag(&mut self, tag: &'static str) {
        self.write_byte(b'<');
        self.write_str(tag);
        self.write_byte(b'>');
    }

    /// Write closing tag: `</tagname>`
    #[inline]
    pub fn close_tag(&mut self, tag: &'static str) {
        self.write_str("</");
        self.write_str(tag);
        self.write_byte(b'>');
    }

    /// Write self-closing tag: `<tagname />`
    #[inline]
    pub fn self_closing_tag(&mut self, tag: &'static str) {
        self.write_byte(b'<');
        self.write_str(tag);
        self.write_str(" />");
    }

    /// Write opening tag with newline: `<tagname>\n`
    #[inline]
    pub fn open_tag_nl(&mut self, tag: &'static str) {
        self.open_tag(tag);
        self.newline();
    }

    /// Write closing tag with newline: `</tagname>\n`
    #[inline]
    pub fn close_tag_nl(&mut self, tag: &'static str) {
        self.close_tag(tag);
        self.newline();
    }

    // --- Common HTML Elements ---

    /// Write paragraph start: `<p>`
    #[inline]
    pub fn paragraph_start(&mut self) {
        self.write_str("<p>");
    }

    /// Write paragraph end: `</p>\n`
    #[inline]
    pub fn paragraph_end(&mut self) {
        self.write_str("</p>\n");
    }

    /// Write heading start: `<hN>`
    #[inline]
    pub fn heading_start(&mut self, level: u8) {
        debug_assert!((1..=6).contains(&level));
        self.write_str("<h");
        self.write_byte(b'0' + level);
        self.write_byte(b'>');
    }

    /// Write heading start with ID: `<hN id="slug">`
    #[inline]
    pub fn heading_start_with_id(&mut self, level: u8, id: &str) {
        debug_assert!((1..=6).contains(&level));
        self.write_str("<h");
        self.write_byte(b'0' + level);
        self.write_str(" id=\"");
        self.write_string(id);
        self.write_str("\">");
    }

    /// Write heading end: `</hN>\n`
    #[inline]
    pub fn heading_end(&mut self, level: u8) {
        debug_assert!((1..=6).contains(&level));
        self.write_str("</h");
        self.write_byte(b'0' + level);
        self.write_str(">\n");
    }

    /// Write code block start with optional language class.
    /// Processes backslash escapes in the language string.
    #[inline]
    pub fn code_block_start(&mut self, lang: Option<&[u8]>) {
        match lang {
            Some(l) if !l.is_empty() => {
                let first = Self::first_word(l);
                if first.is_empty() {
                    self.write_str("<pre><code>");
                    return;
                }
                self.write_str("<pre><code class=\"language-");
                // Decode entities and escape for attribute
                self.write_info_string_attr(first);
                self.write_str("\">");
            }
            _ => {
                self.write_str("<pre><code>");
            }
        }
    }

    /// Write fenced code info string with entity decoding and attribute escaping.
    #[inline]
    pub fn write_info_string_attr(&mut self, info: &[u8]) {
        // First unescape backslash escapes
        let unescaped = Self::unescape_backslashes(info);
        // Then decode HTML entities
        let info_str = core::str::from_utf8(&unescaped).unwrap_or("");
        let decoded = decode_entities_commonmark(info_str);
        // Then HTML-escape for attribute context
        escape::escape_full_into(&mut self.out, decoded.as_bytes());
    }

    fn unescape_backslashes(input: &[u8]) -> Vec<u8> {
        let mut out = Vec::with_capacity(input.len());
        let mut i = 0usize;
        while i < input.len() {
            if input[i] == b'\\' && i + 1 < input.len() && Self::is_escapable(input[i + 1]) {
                out.push(input[i + 1]);
                i += 2;
            } else {
                out.push(input[i]);
                i += 1;
            }
        }
        out
    }

    #[inline]
    fn is_escapable(b: u8) -> bool {
        matches!(
            b,
            b'!' | b'"'
                | b'#'
                | b'$'
                | b'%'
                | b'&'
                | b'\''
                | b'('
                | b')'
                | b'*'
                | b'+'
                | b','
                | b'-'
                | b'.'
                | b'/'
                | b':'
                | b';'
                | b'<'
                | b'='
                | b'>'
                | b'?'
                | b'@'
                | b'['
                | b'\\'
                | b']'
                | b'^'
                | b'_'
                | b'`'
                | b'{'
                | b'|'
                | b'}'
                | b'~'
        )
    }

    #[inline]
    fn is_html_whitespace(b: u8) -> bool {
        matches!(b, b' ' | b'\t' | b'\n' | b'\r' | b'\x0c')
    }

    fn first_word(info: &[u8]) -> &[u8] {
        let mut end = 0usize;
        while end < info.len() && !Self::is_html_whitespace(info[end]) {
            end += 1;
        }
        &info[..end]
    }

    /// Write code block end: `</code></pre>\n`
    #[inline]
    pub fn code_block_end(&mut self) {
        self.write_str("</code></pre>\n");
    }

    /// Write thematic break: `<hr />\n`
    #[inline]
    pub fn thematic_break(&mut self) {
        self.write_str("<hr />\n");
    }

    /// Write blockquote start: `<blockquote>\n`
    #[inline]
    pub fn blockquote_start(&mut self) {
        self.write_str("<blockquote>\n");
    }

    /// Write blockquote end: `</blockquote>\n`
    #[inline]
    pub fn blockquote_end(&mut self) {
        self.write_str("</blockquote>\n");
    }

    /// Write callout/admonition start.
    #[inline]
    pub fn callout_start(&mut self, callout: crate::block::CalloutType) {
        self.write_str("<div class=\"markdown-alert markdown-alert-");
        self.write_str(callout.css_suffix());
        self.write_str("\">\n<p class=\"markdown-alert-title\">");
        self.write_str(callout.title());
        self.write_str("</p>\n");
    }

    /// Write callout/admonition end.
    #[inline]
    pub fn callout_end(&mut self) {
        self.write_str("</div>\n");
    }

    /// Write list start (unordered): `<ul>\n`
    #[inline]
    pub fn ul_start(&mut self) {
        self.write_str("<ul>\n");
    }

    /// Write list end (unordered): `</ul>\n`
    #[inline]
    pub fn ul_end(&mut self) {
        self.write_str("</ul>\n");
    }

    /// Write list start (ordered): `<ol>\n` or `<ol start="N">\n`
    #[inline]
    pub fn ol_start(&mut self, start: Option<u32>) {
        match start {
            Some(n) if n != 1 => {
                self.write_str("<ol start=\"");
                self.write_u32(n);
                self.write_str("\">\n");
            }
            _ => {
                self.write_str("<ol>\n");
            }
        }
    }

    /// Write list end (ordered): `</ol>\n`
    #[inline]
    pub fn ol_end(&mut self) {
        self.write_str("</ol>\n");
    }

    /// Write list item start: `<li>`
    #[inline]
    pub fn li_start(&mut self) {
        self.write_str("<li>");
    }

    /// Write list item end: `</li>\n`
    #[inline]
    pub fn li_end(&mut self) {
        self.write_str("</li>\n");
    }

    // --- Table Elements ---

    /// Write table start: `<table>\n`
    #[inline]
    pub fn table_start(&mut self) {
        self.write_str("<table>\n");
    }

    /// Write table end: `</table>\n`
    #[inline]
    pub fn table_end(&mut self) {
        self.write_str("</table>\n");
    }

    /// Write thead start: `<thead>\n`
    #[inline]
    pub fn thead_start(&mut self) {
        self.write_str("<thead>\n");
    }

    /// Write thead end: `</thead>\n`
    #[inline]
    pub fn thead_end(&mut self) {
        self.write_str("</thead>\n");
    }

    /// Write tbody start: `<tbody>\n`
    #[inline]
    pub fn tbody_start(&mut self) {
        self.write_str("<tbody>\n");
    }

    /// Write tbody end: `</tbody>\n`
    #[inline]
    pub fn tbody_end(&mut self) {
        self.write_str("</tbody>\n");
    }

    /// Write tr start: `<tr>\n`
    #[inline]
    pub fn tr_start(&mut self) {
        self.write_str("<tr>\n");
    }

    /// Write tr end: `</tr>\n`
    #[inline]
    pub fn tr_end(&mut self) {
        self.write_str("</tr>\n");
    }

    /// Write th start with optional alignment: `<th>` or `<th align="...">`
    #[inline]
    pub fn th_start(&mut self, align: crate::block::Alignment) {
        match align {
            crate::block::Alignment::None => self.write_str("<th>"),
            crate::block::Alignment::Left => self.write_str("<th align=\"left\">"),
            crate::block::Alignment::Center => self.write_str("<th align=\"center\">"),
            crate::block::Alignment::Right => self.write_str("<th align=\"right\">"),
        }
    }

    /// Write th end: `</th>\n`
    #[inline]
    pub fn th_end(&mut self) {
        self.write_str("</th>\n");
    }

    /// Write td start with optional alignment: `<td>` or `<td align="...">`
    #[inline]
    pub fn td_start(&mut self, align: crate::block::Alignment) {
        match align {
            crate::block::Alignment::None => self.write_str("<td>"),
            crate::block::Alignment::Left => self.write_str("<td align=\"left\">"),
            crate::block::Alignment::Center => self.write_str("<td align=\"center\">"),
            crate::block::Alignment::Right => self.write_str("<td align=\"right\">"),
        }
    }

    /// Write td end: `</td>\n`
    #[inline]
    pub fn td_end(&mut self) {
        self.write_str("</td>\n");
    }

    /// Write inline code: `<code>escaped_content</code>`
    #[inline]
    pub fn inline_code(&mut self, content: &[u8]) {
        self.write_str("<code>");
        self.write_escaped_text(content);
        self.write_str("</code>");
    }

    /// Write emphasis start: `<em>`
    #[inline]
    pub fn em_start(&mut self) {
        self.write_str("<em>");
    }

    /// Write emphasis end: `</em>`
    #[inline]
    pub fn em_end(&mut self) {
        self.write_str("</em>");
    }

    /// Write strong start: `<strong>`
    #[inline]
    pub fn strong_start(&mut self) {
        self.write_str("<strong>");
    }

    /// Write strong end: `</strong>`
    #[inline]
    pub fn strong_end(&mut self) {
        self.write_str("</strong>");
    }

    /// Write strikethrough start: `<del>`
    #[inline]
    pub fn del_start(&mut self) {
        self.write_str("<del>");
    }

    /// Write strikethrough end: `</del>`
    #[inline]
    pub fn del_end(&mut self) {
        self.write_str("</del>");
    }

    /// Write link start: `<a href="url">`
    #[inline]
    pub fn link_start(&mut self, url: &[u8], title: Option<&[u8]>) {
        self.write_str("<a href=\"");
        self.write_escaped_attr(url);
        if let Some(t) = title {
            self.write_str("\" title=\"");
            self.write_escaped_attr(t);
        }
        self.write_str("\">");
    }

    /// Write link end: `</a>`
    #[inline]
    pub fn link_end(&mut self) {
        self.write_str("</a>");
    }

    /// Write line break: `<br />\n`
    #[inline]
    pub fn line_break(&mut self) {
        self.write_str("<br />\n");
    }

    /// Write raw HTML with GFM disallowed-tag filtering.
    /// Replaces `<` with `&lt;` before disallowed tag names.
    pub fn write_html_filtered(&mut self, html: &[u8]) {
        let mut pos = 0;
        while pos < html.len() {
            if let Some(offset) = memchr(b'<', &html[pos..]) {
                let abs = pos + offset;
                if abs + 1 < html.len() && is_disallowed_tag_at(html, abs) {
                    self.out.extend_from_slice(&html[pos..abs]);
                    self.out.extend_from_slice(b"&lt;");
                    pos = abs + 1;
                } else {
                    // Include the '<' and advance past it
                    self.out.extend_from_slice(&html[pos..abs + 1]);
                    pos = abs + 1;
                }
            } else {
                self.out.extend_from_slice(&html[pos..]);
                break;
            }
        }
    }

    /// Write a u32 as decimal.
    fn write_u32(&mut self, mut n: u32) {
        if n == 0 {
            self.write_byte(b'0');
            return;
        }

        let mut buf = [0u8; 10]; // Max digits for u32
        let mut i = buf.len();

        while n > 0 {
            i -= 1;
            buf[i] = b'0' + (n % 10) as u8;
            n /= 10;
        }

        self.write_bytes(&buf[i..]);
    }
}

/// GFM disallowed raw HTML tag names (lowercase).
const DISALLOWED_HTML_TAGS: [&[u8]; 9] = [
    b"title",
    b"textarea",
    b"style",
    b"xmp",
    b"iframe",
    b"noembed",
    b"noframes",
    b"script",
    b"plaintext",
];

/// Check whether `html[pos]` (which must be `b'<'`) starts a disallowed tag.
#[inline]
fn is_disallowed_tag_at(html: &[u8], pos: usize) -> bool {
    let rest = &html[pos + 1..];
    let rest = if rest.first() == Some(&b'/') {
        &rest[1..]
    } else {
        rest
    };
    for tag in &DISALLOWED_HTML_TAGS {
        if rest.len() >= tag.len() && rest[..tag.len()].eq_ignore_ascii_case(tag) {
            // Character after tag name must be whitespace, >, /, or end of input
            if rest.len() == tag.len() {
                return true;
            }
            match rest[tag.len()] {
                b' ' | b'\t' | b'\n' | b'\r' | b'>' | b'/' => return true,
                _ => {}
            }
        }
    }
    false
}

/// Characters that can be escaped with backslash in CommonMark links.
#[inline]
fn is_link_escapable(b: u8) -> bool {
    matches!(
        b,
        b'!' | b'"'
            | b'#'
            | b'$'
            | b'%'
            | b'&'
            | b'\''
            | b'('
            | b')'
            | b'*'
            | b'+'
            | b','
            | b'-'
            | b'.'
            | b'/'
            | b':'
            | b';'
            | b'<'
            | b'='
            | b'>'
            | b'?'
            | b'@'
            | b'['
            | b'\\'
            | b']'
            | b'^'
            | b'_'
            | b'`'
            | b'{'
            | b'|'
            | b'}'
            | b'~'
    )
}

impl Default for HtmlWriter {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Write for HtmlWriter {
    fn write_str(&mut self, s: &str) -> std::fmt::Result {
        self.out.extend_from_slice(s.as_bytes());
        Ok(())
    }
}

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

    #[test]
    fn test_writer_new() {
        let writer = HtmlWriter::new();
        assert!(writer.is_empty());
    }

    #[test]
    fn test_writer_capacity() {
        let writer = HtmlWriter::with_capacity_for(1000);
        assert!(writer.out.capacity() >= 1250);
    }

    #[test]
    fn test_writer_write_str() {
        let mut writer = HtmlWriter::new();
        writer.write_str("<p>");
        assert_eq!(writer.as_str(), "<p>");
    }

    #[test]
    fn test_writer_escaped_text() {
        let mut writer = HtmlWriter::new();
        writer.write_escaped_text(b"<script>");
        assert_eq!(writer.as_str(), "&lt;script&gt;");
    }

    #[test]
    fn test_writer_paragraph() {
        let mut writer = HtmlWriter::new();
        writer.paragraph_start();
        writer.write_escaped_text(b"Hello");
        writer.paragraph_end();
        assert_eq!(writer.as_str(), "<p>Hello</p>\n");
    }

    #[test]
    fn test_writer_heading() {
        let mut writer = HtmlWriter::new();
        writer.heading_start(1);
        writer.write_escaped_text(b"Title");
        writer.heading_end(1);
        assert_eq!(writer.as_str(), "<h1>Title</h1>\n");
    }

    #[test]
    fn test_writer_heading_levels() {
        for level in 1..=6 {
            let mut writer = HtmlWriter::new();
            writer.heading_start(level);
            writer.heading_end(level);
            let expected = format!("<h{level}></h{level}>\n");
            assert_eq!(writer.as_str(), expected);
        }
    }

    #[test]
    fn test_writer_code_block() {
        let mut writer = HtmlWriter::new();
        writer.code_block_start(Some(b"rust"));
        writer.write_escaped_text(b"fn main() {}");
        writer.code_block_end();
        assert_eq!(
            writer.as_str(),
            "<pre><code class=\"language-rust\">fn main() {}</code></pre>\n"
        );
    }

    #[test]
    fn test_writer_code_block_no_lang() {
        let mut writer = HtmlWriter::new();
        writer.code_block_start(None);
        writer.write_escaped_text(b"code");
        writer.code_block_end();
        assert_eq!(writer.as_str(), "<pre><code>code</code></pre>\n");
    }

    #[test]
    fn test_writer_thematic_break() {
        let mut writer = HtmlWriter::new();
        writer.thematic_break();
        assert_eq!(writer.as_str(), "<hr />\n");
    }

    #[test]
    fn test_writer_link() {
        let mut writer = HtmlWriter::new();
        writer.link_start(b"https://example.com", None);
        writer.write_escaped_text(b"link");
        writer.link_end();
        assert_eq!(writer.as_str(), "<a href=\"https://example.com\">link</a>");
    }

    #[test]
    fn test_writer_link_with_title() {
        let mut writer = HtmlWriter::new();
        writer.link_start(b"https://example.com", Some(b"My Title"));
        writer.write_escaped_text(b"link");
        writer.link_end();
        assert_eq!(
            writer.as_str(),
            "<a href=\"https://example.com\" title=\"My Title\">link</a>"
        );
    }

    #[test]
    fn test_writer_link_escape_url() {
        let mut writer = HtmlWriter::new();
        writer.link_start(b"https://example.com?a=1&b=2", None);
        writer.link_end();
        assert_eq!(
            writer.as_str(),
            "<a href=\"https://example.com?a=1&amp;b=2\"></a>"
        );
    }

    #[test]
    fn test_writer_clear_reuse() {
        let mut writer = HtmlWriter::new();
        writer.write_str("first");
        let cap1 = writer.out.capacity();

        writer.clear();
        assert!(writer.is_empty());
        assert_eq!(writer.out.capacity(), cap1);

        writer.write_str("second");
        assert_eq!(writer.as_str(), "second");
    }

    #[test]
    fn test_writer_into_string() {
        let mut writer = HtmlWriter::new();
        writer.write_str("<p>Hello</p>");
        let s = writer.into_string();
        assert_eq!(s, "<p>Hello</p>");
    }

    #[test]
    fn test_writer_ol_with_start() {
        let mut writer = HtmlWriter::new();
        writer.ol_start(Some(5));
        writer.ol_end();
        assert_eq!(writer.as_str(), "<ol start=\"5\">\n</ol>\n");
    }

    #[test]
    fn test_writer_ol_default_start() {
        let mut writer = HtmlWriter::new();
        writer.ol_start(Some(1));
        writer.ol_end();
        assert_eq!(writer.as_str(), "<ol>\n</ol>\n");
    }

    #[test]
    fn test_write_u32() {
        let mut writer = HtmlWriter::new();
        writer.write_u32(0);
        assert_eq!(writer.as_str(), "0");

        writer.clear();
        writer.write_u32(42);
        assert_eq!(writer.as_str(), "42");

        writer.clear();
        writer.write_u32(1234567890);
        assert_eq!(writer.as_str(), "1234567890");
    }
}