@@ -205,6 +205,28 @@ impl<T> Tree<T> {
205
205
self . vec . push ( Node :: new ( value) ) ;
206
206
unsafe { self . get_unchecked_mut ( id) }
207
207
}
208
+
209
+ /// Merge with another tree as orphan, returning the new root of tree being merged.
210
+ pub fn extend_tree ( & mut self , mut other_tree : Tree < T > ) -> NodeMut < T > {
211
+ let offset = self . vec . len ( ) ;
212
+ let offset_id = |id : NodeId | -> NodeId {
213
+ let old_index = id. to_index ( ) ;
214
+ let new_index = old_index + offset;
215
+ unsafe { NodeId :: from_index ( new_index) }
216
+ } ;
217
+ let other_tree_root_id = offset_id ( other_tree. root ( ) . id ) ;
218
+ for node in other_tree. vec . iter_mut ( ) {
219
+ node. parent . as_mut ( ) . map ( |id| * id = offset_id ( * id) ) ;
220
+ node. prev_sibling . as_mut ( ) . map ( |id| * id = offset_id ( * id) ) ;
221
+ node. next_sibling . as_mut ( ) . map ( |id| * id = offset_id ( * id) ) ;
222
+ node. children . as_mut ( ) . map ( |( id1, id2) | {
223
+ * id1 = offset_id ( * id1) ;
224
+ * id2 = offset_id ( * id2) ;
225
+ } ) ;
226
+ }
227
+ self . vec . extend ( other_tree. vec ) ;
228
+ unsafe { self . get_unchecked_mut ( other_tree_root_id) }
229
+ }
208
230
}
209
231
210
232
impl < ' a , T : ' a > NodeRef < ' a , T > {
@@ -341,6 +363,18 @@ impl<'a, T: 'a> NodeMut<'a, T> {
341
363
self . prepend_id ( id)
342
364
}
343
365
366
+ /// Appends a subtree, return the root of the merged subtree.
367
+ pub fn append_subtree ( & mut self , subtree : Tree < T > ) -> NodeMut < T > {
368
+ let root_id = self . tree . extend_tree ( subtree) . id ;
369
+ self . append_id ( root_id)
370
+ }
371
+
372
+ /// Prepends a subtree, return the root of the merged subtree.
373
+ pub fn prepend_subtree ( & mut self , subtree : Tree < T > ) -> NodeMut < T > {
374
+ let root_id = self . tree . extend_tree ( subtree) . id ;
375
+ self . prepend_id ( root_id)
376
+ }
377
+
344
378
/// Inserts a new sibling before this node.
345
379
///
346
380
/// # Panics
0 commit comments