@@ -109,6 +109,8 @@ pub struct Node {
109
109
pub children : RefCell < Vec < Handle > > ,
110
110
/// Represents this node's data.
111
111
pub data : NodeData ,
112
+ /// Flag to control whether to free any children on destruction.
113
+ leak_children_on_drop : Cell < bool > ,
112
114
}
113
115
114
116
impl Node {
@@ -118,8 +120,38 @@ impl Node {
118
120
data : data,
119
121
parent : Cell :: new ( None ) ,
120
122
children : RefCell :: new ( Vec :: new ( ) ) ,
123
+ leak_children_on_drop : Cell :: new ( true ) ,
121
124
} )
122
125
}
126
+
127
+ /// Drop any child nodes remaining in this node at destruction.
128
+ ///
129
+ /// RcDom's destructor automatically drops any nodes and children that are
130
+ /// present in the document. This setting only affects nodes that are dropped
131
+ /// by manipulating the tree before RcDom's destructor runs (such as manually
132
+ /// removing children from a node after parsing is complete).
133
+ ///
134
+ /// Unsafety: due to the representation of children, this can trigger
135
+ /// stack overflow if dropping a node with a very deep tree of children.
136
+ /// This is not a recommended configuration to use when interacting with
137
+ /// arbitrary HTML content.
138
+ pub unsafe fn free_child_nodes_on_drop ( & self ) {
139
+ self . leak_children_on_drop . set ( false ) ;
140
+ }
141
+ }
142
+
143
+ impl Drop for Node {
144
+ fn drop ( & mut self ) {
145
+ if !self . children . borrow ( ) . is_empty ( ) {
146
+ if self . leak_children_on_drop . get ( ) {
147
+ warn ! ( "Dropping node with children outside of RcDom's destructor. \
148
+ Leaking memory for {} children.", self . children. borrow( ) . len( ) ) ;
149
+ for child in mem:: replace ( & mut * self . children . borrow_mut ( ) , vec ! [ ] ) {
150
+ mem:: forget ( child) ;
151
+ }
152
+ }
153
+ }
154
+ }
123
155
}
124
156
125
157
impl fmt:: Debug for Node {
@@ -195,6 +227,18 @@ pub struct RcDom {
195
227
pub quirks_mode : QuirksMode ,
196
228
}
197
229
230
+ impl Drop for RcDom {
231
+ fn drop ( & mut self ) {
232
+ // Ensure that node destructors execute linearly, rather
233
+ // than recursing through a tree of arbitrary depth.
234
+ let mut to_be_processed = vec ! [ self . document. clone( ) ] ;
235
+ while let Some ( node) = to_be_processed. pop ( ) {
236
+ to_be_processed. extend_from_slice ( & * node. children . borrow ( ) ) ;
237
+ node. children . borrow_mut ( ) . clear ( ) ;
238
+ }
239
+ }
240
+ }
241
+
198
242
impl TreeSink for RcDom {
199
243
type Output = Self ;
200
244
fn finish ( self ) -> Self {
0 commit comments