@@ -26,13 +26,21 @@ pub struct SerializeOpts {
26
26
27
27
/// Serialize the root node? Default: ChildrenOnly
28
28
pub traversal_scope : TraversalScope ,
29
+
30
+ /// If the serializer is asked to serialize an invalid tree, the default
31
+ /// behavior is to panic in the event that an `end_elem` is created without a
32
+ /// matching `start_elem`. Setting this to true will prevent those panics by
33
+ /// creating a default parent on the element stack. No extra start elem will
34
+ /// actually be written. Default: false
35
+ pub create_missing_parent : bool ,
29
36
}
30
37
31
38
impl Default for SerializeOpts {
32
39
fn default ( ) -> SerializeOpts {
33
40
SerializeOpts {
34
41
scripting_enabled : true ,
35
42
traversal_scope : TraversalScope :: ChildrenOnly ,
43
+ create_missing_parent : false ,
36
44
}
37
45
}
38
46
}
@@ -73,8 +81,12 @@ impl<Wr: Write> HtmlSerializer<Wr> {
73
81
74
82
fn parent ( & mut self ) -> & mut ElemInfo {
75
83
if self . stack . len ( ) == 0 {
76
- warn ! ( "ElemInfo stack empty, creating new parent" ) ;
77
- self . stack . push ( Default :: default ( ) ) ;
84
+ if self . opts . create_missing_parent {
85
+ warn ! ( "ElemInfo stack empty, creating new parent" ) ;
86
+ self . stack . push ( Default :: default ( ) ) ;
87
+ } else {
88
+ panic ! ( "no parent ElemInfo" )
89
+ }
78
90
}
79
91
self . stack . last_mut ( ) . unwrap ( )
80
92
}
@@ -160,10 +172,14 @@ impl<Wr: Write> Serializer for HtmlSerializer<Wr> {
160
172
}
161
173
162
174
fn end_elem ( & mut self , name : QualName ) -> io:: Result < ( ) > {
163
- let info = self . stack . pop ( ) . unwrap_or_else ( || {
164
- warn ! ( "missing ElemInfo, creating default." ) ;
165
- Default :: default ( )
166
- } ) ;
175
+ let info = match self . stack . pop ( ) {
176
+ Some ( info) => info,
177
+ None if self . opts . create_missing_parent => {
178
+ warn ! ( "missing ElemInfo, creating default." ) ;
179
+ Default :: default ( )
180
+ }
181
+ _ => panic ! ( "no ElemInfo" ) ,
182
+ } ;
167
183
if info. ignore_children {
168
184
return Ok ( ( ) ) ;
169
185
}
0 commit comments