[K/N] ArrayList.ensureCapacity() should ignore negative arguments

This commit is contained in:
Abduqodiri Qurbonzoda
2023-05-31 00:21:40 +03:00
committed by Space Team
parent ae394caf42
commit 89d1cfe05b
3 changed files with 25 additions and 16 deletions
@@ -179,15 +179,6 @@ internal class ListBuilder<E> private constructor(
// ---------------------------- private ----------------------------
private fun ensureCapacity(minCapacity: Int) {
if (backing != null) throw IllegalStateException() // just in case somebody casts subList to ListBuilder
if (minCapacity < 0) throw OutOfMemoryError() // overflow
if (minCapacity > array.size) {
val newSize = AbstractList.newCapacity(array.size, minCapacity)
array = array.copyOfUninitializedElements(newSize)
}
}
private fun checkIsMutable() {
if (isEffectivelyReadOnly) throw UnsupportedOperationException()
}
@@ -196,7 +187,15 @@ internal class ListBuilder<E> private constructor(
get() = isReadOnly || root != null && root.isReadOnly
private fun ensureExtraCapacity(n: Int) {
ensureCapacity(length + n)
ensureCapacityInternal(length + n)
}
private fun ensureCapacityInternal(minCapacity: Int) {
if (minCapacity < 0) throw OutOfMemoryError() // overflow
if (minCapacity > array.size) {
val newSize = AbstractList.newCapacity(array.size, minCapacity)
array = array.copyOfUninitializedElements(newSize)
}
}
private fun contentEquals(other: List<*>): Boolean {
@@ -146,11 +146,8 @@ actual class ArrayList<E> private constructor(
final actual fun ensureCapacity(minCapacity: Int) {
if (backingList != null) throw IllegalStateException() // just in case somebody casts subList to ArrayList
if (minCapacity < 0) throw OutOfMemoryError() // overflow
if (minCapacity > backingArray.size) {
val newSize = AbstractList.newCapacity(backingArray.size, minCapacity)
backingArray = backingArray.copyOfUninitializedElements(newSize)
}
if (minCapacity <= backingArray.size) return
ensureCapacityInternal(minCapacity)
}
override fun equals(other: Any?): Boolean {
@@ -214,7 +211,15 @@ actual class ArrayList<E> private constructor(
}
private fun ensureExtraCapacity(n: Int) {
ensureCapacity(length + n)
ensureCapacityInternal(length + n)
}
private fun ensureCapacityInternal(minCapacity: Int) {
if (minCapacity < 0) throw OutOfMemoryError() // overflow
if (minCapacity > backingArray.size) {
val newSize = AbstractList.newCapacity(backingArray.size, minCapacity)
backingArray = backingArray.copyOfUninitializedElements(newSize)
}
}
private fun contentEquals(other: List<*>): Boolean {
@@ -1256,4 +1256,9 @@ class CollectionTest {
val arr2: Array<String> = coll.toArray(Array(coll.size + 1) { "" })
assertEquals(data + listOf(null), arr2.asList())
}
@Test
fun ensureCapacity() {
ArrayList<String>().ensureCapacity(-1) // negative argument is ignored
}
}