html-to-markdown-rs 3.18.2

High-performance HTML to Markdown converter using the astral-tl parser. Part of the Xberg ecosystem.
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
//! HTML preprocessing and normalization.
//!
//! Functions for preprocessing HTML before conversion, including script/style stripping,
//! tag repair, and malformed HTML handling.

use std::borrow::Cow;
use std::str;

use super::kept_scripts::{ESCAPED_LT, KeptScripts, push_owner_mark};
use super::markup::{
    find_html_comment_end, find_tag_end, is_json_ld_script_open_tag, matches_end_tag_start, matches_tag_start,
};
use super::structured_data::push_without_standalone_slashes;
use super::visibility::{after_bogus_comment, is_bogus_comment_marker};

/// If the `<` at `idx` starts a bogus comment (see `strip_bogus_comments`), return the position
/// after it. The caller has read a real comment (`<!--`) before.
///
/// ~keep The first pass over raw-text elements reads a bogus comment with this function, so a
/// ~keep `<textarea>` in `<? ... >` starts nothing there. It reads `<![CDATA[` as a bogus
/// ~keep comment too: it reads no markup inside `<svg>`, and outside foreign content the
/// ~keep tokenizer ends the comment at the first `>`.
fn bogus_comment_end(bytes: &[u8], idx: usize) -> Option<usize> {
    let next = *bytes.get(idx + 1)?;
    is_bogus_comment_marker(bytes, idx, bytes.len(), next, &bytes[idx + 2..]).then(|| after_bogus_comment(bytes, idx))
}

/// If `idx` starts an `<svg`/`</svg` tag, adjust `svg_depth` accordingly and return the index
/// just past the tag. Returns `None` when `idx` does not start an svg tag (or the tag is
/// unterminated), in which case the caller's scan is unaffected.
///
/// ~keep A start tag that ends with `/>` opens nothing: the parser and the tree builder end the
/// ~keep element there, so what follows `<svg/>` is outside it and the passes read it.
pub(super) fn track_svg_tag(bytes: &[u8], idx: usize, svg_depth: &mut usize) -> Option<usize> {
    if matches_tag_start(bytes, idx + 1, b"svg") {
        if let Some(open_end) = find_tag_end(bytes, idx + 1 + b"svg".len()) {
            if !bytes[idx..open_end].ends_with(b"/>") {
                *svg_depth += 1;
            }
            return Some(open_end);
        }
    } else if matches_end_tag_start(bytes, idx + 1, b"svg") {
        if let Some(close_end) = find_tag_end(bytes, idx + 2 + b"svg".len()) {
            if *svg_depth > 0 {
                *svg_depth = svg_depth.saturating_sub(1);
            }
            return Some(close_end);
        }
    }
    None
}

/// What the first pass does with the content of a raw-text element.
#[derive(Clone, Copy, PartialEq, Eq)]
enum RawTextContent {
    /// The element is removed (`style`).
    Removed,
    /// The element is removed, but a structured data script is kept for the metadata.
    RemovedUnlessStructuredData,
    /// The element is kept and its content is text (`textarea`).
    Kept,
}

/// What the first pass did with a raw-text element.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Outcome {
    /// The element stays as the page has it.
    Unchanged,
    /// The element is removed.
    Removed,
    /// The element is written again, with its content as text.
    Kept,
}

/// A candidate raw-text element: `idx` is its `<`, `last` is the end of the copied input and
/// `name` is the tag name in lower case. `mark` is the number of its owner mark, when it is a
/// kept script that has one.
struct RawTextElement<'a> {
    input: &'a str,
    idx: usize,
    last: usize,
    name: &'a str,
    content: RawTextContent,
    preformatted: bool,
    mark: Option<usize>,
}

/// Remove or rewrite the raw-text element that starts at `element.idx`, appending the input
/// before it to `*output` (lazily allocated). `tag_end` is the end of its start tag;
/// `close_start` and `close_idx` are the two ends of its end tag.
///
/// Outside preformatted content, a removed `style` leaves one space between non-whitespace neighbors.
/// A removed script leaves none (#827). A kept element is written by `push_kept_element` and adds no space: the walker reads the
/// white space on its two sides as if the element were not there.
///
/// Returns what it did. A `textarea` with no `<` needs no change and is not written again.
fn strip_raw_text_element(
    element: &RawTextElement<'_>,
    tag_end: usize,
    (close_start, close_idx): (usize, usize),
    output: &mut Option<String>,
) -> Outcome {
    let bytes = element.input.as_bytes();
    let name = element.name.as_bytes();
    let body = &element.input[tag_end..close_start];

    let kept = match element.content {
        RawTextContent::Removed => false,
        RawTextContent::RemovedUnlessStructuredData => is_json_ld_script_open_tag(&element.input[element.idx..tag_end]),
        // ~keep A `textarea` with no `<` in it is already one text for the parser.
        RawTextContent::Kept if !body.contains('<') => return Outcome::Unchanged,
        RawTextContent::Kept => true,
    };

    let out = output.get_or_insert_with(|| String::with_capacity(element.input.len()));
    out.push_str(&element.input[element.last..element.idx]);
    if kept {
        // ~keep A kept element adds no space of its own: the white space around it is the page's.
        let attributes = &element.input[element.idx + 1 + name.len()..tag_end];
        push_kept_element(out, element.name, element.mark, attributes, body);
        return Outcome::Kept;
    }
    if element.content == RawTextContent::Removed
        && !element.preformatted
        && element.idx > 0
        && close_idx < bytes.len()
        && !bytes[element.idx - 1].is_ascii_whitespace()
        && !bytes[close_idx].is_ascii_whitespace()
    {
        out.push(' ');
    }
    Outcome::Removed
}

/// Write a kept raw-text element in a form the parser reads as one element with one text.
/// `mark` is the number of its owner mark, `attributes` is the open tag after its name, with
/// the `>`, and `body` is the content.
///
/// ~keep The parser has no raw-text rule: a `<p>` in the content would open an element that
/// ~keep holds the rest of the page, so each `<` of the body is written as `&lt;`. Nothing else
/// ~keep of the body changes, so this function changes nothing in a body that it wrote: the
/// ~keep pass reads a repaired page as it reads the page of the author. `KeptScripts` gives the
/// ~keep text of a script as written. The parser also closes an element only with an end tag of
/// ~keep the same spelling, so the two tag names are written in one spelling.
fn push_kept_element(out: &mut String, name: &str, mark: Option<usize>, attributes: &str, body: &str) {
    out.push('<');
    out.push_str(name);
    push_kept_attributes(out, mark, attributes);
    let mut rest = body;
    while let Some(at) = memchr::memchr(b'<', rest.as_bytes()) {
        out.push_str(&rest[..at]);
        out.push_str(ESCAPED_LT);
        rest = &rest[at + 1..];
    }
    out.push_str(rest);
    out.push_str("</");
    out.push_str(name);
    out.push('>');
}

/// Write the start tag of a kept element after its name: the owner mark with the number
/// `mark`, then `attributes`, the open tag after its name, with the `>`.
///
/// ~keep The parser reads only white space after the name, so a `/` or a form feed there is
/// ~keep written as a space. The parser also ends a start tag at a `/` that stands alone
/// ~keep between two attributes, and the rest of the tag is text of the page then. The HTML
/// ~keep rule reads such a `/` as nothing, so it is not written: the repair of a script with no
/// ~keep end tag has the rule (`push_without_standalone_slashes`).
fn push_kept_attributes(out: &mut String, mark: Option<usize>, attributes: &str) {
    if let Some(mark) = mark {
        push_owner_mark(out, mark);
    }
    let attributes = match attributes.as_bytes().first() {
        Some(b'/' | b'\x0C') => {
            out.push(' ');
            &attributes[1..]
        }
        _ => attributes,
    };
    push_without_standalone_slashes(out, attributes);
}

/// The raw-text elements the first pass reads, each with what happens to its content.
const FIRST_PASS_ELEMENTS: [(&str, RawTextContent); 3] = [
    ("script", RawTextContent::RemovedUnlessStructuredData),
    ("style", RawTextContent::Removed),
    ("textarea", RawTextContent::Kept),
];

/// The name of the raw-text element `FIRST_PASS_ELEMENTS[slot]` when the two passes remove
/// it (`script`, `style`). `None` for an element that is kept.
pub(super) fn removed_element_name(slot: usize) -> Option<&'static str> {
    let (name, content) = FIRST_PASS_ELEMENTS[slot];
    (content != RawTextContent::Kept).then_some(name)
}

/// Strip script and style tags and their content from HTML, and write the content of a
/// structured data script and of a `textarea` as text.
///
/// ~keep This pass writes no owner mark. The pass over a repaired page is this one: the tree
/// ~keep builder writes the marks of the first page again, and a second mark on one script
/// ~keep would have no record.
pub fn strip_script_and_style_tags(input: &str) -> Cow<'_, str> {
    FirstPass::new(input, |_| {}).run().0
}

/// [`strip_script_and_style_tags`], with an owner mark in the start tag of each kept script
/// whose escaped text holds `&lt;`, and with the kept scripts that the reader of the
/// structured data asks for the text as written.
pub fn strip_script_and_style_tags_with_kept_scripts(input: &str) -> (Cow<'_, str>, KeptScripts) {
    #[cfg(feature = "metadata")]
    let kept_scripts = KeptScripts::with_marks();
    #[cfg(not(feature = "metadata"))]
    let kept_scripts = KeptScripts::new();
    FirstPass::with_kept_scripts(input, kept_scripts, |_| {}).run()
}

/// [`strip_script_and_style_tags_with_kept_scripts`] for the second pass over a page:
/// `kept_scripts` is what `KeptScripts::reserving_owner_names_of` gives, so no owner mark has a
/// number that the cleaned page of the first pass has.
#[cfg(feature = "metadata")]
pub fn strip_script_and_style_tags_for_second_pass(
    input: &str,
    kept_scripts: KeptScripts,
) -> (Cow<'_, str>, KeptScripts) {
    FirstPass::with_kept_scripts(input, kept_scripts, |_| {}).run()
}

/// A read of the first pass or of the second pass that a test counts.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum PassRead {
    /// A `<` of the page.
    Markup,
    /// A search for the end tag of a raw-text element. It can read to the end of the page.
    EndTagSearch,
    /// A search for the end of a comment. It can read to the end of the page.
    CommentEndSearch,
    /// A read of a tag to its end, with the count of the bytes it went over. It can read to
    /// the end of the page.
    TagRead(usize),
    /// The count of the places where that read stopped to look at a byte: each `=` and the
    /// `>`. A read that looks at each byte of the tag stops at each byte.
    TagStops(usize),
}

/// The reads of one pass over one page that can go to the end of the page: the end of a
/// comment, the end of a tag and the end tag of a raw-text element. The first pass and the
/// second pass read a comment and a tag whole with it, so a tag in a comment or in an
/// attribute value starts nothing in either pass.
///
/// ~keep A read that finds no end is not made again, so the reads of a pass are linear. A later
/// ~keep comment has no end either, and a later start tag of the same name has no end tag
/// ~keep either. A tag that does not end holds the rest of the page, so a later `<` is in it:
/// ~keep it ends at its first `>`, as a tag with a quote that never ends.
pub(super) struct PageReads<C: FnMut(PassRead)> {
    comments_never_end: bool,
    tags_never_end: bool,
    no_end_tag: [bool; FIRST_PASS_ELEMENTS.len()],
    count: C,
}

impl<C: FnMut(PassRead)> PageReads<C> {
    pub(super) const fn new(count: C) -> Self {
        Self {
            comments_never_end: false,
            tags_never_end: false,
            no_end_tag: [false; FIRST_PASS_ELEMENTS.len()],
            count,
        }
    }

    /// The first end tag of the raw-text element `FIRST_PASS_ELEMENTS[slot]` at or after
    /// `from`: the position of its `<` and the position after its `>`.
    pub(super) fn raw_text_end_tag(&mut self, bytes: &[u8], from: usize, slot: usize) -> Option<(usize, usize)> {
        if self.no_end_tag[slot] {
            return None;
        }
        self.count(PassRead::EndTagSearch);
        let found = find_raw_text_end_tag(bytes, from, FIRST_PASS_ELEMENTS[slot].0.as_bytes());
        // ~keep A search that stopped at the scan limit did not read the whole page and proves
        // ~keep nothing.
        self.no_end_tag[slot] = found.is_none() && bytes.len() - from <= MAX_CLOSING_TAG_SCAN;
        found
    }

    /// Count one read of the pass.
    pub(super) fn count(&mut self, read: PassRead) {
        (self.count)(read);
    }

    /// The position after the comment that the `<` at `idx` starts, when it starts a comment
    /// that ends.
    pub(super) fn comment_end(&mut self, bytes: &[u8], idx: usize) -> Option<usize> {
        if self.comments_never_end || !bytes[idx..].starts_with(COMMENT_OPEN) {
            return None;
        }
        self.count(PassRead::CommentEndSearch);
        // ~keep `<!-->` and `<!--->` are whole comments: the search starts in the opening.
        let from = idx + 2;
        let found = find_html_comment_end(bytes, from);
        self.comments_never_end = found.is_none();
        found
    }

    /// The position after the tag that the `<` at `idx` starts, read whole with its quoted
    /// attribute values. Returns `None` for a `<` of the text and for a tag with no `>`.
    pub(super) fn tag_end(&mut self, bytes: &[u8], idx: usize) -> Option<usize> {
        if !opens_a_tag(bytes, idx) {
            return None;
        }
        self.tag_end_from(bytes, idx + 1, None)
    }

    /// If the `<` at `lt` starts a raw-text element of `FIRST_PASS_ELEMENTS`, return its slot
    /// there and the position after its start tag, read whole with its quoted attribute
    /// values.
    pub(super) fn raw_text_start_tag_end(&mut self, bytes: &[u8], lt: usize) -> Option<(usize, usize)> {
        let (slot, after_name) = FIRST_PASS_ELEMENTS.iter().enumerate().find_map(|(slot, (name, _))| {
            let after_name = raw_text_tag_name_end(bytes, lt, name.as_bytes(), TagSide::Start)?;
            Some((slot, after_name))
        })?;
        let tag_end = self.tag_end_from(bytes, after_name, Some(after_name))?;
        Some((slot, tag_end))
    }

    /// The position after the `>` that ends the tag read from `from`, a position in the tag
    /// after its `<`. `attributes` is the position after the name of the tag, when the caller
    /// read the name.
    fn tag_end_from(&mut self, bytes: &[u8], from: usize, attributes: Option<usize>) -> Option<usize> {
        if !self.tags_never_end {
            let mut stops = 0;
            let whole = whole_tag_end(bytes, from, attributes, &mut stops);
            self.count(PassRead::TagRead(whole.unwrap_or(bytes.len()) - from));
            self.count(PassRead::TagStops(stops));
            self.tags_never_end = whole.is_none();
            if whole.is_some() {
                return whole;
            }
        }
        memchr::memchr(b'>', &bytes[from..]).map(|offset| from + offset + 1)
    }
}

/// The first pass over one page.
///
/// ~keep The pass reads markup as a tokenizer does: a comment whole, a tag to its end with its
/// ~keep quoted attribute values, a raw-text element to its end tag. The next `<` it tries is
/// ~keep after that, so a `<textarea>` in a comment or in an attribute value starts nothing.
/// ~keep A bogus comment is read to its first `>`: a `<textarea>` in `<? ... >` starts nothing.
/// ~keep The pass is linear: a search that finds no end is not made again. A later start tag
/// ~keep of the same name has no end tag either; `PageReads` has the rule of a comment and of
/// ~keep a tag.
pub(super) struct FirstPass<'a, C: FnMut(PassRead)> {
    input: &'a str,
    last: usize,
    output: Option<String>,
    svg_depth: usize,
    pre_depth: usize,
    reads: PageReads<C>,
    kept_scripts: KeptScripts,
}

impl<'a, C: FnMut(PassRead)> FirstPass<'a, C> {
    /// The pass that writes no owner mark.
    pub(super) const fn new(input: &'a str, count: C) -> Self {
        Self::with_kept_scripts(input, KeptScripts::new(), count)
    }

    const fn with_kept_scripts(input: &'a str, kept_scripts: KeptScripts, count: C) -> Self {
        Self {
            input,
            last: 0,
            output: None,
            svg_depth: 0,
            pre_depth: 0,
            reads: PageReads::new(count),
            kept_scripts,
        }
    }

    pub(super) fn run(mut self) -> (Cow<'a, str>, KeptScripts) {
        let bytes = self.input.as_bytes();
        // ~keep No tag ends after the last `>` of the page: nothing after it is an element,
        // ~keep and no search for the end of a tag starts there.
        let last_gt = memchr::memrchr(b'>', bytes).unwrap_or(0);
        let mut idx = 0;
        while idx < last_gt {
            let Some(offset) = memchr::memchr(b'<', &bytes[idx..last_gt]) else {
                break;
            };
            idx = self.read_markup(idx + offset);
        }
        let page = match self.output {
            Some(mut out) => {
                out.push_str(&self.input[self.last..]);
                Cow::Owned(out)
            }
            None => Cow::Borrowed(self.input),
        };
        (page, self.kept_scripts)
    }

    /// Read the markup that the `<` at `idx` starts. Returns the position of the next read.
    fn read_markup(&mut self, idx: usize) -> usize {
        let bytes = self.input.as_bytes();
        self.reads.count(PassRead::Markup);
        if let Some(after_tag) = track_svg_tag(bytes, idx, &mut self.svg_depth) {
            return after_tag;
        }
        if self.svg_depth > 0 {
            return idx + 1;
        }
        if bytes[idx..].starts_with(COMMENT_OPEN) {
            return self.reads.comment_end(bytes, idx).unwrap_or(idx + 1);
        }
        if let Some(after_comment) = bogus_comment_end(bytes, idx) {
            return after_comment;
        }
        if let Some((slot, tag_end)) = self.reads.raw_text_start_tag_end(bytes, idx) {
            return self.read_raw_text_element(idx, slot, tag_end);
        }
        if matches_tag_start(bytes, idx + 1, b"pre") {
            self.pre_depth += 1;
        } else if matches_end_tag_start(bytes, idx + 1, b"pre") {
            self.pre_depth = self.pre_depth.saturating_sub(1);
        }
        self.reads.tag_end(bytes, idx).unwrap_or(idx + 1)
    }

    /// Read the raw-text element of `FIRST_PASS_ELEMENTS[slot]` whose start tag is at `idx`
    /// and ends at `tag_end`. Returns the position of the next read.
    fn read_raw_text_element(&mut self, idx: usize, slot: usize, tag_end: usize) -> usize {
        let bytes = self.input.as_bytes();
        let (name, content) = FIRST_PASS_ELEMENTS[slot];
        let Some(close) = self.reads.raw_text_end_tag(bytes, tag_end, slot) else {
            // ~keep The second pass reads an element with no end tag.
            #[cfg(feature = "metadata")]
            self.mark_script_with_no_end_tag(idx, tag_end, name, content);
            return tag_end;
        };
        let element = RawTextElement {
            input: self.input,
            idx,
            last: self.last,
            name,
            content,
            preformatted: self.pre_depth != 0,
            mark: None,
        };
        #[cfg(feature = "metadata")]
        let element = RawTextElement {
            mark: self.owner_mark(&element, tag_end, close.0),
            ..element
        };
        let outcome = strip_raw_text_element(&element, tag_end, close, &mut self.output);
        if outcome != Outcome::Unchanged {
            self.last = close.1;
        }
        close.1
    }

    /// The number of the owner mark of `element`, when it is a kept script whose escaped text
    /// holds `&lt;`. `tag_end` is the end of its start tag and `body_end` is the end of its
    /// content.
    #[cfg(feature = "metadata")]
    fn owner_mark(&mut self, element: &RawTextElement<'_>, tag_end: usize, body_end: usize) -> Option<usize> {
        let is_kept_script = element.content == RawTextContent::RemovedUnlessStructuredData
            && self.kept_scripts.marks
            && is_json_ld_script_open_tag(&self.input[element.idx..tag_end]);
        if !is_kept_script {
            return None;
        }
        self.kept_scripts.mark(self.input, &self.input[tag_end..body_end])
    }

    /// Write the owner mark in the start tag of the first kept script with no end tag, when
    /// the rest of the page, which is its text, holds a `<` or `&lt;`. `idx` is the `<` of the
    /// start tag, `tag_end` is its end and `name` is the name of the element.
    ///
    /// ~keep The tree builder ends this script at the end of the page and writes the mark
    /// ~keep again, so the script of the final tree has the rest of the page as its record.
    #[cfg(feature = "metadata")]
    fn mark_script_with_no_end_tag(&mut self, idx: usize, tag_end: usize, name: &str, content: RawTextContent) {
        let input = self.input;
        if content != RawTextContent::RemovedUnlessStructuredData
            || self.kept_scripts.has_no_end_tag
            || !is_json_ld_script_open_tag(&input[idx..tag_end])
        {
            return;
        }
        self.kept_scripts.has_no_end_tag = true;
        let Some(mark) = self.kept_scripts.mark(input, &input[tag_end..]) else {
            return;
        };
        let after_name = idx + 1 + name.len();
        let out = self.output.get_or_insert_with(|| String::with_capacity(input.len()));
        out.push_str(&input[self.last..after_name]);
        push_kept_attributes(out, Some(mark), &input[after_name..tag_end]);
        self.last = tag_end;
    }
}

/// Upper bound on how far a closing-tag scan may travel from its start offset.
///
/// ~keep DoS guard: hostile input can contain an unterminated element followed
/// ~keep by hundreds of megabytes of text; the scan gives up rather than walking
/// ~keep the whole document for every such tag.
pub(super) const MAX_CLOSING_TAG_SCAN: usize = 100_000_000;

/// The side of an element that a tag is on.
#[derive(Clone, Copy, PartialEq, Eq)]
enum TagSide {
    /// `<name ...>`
    Start,
    /// `</name ...>`
    End,
}

/// If the `<` at `lt` starts the start tag of the raw-text element `name`, return the index
/// after the `>` of the tag. A scan that skips a raw-text element reads its start tag here.
///
/// ~keep A `>` in a quoted attribute value does not end a start tag. A start tag with a quote
/// ~keep that never ends ends at its first `>`. A pass reads many tags of one page: it reads
/// ~keep them with `PageReads`, which has this rule and makes no read twice.
fn raw_text_start_tag_end(bytes: &[u8], lt: usize, name: &[u8]) -> Option<usize> {
    let after_name = raw_text_tag_name_end(bytes, lt, name, TagSide::Start)?;
    let first_bracket = || memchr::memchr(b'>', &bytes[after_name..]).map(|offset| after_name + offset + 1);
    whole_tag_end(bytes, after_name, Some(after_name), &mut 0).or_else(first_bracket)
}

/// The one rule for the name of the start tag and of the end tag of a raw-text element. If
/// the `<` at `lt` starts a tag of `name` on `side`, return the position after the name.
///
/// ~keep The HTML rule: the name in any case, then tab, LF, FF, CR, space, `/` or `>`. The
/// ~keep two passes, the scan of hidden regions and the fast converter read a tag with this
/// ~keep function; a second copy of the rule is how they came to disagree on the form feed
/// ~keep and the slash.
fn raw_text_tag_name_end(bytes: &[u8], lt: usize, name: &[u8], side: TagSide) -> Option<usize> {
    if bytes.get(lt) != Some(&b'<') {
        return None;
    }
    let name_start = match side {
        TagSide::Start => lt + 1,
        TagSide::End if bytes.get(lt + 1) == Some(&b'/') => lt + 2,
        TagSide::End => return None,
    };
    let after_name = name_start + name.len();
    if !bytes.get(name_start..after_name)?.eq_ignore_ascii_case(name) {
        return None;
    }
    if !matches!(
        bytes.get(after_name)?,
        b'\t' | b'\n' | b'\x0C' | b'\r' | b' ' | b'/' | b'>'
    ) {
        return None;
    }
    Some(after_name)
}

/// The position after the `>` that ends the tag whose name starts at `name`, the position
/// after its `<`. Returns `None` when a value or the tag does not end.
///
/// ~keep One read owns the end of a tag: the first pass of the raw-text elements and the scan
/// ~keep of the repair of a script with no end tag (`scan_markup_end`) both ask it. Two reads
/// ~keep with a rule each ended one start tag at two places, and the text between the two
/// ~keep ends was a record of structured data.
pub(super) fn tag_end_from_name(bytes: &[u8], name: usize) -> Option<usize> {
    whole_tag_end(bytes, name, None, &mut 0)
}

/// The position after the `>` that ends the tag read from `from`, a position in the tag after
/// its `<`. `attributes` is the position after the name of the tag, when the caller read the
/// name. Returns `None` when a value or the tag does not end. `stops` counts the places where
/// the read stops to look at a byte.
///
/// ~keep The HTML rule: a quote opens a value only as the first byte of the value, after `=`
/// ~keep and white space. A value with no quotes ends at white space or at `>`: the apostrophe
/// ~keep of `title=it's` and the `=` and the apostrophe of `href=/search?q='tis` are bytes of
/// ~keep the value. An `=` starts a value only after the name of an attribute: an `=` in the
/// ~keep name of the tag, after a value or after a `/` is a byte of a name, so the quote of
/// ~keep `<a ="x>` opens no value and the tag ends at its `>`.
/// ~keep Outside a value only `>` and `=` change the read, so the read jumps to the next one of
/// ~keep the two: most bytes of a page are in a tag or between two tags, and a read of each
/// ~keep byte of each tag is a cost on every page. The name of the tag is read only at the
/// ~keep first `=` of a tag whose caller did not read it.
fn whole_tag_end(bytes: &[u8], from: usize, attributes: Option<usize>, stops: &mut usize) -> Option<usize> {
    whole_tag_terminator(bytes, from, attributes, stops).map(|(end, _)| end)
}

/// Read a tag from the end of its name and distinguish a closing slash from a value byte.
/// ~keep A slash in an unquoted value belongs to that value, including immediately before `>`.
pub fn tag_terminator_from_attributes(bytes: &[u8], attributes: usize) -> Option<(usize, bool)> {
    whole_tag_terminator(bytes, attributes, Some(attributes), &mut 0)
}

fn whole_tag_terminator(
    bytes: &[u8],
    from: usize,
    attributes: Option<usize>,
    stops: &mut usize,
) -> Option<(usize, bool)> {
    let mut idx = from;
    let mut names = attributes;
    loop {
        *stops += 1;
        idx += memchr::memchr2(b'>', b'=', bytes.get(idx..)?)?;
        if bytes[idx] == b'>' {
            return Some((idx + 1, idx > 0 && bytes[idx - 1] == b'/'));
        }
        let names_start = *names.get_or_insert_with(|| tag_name_end(bytes, from));
        if !ends_an_attribute_name(bytes, names_start, idx) {
            idx += 1;
            continue;
        }
        let after_equals = &bytes[idx + 1..];
        let value = idx + 1 + after_equals.iter().position(|byte| !is_tag_white_space(*byte))?;
        idx = match bytes[value] {
            b'>' => return Some((value + 1, false)),
            quote @ (b'"' | b'\'') => value + 2 + memchr::memchr(quote, &bytes[value + 1..])?,
            _ => value + bytes[value..].iter().copied().position(ends_an_unquoted_value)?,
        };
        if bytes.get(idx) == Some(&b'>') {
            return Some((idx + 1, false));
        }
        names = Some(idx);
    }
}

/// The position after the name of the tag read from `from`, the position after its `<`. The
/// name of an end tag starts after its `/`.
fn tag_name_end(bytes: &[u8], from: usize) -> usize {
    let name = from + usize::from(bytes.get(from) == Some(&b'/'));
    bytes
        .get(name..)
        .and_then(|rest| rest.iter().position(|byte| ends_a_tag_name(*byte)))
        .map_or(bytes.len(), |offset| name + offset)
}

/// Whether the `=` at `equals` comes after the name of an attribute. `names` is the position
/// where the names of the attributes start: after the name of the tag, or after the last
/// value.
///
/// ~keep The read goes back over white space only, so a tag is read a fixed number of times.
fn ends_an_attribute_name(bytes: &[u8], names: usize, equals: usize) -> bool {
    bytes
        .get(names..equals)
        .and_then(|before| before.iter().rev().find(|byte| !is_tag_white_space(**byte)))
        .is_some_and(|last| *last != b'/')
}

/// Whether `byte` ends the name of a tag: white space, `/` or `>`.
const fn ends_a_tag_name(byte: u8) -> bool {
    is_tag_white_space(byte) || matches!(byte, b'/' | b'>')
}

/// Whether `byte` is white space in a tag: tab, LF, FF, CR or space.
const fn is_tag_white_space(byte: u8) -> bool {
    matches!(byte, b'\t' | b'\n' | b'\x0C' | b'\r' | b' ')
}

/// Whether `byte` ends an attribute value with no quotes: white space or `>`.
const fn ends_an_unquoted_value(byte: u8) -> bool {
    is_tag_white_space(byte) || byte == b'>'
}

/// Find the position of the FIRST closing tag in bytes, ignoring nesting.
/// Returns the position AFTER the closing tag (including the '>').
/// This is highly optimized for performance and uses a fast-path scan.
///
/// ~keep First-match (not depth-aware) is correct ONLY for the HTML raw-text
/// ~keep elements `<script>` and `<style>`: inside their bodies `<script` is
/// ~keep text, not a tag, so the first `</script>` is the spec terminator.
/// ~keep Counting depth here would treat `var s = "<script>"` as an opening tag
/// ~keep and run past the real close, swallowing the rest of the document.
/// ~keep Elements that can nest must use `find_closing_tag_bytes_nested`; do not
/// ~keep unify the two functions.
#[inline]
pub fn find_closing_tag_bytes(bytes: &[u8], start: usize, tag: &[u8]) -> Option<usize> {
    find_raw_text_end_tag(bytes, start, tag).map(|(_, end)| end)
}

/// The first end tag of the raw-text element `name` at or after `start`: the position of its
/// `<` and the position after its `>`. Both converters end a raw-text element here.
pub fn find_raw_text_end_tag(bytes: &[u8], start: usize, name: &[u8]) -> Option<(usize, usize)> {
    let mut idx = start;
    while idx < bytes.len() && (idx - start) < MAX_CLOSING_TAG_SCAN {
        idx += memchr::memchr(b'<', &bytes[idx..])?;
        if let Some(after_name) = raw_text_tag_name_end(bytes, idx, name, TagSide::End) {
            // ~keep An end tag with no `>` ends the search: no later end tag has one either.
            let end = after_name + memchr::memchr(b'>', &bytes[after_name..])? + 1;
            return Some((idx, end));
        }
        idx += 1;
    }
    None
}

/// Void elements that never carry a closing tag, so an occurrence of one inside
/// a subtree must not raise the nesting depth of a closing-tag scan.
const VOID_ELEMENT_NAMES: [&[u8]; 4] = [b"br", b"hr", b"img", b"input"];

/// Whether an opening tag closes itself: XHTML-style `<tag/>` or a void element.
///
/// ~keep Shared by `strip_hidden_elements` and `find_closing_tag_bytes_nested`
/// ~keep so the element the stripper treats as self-closing and the element the
/// ~keep depth counter refuses to count can never disagree.
#[inline]
pub(super) fn is_self_closing_tag(tag_slice: &[u8], tag_name: &[u8]) -> bool {
    tag_slice.ends_with(b"/>")
        || VOID_ELEMENT_NAMES
            .iter()
            .any(|void_name| tag_name.eq_ignore_ascii_case(void_name))
}

/// Byte sequences delimiting the regions of an HTML document whose bytes are
/// character data rather than markup.
const COMMENT_OPEN: &[u8] = b"<!--";
const CDATA_OPEN: &[u8] = b"<![CDATA[";
const CDATA_CLOSE: &[u8] = b"]]>";

/// Elements whose body is raw text: `<` inside them never starts a tag.
///
/// ~keep The names of `FIRST_PASS_ELEMENTS`: a scan that skips a region and the first pass
/// ~keep read the same elements as raw text.
const RAW_TEXT_ELEMENT_NAMES: [&[u8]; 3] = [b"script", b"style", b"textarea"];

/// Index just past the first occurrence of `terminator` at or after `from`,
/// or the input length when the region is never terminated.
///
/// ~keep An unterminated comment/CDATA region runs to EOF per HTML5, so
/// ~keep returning `len` (rather than `None`) keeps the caller from resuming a
/// ~keep tag scan inside text that will never be markup.
#[inline]
fn find_sequence_end(bytes: &[u8], from: usize, terminator: &[u8]) -> usize {
    let len = bytes.len();
    if from >= len {
        return len;
    }
    match bytes[from..].windows(terminator.len()).position(|w| w == terminator) {
        Some(offset) => from + offset + terminator.len(),
        None => len,
    }
}

/// If a `<` at `idx` opens a region that is NOT markup — an HTML comment, a
/// CDATA section, or the body of a raw-text element — return the index just
/// past that region. Returns `None` when `idx` does not open such a region.
///
/// ~keep A depth-counting close-tag scan MUST consult this before interpreting
/// ~keep a `<`: `<!-- </div> -->` and `<script>{"a":"</div>"}</script>` contain
/// ~keep byte sequences that look like tags but are text. Counting them ends the
/// ~keep scan early (leaking the hidden element's tail into the output) or
/// ~keep inflates the depth (swallowing the following visible sibling).
#[inline]
pub fn skip_opaque_region(bytes: &[u8], idx: usize) -> Option<usize> {
    let len = bytes.len();
    if idx >= len || bytes[idx] != b'<' {
        return None;
    }

    if bytes[idx..].starts_with(COMMENT_OPEN) {
        return Some(find_html_comment_end(bytes, idx + COMMENT_OPEN.len()).unwrap_or(len));
    }

    if bytes[idx..].starts_with(CDATA_OPEN) {
        return Some(find_sequence_end(bytes, idx + CDATA_OPEN.len(), CDATA_CLOSE));
    }

    for raw_text_name in RAW_TEXT_ELEMENT_NAMES {
        if let Some(open_end) = raw_text_start_tag_end(bytes, idx, raw_text_name) {
            // ~keep First-match close is the spec terminator for raw text — see
            // ~keep the doc comment on `find_closing_tag_bytes`.
            return Some(find_closing_tag_bytes(bytes, open_end, raw_text_name).unwrap_or(len));
        }
    }

    None
}

/// Whether the `<` at `idx` starts a tag rather than a stray `<` in text.
///
/// ~keep Mirrors the `is_valid_tag` test in `preprocess_html`: without it a
/// ~keep literal `<` in text (`a < b`) would make a scan jump to the next `>`,
/// ~keep stepping over the real closing tag in between.
#[inline]
pub(super) fn opens_a_tag(bytes: &[u8], idx: usize) -> bool {
    match bytes.get(idx + 1) {
        Some(b'/' | b'!') => bytes.get(idx + 2).is_some_and(u8::is_ascii_alphabetic),
        Some(byte) => byte.is_ascii_alphabetic(),
        None => false,
    }
}

/// Find the closing tag that matches an opening `<tag>`, counting nested
/// elements of the same name. Returns the position AFTER the closing tag
/// (including the '>'), or `None` if the element is never closed.
///
/// ~keep Required for elements that can nest (`div`, `span`, ...): the
/// ~keep first-match `find_closing_tag_bytes` stops at the INNER `</tag>`, which
/// ~keep leaves the hidden element's tail in the document. Kept separate from
/// ~keep that function because raw-text elements must NOT count depth — see its
/// ~keep doc comment.
///
/// ~keep Only real markup may move the depth counter, so every `<` is first
/// ~keep offered to `skip_opaque_region`, and a tag that is not the target is
/// ~keep jumped via the quote-aware `find_tag_end` rather than byte-by-byte:
/// ~keep otherwise `</tag>` written inside a comment, a quoted attribute value,
/// ~keep or a raw-text body is mistaken for the element's terminator.
#[inline]
pub fn find_closing_tag_bytes_nested(bytes: &[u8], start: usize, tag: &[u8]) -> Option<usize> {
    let len = bytes.len();
    if tag.is_empty() {
        return None;
    }

    let mut idx = start;
    let mut depth = 1usize;

    while idx < len && (idx - start) < MAX_CLOSING_TAG_SCAN {
        if bytes[idx] != b'<' {
            match memchr::memchr(b'<', &bytes[idx..]) {
                Some(pos) => idx += pos,
                None => break,
            }
        }

        if let Some(region_end) = skip_opaque_region(bytes, idx) {
            idx = region_end;
            continue;
        }

        if matches_end_tag_start(bytes, idx + 1, tag) {
            if let Some(close_end) = find_tag_end(bytes, idx + 2 + tag.len()) {
                depth -= 1;
                if depth == 0 {
                    return Some(close_end);
                }
                idx = close_end;
                continue;
            }
        } else if matches_tag_start(bytes, idx + 1, tag) {
            if let Some(open_end) = find_tag_end(bytes, idx + 1 + tag.len()) {
                if !is_self_closing_tag(&bytes[idx..open_end], tag) {
                    depth += 1;
                }
                idx = open_end;
                continue;
            }
        } else if opens_a_tag(bytes, idx) {
            if let Some(unrelated_tag_end) = find_tag_end(bytes, idx + 1) {
                idx = unrelated_tag_end;
                continue;
            }
        }

        idx += 1;
    }

    None
}

// ~keep Match each same-name nesting stack once; repeated hidden opens without closes
// otherwise search the entire suffix independently (#773).
pub(super) fn matching_tag_ends(bytes: &[u8]) -> ahash::AHashMap<usize, Option<usize>> {
    let mut stacks: ahash::AHashMap<Vec<u8>, Vec<usize>> = ahash::AHashMap::new();
    let mut ends = ahash::AHashMap::new();
    let mut idx = 0;
    let last_gt = bytes.iter().rposition(|&byte| byte == b'>').unwrap_or(0);
    while idx < last_gt {
        let Some(offset) = memchr::memchr(b'<', &bytes[idx..]) else {
            break;
        };
        idx += offset;
        if let Some(end) = skip_opaque_region(bytes, idx) {
            idx = end;
            continue;
        }
        if !opens_a_tag(bytes, idx) {
            idx += 1;
            continue;
        }
        let closing = bytes.get(idx + 1) == Some(&b'/');
        let start = idx + if closing { 2 } else { 1 };
        let name_len = bytes[start..]
            .iter()
            .take_while(|byte| !byte.is_ascii_whitespace() && !matches!(byte, b'>' | b'/'))
            .count();
        let name = bytes[start..start + name_len].to_ascii_lowercase();
        let Some(end) = find_tag_end(bytes, start + name_len) else {
            break;
        };
        let stack = stacks.entry(name.clone()).or_default();
        if closing {
            if let Some(open) = stack.pop() {
                ends.insert(open, Some(end));
            }
        } else if !is_self_closing_tag(&bytes[idx..end], &name) {
            ends.insert(idx, None);
            stack.push(idx);
        }
        idx = end;
    }
    ends
}