Make sure index and count do not overflow for long sequences

Throw an exception immediately before an overflow becomes observable.
Place check to prevent negative index from indexOf, indexOfFirst.
Do not insert overflow checks for arrays, lists, maps and char sequences.

#KT-16097
This commit is contained in:
Ilya Gorbunov
2018-08-09 23:31:31 +03:00
parent c44f62a3d4
commit 357c5be4fb
16 changed files with 252 additions and 58 deletions
@@ -9,6 +9,8 @@
package kotlin.collections
import kotlin.*
import kotlin.internal.InlineOnly
import kotlin.internal.apiVersionIsAtLeast
/**
* Returns an immutable list containing only the specified object [element].
@@ -42,3 +44,31 @@ internal actual fun <T> Array<out T>.copyToArrayOfAny(isVarargs: Boolean): Array
@Suppress("UNCHECKED_CAST") (this as Array<Any?>)
else
java.util.Arrays.copyOf(this, this.size, Array<Any?>::class.java)
@PublishedApi
@SinceKotlin("1.3")
@InlineOnly
internal actual inline fun checkIndexOverflow(index: Int): Int {
if (index < 0) {
if (apiVersionIsAtLeast(1, 3, 0))
throwIndexOverflow()
else
throw ArithmeticException("Index overflow has happened.")
}
return index
}
@PublishedApi
@SinceKotlin("1.3")
@InlineOnly
internal actual inline fun checkCountOverflow(count: Int): Int {
if (count < 0) {
if (apiVersionIsAtLeast(1, 3, 0))
throwCountOverflow()
else
throw ArithmeticException("Count overflow has happened.")
}
return count
}