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 1a3afb09d Fix premature overflow in StringUtils.repeat with separators
1a3afb09d is described below

commit 1a3afb09d55f8666c87035b57c5cb7a0a5dfce1c
Author: Gary Gregory <[email protected]>
AuthorDate: Sun Nov 15 15:04:58 2026 -0500

    Fix premature overflow in StringUtils.repeat with separators
    
    Calculate the final length using long arithmetic and append separators
    only between copies, avoiding an oversized intermediate result.
    
    Add boundary and regression tests without duplicating existing coverage.
    Update Javadoc and release notes.
    
    Assisted-By: OpenAI Codex
---
 src/changes/changes.xml                            |  1 +
 .../java/org/apache/commons/lang3/StringUtils.java | 29 +++++++++++++----
 .../commons/lang3/StringUtilsOverflowTest.java     | 37 ++++++++++++++++++++++
 .../org/apache/commons/lang3/StringUtilsTest.java  | 34 ++++++++++++++++++++
 4 files changed, 95 insertions(+), 6 deletions(-)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 3ae97a59f..e9c346188 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -92,6 +92,7 @@ The <action> type attribute can be add,update,fix,remove.
     <action                   type="fix" dev="ggregory" due-to="Gary Gregory, 
Amar Ghugare">Correct NumberUtils.createNumber(String) result types for 
negative hexadecimal minima: Integer.MIN_VALUE now returns Integer instead of 
Long, and Long.MIN_VALUE returns Long instead of BigInteger; numeric values are 
unchanged (#1877).</action>
     <action                   type="fix" dev="ggregory" due-to="Gary Gregory, 
simpleqt">Fix integer overflow in StringUtils.join range handling.</action>
     <action                   type="fix" dev="ggregory" due-to="Gary 
Gregory">Prevent capacity overflow in StringUtils.wrapIfMissing(String, String) 
when only one wrapper is missing and the result is representable.</action>
+    <action                   type="fix" dev="ggregory" due-to="Gary 
Gregory">Prevent premature length overflow in StringUtils.repeat(String, 
String, int) when the final result is representable but the intermediate result 
with a trailing separator is not.</action>
     <!-- ADD -->
     <!-- UPDATE -->
   </release>
diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java 
b/src/main/java/org/apache/commons/lang3/StringUtils.java
index d7d0ad87f..0bce0a157 100644
--- a/src/main/java/org/apache/commons/lang3/StringUtils.java
+++ b/src/main/java/org/apache/commons/lang3/StringUtils.java
@@ -6264,7 +6264,7 @@ public static String repeat(final String repeat, final 
int count) {
     }
 
     /**
-     * Repeats a String {@code repeat} times to form a new String, with a 
String separator injected each time.
+     * Repeats a String {@code count} times, with a separator between 
successive copies.
      *
      * <pre>
      * StringUtils.repeat(null, null, 2) = null
@@ -6278,16 +6278,33 @@ public static String repeat(final String repeat, final 
int count) {
      * @param repeat    The String to repeat, may be null.
      * @param separator The String to inject, may be null.
      * @param count     number of times to repeat str, negative treated as 
zero.
-     * @return A new String consisting of the original String repeated, {@code 
null} if null String input.
+     * @return A String consisting of the original String repeated with 
separators, {@code null} if null String input.
+     * @throws IllegalArgumentException if the requested result length exceeds 
{@link Integer#MAX_VALUE}.
      * @since 2.5
      */
     public static String repeat(final String repeat, final String separator, 
final int count) {
-        if (repeat == null || separator == null) {
+        if (repeat == null || isEmpty(separator)) {
             return repeat(repeat, count);
         }
-        // given that repeat(String, int) is quite optimized, better to rely 
on it than try and splice this into it
-        final String result = repeat(repeat + separator, count);
-        return Strings.CS.removeEnd(result, separator);
+        if (count <= 0) {
+            return EMPTY;
+        }
+        if (count == 1) {
+            return repeat;
+        }
+        if (repeat.isEmpty()) {
+            return repeat(separator, count - 1);
+        }
+        final long outputLength = (long) repeat.length() * count + (long) 
separator.length() * (count - 1);
+        if (outputLength > Integer.MAX_VALUE) {
+            throw new IllegalArgumentException("The requested result is too 
large for a String.");
+        }
+        final StringBuilder builder = new StringBuilder((int) outputLength);
+        builder.append(repeat);
+        for (int i = 1; i < count; i++) {
+            builder.append(separator).append(repeat);
+        }
+        return builder.toString();
     }
 
     /**
diff --git 
a/src/test/java/org/apache/commons/lang3/StringUtilsOverflowTest.java 
b/src/test/java/org/apache/commons/lang3/StringUtilsOverflowTest.java
index fc6fb1606..5ff2d2a95 100644
--- a/src/test/java/org/apache/commons/lang3/StringUtilsOverflowTest.java
+++ b/src/test/java/org/apache/commons/lang3/StringUtilsOverflowTest.java
@@ -20,6 +20,7 @@
 import static org.junit.jupiter.api.Assertions.assertAll;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 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.lang.reflect.Method;
@@ -79,6 +80,42 @@ void testOversizedCapacityEstimate(final long estimate) 
throws Exception {
         assertEquals("result", builder.append("result").toString());
     }
 
+    /**
+     * Exercises counts immediately below and above overflow of the former 
intermediate length, with and without non-empty repeated text.
+     */
+    @ParameterizedTest
+    @CsvSource({
+        "'', 21474835, 2147483400",
+        "'', 21474836, 2147483500",
+        "'', 21474837, 2147483600",
+        "x, 21262213, 2147483413",
+        "x, 21262214, 2147483514",
+        "x, 21262215, 2147483615"
+    })
+    @EnabledIfSystemProperty(named = "test.stringutils.large.heap", matches = 
"true")
+    void testRepeatWithSeparatorLengthBoundaries(final String text, final int 
count, final int expectedLength) {
+        final String separator = new String(new byte[100], 
StandardCharsets.ISO_8859_1);
+        final String result = StringUtils.repeat(text, separator, count);
+        final int textCount = text.isEmpty() ? 0 : count;
+        assertEquals(expectedLength, result.length());
+        assertEquals(textCount, StringUtils.countMatches(result, 'x'));
+        assertEquals(expectedLength - textCount, 
StringUtils.countMatches(result, '\0'));
+        assertTrue(result.startsWith(text + separator + text));
+        assertTrue(result.endsWith(text + separator + text));
+    }
+
+    @ParameterizedTest
+    @CsvSource({
+        "a, b, 1073741825",
+        "'', ab, 1073741825",
+        "ab, '', 1073741824",
+        "abc, d, 536870913",
+        "ab, cd, 2147483647"
+    })
+    void testRepeatWithSeparatorRejectsUnrepresentableLength(final String 
text, final String separator, final int count) {
+        assertThrows(IllegalArgumentException.class, () -> 
StringUtils.repeat(text, separator, count));
+    }
+
     @Test
     @EnabledIfSystemProperty(named = "test.stringutils.large.heap", matches = 
"true")
     void testReplaceEachSingleRuleEstimateOverflow() {
diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsTest.java 
b/src/test/java/org/apache/commons/lang3/StringUtilsTest.java
index bba103808..13fba8583 100644
--- a/src/test/java/org/apache/commons/lang3/StringUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/StringUtilsTest.java
@@ -52,6 +52,7 @@
 import org.junit.jupiter.params.ParameterizedTest;
 import org.junit.jupiter.params.provider.CsvSource;
 import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.NullAndEmptySource;
 import org.junit.jupiter.params.provider.ValueSource;
 import org.junitpioneer.jupiter.DefaultLocale;
 import org.junitpioneer.jupiter.ReadsDefaultLocale;
@@ -1966,6 +1967,39 @@ void testRepeat_StringStringInt() {
         assertThrows(IllegalArgumentException.class, () -> 
StringUtils.repeat("?", ", ", 1_073_741_824));
     }
 
+    @ParameterizedTest
+    @CsvSource({
+        "'', ab, 4, ababab",
+        "'', abc, 3, abcabc",
+        "ab, ab, 2, ababab",
+        "a-, -, 3, a--a--a-",
+        "\uD83D\uDE00, \uD83D\uDE80, 3, 
\uD83D\uDE00\uD83D\uDE80\uD83D\uDE00\uD83D\uDE80\uD83D\uDE00"
+    })
+    void testRepeatWithSeparatorContent(final String text, final String 
separator, final int count, final String expected) {
+        assertEquals(expected, StringUtils.repeat(text, separator, count));
+    }
+
+    @ParameterizedTest
+    @ValueSource(ints = { Integer.MIN_VALUE, -1, 0 })
+    void testRepeatWithSeparatorNonPositiveCount(final int count) {
+        assertEquals("", StringUtils.repeat("ab", "<>", count));
+        assertEquals("", StringUtils.repeat("", "<>", count));
+        assertNull(StringUtils.repeat(null, "<>", count));
+    }
+
+    @ParameterizedTest
+    @NullAndEmptySource
+    void testRepeatWithSeparatorNullOrEmpty(final String separator) {
+        assertEquals("ababab", StringUtils.repeat("ab", separator, 3));
+        assertEquals("", StringUtils.repeat("", separator, Integer.MAX_VALUE));
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = { "", "ab" })
+    void testRepeatWithSeparatorSingleCopy(final String text) {
+        assertEquals(text, StringUtils.repeat(text, "unused", 1));
+    }
+
     /**
      * Test method for 'StringUtils.replaceEach(String, String[], String[])'
      */

Reply via email to