diff --git a/backend.native/tests/build.gradle b/backend.native/tests/build.gradle index b19e50bd617..0c2ea8f441e 100644 --- a/backend.native/tests/build.gradle +++ b/backend.native/tests/build.gradle @@ -1059,6 +1059,11 @@ standaloneTest("lazy3") { source = "runtime/workers/lazy3.kt" } +task mutableData1(type: KonanLocalTest) { + enabled = (project.testTarget != 'wasm32') // Workers need pthreads. Need exceptions + source = "runtime/workers/mutableData1.kt" +} + task enumIdentity(type: KonanLocalTest) { enabled = (project.testTarget != 'wasm32') // Workers need pthreads. goldValue = "true\n" diff --git a/backend.native/tests/runtime/workers/mutableData1.kt b/backend.native/tests/runtime/workers/mutableData1.kt new file mode 100644 index 00000000000..4cadf459db0 --- /dev/null +++ b/backend.native/tests/runtime/workers/mutableData1.kt @@ -0,0 +1,47 @@ +package runtime.workers.mutableData1 + +import kotlin.native.concurrent.* +import kotlin.test.* + +// See https://youtrack.jetbrains.com/issue/KT-39145 +@Test +fun kt39145_1() = withWorker { + execute(TransferMode.SAFE, { "test" }) { + val data = MutableData(1_000) + val bytes = byteArrayOf(0, 10, 20, 30) + data.append(bytes, 0, 4) + assertEquals(4, data.size) + + assertContentsEquals(bytes, data) + }.result +} + +@Test +fun kt39145_2() = withWorker { + val externalData = MutableData(1_000) + execute(TransferMode.SAFE, { externalData }) { + val bytes = byteArrayOf(0, 10, 20, 30) + it.append(bytes, 0, 4) + assertEquals(4, it.size) + + assertContentsEquals(bytes, it) + }.result +} + +@Test +fun kt39145_3() { + val mainThreadData = MutableData(1_000) + val bytes = byteArrayOf(0, 10, 20, 30) + mainThreadData.append(bytes, 0, 4) + assertEquals(4, mainThreadData.size) + + assertContentsEquals(bytes, mainThreadData) +} + +private fun assertContentsEquals(expected: ByteArray, actual: MutableData) { + assertEquals(expected.size, actual.size) + + expected.forEachIndexed { index, byte -> + assertEquals(byte, actual.get(index)) + } +} \ No newline at end of file diff --git a/runtime/src/main/kotlin/kotlin/native/concurrent/MutableData.kt b/runtime/src/main/kotlin/kotlin/native/concurrent/MutableData.kt index 4be56b1bd8b..5f17ff70695 100644 --- a/runtime/src/main/kotlin/kotlin/native/concurrent/MutableData.kt +++ b/runtime/src/main/kotlin/kotlin/native/concurrent/MutableData.kt @@ -78,7 +78,7 @@ public class MutableData constructor(capacity: Int = 16) { public fun append(data: ByteArray, fromIndex: Int = 0, toIndex: Int = data.size): Unit = locked(lock) { if (fromIndex > toIndex) throw IndexOutOfBoundsException("$fromIndex is bigger than $toIndex") - if (toIndex == toIndex) return + if (fromIndex == toIndex) return val where = resizeDataLocked(this.size + (toIndex - fromIndex)) data.copyInto(buffer, where, fromIndex, toIndex) }