html-to-markdown-rs 3.18.6

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
// ~keep Vendored from markup5ever_rcdom v0.36.0+unofficial
// ~keep Original source: https://github.com/servo/html5ever (rcdom/)
// ~keep Copyright (c) 2014 The html5ever Project Developers
// ~keep Licensed under MIT OR Apache-2.0 (see ATTRIBUTIONS.md)
// ~keep
// ~keep Vendored to:
// ~keep - Remove unused xml5ever transitive dependency
// ~keep - Eliminate pinned external dependency on "+unofficial" crate
// ~keep - Gain full control over this small, critical module
// ~keep
// ~keep Changes from upstream:
// ~keep - Replaced `extern crate markup5ever` / `extern crate tendril` with
// ~keep   `use` imports through `html5ever` (edition 2024 compatibility)
// ~keep - Added module-level clippy allows for vendored code style

// ~keep reason: this is vendored upstream code (markup5ever_rcdom v0.36.0) reproduced verbatim
// ~keep to eliminate the pinned "+unofficial" crate dependency. The original code uses panics
// ~keep and expect() calls as part of its internal invariant enforcement. All lints are
// ~keep suppressed on this module to keep the diff from upstream minimal and make future
// ~keep upstream syncs straightforward.
#![allow(
    clippy::panic,
    clippy::expect_used,
    clippy::missing_panics_doc,
    clippy::must_use_candidate,
    clippy::return_self_not_must_use,
    clippy::module_name_repetitions,
    clippy::redundant_else,
    clippy::match_wildcard_for_single_variants,
    clippy::similar_names,
    clippy::items_after_statements,
    clippy::use_self,
    clippy::missing_fields_in_debug,
    clippy::semicolon_if_nothing_returned,
    missing_docs
)]

//! A simple reference-counted DOM.
//!
//! This is sufficient as a static parse tree, but don't build a
//! web browser using it. :)

use std::borrow::Cow;
use std::cell::{Cell, RefCell};
use std::collections::{HashSet, VecDeque};
use std::default::Default;
use std::fmt;
use std::io;
use std::mem;
use std::rc::{Rc, Weak};

use html5ever::tendril::StrTendril;

use html5ever::Attribute;
use html5ever::ExpandedName;
use html5ever::QualName;
use html5ever::interface::tree_builder;
use html5ever::interface::tree_builder::{ElementFlags, NodeOrText, QuirksMode, TreeSink};
use html5ever::serialize::TraversalScope;
use html5ever::serialize::TraversalScope::{ChildrenOnly, IncludeNode};
use html5ever::serialize::{Serialize, Serializer};

/// The different kinds of nodes in the DOM.
#[derive(Debug)]
pub enum NodeData {
    /// The `Document` itself - the root node of a HTML document.
    Document,

    /// A `DOCTYPE` with name, public id, and system id. See
    /// [document type declaration on wikipedia][dtd wiki].
    ///
    /// [dtd wiki]: https://en.wikipedia.org/wiki/Document_type_declaration
    Doctype {
        name: StrTendril,
        // ~keep Fields required by html5ever's DOM model; not accessed during conversion.
        #[allow(dead_code)]
        public_id: StrTendril,
        #[allow(dead_code)]
        system_id: StrTendril,
    },

    /// A text node.
    Text { contents: RefCell<StrTendril> },

    /// A comment.
    Comment { contents: StrTendril },

    /// An element with attributes.
    Element {
        name: QualName,
        attrs: RefCell<Vec<Attribute>>,

        /// For HTML \<template\> elements, the [template contents].
        ///
        /// [template contents]: https://html.spec.whatwg.org/multipage/#template-contents
        template_contents: RefCell<Option<Handle>>,

        /// Whether the node is a [HTML integration point].
        ///
        /// [HTML integration point]: https://html.spec.whatwg.org/multipage/#html-integration-point
        mathml_annotation_xml_integration_point: bool,
    },

    /// A Processing instruction.
    ProcessingInstruction { target: StrTendril, contents: StrTendril },
}

struct DepthCache {
    epoch: usize,
    depth: usize,
    root: WeakHandle,
}

/// A DOM node.
pub struct Node {
    /// Parent node.
    pub parent: Cell<Option<WeakHandle>>,
    /// The `<template>` element whose contents this node is. The contents are not a child of
    /// the template and have no parent; only the depth count of the repair reads this link.
    template_host: Cell<Option<WeakHandle>>,
    depth_cache: RefCell<Option<DepthCache>>,
    /// Child nodes of this node.
    pub children: RefCell<Vec<Handle>>,
    /// Represents this node's data.
    pub data: NodeData,
}

impl Node {
    /// Create a new node from its contents
    pub fn new(data: NodeData) -> Rc<Self> {
        Rc::new(Node {
            data,
            parent: Cell::new(None),
            template_host: Cell::new(None),
            depth_cache: RefCell::new(None),
            children: RefCell::new(Vec::new()),
        })
    }
}

impl Drop for Node {
    fn drop(&mut self) {
        let mut nodes = mem::take(&mut *self.children.borrow_mut());
        while let Some(node) = nodes.pop() {
            let children = mem::take(&mut *node.children.borrow_mut());
            nodes.extend(children);
            if let NodeData::Element {
                ref template_contents, ..
            } = node.data
            {
                if let Some(template_contents) = template_contents.borrow_mut().take() {
                    nodes.push(template_contents);
                }
            }
        }
    }
}

impl fmt::Debug for Node {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("Node")
            .field("data", &self.data)
            .field("children", &self.children)
            .finish()
    }
}

/// Reference to a DOM node.
pub type Handle = Rc<Node>;

/// Weak reference to a DOM node, used for parent pointers.
pub type WeakHandle = Weak<Node>;

/// Append a parentless node to another nodes' children
fn append(new_parent: &Handle, child: Handle) {
    let previous_parent = child.parent.replace(Some(Rc::downgrade(new_parent)));
    assert!(previous_parent.is_none());
    new_parent.children.borrow_mut().push(child);
}

/// The node one level above `node` for the depth count of the repair: its parent, or the
/// template when `node` is the contents of one.
fn depth_ancestor(node: &Handle) -> Option<Handle> {
    let read = |link: &Cell<Option<WeakHandle>>| {
        let weak = link.take();
        let handle = weak.as_ref().and_then(Weak::upgrade);
        link.set(weak);
        handle
    };
    read(&node.parent).or_else(|| read(&node.template_host))
}

/// If the node has a parent, get it and this node's position in its children
fn get_parent_and_index(target: &Handle) -> Option<(Handle, usize)> {
    if let Some(weak) = target.parent.take() {
        let parent = weak.upgrade().expect("dangling weak pointer");
        target.parent.set(Some(weak));
        let i = match parent
            .children
            .borrow()
            .iter()
            .enumerate()
            .find(|&(_, child)| Rc::ptr_eq(child, target))
        {
            Some((i, _)) => i,
            None => panic!("have parent but couldn't find in parent's children!"),
        };
        Some((parent, i))
    } else {
        None
    }
}

fn append_to_existing_text(prev: &Handle, text: &str) -> bool {
    match prev.data {
        NodeData::Text { ref contents } => {
            contents.borrow_mut().push_slice(text);
            true
        }
        _ => false,
    }
}

fn remove_from_parent(target: &Handle) {
    if let Some((parent, i)) = get_parent_and_index(target) {
        parent.children.borrow_mut().remove(i);
        target.parent.set(None);
    }
}

/// The DOM itself; the result of parsing.
pub struct RcDom {
    /// The `Document` itself.
    pub document: Handle,

    /// Errors that occurred during parsing.
    pub errors: RefCell<Vec<Cow<'static, str>>>,

    /// The document's quirks mode.
    pub quirks_mode: Cell<QuirksMode>,
    node_count: Cell<usize>,
    max_nodes: usize,
    max_depth: usize,
    topology_epoch: Cell<usize>,
    #[cfg(test)]
    depth_reads: Cell<usize>,
    pub(crate) repair_limit: Cell<Option<crate::types::WarningKind>>,
}

impl RcDom {
    pub(crate) fn bounded(max_nodes: usize, max_depth: usize) -> Self {
        Self {
            max_nodes,
            max_depth,
            ..Self::default()
        }
    }

    fn new_node(&self, data: NodeData) -> Handle {
        self.node_count.set(self.node_count.get().saturating_add(1));
        if self.node_count.get() > self.max_nodes {
            self.repair_limit.set(Some(crate::types::WarningKind::TruncatedInput));
        }
        Node::new(data)
    }

    fn subtree_fits_depth(&self, parent: &Handle, children: &[Handle]) -> bool {
        if self.max_depth == usize::MAX || children.is_empty() {
            return true;
        }
        let depth = self.parent_depth(parent);
        if depth > self.max_depth {
            self.repair_limit
                .set(Some(crate::types::WarningKind::DepthLimitExceeded));
            return false;
        }
        let mut work: Vec<_> = children.iter().map(|child| (Rc::clone(child), depth + 1)).collect();
        while let Some((node, depth)) = work.pop() {
            if depth > self.max_depth {
                self.repair_limit
                    .set(Some(crate::types::WarningKind::DepthLimitExceeded));
                return false;
            }
            work.extend(node.children.borrow().iter().map(|child| (Rc::clone(child), depth + 1)));
        }
        true
    }

    fn read_depth_ancestor(&self, node: &Handle) -> Option<Handle> {
        #[cfg(test)]
        self.depth_reads.set(self.depth_reads.get() + 1);
        depth_ancestor(node)
    }

    fn invalidate_depths(&self) {
        self.topology_epoch.set(self.topology_epoch.get().saturating_add(1));
    }

    fn prepare_attachment(&self, parent: &Handle, child: &Handle) {
        // ~keep A fresh leaf has no descendants whose cached ancestry can change (#830).
        // ~keep Template contents are linked through their host rather than children.
        if Rc::ptr_eq(parent, child)
            || !child.children.borrow().is_empty()
            || matches!(child.data, NodeData::Element { ref template_contents, .. }
                if template_contents.borrow().is_some())
        {
            self.invalidate_depths();
            child.depth_cache.borrow_mut().take();
            return;
        }
        *child.depth_cache.borrow_mut() = parent.depth_cache.borrow().as_ref().map(|cache| DepthCache {
            epoch: cache.epoch,
            depth: cache.depth.saturating_add(1),
            root: cache.root.clone(),
        });
    }

    fn parent_depth(&self, parent: &Handle) -> usize {
        let epoch = self.topology_epoch.get();
        let mut path = Vec::new();
        let mut current = Rc::clone(parent);
        let (mut depth, root) = loop {
            if epoch != usize::MAX {
                if let Some(cache) = current.depth_cache.borrow().as_ref() {
                    if cache.epoch == epoch && cache.root.strong_count() != 0 {
                        break (cache.depth, cache.root.clone());
                    }
                }
            }
            path.push(Rc::clone(&current));
            if path.len() > self.max_depth.saturating_add(1) {
                return self.max_depth.saturating_add(1);
            }
            let Some(ancestor) = self.read_depth_ancestor(&current) else {
                path.pop();
                let root = Rc::downgrade(&current);
                *current.depth_cache.borrow_mut() = Some(DepthCache {
                    epoch,
                    depth: 0,
                    root: root.clone(),
                });
                break (0, root);
            };
            current = ancestor;
        };
        for node in path.into_iter().rev() {
            depth = depth.saturating_add(1);
            *node.depth_cache.borrow_mut() = Some(DepthCache {
                epoch,
                depth,
                root: root.clone(),
            });
        }
        depth
    }

    fn observe_depth(&self, parent: &Handle) {
        if self.max_depth != usize::MAX && self.parent_depth(parent) >= self.max_depth {
            self.repair_limit
                .set(Some(crate::types::WarningKind::DepthLimitExceeded));
        }
    }
}

impl TreeSink for RcDom {
    type Output = Self;
    fn finish(self) -> Self {
        self
    }

    type Handle = Handle;

    type ElemName<'a>
        = ExpandedName<'a>
    where
        Self: 'a;

    fn parse_error(&self, msg: Cow<'static, str>) {
        self.errors.borrow_mut().push(msg);
    }

    fn get_document(&self) -> Handle {
        self.document.clone()
    }

    fn get_template_contents(&self, target: &Handle) -> Handle {
        if let NodeData::Element {
            ref template_contents, ..
        } = target.data
        {
            template_contents
                .borrow()
                .as_ref()
                .expect("not a template element!")
                .clone()
        } else {
            panic!("not a template element!")
        }
    }

    fn set_quirks_mode(&self, mode: QuirksMode) {
        self.quirks_mode.set(mode);
    }

    fn same_node(&self, x: &Handle, y: &Handle) -> bool {
        Rc::ptr_eq(x, y)
    }

    fn elem_name<'a>(&self, target: &'a Handle) -> ExpandedName<'a> {
        match target.data {
            NodeData::Element { ref name, .. } => name.expanded(),
            _ => panic!("not an element!"),
        }
    }

    fn create_element(&self, name: QualName, attrs: Vec<Attribute>, flags: ElementFlags) -> Handle {
        let contents = flags.template.then(|| self.new_node(NodeData::Document));
        let element = self.new_node(NodeData::Element {
            name,
            attrs: RefCell::new(attrs),
            template_contents: RefCell::new(contents.clone()),
            mathml_annotation_xml_integration_point: flags.mathml_annotation_xml_integration_point,
        });
        // ~keep The contents of a template are not its children, so the depth limit would
        // ~keep count each template from zero. The contents name the template as their host,
        // ~keep and the count goes on through nested templates (issue #808). The contents keep
        // ~keep no parent: a node in them is not in the document (the `<base>` lookup reads that).
        if let Some(contents) = contents {
            contents.template_host.set(Some(Rc::downgrade(&element)));
        }
        element
    }

    fn create_comment(&self, text: StrTendril) -> Handle {
        self.new_node(NodeData::Comment { contents: text })
    }

    fn create_pi(&self, target: StrTendril, data: StrTendril) -> Handle {
        self.new_node(NodeData::ProcessingInstruction { target, contents: data })
    }

    fn append(&self, parent: &Handle, child: NodeOrText<Handle>) {
        self.observe_depth(parent);
        if let NodeOrText::AppendNode(node) = &child {
            if !node.children.borrow().is_empty() && !self.subtree_fits_depth(parent, std::slice::from_ref(node)) {
                return;
            }
        }
        if let NodeOrText::AppendText(text) = &child {
            if let Some(h) = parent.children.borrow().last() {
                if append_to_existing_text(h, text) {
                    return;
                }
            }
        }

        if let NodeOrText::AppendNode(node) = &child {
            self.prepare_attachment(parent, node);
        }
        append(
            parent,
            match child {
                NodeOrText::AppendText(text) => self.new_node(NodeData::Text {
                    contents: RefCell::new(text),
                }),
                NodeOrText::AppendNode(node) => node,
            },
        );
    }

    fn append_before_sibling(&self, sibling: &Handle, child: NodeOrText<Handle>) {
        let (parent, i) = get_parent_and_index(sibling).expect("append_before_sibling called on node without parent");

        self.observe_depth(&parent);
        if let NodeOrText::AppendNode(node) = &child {
            if !node.children.borrow().is_empty() && !self.subtree_fits_depth(&parent, std::slice::from_ref(node)) {
                return;
            }
        }
        let child = match (child, i) {
            (NodeOrText::AppendText(text), 0) => self.new_node(NodeData::Text {
                contents: RefCell::new(text),
            }),

            (NodeOrText::AppendText(text), i) => {
                let children = parent.children.borrow();
                let prev = &children[i - 1];
                if append_to_existing_text(prev, &text) {
                    return;
                }
                self.new_node(NodeData::Text {
                    contents: RefCell::new(text),
                })
            }

            (NodeOrText::AppendNode(node), _) => node,
        };

        self.invalidate_depths();
        remove_from_parent(&child);

        child.parent.set(Some(Rc::downgrade(&parent)));
        parent.children.borrow_mut().insert(i, child);
    }

    fn append_based_on_parent_node(
        &self,
        element: &Self::Handle,
        prev_element: &Self::Handle,
        child: NodeOrText<Self::Handle>,
    ) {
        let parent = element.parent.take();
        let has_parent = parent.is_some();
        element.parent.set(parent);

        if has_parent {
            self.append_before_sibling(element, child);
        } else {
            self.append(prev_element, child);
        }
    }

    fn append_doctype_to_document(&self, name: StrTendril, public_id: StrTendril, system_id: StrTendril) {
        append(
            &self.document,
            self.new_node(NodeData::Doctype {
                name,
                public_id,
                system_id,
            }),
        );
    }

    fn add_attrs_if_missing(&self, target: &Handle, attrs: Vec<Attribute>) {
        let mut existing = if let NodeData::Element { ref attrs, .. } = target.data {
            attrs.borrow_mut()
        } else {
            panic!("not an element")
        };

        let existing_names = existing.iter().map(|e| e.name.clone()).collect::<HashSet<_>>();
        existing.extend(attrs.into_iter().filter(|attr| !existing_names.contains(&attr.name)));
    }

    fn remove_from_parent(&self, target: &Handle) {
        self.invalidate_depths();
        remove_from_parent(target);
    }

    fn reparent_children(&self, node: &Handle, new_parent: &Handle) {
        self.observe_depth(new_parent);
        // ~keep Moving a subtree can exceed the limit even when its new parent's own depth is safe.
        if !self.subtree_fits_depth(new_parent, &node.children.borrow()) {
            return;
        }
        self.invalidate_depths();
        let mut children = node.children.borrow_mut();
        let mut new_children = new_parent.children.borrow_mut();
        for child in children.iter() {
            let previous_parent = child.parent.replace(Some(Rc::downgrade(new_parent)));
            assert!(Rc::ptr_eq(
                node,
                &previous_parent
                    .expect("invariant: child must have a parent during reparenting")
                    .upgrade()
                    .expect("dangling weak")
            ))
        }
        new_children.extend(mem::take(&mut *children));
    }

    fn is_mathml_annotation_xml_integration_point(&self, target: &Handle) -> bool {
        if let NodeData::Element {
            mathml_annotation_xml_integration_point,
            ..
        } = target.data
        {
            mathml_annotation_xml_integration_point
        } else {
            panic!("not an element!")
        }
    }
}

impl Default for RcDom {
    fn default() -> RcDom {
        RcDom {
            document: Node::new(NodeData::Document),
            errors: Default::default(),
            quirks_mode: Cell::new(tree_builder::NoQuirks),
            node_count: Cell::new(1),
            max_nodes: usize::MAX,
            max_depth: usize::MAX,
            topology_epoch: Cell::new(0),
            #[cfg(test)]
            depth_reads: Cell::new(0),
            repair_limit: Cell::new(None),
        }
    }
}

enum SerializeOp {
    Open(Handle),
    Close(QualName),
}

pub struct SerializableHandle(Handle, bool);

impl From<Handle> for SerializableHandle {
    fn from(h: Handle) -> SerializableHandle {
        SerializableHandle(h, false)
    }
}

impl SerializableHandle {
    /// A handle that writes the contents of each `<template>` between its two tags, as the
    /// HTML serialization does. [`From`] gives a handle that writes an empty `<template>`.
    pub const fn with_template_contents(h: Handle) -> SerializableHandle {
        SerializableHandle(h, true)
    }
}

impl Serialize for SerializableHandle {
    fn serialize<S>(&self, serializer: &mut S, traversal_scope: TraversalScope) -> io::Result<()>
    where
        S: Serializer,
    {
        let mut ops = VecDeque::new();
        match traversal_scope {
            IncludeNode => ops.push_back(SerializeOp::Open(self.0.clone())),
            ChildrenOnly(_) => ops.extend(self.0.children.borrow().iter().map(|h| SerializeOp::Open(h.clone()))),
        }

        while let Some(op) = ops.pop_front() {
            match op {
                SerializeOp::Open(handle) => match handle.data {
                    NodeData::Element {
                        ref name,
                        ref attrs,
                        ref template_contents,
                        ..
                    } => {
                        serializer
                            .start_elem(name.clone(), attrs.borrow().iter().map(|at| (&at.name, &at.value[..])))?;

                        // ~keep The contents of a template are not its children.
                        let contents = template_contents.borrow().clone().filter(|_| self.1);
                        let parent = contents.as_ref().unwrap_or(&handle);
                        // ~keep HTML parsing discards the first LF in these elements. Restore
                        // ~keep it when serializing so reparsing does not discard a content LF (#850).
                        if name.ns == html5ever::ns!(html)
                            && matches!(&*name.local, "pre" | "textarea" | "listing")
                            && parent.children.borrow().first().is_some_and(|child| {
                                matches!(&child.data, NodeData::Text { contents } if contents.borrow().starts_with('\n'))
                            })
                        {
                            serializer.write_text("\n")?;
                        }
                        ops.reserve(1 + parent.children.borrow().len());
                        ops.push_front(SerializeOp::Close(name.clone()));

                        for child in parent.children.borrow().iter().rev() {
                            ops.push_front(SerializeOp::Open(child.clone()));
                        }
                    }

                    NodeData::Doctype { ref name, .. } => serializer.write_doctype(name)?,

                    NodeData::Text { ref contents } => serializer.write_text(&contents.borrow())?,

                    NodeData::Comment { ref contents } => serializer.write_comment(contents)?,

                    NodeData::ProcessingInstruction {
                        ref target,
                        ref contents,
                    } => serializer.write_processing_instruction(target, contents)?,

                    NodeData::Document => panic!("Can't serialize Document node itself"),
                },

                SerializeOp::Close(name) => {
                    serializer.end_elem(name)?;
                }
            }
        }

        Ok(())
    }
}

#[cfg(test)]
mod bounded_reparent_tests {
    use super::*;
    use html5ever::{local_name, ns};

    #[test]
    fn bounded_repair_should_detect_descendant_depth_when_reparenting() {
        let dom = RcDom::bounded(100, 4);
        let element = || {
            dom.create_element(
                QualName::new(None, ns!(html), local_name!(div)),
                Vec::new(),
                ElementFlags::default(),
            )
        };
        let mut branch = dom.document.clone();
        let mut first = None;
        for _ in 0..4 {
            let child = element();
            dom.append(&branch, NodeOrText::AppendNode(child.clone()));
            first.get_or_insert_with(|| child.clone());
            branch = child;
        }
        let destination = element();
        dom.append(&dom.document, NodeOrText::AppendNode(destination.clone()));
        let nested_destination = element();
        dom.append(&destination, NodeOrText::AppendNode(nested_destination.clone()));
        assert_eq!(dom.repair_limit.get(), None);
        dom.reparent_children(&first.expect("source branch"), &nested_destination);
        assert_eq!(
            dom.repair_limit.get(),
            Some(crate::types::WarningKind::DepthLimitExceeded)
        );
    }
}

#[cfg(test)]
mod depth_cache_tests;

#[cfg(test)]
mod preformatted_serialization_tests {
    use super::{RcDom, SerializableHandle};
    use html5ever::serialize::{SerializeOpts, serialize};
    use html5ever::tendril::TendrilSink;

    #[test]
    fn should_preserve_initial_text_line_feeds_when_reparsed() {
        for name in ["pre", "textarea", "listing"] {
            for leading in 0..=3 {
                let input = format!("<{name}>{}x</{name}>", "\n".repeat(leading));
                let dom = html5ever::parse_document(RcDom::default(), Default::default()).one(input);
                let mut output = Vec::new();
                serialize(
                    &mut output,
                    &SerializableHandle::from(dom.document),
                    SerializeOpts::default(),
                )
                .expect("serialize preformatted element");
                let serialized_feeds = if leading == 1 { 0 } else { leading };
                assert_eq!(
                    String::from_utf8(output).expect("serialized HTML is UTF-8"),
                    format!(
                        "<html><head></head><body><{name}>{}x</{name}></body></html>",
                        "\n".repeat(serialized_feeds),
                    ),
                    "{name}: {leading} original line feeds",
                );
            }
        }
    }
}