From 05804a35dfe8a0d013754ba19a8830b5232aa496 Mon Sep 17 00:00:00 2001 From: John Bauer Date: Thu, 15 Aug 2024 05:26:18 -0700 Subject: [PATCH] Remove recursion - really weird graphs can cause a stack overflow. Instead, just loop until the vertexIterator is used up. Observed in https://github.com/stanfordnlp/CoreNLP/issues/1461 --- .../nlp/graph/DirectedMultiGraph.java | 30 ++++++++++--------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/src/edu/stanford/nlp/graph/DirectedMultiGraph.java b/src/edu/stanford/nlp/graph/DirectedMultiGraph.java index 68dd9255cc..26639d8f50 100644 --- a/src/edu/stanford/nlp/graph/DirectedMultiGraph.java +++ b/src/edu/stanford/nlp/graph/DirectedMultiGraph.java @@ -571,20 +571,22 @@ public E next() { } private void primeIterator() { - if (edgeIterator != null && edgeIterator.hasNext()) { - hasNext = true; // technically, we shouldn't need to put this here, but let's be safe - } else if (connectionIterator != null && connectionIterator.hasNext()) { - Map.Entry> nextConnection = connectionIterator.next(); - edgeIterator = nextConnection.getValue().iterator(); - currentTarget = nextConnection.getKey(); - primeIterator(); - } else if (vertexIterator != null && vertexIterator.hasNext()) { - Map.Entry>> nextVertex = vertexIterator.next(); - connectionIterator = nextVertex.getValue().entrySet().iterator(); - currentSource = nextVertex.getKey(); - primeIterator(); - } else { - hasNext = false; + while (true) { + if (edgeIterator != null && edgeIterator.hasNext()) { + hasNext = true; // technically, we shouldn't need to put this here, but let's be safe + return; + } else if (connectionIterator != null && connectionIterator.hasNext()) { + Map.Entry> nextConnection = connectionIterator.next(); + edgeIterator = nextConnection.getValue().iterator(); + currentTarget = nextConnection.getKey(); + } else if (vertexIterator != null && vertexIterator.hasNext()) { + Map.Entry>> nextVertex = vertexIterator.next(); + connectionIterator = nextVertex.getValue().entrySet().iterator(); + currentSource = nextVertex.getKey(); + } else { + hasNext = false; + return; + } } }