Skip to content

Commit 6449f38

Browse files
committed
Pull the (m, n) calculation out into sub function
The `normalize` function spans more than a screen (on my monitor), as such it is hard to work on. Refactor out the (m, n)-thresh calculation to a function so that the body of the function becomes shorter. Refactor only, no logic changes.
1 parent 2c3d41d commit 6449f38

File tree

1 file changed

+22
-11
lines changed

1 file changed

+22
-11
lines changed

src/policy/semantic.rs

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -402,6 +402,26 @@ impl<Pk: MiniscriptKey> Policy<Pk> {
402402
/// Flattens out trees of `And`s and `Or`s; eliminate `Trivial` and
403403
/// `Unsatisfiable`s. Does not reorder any branches; use `.sort`.
404404
pub fn normalized(self) -> Policy<Pk> {
405+
// Returns (m, n)-thresh values for the normalized (k, subs.len())-thresh.
406+
fn normalized_threshold_values<Pk: MiniscriptKey>(
407+
k: usize,
408+
subs: &[Arc<Policy<Pk>>],
409+
) -> (usize, usize) {
410+
let trivial_count = subs
411+
.iter()
412+
.filter(|&pol| *pol.as_ref() == Policy::Trivial)
413+
.count();
414+
let unsatisfied_count = subs
415+
.iter()
416+
.filter(|&pol| *pol.as_ref() == Policy::Unsatisfiable)
417+
.count();
418+
419+
let n = subs.len() - unsatisfied_count - trivial_count; // remove all true/false
420+
let m = k.checked_sub(trivial_count).unwrap_or(0); // satisfy all trivial
421+
422+
(m, n)
423+
}
424+
405425
match self {
406426
Policy::Threshold(k, subs) => {
407427
let mut ret_subs = Vec::with_capacity(subs.len());
@@ -410,17 +430,8 @@ impl<Pk: MiniscriptKey> Policy<Pk> {
410430
.into_iter()
411431
.map(|sub| Arc::new(sub.as_ref().clone().normalized()))
412432
.collect();
413-
let trivial_count = subs
414-
.iter()
415-
.filter(|&pol| *pol.as_ref() == Policy::Trivial)
416-
.count();
417-
let unsatisfied_count = subs
418-
.iter()
419-
.filter(|&pol| *pol.as_ref() == Policy::Unsatisfiable)
420-
.count();
421-
422-
let n = subs.len() - unsatisfied_count - trivial_count; // remove all true/false
423-
let m = k.checked_sub(trivial_count).unwrap_or(0); // satisfy all trivial
433+
434+
let (m, n) = normalized_threshold_values(k, &subs);
424435

425436
let parent_is_and = m == n; // (n, n)-thresh is an AND
426437
let parent_is_or = m == 1; // (1, n)-thresh is an OR

0 commit comments

Comments
 (0)