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
@@ -6,6 +6,7 @@
package kotlin.collections
import kotlin.comparisons.naturalOrder
import kotlin.internal.InlineOnly
import kotlin.random.Random
/** Returns the array if it's not `null`, or an empty array otherwise. */
@@ -140,3 +141,22 @@ internal actual inline fun <T> Array<out T>.copyToArrayOfAny(isVarargs: Boolean)
this
else
this.copyOf()
@PublishedApi
internal actual fun checkIndexOverflow(index: Int): Int {
if (index < 0) {
throwIndexOverflow()
}
return index
}
@PublishedApi
internal actual fun checkCountOverflow(count: Int): Int {
if (count < 0) {
throwCountOverflow()
}
return count
}