@@ -94,6 +94,32 @@ impl<T> Node<T> {
9494 value,
9595 }
9696 }
97+
98+ pub fn map < F , U > ( self , mut transform : F ) -> Node < U >
99+ where
100+ F : FnMut ( T ) -> U ,
101+ {
102+ Node {
103+ parent : self . parent ,
104+ prev_sibling : self . prev_sibling ,
105+ next_sibling : self . next_sibling ,
106+ children : self . children ,
107+ value : transform ( self . value ) ,
108+ }
109+ }
110+
111+ pub fn map_ref < F , U > ( & self , mut transform : F ) -> Node < U >
112+ where
113+ F : FnMut ( & T ) -> U ,
114+ {
115+ Node {
116+ parent : self . parent ,
117+ prev_sibling : self . prev_sibling ,
118+ next_sibling : self . next_sibling ,
119+ children : self . children ,
120+ value : transform ( & self . value ) ,
121+ }
122+ }
97123}
98124
99125/// Node reference.
@@ -232,6 +258,36 @@ impl<T> Tree<T> {
232258 self . vec . extend ( other_tree. vec ) ;
233259 unsafe { self . get_unchecked_mut ( other_tree_root_id) }
234260 }
261+
262+ /// Maps a `Tree<T>` to `Tree<U>` by applying a function to all node values,
263+ /// copying over the tree's structure and node ids untouched, consuming `self`.
264+ pub fn map < F , U > ( self , mut transform : F ) -> Tree < U >
265+ where
266+ F : FnMut ( T ) -> U ,
267+ {
268+ Tree {
269+ vec : self
270+ . vec
271+ . into_iter ( )
272+ . map ( |node| node. map ( & mut transform) )
273+ . collect ( ) ,
274+ }
275+ }
276+
277+ /// Maps a `&Tree<T>` to `Tree<U>` by applying a function to all node values,
278+ /// copying over the tree's structure and node ids untouched.
279+ pub fn map_ref < F , U > ( & self , mut transform : F ) -> Tree < U >
280+ where
281+ F : FnMut ( & T ) -> U ,
282+ {
283+ Tree {
284+ vec : self
285+ . vec
286+ . iter ( )
287+ . map ( |node| node. map_ref ( & mut transform) )
288+ . collect ( ) ,
289+ }
290+ }
235291}
236292
237293impl < ' a , T : ' a > NodeRef < ' a , T > {
0 commit comments