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
// Copyright © 2019 David Kellum
//
// This `Serialize` implementation was originally derived from
// `kuchiki::serializer` source, found here:
//
// https://github.com/kuchiki-rs/kuchiki
// (No copyright notice.)
// Licensed (per Cargo.toml) under the MIT license
//
// This in turn may have been derived in part from html5ever's implementation,
// see:
//
// https://github.com/servo/html5ever
// Copyright © 2014-2017 The html5ever Project Developers.
// Licensed under the Apache license v2.0, or the MIT license

use std::io;
use std::io::Write;
use std::string::ToString;

use html5ever::serialize::{
    serialize, Serialize, SerializeOpts, Serializer,
    TraversalScope, TraversalScope::*
};

use crate::dom::{Document, NodeData, NodeRef};

impl<'a> Serialize for NodeRef<'a> {
    fn serialize<S>(
        &self,
        serializer: &mut S,
        traversal_scope: TraversalScope)
        -> io::Result<()>
        where S: Serializer
    {
        use NodeData::*;

        match (traversal_scope, &self.data) {
            (ref scope, Elem(ref elm)) => {
                if *scope == IncludeNode {
                    serializer.start_elem(
                        elm.name.clone(),
                        elm.attrs.iter().map(|a| (&a.name, a.value.as_ref()))
                    )?;
                }
                for child in self.children() {
                    Serialize::serialize(&child, serializer, IncludeNode)?;
                }

                if *scope == IncludeNode {
                    serializer.end_elem(elm.name.clone())?;
                }
                Ok(())
            }

            (_, Hole) => {
                panic!("Hole in Document")
            }

            (_, Document) => {
                for child in self.children() {
                    Serialize::serialize(&child, serializer, IncludeNode)?;
                }
                Ok(())
            }

            (ChildrenOnly(_), _) => Ok(()),

            (IncludeNode, DocType(ref dt)) => {
                serializer.write_doctype(&dt.name)
            }
            (IncludeNode, Text(ref t)) => {
                serializer.write_text(&t)
            }
            (IncludeNode, Comment(ref t)) => {
                serializer.write_comment(&t)
            }
            (IncludeNode, Pi(ref pi)) => {
                serializer.write_processing_instruction(&"", &pi.data)
            }
        }
    }
}

/// Implemented via [`Document::serialize`].
impl ToString for Document {
    fn to_string(&self) -> String {
        let mut u8_vec = Vec::new();
        self.serialize(&mut u8_vec).unwrap();
        unsafe { String::from_utf8_unchecked(u8_vec) }
    }
}

/// Serialize convenience method.
impl Document {
    /// Serialize the contents of the document node and descendants in HTML
    /// syntax to the given stream.
    pub fn serialize<W>(&self, writer: &mut W) -> io::Result<()>
        where W: Write
    {
        serialize(
            writer,
            &self.document_node_ref(),
            SerializeOpts {
                traversal_scope: ChildrenOnly(None),
                ..Default::default()
            },
        )
    }
}

/// Serialize convenience method.
impl<'a> NodeRef<'a> {
    /// Serialize the referenced node and its descendants in HTML syntax to the
    /// given stream.
    pub fn serialize<W>(&'a self, writer: &mut W) -> io::Result<()>
        where W: Write
    {
        serialize(
            writer,
            self,
            SerializeOpts {
                traversal_scope: IncludeNode,
                ..Default::default()
            },
        )
    }
}

/// Implemented via [`NodeRef::serialize`].
impl<'a> ToString for NodeRef<'a> {
    fn to_string(&self) -> String {
        let mut u8_vec = Vec::new();
        self.serialize(&mut u8_vec).unwrap();
        unsafe { String::from_utf8_unchecked(u8_vec) }
    }
}