11use core:: {
22 fmt:: Debug ,
33 ops:: { Deref , DerefMut } ,
4- slice:: IterMut ,
4+ slice:: { Iter , IterMut } ,
55} ;
66
77use alloc:: { string:: String , vec:: Vec } ;
88
9- use crate :: { Context , Node , Property , ctx } ;
9+ use crate :: { Context , Node , Property } ;
1010
1111#[ derive( Clone , Debug ) ]
1212pub enum NodeRef < ' a > {
@@ -127,13 +127,19 @@ impl<'a> DerefMut for NodeMut<'a> {
127127}
128128
129129pub struct NodeIter < ' a > {
130- stack : Vec < ( & ' a Node , Context < ' a > ) > ,
130+ ctx : Context < ' a > ,
131+ node : Option < & ' a Node > ,
132+ stack : Vec < Iter < ' a , Node > > ,
131133}
132134
133135impl < ' a > NodeIter < ' a > {
134136 pub fn new ( root : & ' a Node ) -> Self {
137+ let ctx = Context :: new ( ) ;
138+
135139 Self {
136- stack : vec ! [ ( root, Context :: new( ) ) ] ,
140+ ctx,
141+ node : Some ( root) ,
142+ stack : vec ! [ ] ,
137143 }
138144 }
139145}
@@ -142,16 +148,28 @@ impl<'a> Iterator for NodeIter<'a> {
142148 type Item = NodeRef < ' a > ;
143149
144150 fn next ( & mut self ) -> Option < Self :: Item > {
145- let ( node, ctx) = self . stack . pop ( ) ?;
151+ if let Some ( n) = self . node . take ( ) {
152+ // 返回当前节点,并将其子节点压入栈中
153+ let ctx = self . ctx . clone ( ) ;
154+ self . ctx . push ( n) ;
155+ self . stack . push ( n. children . iter ( ) ) ;
156+ return Some ( NodeRef :: new ( n, ctx) ) ;
157+ }
158+
159+ let iter = self . stack . last_mut ( ) ?;
146160
147- // 使用栈实现前序深度优先,保持原始子节点顺序
148- for child in node. children . iter ( ) . rev ( ) {
149- // 为子节点创建新的上下文,当前节点成为父节点
150- let child_ctx = ctx. for_child ( node) ;
151- self . stack . push ( ( child, child_ctx) ) ;
161+ if let Some ( child) = iter. next ( ) {
162+ // 返回子节点,并将其子节点压入栈中
163+ let ctx = self . ctx . clone ( ) ;
164+ self . ctx . push ( child) ;
165+ self . stack . push ( child. children . iter ( ) ) ;
166+ return Some ( NodeRef :: new ( child, ctx) ) ;
152167 }
153168
154- Some ( NodeRef :: new ( node, ctx) )
169+ // 当前迭代器耗尽,弹出栈顶
170+ self . stack . pop ( ) ;
171+ self . ctx . parents . pop ( ) ;
172+ self . next ( )
155173 }
156174}
157175
0 commit comments