@@ -2,7 +2,7 @@ use std::iter::FusedIterator;
2
2
use std:: ops:: Range ;
3
3
use std:: { slice, vec} ;
4
4
5
- use crate :: { Node , NodeId , NodeRef , Tree } ;
5
+ use crate :: { Node , NodeId , NodeMut , NodeRef , Tree } ;
6
6
7
7
/// Iterator that moves out of a tree in insert order.
8
8
#[ derive( Debug ) ]
@@ -216,6 +216,52 @@ impl<'a, T: 'a> DoubleEndedIterator for Children<'a, T> {
216
216
}
217
217
}
218
218
219
+ /// Iterator over mutable children.
220
+ #[ derive( Debug ) ]
221
+ pub struct ChildrenMut < ' a , T : ' a > {
222
+ tree : & ' a mut Tree < T > ,
223
+ front : Option < NodeId > ,
224
+ back : Option < NodeId > ,
225
+ }
226
+ impl < ' a , T : ' a > FusedIterator for ChildrenMut < ' a , T > { }
227
+ impl < ' a , T : ' a > Iterator for ChildrenMut < ' a , T > {
228
+ type Item = NodeMut < ' a , T > ;
229
+ fn next ( & mut self ) -> Option < Self :: Item > {
230
+ // lifetime cast here is safe because &mut self living shorter than 'a
231
+ let tree = unsafe { & mut * ( self . tree as * mut Tree < T > ) } ;
232
+ if self . front == self . back {
233
+ let node = self . front . take ( ) . and_then ( |x| tree. get_mut ( x) ) ;
234
+ self . back = None ;
235
+ node
236
+ } else {
237
+ let mut node = self . front . take ( ) . and_then ( |x| tree. get_mut ( x) ) ;
238
+ self . front = node
239
+ . as_mut ( )
240
+ . and_then ( |x : & mut NodeMut < T > | x. next_sibling ( ) )
241
+ . map ( |x| x. id ( ) ) ;
242
+ node
243
+ }
244
+ }
245
+ }
246
+ impl < ' a , T : ' a > DoubleEndedIterator for ChildrenMut < ' a , T > {
247
+ fn next_back ( & mut self ) -> Option < Self :: Item > {
248
+ // lifetime cast here is safe because &mut self living shorter than 'a
249
+ let tree = unsafe { & mut * ( self . tree as * mut Tree < T > ) } ;
250
+ if self . front == self . back {
251
+ let node = self . back . take ( ) . and_then ( |x| tree. get_mut ( x) ) ;
252
+ self . front = None ;
253
+ node
254
+ } else {
255
+ let mut node = self . back . take ( ) . and_then ( |x| tree. get_mut ( x) ) ;
256
+ self . back = node
257
+ . as_mut ( )
258
+ . and_then ( |x : & mut NodeMut < T > | x. prev_sibling ( ) )
259
+ . map ( |x| x. id ( ) ) ;
260
+ node
261
+ }
262
+ }
263
+ }
264
+
219
265
/// Open or close edge of a node.
220
266
#[ derive( Debug ) ]
221
267
pub enum Edge < ' a , T : ' a > {
@@ -354,3 +400,15 @@ impl<'a, T: 'a> NodeRef<'a, T> {
354
400
Descendants ( self . traverse ( ) )
355
401
}
356
402
}
403
+
404
+ impl < ' a , T : ' a > NodeMut < ' a , T > {
405
+ /// Returns an iterator over mutable children.
406
+ pub fn children_mut < ' b > ( & ' b mut self ) -> ChildrenMut < ' b , T > {
407
+ let ( front, back) = self . node ( ) . children . unzip ( ) ;
408
+ ChildrenMut {
409
+ tree : self . tree ,
410
+ front,
411
+ back,
412
+ }
413
+ }
414
+ }
0 commit comments