Skip to content

Commit 4740ceb

Browse files
committed
Compute memory usage well
1 parent 0835a72 commit 4740ceb

File tree

1 file changed

+33
-18
lines changed
  • regex-automata/src/nfa/thompson

1 file changed

+33
-18
lines changed

regex-automata/src/nfa/thompson/nfa.rs

Lines changed: 33 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1185,7 +1185,10 @@ impl NFA {
11851185
+ self.0.states.len() * size_of::<State>()
11861186
+ self.0.start_pattern.len() * size_of::<StateID>()
11871187
+ self.0.group_info.memory_usage()
1188-
+ self.0.start_look_behind.len() * size_of::<StateID>()
1188+
+ self.0.lookbehinds.iter()
1189+
.map(|b|
1190+
b.try_fold(0, &|acc, _| Some(acc + 1)).unwrap()
1191+
).sum::<usize>() * size_of::<LookBehindTree>()
11891192
+ self.0.memory_extra
11901193
}
11911194
}
@@ -1319,23 +1322,30 @@ impl LookBehindTree {
13191322
}
13201323

13211324
/// Calls `fun` on this look-behind tree and all of its children in pre-order.
1322-
/// `fun` should return `true` if the traversal should continue and `false`
1325+
/// `fun` should return `Some` if the traversal should continue and `None`
13231326
/// if it should stop.
13241327
///
1325-
/// The return value indicates whether the traversal was at any point stopped.
1326-
pub fn preorder(&self, fun: &impl Fn(&LookBehindTree) -> bool) -> bool {
1327-
if !fun(self) {
1328-
return false;
1329-
}
1330-
for child in &self.children {
1331-
if !child.preorder(fun) {
1332-
return false;
1333-
}
1328+
/// The return value is the fold of all `Some`s, or `None` if at any point `None`
1329+
/// was returned.
1330+
pub fn try_fold<A>(
1331+
&self,
1332+
acc: A,
1333+
fun: &impl Fn(A, &LookBehindTree) -> Option<A>,
1334+
) -> Option<A> {
1335+
if let Some(acc) = fun(acc, self) {
1336+
self.children
1337+
.iter()
1338+
.try_fold(acc, |acc, child| child.try_fold(acc, fun))
1339+
} else {
1340+
None
13341341
}
1335-
true
13361342
}
13371343

1338-
/// Like [`preorder`], but allows mutating the nodes.
1344+
/// Calls `fun` on this look-behind tree and all of its children in pre-order.
1345+
/// `fun` should return `true` if the traversal should continue and `false`
1346+
/// if it should stop.
1347+
///
1348+
/// The return value indicates whether the traversal was at any point stopped.
13391349
pub fn preorder_mut(
13401350
&mut self,
13411351
fun: &impl Fn(&mut LookBehindTree) -> bool,
@@ -1577,11 +1587,16 @@ impl fmt::Debug for Inner {
15771587
'^'
15781588
} else if sid == self.start_unanchored {
15791589
'>'
1580-
} else if self
1581-
.lookbehinds
1582-
.iter()
1583-
.any(|i| !i.preorder(&|e| e.start_id() != sid))
1584-
{
1590+
} else if self.lookbehinds.iter().any(|i| {
1591+
i.try_fold((), &|_, e| {
1592+
if e.start_id() == sid {
1593+
None
1594+
} else {
1595+
Some(())
1596+
}
1597+
})
1598+
.is_none()
1599+
}) {
15851600
'<'
15861601
} else {
15871602
' '

0 commit comments

Comments
 (0)