Parse input bytes into an HTML document.
(
bytes: &[u8],
preallocate_node_capacity: usize,
mode: InliningMode,
)
| 24 | |
| 25 | /// Parse input bytes into an HTML document. |
| 26 | pub(crate) fn parse_with_options( |
| 27 | bytes: &[u8], |
| 28 | preallocate_node_capacity: usize, |
| 29 | mode: InliningMode, |
| 30 | ) -> Document { |
| 31 | let sink = Sink { |
| 32 | document: RefCell::new(Document::with_capacity( |
| 33 | preallocate_node_capacity, |
| 34 | bytes.len(), |
| 35 | )), |
| 36 | }; |
| 37 | let options = html5ever::ParseOpts::default(); |
| 38 | match mode { |
| 39 | InliningMode::Document => html5ever::parse_document(sink, options) |
| 40 | .from_utf8() |
| 41 | .one(bytes), |
| 42 | InliningMode::Fragment => { |
| 43 | let mut document = html5ever::parse_fragment( |
| 44 | sink, |
| 45 | options, |
| 46 | QualName::new(None, ns!(html), local_name!("")), |
| 47 | vec![], |
| 48 | false, |
| 49 | ) |
| 50 | .from_utf8() |
| 51 | .one(bytes); |
| 52 | let document_id = NodeId::document_id(); |
| 53 | let context_element_id = NodeId::new( |
| 54 | document_id |
| 55 | .get() |
| 56 | // The first one is a node representing the "" element passed above, then the |
| 57 | // second one is the "html" element. |
| 58 | .checked_add(2) |
| 59 | .expect("Document id is too small to overflow"), |
| 60 | ); |
| 61 | document.reparent_children(context_element_id, document_id); |
| 62 | document |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | /// Intermediary structure for parsing an HTML document. |
| 68 | /// It takes care of creating and appending nodes to the document as the parsing progresses. |