This is an automated email from the ASF dual-hosted git repository.

garydgregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-lang.git


The following commit(s) were added to refs/heads/master by this push:
     new e2a0789bc Fix search overflow and excessive allocation in Strings
e2a0789bc is described below

commit e2a0789bc936783fa2a75263412e3359d4c0f97b
Author: Gary Gregory <[email protected]>
AuthorDate: Sun Nov 15 17:34:53 2026 -0500

    Fix search overflow and excessive allocation in Strings
    
    Use overflow-safe bounds in CI.indexOf and the CharSequenceUtils
    lastIndexOf fallback. Limit replacement capacity estimates by the
    possible match count and a 20% growth allowance.
    
    Add virtual-input boundary tests and constrained-heap regressions,
    replace obsolete capacity tests, and correct Javadoc and release notes.
    
    Assisted-By: OpenAI Codex
---
 src/changes/changes.xml                            |   4 +
 .../apache/commons/lang3/CharSequenceUtils.java    |   2 +-
 .../java/org/apache/commons/lang3/Strings.java     |  79 +++++++------
 .../apache/commons/lang3/StringsOverflowTest.java  | 130 +++++++++++++++++++++
 .../commons/lang3/StringsReplaceMemoryTest.java    | 109 +++++++++++++++++
 .../java/org/apache/commons/lang3/StringsTest.java |  80 ++++++-------
 6 files changed, 322 insertions(+), 82 deletions(-)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index f5aed66d1..f87a4efe0 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -96,6 +96,10 @@ The <action> type attribute can be add,update,fix,remove.
     <action                   type="fix" dev="ggregory" due-to="Gary 
Gregory">Prevent loop-counter and edit-cost overflow in 
StringUtils.getLevenshteinDistance for CharSequence inputs of Integer.MAX_VALUE 
length, with and without a threshold.</action>
     <action                   type="fix" dev="ggregory" due-to="Gary 
Gregory">Prevent score overflow in StringUtils.getFuzzyDistance(CharSequence, 
CharSequence, Locale), throwing ArithmeticException when the score exceeds 
Integer.MAX_VALUE.</action>
     <action                   type="fix" dev="ggregory" due-to="Gary Gregory, 
Amar Ghugare">Fix class loader resolution when cloning dynamic proxies.</action>
+    <action                   type="fix" dev="ggregory" due-to="Gary 
Gregory">Prevent empty-search index overflow in Strings.CI.indexOf for 
CharSequence inputs of Integer.MAX_VALUE length.</action>
+    <action                   type="fix" dev="ggregory" due-to="Gary 
Gregory">Prevent search-bound overflow in CharSequenceUtils.lastIndexOf, 
including calls through Strings.CS.lastIndexOf.</action>
+    <action                   type="fix" dev="ggregory" due-to="Gary 
Gregory">Bound speculative initial capacity in Strings.replace by the possible 
match count and a 20% growth limit, avoiding premature memory exhaustion for 
large replacements.</action>
+    <action                   type="fix" dev="ggregory" due-to="Gary 
Gregory">Correct Strings Javadoc for case sensitivity, null ordering, prefix 
and suffix matching, and search bounds.</action>
     <!-- ADD -->
     <!-- UPDATE -->
   </release>
diff --git a/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java 
b/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java
index b5b3401fd..f7a176e99 100644
--- a/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java
+++ b/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java
@@ -224,7 +224,7 @@ static int lastIndexOf(final CharSequence cs, final 
CharSequence searchChar, int
             }
         }
 
-        if (start + len2 > len1) {
+        if (start > len1 - len2) {
             start = len1 - len2;
         }
 
diff --git a/src/main/java/org/apache/commons/lang3/Strings.java 
b/src/main/java/org/apache/commons/lang3/Strings.java
index d7157d283..49a10de21 100644
--- a/src/main/java/org/apache/commons/lang3/Strings.java
+++ b/src/main/java/org/apache/commons/lang3/Strings.java
@@ -148,15 +148,16 @@ public int indexOf(final CharSequence str, final 
CharSequence searchStr, int sta
             if (startPos < 0) {
                 startPos = 0;
             }
-            final int endLimit = str.length() - searchStr.length() + 1;
-            if (startPos >= endLimit) {
+            final int searchStrLength = searchStr.length();
+            final int lastStart = str.length() - searchStrLength;
+            if (startPos > lastStart) {
                 return INDEX_NOT_FOUND;
             }
-            if (searchStr.length() == 0) {
+            if (searchStrLength == 0) {
                 return startPos;
             }
-            for (int i = startPos; i < endLimit; i++) {
-                if (CharSequenceUtils.regionMatches(str, true, i, searchStr, 
0, searchStr.length())) {
+            for (int i = startPos; i <= lastStart; i++) {
+                if (CharSequenceUtils.regionMatches(str, true, i, searchStr, 
0, searchStrLength)) {
                     return i;
                 }
             }
@@ -309,27 +310,30 @@ private static boolean eq(final Object o1, final Object 
o2) {
     }
 
     /**
-     * Computes a safe initial capacity for the {@link StringBuilder} used by 
{@link #replace(String, String, String, int)}.
+     * Computes a bounded initial capacity for the {@link StringBuilder} used 
by {@link #replace(String, String, String, int)}.
+     *
      * <p>
-     * Uses {@code long} arithmetic so that the estimated growth cannot 
overflow {@code int} when {@code replacementLength} is much greater than
-     * {@code searchLength}, and clamps the result to {@link 
ArrayUtils#SAFE_MAX_ARRAY_LENGTH} so that {@code new StringBuilder(int)} is 
never invoked with a
-     * value that exceeds the VM's array-size limit.
+     * Estimates at most 16 replacements when {@code max} is negative, or 64 
otherwise, and never more than can fit in the input. Estimated growth is capped
+     * at 20% of the input length, as in {@link 
StringUtils#replaceEach(String, String[], String[])}, so a large replacement 
does not force a large speculative
+     * allocation. The builder can grow as needed.
      * </p>
+     *
      * <p>
-     * The estimated number of matches is {@code 16} when {@code max} is 
negative (unbounded), otherwise {@code Math.min(max, 64)}. These multipliers 
preserve
-     * the historical behavior of the inlined estimate.
+     * Uses {@code long} arithmetic to avoid overflow. If the estimate exceeds 
{@link ArrayUtils#SAFE_MAX_ARRAY_LENGTH}, starts with zero capacity instead.
      * </p>
      *
-     * @param textLen        The length of the input text, in characters.
-     * @param searchLen      The length of the search string, in characters.
-     * @param replacementLen The length of the replacement string, in 
characters.
-     * @param max               The maximum number of replacements, or {@code 
-1} for no maximum.
-     * @return A non-negative initial capacity, never greater than {@link 
ArrayUtils#SAFE_MAX_ARRAY_LENGTH}.
+     * @param textLen The non-negative length of the input text, in characters.
+     * @param searchLen The positive length of the search string, in 
characters.
+     * @param replacementLen The non-negative length of the replacement 
string, in characters.
+     * @param max The maximum number of replacements, or a negative value for 
no maximum.
+     * @return A non-negative initial capacity, or zero if the estimate 
exceeds the array-size limit.
      */
     static int initialCapacity(final int textLen, final int searchLen, final 
int replacementLen, final int max) {
+        final int estimatedMatches = Math.min(textLen / searchLen, max < 0 ? 
16 : Math.min(max, 64));
         final long perReplacementGrowth = Math.max((long) replacementLen - 
searchLen, 0L);
-        final long totalGrowth = perReplacementGrowth * (max < 0 ? 16 : 
Math.min(max, 64));
-        return (int) Math.min(textLen + totalGrowth, 
ArrayUtils.SAFE_MAX_ARRAY_LENGTH);
+        final long growth = Math.min(textLen / 5, perReplacementGrowth * 
estimatedMatches);
+        final long capacity = textLen + growth;
+        return capacity > ArrayUtils.SAFE_MAX_ARRAY_LENGTH ? 0 : (int) 
capacity;
     }
 
     /**
@@ -434,7 +438,7 @@ public String appendIfMissing(final String str, final 
CharSequence suffix, final
     }
 
     /**
-     * Compare two Strings lexicographically, like {@link 
String#compareTo(String)}.
+     * Compares two Strings lexicographically, using this instance's 
case-sensitivity and null-ordering settings.
      * <p>
      * The return values are:
      * </p>
@@ -445,15 +449,13 @@ public String appendIfMissing(final String str, final 
CharSequence suffix, final
      * </ul>
      *
      * <p>
-     * This is a {@code null} safe version of :
+     * Non-null strings are compared using {@link String#compareTo(String)} 
for case-sensitive instances and {@link String#compareToIgnoreCase(String)} for
+     * case-insensitive instances.
      * </p>
      *
-     * <pre>
-     * str1.compareTo(str2)
-     * </pre>
-     *
      * <p>
-     * {@code null} value is considered less than non-{@code null} value. Two 
{@code null} references are considered equal.
+     * The {@link #CS} and {@link #CI} instances consider {@code null} less 
than non-{@code null}. Instances created with {@link #builder()} use the 
ordering
+     * configured by {@link Builder#setNullIsLess(boolean)}; the builder 
defaults to sorting nulls last. Two {@code null} references compare as equal.
      * </p>
      *
      * <p>
@@ -487,10 +489,10 @@ public String appendIfMissing(final String str, final 
CharSequence suffix, final
      * Strings.CI.compare("ab", "ABC")  < 0
      * }</pre>
      *
-     * @see String#compareTo(String)
      * @param str1 The String to compare from
      * @param str2 The String to compare to
      * @return &lt; 0, 0, &gt; 0, if {@code str1} is respectively less, equal 
or greater than {@code str2}
+     * @see String#compareTo(String)
      */
     public abstract int compare(String str1, String str2);
 
@@ -610,7 +612,7 @@ public boolean containsAny(final CharSequence cs, final 
CharSequence... searchCh
      *
      * @param str    The CharSequence to check, may be null.
      * @param suffix The suffix to find, may be null.
-     * @return {@code true} if the CharSequence starts with the prefix or both 
{@code null}.
+     * @return {@code true} if the CharSequence ends with the suffix or both 
are {@code null}.
      * @see String#endsWith(String)
      */
     public boolean endsWith(final CharSequence str, final CharSequence suffix) 
{
@@ -644,9 +646,9 @@ public boolean endsWith(final CharSequence str, final 
CharSequence suffix) {
      *
      * @param sequence      The CharSequence to check, may be null
      * @param searchStrings The CharSequence suffixes to find, may be empty or 
contain {@code null}
+     * @return {@code true} if the non-empty input ends with any provided 
suffix; {@code false} if the input is null or empty, the search array is null or
+     *         empty, or no suffix matches.
      * @see Strings#endsWith(CharSequence, CharSequence)
-     * @return {@code true} if the input {@code sequence} is {@code null} AND 
no {@code searchStrings} are provided, or the input {@code sequence} ends in any
-     *         of the provided {@code searchStrings}.
      */
     public boolean endsWithAny(final CharSequence sequence, final 
CharSequence... searchStrings) {
         if (StringUtils.isEmpty(sequence) || 
ArrayUtils.isEmpty(searchStrings)) {
@@ -830,8 +832,9 @@ public int indexOf(final CharSequence seq, final 
CharSequence searchSeq) {
      * Finds the first index within a CharSequence, handling {@code null}. 
This method uses {@link String#indexOf(String, int)} if possible.
      *
      * <p>
-     * A {@code null} CharSequence will return {@code -1}. A negative start 
position is treated as zero. An empty ("") search CharSequence always matches. A
-     * start position greater than the string length only matches an empty 
search CharSequence.
+     * A {@code null} input returns {@code -1}. A negative start position is 
treated as zero. For an empty search, case-sensitive instances return the start
+     * position, clamped to the input length. Case-insensitive instances 
return the start position when it is at or before the end, or {@code -1} when 
it is
+     * past the end. For a non-empty search, a start position past the end 
returns {@code -1}.
      * </p>
      *
      * <p>
@@ -873,14 +876,14 @@ public int indexOf(final CharSequence seq, final 
CharSequence searchSeq) {
      * @param seq       The CharSequence to check, may be null
      * @param searchSeq The CharSequence to find, may be null
      * @param startPos  The start position, negative treated as zero
-     * @return The first index of the search CharSequence (always &ge; 
startPos), -1 if no match or {@code null} string input
+     * @return The first matching index, or {@code -1} if no match or either 
input is {@code null}.
      */
     public abstract int indexOf(CharSequence seq, CharSequence searchSeq, int 
startPos);
 
     /**
-     * Tests whether to ignore case.
+     * Tests whether comparisons are case-sensitive.
      *
-     * @return whether to ignore case.
+     * @return {@code true} for case-sensitive comparisons, {@code false} when 
case is ignored.
      */
     public boolean isCaseSensitive() {
         return !ignoreCase;
@@ -983,8 +986,8 @@ public int lastIndexOf(final CharSequence str, final 
CharSequence searchStr) {
      *
      * @param seq       The CharSequence to check, may be null
      * @param searchSeq The CharSequence to find, may be null
-     * @param startPos  The start position, negative treated as zero
-     * @return The last index of the search CharSequence (always &le; 
startPos), -1 if no match or {@code null} string input
+     * @param startPos The start position; a negative value returns {@code -1}.
+     * @return The last matching index, at or before {@code startPos}, or 
{@code -1} if no match or either input is {@code null}.
      */
     public abstract int lastIndexOf(CharSequence seq, CharSequence searchSeq, 
int startPos);
 
@@ -1459,9 +1462,9 @@ public boolean startsWith(final CharSequence str, final 
CharSequence prefix) {
      *
      * @param sequence      The CharSequence to check, may be null
      * @param searchStrings The CharSequence prefixes, may be empty or contain 
{@code null}
+     * @return {@code true} if the non-empty input starts with any provided 
prefix; {@code false} if the input is null or empty, the search array is null or
+     *         empty, or no prefix matches.
      * @see Strings#startsWith(CharSequence, CharSequence)
-     * @return {@code true} if the input {@code sequence} is {@code null} AND 
no {@code searchStrings} are provided, or the input {@code sequence} begins with
-     *         any of the provided {@code searchStrings}.
      */
     public boolean startsWithAny(final CharSequence sequence, final 
CharSequence... searchStrings) {
         if (StringUtils.isEmpty(sequence) || 
ArrayUtils.isEmpty(searchStrings)) {
diff --git a/src/test/java/org/apache/commons/lang3/StringsOverflowTest.java 
b/src/test/java/org/apache/commons/lang3/StringsOverflowTest.java
new file mode 100644
index 000000000..fc45dd8e4
--- /dev/null
+++ b/src/test/java/org/apache/commons/lang3/StringsOverflowTest.java
@@ -0,0 +1,130 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.commons.lang3;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.stream.IntStream;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/**
+ * Index-boundary regressions using virtual inputs, without large allocations 
or long scans.
+ */
+class StringsOverflowTest extends AbstractLangTest {
+
+    private static final class RepeatedCharSequence implements CharSequence {
+
+        private final int length;
+
+        private RepeatedCharSequence(final int length) {
+            this.length = length;
+        }
+
+        @Override
+        public char charAt(final int index) {
+            if (index < 0 || index >= length) {
+                throw new IndexOutOfBoundsException("Index: " + index + ", 
length: " + length);
+            }
+            return 'a';
+        }
+
+        @Override
+        public int length() {
+            return length;
+        }
+
+        @Override
+        public CharSequence subSequence(final int start, final int end) {
+            if (start < 0 || end < start || end > length) {
+                throw new IndexOutOfBoundsException();
+            }
+            return new RepeatedCharSequence(end - start);
+        }
+
+        @Override
+        public String toString() {
+            throw new AssertionError("The search must not materialize the 
virtual input");
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(ints = { Integer.MAX_VALUE - 1, Integer.MAX_VALUE })
+    void testIndexOfEmptySearchAtMaximumLength(final int length) {
+        final CharSequence input = new RepeatedCharSequence(length);
+        assertEquals(0, Strings.CI.indexOf(input, ""));
+        for (final int start : new int[] { Integer.MIN_VALUE, -1, 1, length - 
1, length }) {
+            assertEquals(Math.max(start, 0), Strings.CI.indexOf(input, "", 
start), "start=" + start);
+        }
+        if (length < Integer.MAX_VALUE) {
+            assertEquals(-1, Strings.CI.indexOf(input, "", length + 1));
+        }
+    }
+
+    @ParameterizedTest
+    @CsvSource({
+        "2147483646, 1",
+        "2147483646, 2",
+        "2147483647, 1",
+        "2147483647, 2"
+    })
+    void testIndexOfNonEmptySearchAtMaximumLength(final int length, final int 
searchLength) {
+        final CharSequence input = new RepeatedCharSequence(length);
+        final String search = StringUtils.repeat('A', searchLength);
+        final int lastStart = length - searchLength;
+        assertEquals(lastStart - 1, Strings.CI.indexOf(input, search, 
lastStart - 1));
+        assertEquals(lastStart, Strings.CI.indexOf(input, search, lastStart));
+        assertEquals(-1, Strings.CI.indexOf(input, search, lastStart + 1));
+        // A miss at the last candidate must terminate without wrapping the 
loop counter.
+        assertEquals(-1, Strings.CI.indexOf(input, StringUtils.repeat('B', 
searchLength), lastStart));
+    }
+
+    @ParameterizedTest
+    @CsvSource({
+        "2147483630, 17",
+        "2147483630, 18",
+        "2147483631, 16",
+        "2147483631, 17",
+        "2147483646, 1",
+        "2147483646, 2",
+        "2147483647, 1",
+        "2147483647, 2"
+    })
+    void testLastIndexOfAtMaximumLength(final int length, final int 
searchLength) {
+        final CharSequence input = new RepeatedCharSequence(length);
+        final String search = StringUtils.repeat('a', searchLength);
+        final int lastStart = length - searchLength;
+        assertEquals(lastStart, Strings.CS.lastIndexOf(input, search));
+        // Cross both the last valid match and the former start+searchLength 
overflow boundary.
+        final int[] starts = IntStream.of(lastStart - 1, lastStart, lastStart 
+ 1, length - 1, Integer.MAX_VALUE).distinct().toArray();
+        for (final int start : starts) {
+            assertEquals(Math.min(start, lastStart), 
Strings.CS.lastIndexOf(input, search, start), "start=" + start);
+        }
+    }
+
+    @Test
+    void testSearchLongerThanMaximumLengthInput() {
+        final CharSequence input = new RepeatedCharSequence(Integer.MAX_VALUE 
- 1);
+        final CharSequence search = new 
RepeatedCharSequence(Integer.MAX_VALUE);
+        assertEquals(-1, Strings.CI.indexOf(input, search));
+        assertEquals(-1, Strings.CS.lastIndexOf(input, search));
+    }
+}
diff --git 
a/src/test/java/org/apache/commons/lang3/StringsReplaceMemoryTest.java 
b/src/test/java/org/apache/commons/lang3/StringsReplaceMemoryTest.java
new file mode 100644
index 000000000..822fed874
--- /dev/null
+++ b/src/test/java/org/apache/commons/lang3/StringsReplaceMemoryTest.java
@@ -0,0 +1,109 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.commons.lang3;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.File;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+
+/**
+ * Verifies that speculative replacement capacity does not exhaust a heap that 
can hold the actual result.
+ */
+class StringsReplaceMemoryTest extends AbstractLangTest {
+
+    /**
+     * Runs the allocation workload without requiring JUnit in the child JVM.
+     */
+    public static final class MemoryProbe {
+
+        private static void check(final Strings strings, final String 
replacement, final String search, final int max) {
+            final String result = strings.replace("ab", search, replacement, 
max);
+            if (!result.equals(replacement)) {
+                throw new AssertionError("The full-input replacement must 
equal the replacement string");
+            }
+        }
+
+        private static void checkMultipleMatches(final Strings strings, final 
String replacement, final String search, final int max) {
+            final String result = strings.replace("ab!ab", search, 
replacement, max);
+            if (result.length() != 2 * replacement.length() + 1 || 
!result.startsWith(replacement) || !result.endsWith(replacement)
+                    || result.charAt(replacement.length()) != '!') {
+                throw new AssertionError("Both replacements and the 
intervening text must be preserved");
+            }
+        }
+
+        private static void checkSparseMatch(final Strings strings, final 
String replacement, final String search, final int max) {
+            // Many matches could fit by length, but only one actually occurs.
+            final String suffix = StringUtils.repeat('z', 126);
+            final String result = strings.replace("ab" + suffix, search, 
replacement, max);
+            if (result.length() != replacement.length() + suffix.length() || 
!result.startsWith(replacement) || !result.endsWith(suffix)) {
+                throw new AssertionError("The replacement and unmatched suffix 
must be preserved");
+            }
+        }
+
+        /**
+         * Replaces strings with Latin-1 and UTF-16 data in a bounded heap, 
checking full result contents.
+         *
+         * @param args whether to ignore case and the maximum replacement 
count.
+         */
+        public static void main(final String[] args) {
+            final boolean ignoreCase = Boolean.parseBoolean(args[0]);
+            final int max = Integer.parseInt(args[1]);
+            final Strings strings = ignoreCase ? Strings.CI : Strings.CS;
+            final String search = ignoreCase ? "AB" : "ab";
+            for (final char ch : new char[] { 'x', '\u0101' }) {
+                // The former 16-match estimate needs over 64 MB even with 
compact strings; actual results fit on Java 8 as well.
+                // Leave headroom for the two-match UTF-16 result with Serial 
GC.
+                final String replacement = StringUtils.repeat(ch, 4_250_000);
+                check(strings, replacement, search, max);
+                checkSparseMatch(strings, replacement, search, max);
+                checkMultipleMatches(strings, replacement, search, max);
+            }
+            System.out.println("Completed replacement memory checks");
+        }
+    }
+
+    @ParameterizedTest
+    @CsvSource({ "false, -1", "false, 64", "true, -1", "true, 64" })
+    void testLargeReplacementWithBoundedHeap(final boolean ignoreCase, final 
int max, @TempDir final Path tempDir) throws Exception {
+        final Path java = Paths.get(System.getProperty("java.home"), "bin", 
SystemUtils.IS_OS_WINDOWS ? "java.exe" : "java");
+        final String classPath = 
Paths.get(MemoryProbe.class.getProtectionDomain().getCodeSource().getLocation().toURI())
 + File.pathSeparator
+                + 
Paths.get(Strings.class.getProtectionDomain().getCodeSource().getLocation().toURI());
+        final Path log = tempDir.resolve("memory-probe.log");
+        final Process process = new ProcessBuilder(java.toString(), "-Xmx64m", 
"-cp", classPath, MemoryProbe.class.getName(),
+                Boolean.toString(ignoreCase), 
Integer.toString(max)).redirectErrorStream(true).redirectOutput(log.toFile()).start();
+        try {
+            assertTrue(process.waitFor(60, TimeUnit.SECONDS), "The memory 
probe must finish within its time limit");
+            final String output = new String(Files.readAllBytes(log), 
StandardCharsets.UTF_8);
+            assertEquals(0, process.exitValue(), output);
+            assertTrue(output.contains("Completed replacement memory checks"), 
output);
+        } finally {
+            process.destroyForcibly();
+            assertTrue(process.waitFor(10, TimeUnit.SECONDS), "The child JVM 
must terminate even if the test fails");
+        }
+    }
+}
diff --git a/src/test/java/org/apache/commons/lang3/StringsTest.java 
b/src/test/java/org/apache/commons/lang3/StringsTest.java
index 45227bfd1..e94ce3fad 100644
--- a/src/test/java/org/apache/commons/lang3/StringsTest.java
+++ b/src/test/java/org/apache/commons/lang3/StringsTest.java
@@ -26,6 +26,7 @@
 
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
 import org.junit.jupiter.params.provider.MethodSource;
 import org.junitpioneer.jupiter.DefaultLocale;
 
@@ -119,49 +120,6 @@ void testCaseSensitiveConstant() {
         assertTrue(Strings.CS.isCaseSensitive());
     }
 
-    @Test
-    void testComputeInitialCapacityDoesNotReturnSafeMaxDueToOverflow() {
-        final int textLength = 100;
-        final int searchLength = 0;
-        final int replacementLength = Integer.MAX_VALUE;
-        final int max = 1;
-        // Expected mathematical result:
-        // 100 + (2147483647 - 0) * 1 = 2147483747
-        // which exceeds SAFE_MAX_ARRAY_LENGTH (2147483639)
-        final int expected = Integer.MAX_VALUE - 8;
-        assertEquals(expected, Strings.initialCapacity(textLength, 
searchLength, replacementLength, max));
-    }
-
-    @Test
-    void testComputeInitialCapacityLargeInputsDoNotIncorrectlyClampToSafeMax() 
{
-        final int result = Strings.initialCapacity(Integer.MAX_VALUE - 1000, 
Integer.MAX_VALUE - 500, Integer.MAX_VALUE, 1);
-        // Growth = 500
-        // Expected = Integer.MAX_VALUE - 500
-        assertEquals(Integer.MAX_VALUE - 500, result);
-    }
-
-    @Test
-    void testComputeInitialCapacityNeverOverflowsForMaxValueInputs() {
-        final int capacity = Strings.initialCapacity(Integer.MAX_VALUE, 0, 
Integer.MAX_VALUE, 64);
-        assertEquals(ArrayUtils.SAFE_MAX_ARRAY_LENGTH, capacity);
-    }
-
-    @Test
-    void testComputeInitialCapacityReplacementGrowthDoesNotOverflowInt() {
-        final int capacity = Strings.initialCapacity(0, 0, 50_000_000, 64);
-        assertEquals(ArrayUtils.SAFE_MAX_ARRAY_LENGTH, capacity);
-    }
-
-    @Test
-    void 
testComputeInitialCapacityReturnsSmallerValueWhenResultIsBelowSafeMax() {
-        final int textLength = 100;
-        final int searchLength = 0;
-        final int replacementLength = 1000;
-        final int max = 1;
-        final int expected = 1100;
-        assertEquals(expected, Strings.initialCapacity(textLength, 
searchLength, replacementLength, max));
-    }
-
     @ParameterizedTest
     @MethodSource("stringsFactory")
     void testEqualsCharSequence(final Strings strings) {
@@ -179,4 +137,40 @@ void testEqualsStrings(final Strings strings) {
         assertFalse(strings.equals(nullStr, ""));
         assertFalse(strings.equals("", nullStr));
     }
+
+    @ParameterizedTest
+    @CsvSource({
+        // Shrinking, unchanged and growing replacements; zero, finite and 
unbounded replacement counts.
+        "100, 10, 9,  -1, 100",
+        "100, 10, 10, -1, 100",
+        "100, 10, 11,  0, 100",
+        "100, 10, 11,  1, 101",
+        "100, 10, 11,  2, 102",
+        "100, 10, 11, -1, 110",
+        "100, 100, 101, 64, 101",
+        // The historical match estimates and their boundaries.
+        "1000, 1, 2, -2147483648, 1016",
+        "1000, 1, 2, -1, 1016",
+        "1000, 1, 2, 63, 1063",
+        "1000, 1, 2, 64, 1064",
+        "1000, 1, 2, 65, 1064",
+        "1000, 1, 2, 2147483647, 1064",
+        // Just below, at and above the 20% growth cap, including its 
integer-rounding boundary.
+        "100, 1, 2, 19, 119",
+        "100, 1, 2, 20, 120",
+        "100, 1, 2, 21, 120",
+        "4, 1, 2147483647, 64, 4",
+        "5, 1, 2147483647, 64, 6",
+        "6, 1, 2147483647, 64, 7",
+        // Growth multiplication and total capacity must not overflow or force 
a maximum-size allocation.
+        "100, 1, 2147483647, 64, 120",
+        "1789569699, 1, 2147483647, 64, 2147483638",
+        "1789569700, 1, 2147483647, 64, 0",
+        "2147483639, 1, 1, 1, 2147483639",
+        "2147483640, 1, 1, 1, 0",
+        "2147483647, 1, 2147483647, 64, 0"
+    })
+    void testInitialCapacity(final int textLength, final int searchLength, 
final int replacementLength, final int max, final int expected) {
+        assertEquals(expected, Strings.initialCapacity(textLength, 
searchLength, replacementLength, max));
+    }
 }

Reply via email to