Adam S
05/23/2023, 11:08 AMArrays.copyOfRange()
fun copyData(
codePointsWindow: IntArray,
pointer: Int,
dataLength: Int,
read: Int,
): IntArray {
return Arrays.copyOfRange(codePointsWindow, pointer, dataLength + read)
}
IntelliJ pops-up a warning, “Should be replaced with Kotlin function”, and provides a quickfix:
return codePointsWindow.copyOfRange(pointer, dataLength + read)
However then a lot of tests fail with
toIndex (11) is greater than size (0).
java.lang.IndexOutOfBoundsException: toIndex (11) is greater than size (0).
at kotlin.collections.ArraysKt__ArraysJVMKt.copyOfRangeToIndexCheck(ArraysJVM.kt:49)
at kotlin.collections.ArraysKt___ArraysJvmKt.copyOfRange(_ArraysJvm.kt:1859)
I’ve made an issue IDEA-320926 for the quickfix not producing equivalent code, but can someone help me with a suitable replacement for now?Adam S
05/23/2023, 11:11 AMArrays.copyOfRange()
allows for the index to lie outside of the source array’s bounds, while Kotlin’s copyOfRange()
performs a checkAdam S
05/23/2023, 11:19 AM/**
* Like [IntArray.copyOfRange], but allows for [toIndex] to be out-of-bounds.
*/
private fun IntArray.copyOfRangeSafe(fromIndex: Int, toIndex: Int): IntArray =
IntArray(toIndex - fromIndex) { getOrNull(fromIndex + it) ?: 0 }
thank for rubber ducking rubber duck , any further suggestions or refinements are welcome!hho
05/23/2023, 11:28 AMfun IntArray.copyOfRangeSafe(fromIndex: Int, toIndex: Int) =
copyOfRange(fromIndex, toIndex.coerceAtMost(size))
Adam S
05/23/2023, 11:29 AMfromIndex == toIndex
java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
hho
05/23/2023, 11:31 AMcopyOfRange
function instead of doing the copying yourself.Adam S
05/23/2023, 11:31 AMhho
05/23/2023, 11:32 AMAdam S
05/23/2023, 11:32 AMAdam S
05/23/2023, 11:34 AMprintln(indices)
returns 0..-1
hho
05/23/2023, 11:35 AMhho
05/23/2023, 11:38 AMAdam S
05/23/2023, 11:44 AMKlitos Kyriacou
05/23/2023, 2:37 PMtoIndex.coerceAtMost(size)
will not work, because Java's copyOfRange
guarantees the returned array will have size toIndex - fromIndex
.