Skip to content

Commit

Permalink
Merge a8a9d6b into ea03fa0
Browse files Browse the repository at this point in the history
  • Loading branch information
ValentijnvdBeek committed May 28, 2020
2 parents ea03fa0 + a8a9d6b commit d3126b5
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
13 changes: 12 additions & 1 deletion src/main/java/org/apache/commons/text/TextStringBuilder.java
Expand Up @@ -82,6 +82,11 @@ public class TextStringBuilder implements CharSequence, Appendable, Serializable
*/
private static final int TRUE_STRING_SIZE = "true".length();

/**
* An upper bound for amortized array space allocation.
*/
private static final int AMORTIZED_ARRAY_ALLOCATION_UPPER_BOUND = Integer.MAX_VALUE >>> 1;

/**
* The extra capacity for new builders.
*/
Expand Down Expand Up @@ -246,7 +251,13 @@ public int capacity() {
public TextStringBuilder ensureCapacity(final int capacity) {
if (capacity > buffer.length) {
final char[] old = buffer;
buffer = new char[capacity * 2];

int newCapacity = capacity << 1;
if (capacity > AMORTIZED_ARRAY_ALLOCATION_UPPER_BOUND) {
newCapacity = Integer.MAX_VALUE;
}

buffer = new char[newCapacity];
System.arraycopy(old, 0, buffer, 0, size);
}
return this;
Expand Down
Expand Up @@ -345,6 +345,9 @@ public void testEnsureCapacity() {
sb.append("HelloWorld");
sb.ensureCapacity(40);
assertTrue(sb.capacity() >= 40);

assertThrows(OutOfMemoryError.class, () -> sb.ensureCapacity(Integer.MAX_VALUE / 2));
assertThrows(OutOfMemoryError.class, () -> sb.ensureCapacity(Integer.MAX_VALUE));
}

@Test
Expand Down

0 comments on commit d3126b5

Please sign in to comment.