Throw OutOfMemoryError instead of NegativeArraySizeException
A different solution to what was proposed in PR #132.
diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 7bd5a87..9196d52 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -69,6 +69,7 @@
<action issue="TEXT=212" type="fix" dev="kinow" due-to="Ali Ghanbari">A More Efficient Implementation for Calculating Size of Longest Common Subsequence.</action>
<action issue="TEXT-209" type="fix" dev="kinow" due-to="fourAjeff">LookupTranslator returns count of chars consumed, not of codepoints consumed.</action>
<action issue="TEXT-209" type="fix" dev="ggregory" due-to="Arturo Bernal">Use Math.min() call instead of doing it manually. #335.</action>
+ <action type="fix" dev="ggregory" due-to="ValentijnvdBeek, Gary Gregory">Throw OutOfMemoryError instead of NegativeArraySizeException.</action>
<!-- ADD -->
<action issue="TEXT-207" type="add" dev="mattjuntunen">Add DoubleFormat utility.</action>
<action issue="TEXT-190" type="add" dev="kinow" due-to="Benjamin Bing">Document negative limit for WordUtils abbreviate method</action>
diff --git a/src/main/java/org/apache/commons/text/TextStringBuilder.java b/src/main/java/org/apache/commons/text/TextStringBuilder.java
index 4fafcf1..296c226 100644
--- a/src/main/java/org/apache/commons/text/TextStringBuilder.java
+++ b/src/main/java/org/apache/commons/text/TextStringBuilder.java
@@ -325,7 +325,7 @@
private int size;
/**
- * Constructs an empty builder initial capacity 32 characters.
+ * Constructs an empty builder with an initial capacity of 32 characters.
*/
public TextStringBuilder() {
this(CAPACITY);
@@ -1834,8 +1834,9 @@
* @return this, to enable chaining
*/
public TextStringBuilder ensureCapacity(final int capacity) {
- if (capacity > buffer.length) {
- reallocate(capacity * 2);
+ // checks for overflow
+ if (capacity > 0 && capacity - buffer.length > 0) {
+ reallocate(capacity);
}
return this;
}
diff --git a/src/test/java/org/apache/commons/text/TextStringBuilderTest.java b/src/test/java/org/apache/commons/text/TextStringBuilderTest.java
index c600185..6656ccf 100644
--- a/src/test/java/org/apache/commons/text/TextStringBuilderTest.java
+++ b/src/test/java/org/apache/commons/text/TextStringBuilderTest.java
@@ -881,6 +881,17 @@
}
@Test
+ public void testEnsureCapacityOutOfMemoryError() {
+ final TextStringBuilder sb = new TextStringBuilder();
+ // Should not be a NegativeArraySizeException
+ sb.ensureCapacity(Integer.MIN_VALUE);
+ sb.ensureCapacity(-1);
+ sb.ensureCapacity(0);
+ sb.ensureCapacity(Integer.MAX_VALUE / 2);
+ assertThrows(OutOfMemoryError.class, () -> sb.ensureCapacity(Integer.MAX_VALUE));
+ }
+
+ @Test
public void testEquals() {
final TextStringBuilder sb1 = new TextStringBuilder(50);
final TextStringBuilder sb2 = new TextStringBuilder(100);