Skip to content

Commit 8b122e5

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 bfa00f0 commit 8b122e5

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
@@ -189,11 +189,21 @@ impl<Pk: MiniscriptKey> Policy<Pk> {
189189

190190
// Helper function to compute the number of constraints in policy.
191191
fn n_terminals(&self) -> usize {
192-
match self {
193-
&Policy::Threshold(_k, ref subs) => subs.iter().map(|sub| sub.n_terminals()).sum(),
194-
&Policy::Trivial | &Policy::Unsatisfiable => 0,
195-
_leaf => 1,
192+
use Policy::*;
193+
194+
let mut n_terminals = vec![];
195+
for data in self.post_order_iter() {
196+
let n_terminals_for_child_n = |n| n_terminals[data.child_indices[n]];
197+
198+
let num = match data.node {
199+
Threshold(_k, subs) => (0..subs.len()).map(n_terminals_for_child_n).sum(),
200+
Trivial | Unsatisfiable => 0,
201+
_leaf => 1,
202+
};
203+
n_terminals.push(num);
196204
}
205+
// Ok to unwrap because we know we processed at least one node.
206+
n_terminals.pop().unwrap()
197207
}
198208

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

0 commit comments

Comments
 (0)