Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix length change omission for StringSubstitutor cyclic detection #115

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1408,7 +1408,7 @@ private int substitute(final TextStringBuilder buf, final int offset, final int
// on the first call initialize priorVariables
if (priorVariables == null) {
priorVariables = new ArrayList<>();
priorVariables.add(new String(chars, offset, length));
priorVariables.add(new String(chars, offset, length + lengthChange));
}

// handle cyclic substitution
Expand Down
25 changes: 25 additions & 0 deletions src/test/java/org/apache/commons/text/StringSubstitutorTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.HashMap;
Expand Down Expand Up @@ -541,6 +542,30 @@ public void testReplaceToIdentical() {
doTestReplace("The ${animal} jumps.", "The ${animal} jumps.", true);
}

/**
* Tests a cyclic replace operation.
* The cycle should be detected and cause an exception to be thrown.
*/
@Test
public void testCyclicReplacement() {
final Map<String, String> map = new HashMap<>();
map.put("animal", "${critter}");
map.put("target", "${pet}");
map.put("pet", "${petCharacteristic} dog");
map.put("petCharacteristic", "lazy");
map.put("critter", "${critterSpeed} ${critterColor} ${critterType}");
map.put("critterSpeed", "quick");
map.put("critterColor", "brown");
map.put("critterType", "${animal}");
final StringSubstitutor sub = new StringSubstitutor(map);
assertThrows(IllegalStateException.class, () -> sub.replace("The ${animal} jumps over the ${target}."));

// also check even when default value is set.
map.put("critterType", "${animal:-fox}");
assertThrows(IllegalStateException.class,
() -> new StringSubstitutor(map).replace("The ${animal} jumps over the ${target}."));
}

/**
* Tests unknown key replace.
*/
Expand Down