Skip to content

Commit b1ae1ff

Browse files
committed
semantic: Remove recursion in n_terminals
Done as part of the effort to remove all the recursion crate wide. Use the `TreeLike` trait to iterate over policy nodes and remove the recursive call in `semantic::Policy::n_terminals`.
1 parent 211abad commit b1ae1ff

File tree

1 file changed

+14
-4
lines changed

1 file changed

+14
-4
lines changed

src/policy/semantic.rs

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -181,11 +181,21 @@ impl<Pk: MiniscriptKey> Policy<Pk> {
181181

182182
// Helper function to compute the number of constraints in policy.
183183
fn n_terminals(&self) -> usize {
184-
match self {
185-
&Policy::Threshold(_k, ref subs) => subs.iter().map(|sub| sub.n_terminals()).sum(),
186-
&Policy::Trivial | &Policy::Unsatisfiable => 0,
187-
_leaf => 1,
184+
use Policy::*;
185+
186+
let mut n_terminals = vec![];
187+
for data in self.post_order_iter() {
188+
let n_terminals_for_child_n = |n| n_terminals[data.child_indices[n]];
189+
190+
let num = match data.node {
191+
Threshold(_k, subs) => (0..subs.len()).map(n_terminals_for_child_n).sum(),
192+
Trivial | Unsatisfiable => 0,
193+
_leaf => 1,
194+
};
195+
n_terminals.push(num);
188196
}
197+
// Ok to unwrap because we know we processed at least one node.
198+
n_terminals.pop().unwrap()
189199
}
190200

191201
// Helper function to get the first constraint in the policy.

0 commit comments

Comments
 (0)