diff --git a/crates/xfa/src/proto.rs b/crates/xfa/src/proto.rs index ae1505804e..99dc18b689 100644 --- a/crates/xfa/src/proto.rs +++ b/crates/xfa/src/proto.rs @@ -74,6 +74,7 @@ pub(crate) fn expand(template: Node) -> (Option, Vec) { soms: HashMap::new(), search: MAX_SEARCH, work: MAX_WORK, + child_counts: HashMap::new(), active: HashMap::new(), missing: false, external: false, @@ -124,6 +125,8 @@ struct Writer<'a> { search: usize, /// Children, attributes and namespaces left to look at while merging layers. work: usize, + /// Bounded memoization only; each use still pays the full child count. + child_counts: HashMap, /// The elements being written around the current one: inheriting from one is a loop. active: HashMap, missing: bool, @@ -132,6 +135,22 @@ struct Writer<'a> { layers_cut: bool, } +/// Counting a reused prototype must not itself repeatedly walk its descendants. +/// Cache only complete direct-child counts, and cap the optimization's memory. +/// Truncated counts are not exact and must never be cached. Budget charging is unchanged. +fn child_count(node: Node<'_>, work: usize, cache: &mut HashMap) -> usize { + const MAX_CACHED_COUNTS: usize = 4_096; + let stop = work.saturating_add(1); + if let Some(count) = cache.get(&node.id()) { + return (*count).min(stop); + } + let count = node.children().take(stop).count(); + if count < stop && cache.len() < MAX_CACHED_COUNTS { + cache.insert(node.id(), count); + } + count +} + fn escape(s: &str, attribute: bool, out: &mut String) { for c in s.chars() { match c { @@ -439,7 +458,7 @@ impl<'a> Writer<'a> { // further than the budget left), attributes and namespaces, and the scope around it. let mut cost = scope.len().saturating_add(layers.len()); for l in &layers { - let children = l.children().take(self.work.saturating_add(1)).count(); + let children = child_count(*l, self.work, &mut self.child_counts); cost = cost.saturating_add(children).saturating_add(l.attributes().len()).saturating_add(l.namespaces().len()); } if self.failed.is_some() || !self.charge(cost) { diff --git a/crates/xfa/src/proto/tests.rs b/crates/xfa/src/proto/tests.rs index ba7f6f8316..636886bb62 100644 --- a/crates/xfa/src/proto/tests.rs +++ b/crates/xfa/src/proto/tests.rs @@ -399,3 +399,28 @@ fn a_som_expression_past_its_length_limit_is_not_followed() { assert_eq!(field(&t, "long").common.h, None); assert!(close(field(&t, "short").common.h, 2.0 * MM)); } + +#[test] +fn cached_child_counts_preserve_truncation_and_charge_when_budget_shrinks() { + let doc = crate::xml::Document::parse("").unwrap(); + let node = doc.root_element(); + let mut cache = std::collections::HashMap::new(); + assert_eq!(super::child_count(node, 1, &mut cache), 2); + assert!(cache.is_empty(), "truncated counts are not reusable"); + assert_eq!(super::child_count(node, 10, &mut cache), 3); + assert_eq!(cache.get(&node.id()), Some(&3)); + for remaining in 0..=5 { + assert_eq!(super::child_count(node, remaining, &mut cache), node.children().take(remaining + 1).count()); + } + assert_eq!(super::child_count(node, 10, &mut cache), 3, "a cached use is still charged"); +} + +#[test] +fn child_count_memoization_has_a_fixed_entry_limit() { + let doc = crate::xml::Document::parse(&format!("{}", "".repeat(5_000))).unwrap(); + let mut cache = std::collections::HashMap::new(); + for node in doc.root_element().children() { + assert_eq!(super::child_count(node, 1, &mut cache), 0); + } + assert_eq!(cache.len(), 4_096); +}