Move everything under kotlin-native folder

I was forced to manually do update the following files, because otherwise
they would be ignored according .gitignore settings. Probably they
should be deleted from repo.

Interop/.idea/compiler.xml
Interop/.idea/gradle.xml
Interop/.idea/libraries/Gradle__org_jetbrains_kotlin_kotlin_runtime_1_0_3.xml
Interop/.idea/libraries/Gradle__org_jetbrains_kotlin_kotlin_stdlib_1_0_3.xml
Interop/.idea/modules.xml
Interop/.idea/modules/Indexer/Indexer.iml
Interop/.idea/modules/Runtime/Runtime.iml
Interop/.idea/modules/StubGenerator/StubGenerator.iml
backend.native/backend.native.iml
backend.native/bc.frontend/bc.frontend.iml
backend.native/cli.bc/cli.bc.iml
backend.native/cli.bc/src/org/jetbrains/kotlin/cli/bc/K2Native.kt
backend.native/cli.bc/src/org/jetbrains/kotlin/cli/bc/K2NativeCompilerArguments.kt
backend.native/tests/link/lib/foo.kt
backend.native/tests/link/lib/foo2.kt
backend.native/tests/teamcity-test.property
This commit is contained in:
Stanislav Erokhin
2020-10-27 21:00:28 +03:00
parent 91e4162dad
commit f624800b84
2830 changed files with 0 additions and 0 deletions
@@ -0,0 +1,10 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
fun main(args : Array<String>) {
for (s in args) {
println(s)
}
}
@@ -0,0 +1,8 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
fun main(args: Array<String>) {
assert(false)
}
@@ -0,0 +1,8 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
fun main(args: Array<String>) {
assert(true)
}
@@ -0,0 +1,204 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
@file:OptIn(ExperimentalStdlibApi::class)
package runtime.basic.cleaner_basic
import kotlin.test.*
import kotlin.native.internal.*
import kotlin.native.concurrent.*
import kotlin.native.ref.WeakReference
class AtomicBoolean(initialValue: Boolean) {
private val impl = AtomicInt(if (initialValue) 1 else 0)
init {
freeze()
}
public var value: Boolean
get() = impl.value != 0
set(new) { impl.value = if (new) 1 else 0 }
}
class FunBox(private val impl: () -> Unit) {
fun call() {
impl()
}
}
@Test
fun testCleanerLambda() {
val called = AtomicBoolean(false);
var funBoxWeak: WeakReference<FunBox>? = null
var cleanerWeak: WeakReference<Cleaner>? = null
{
val cleaner = {
val funBox = FunBox { called.value = true }.freeze()
funBoxWeak = WeakReference(funBox)
createCleaner(funBox) { it.call() }
}()
GC.collect() // Make sure local funBox reference is gone
cleanerWeak = WeakReference(cleaner)
assertFalse(called.value)
}()
GC.collect()
performGCOnCleanerWorker()
assertNull(cleanerWeak!!.value)
assertTrue(called.value)
assertNull(funBoxWeak!!.value)
}
@Test
fun testCleanerAnonymousFunction() {
val called = AtomicBoolean(false);
var funBoxWeak: WeakReference<FunBox>? = null
var cleanerWeak: WeakReference<Cleaner>? = null
{
val cleaner = {
val funBox = FunBox { called.value = true }.freeze()
funBoxWeak = WeakReference(funBox)
createCleaner(funBox, fun (it: FunBox) { it.call() })
}()
GC.collect() // Make sure local funBox reference is gone
cleanerWeak = WeakReference(cleaner)
assertFalse(called.value)
}()
GC.collect()
performGCOnCleanerWorker()
assertNull(cleanerWeak!!.value)
assertTrue(called.value)
assertNull(funBoxWeak!!.value)
}
@Test
fun testCleanerFunctionReference() {
val called = AtomicBoolean(false);
var funBoxWeak: WeakReference<FunBox>? = null
var cleanerWeak: WeakReference<Cleaner>? = null
{
val cleaner = {
val funBox = FunBox { called.value = true }.freeze()
funBoxWeak = WeakReference(funBox)
createCleaner(funBox, FunBox::call)
}()
GC.collect() // Make sure local funBox reference is gone
cleanerWeak = WeakReference(cleaner)
assertFalse(called.value)
}()
GC.collect()
performGCOnCleanerWorker()
assertNull(cleanerWeak!!.value)
assertTrue(called.value)
assertNull(funBoxWeak!!.value)
}
@Test
fun testCleanerFailWithNonShareableArgument() {
val funBox = FunBox {}
assertFailsWith<IllegalArgumentException> {
createCleaner(funBox) {}
}
}
@Test
fun testCleanerCleansWithoutGC() {
val called = AtomicBoolean(false);
var funBoxWeak: WeakReference<FunBox>? = null
var cleanerWeak: WeakReference<Cleaner>? = null
{
val cleaner = {
val funBox = FunBox { called.value = true }.freeze()
funBoxWeak = WeakReference(funBox)
createCleaner(funBox) { it.call() }
}()
GC.collect() // Make sure local funBox reference is gone
cleaner.freeze()
cleanerWeak = WeakReference(cleaner)
assertFalse(called.value)
}()
GC.collect()
assertNull(cleanerWeak!!.value)
waitCleanerWorker()
assertTrue(called.value)
// If this fails, GC has somehow ran on the cleaners worker.
assertNotNull(funBoxWeak!!.value)
}
val globalInt = AtomicInt(0)
@Test
fun testCleanerWithInt() {
var cleanerWeak: WeakReference<Cleaner>? = null
{
val cleaner = createCleaner(42) {
globalInt.value = it
}.freeze()
cleanerWeak = WeakReference(cleaner)
assertEquals(0, globalInt.value)
}()
GC.collect()
performGCOnCleanerWorker()
assertNull(cleanerWeak!!.value)
assertEquals(42, globalInt.value)
}
val globalPtr = AtomicNativePtr(NativePtr.NULL)
@Test
fun testCleanerWithNativePtr() {
var cleanerWeak: WeakReference<Cleaner>? = null
{
val cleaner = createCleaner(NativePtr.NULL + 42L) {
globalPtr.value = it
}
cleanerWeak = WeakReference(cleaner)
assertEquals(NativePtr.NULL, globalPtr.value)
}()
GC.collect()
performGCOnCleanerWorker()
assertNull(cleanerWeak!!.value)
assertEquals(NativePtr.NULL + 42L, globalPtr.value)
}
@Test
fun testCleanerWithException() {
val called = AtomicBoolean(false);
var funBoxWeak: WeakReference<FunBox>? = null
var cleanerWeak: WeakReference<Cleaner>? = null
{
val funBox = FunBox { called.value = true }.freeze()
funBoxWeak = WeakReference(funBox)
val cleaner = createCleaner(funBox) {
it.call()
error("Cleaner block failed")
}
cleanerWeak = WeakReference(cleaner)
}()
GC.collect()
performGCOnCleanerWorker()
assertNull(cleanerWeak!!.value)
// Cleaners block started executing.
assertTrue(called.value)
// Even though the block failed, the captured funBox is freed.
assertNull(funBoxWeak!!.value)
}
@@ -0,0 +1,21 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
@file:OptIn(ExperimentalStdlibApi::class)
import kotlin.native.internal.*
import kotlin.native.Platform
fun main() {
// Cleaner holds onto a finalization lambda. If it doesn't get executed,
// the memory will leak. Suppress memory leak checker to check for cleaners
// leak only.
Platform.isMemoryLeakCheckerActive = false
Platform.isCleanersLeakCheckerActive = true
// This cleaner will run, because with the checker active this cleaner
// will get collected, block scheduled and executed before cleaners are disabled.
createCleaner(42) {
println(it)
}
}
@@ -0,0 +1,21 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
@file:OptIn(ExperimentalStdlibApi::class)
import kotlin.native.internal.*
import kotlin.native.Platform
fun main() {
// Cleaner holds onto a finalization lambda. If it doesn't get executed,
// the memory will leak. Suppress memory leak checker to check for cleaners
// leak only.
Platform.isMemoryLeakCheckerActive = false
Platform.isCleanersLeakCheckerActive = false
// This cleaner will not run, because with the checker inactive this cleaner
// will not get collected before cleaners are disabled.
createCleaner(42) {
println(it)
}
}
@@ -0,0 +1,26 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
@file:OptIn(ExperimentalStdlibApi::class)
import kotlin.test.*
import kotlin.native.concurrent.*
import kotlin.native.internal.*
import kotlin.native.Platform
@ThreadLocal
var tlsCleaner: Cleaner? = null
fun main() {
// Cleaner holds onto a finalization lambda. If it doesn't get executed,
// the memory will leak. Suppress memory leak checker to check for cleaners
// leak only.
Platform.isMemoryLeakCheckerActive = false
Platform.isCleanersLeakCheckerActive = true
// This cleaner won't be run
tlsCleaner = createCleaner(42) {
println(it)
}
}
@@ -0,0 +1,26 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
@file:OptIn(ExperimentalStdlibApi::class)
import kotlin.test.*
import kotlin.native.concurrent.*
import kotlin.native.internal.*
import kotlin.native.Platform
@ThreadLocal
var tlsCleaner: Cleaner? = null
fun main() {
// Cleaner holds onto a finalization lambda. If it doesn't get executed,
// the memory will leak. Suppress memory leak checker to check for cleaners
// leak only.
Platform.isMemoryLeakCheckerActive = false
Platform.isCleanersLeakCheckerActive = false
// This cleaner won't be run
tlsCleaner = createCleaner(42) {
println(it)
}
}
@@ -0,0 +1,31 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
@file:OptIn(ExperimentalStdlibApi::class)
import kotlin.test.*
import kotlin.native.concurrent.*
import kotlin.native.internal.*
@ThreadLocal
var tlsCleaner: Cleaner? = null
val value = AtomicInt(0)
fun main() {
val worker = Worker.start()
worker.execute(TransferMode.SAFE, {}) {
tlsCleaner = createCleaner(42) {
value.value = it
}
}
worker.requestTermination().result
waitWorkerTermination(worker)
waitCleanerWorker()
assertEquals(42, value.value)
}
@@ -0,0 +1,24 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
@file:OptIn(ExperimentalStdlibApi::class)
import kotlin.test.*
import kotlin.native.internal.*
// This cleaner won't be run, because it's deinitialized with globals after
// cleaners are disabled.
val globalCleaner = createCleaner(42) {
println(it)
}
fun main() {
// Cleaner holds onto a finalization lambda. If it doesn't get executed,
// the memory will leak. Suppress memory leak checker to check for cleaners
// leak only.
Platform.isMemoryLeakCheckerActive = false
// Make sure cleaner is initialized.
assertNotNull(globalCleaner)
}
@@ -0,0 +1,26 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
@file:OptIn(ExperimentalStdlibApi::class)
import kotlin.test.*
import kotlin.native.internal.*
import kotlin.native.Platform
// This cleaner won't be run, because it's deinitialized with globals after
// cleaners are disabled.
val globalCleaner = createCleaner(42) {
println(it)
}
fun main() {
// Cleaner holds onto a finalization lambda. If it doesn't get executed,
// the memory will leak. Suppress memory leak checker to check for cleaners
// leak only.
Platform.isMemoryLeakCheckerActive = false
Platform.isCleanersLeakCheckerActive = true
// Make sure cleaner is initialized.
assertNotNull(globalCleaner)
}
@@ -0,0 +1,26 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
@file:OptIn(ExperimentalStdlibApi::class)
import kotlin.test.*
import kotlin.native.internal.*
import kotlin.native.Platform
// This cleaner won't be run, because it's deinitialized with globals after
// cleaners are disabled.
val globalCleaner = createCleaner(42) {
println(it)
}
fun main() {
// Cleaner holds onto a finalization lambda. If it doesn't get executed,
// the memory will leak. Suppress memory leak checker to check for cleaners
// leak only.
Platform.isMemoryLeakCheckerActive = false
Platform.isCleanersLeakCheckerActive = false
// Make sure cleaner is initialized.
assertNotNull(globalCleaner)
}
@@ -0,0 +1,174 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
@file:OptIn(ExperimentalStdlibApi::class)
package runtime.basic.cleaner_workers
import kotlin.test.*
import kotlin.native.internal.*
import kotlin.native.concurrent.*
import kotlin.native.ref.WeakReference
class AtomicBoolean(initialValue: Boolean) {
private val impl = AtomicInt(if (initialValue) 1 else 0)
init {
freeze()
}
public var value: Boolean
get() = impl.value != 0
set(new) { impl.value = if (new) 1 else 0 }
}
class FunBox(private val impl: () -> Unit) {
fun call() {
impl()
}
}
@Test
fun testCleanerDestroyInChild() {
val worker = Worker.start()
val called = AtomicBoolean(false);
var funBoxWeak: WeakReference<FunBox>? = null
var cleanerWeak: WeakReference<Cleaner>? = null
worker.execute(TransferMode.SAFE, {
val funBox = FunBox { called.value = true }.freeze()
funBoxWeak = WeakReference(funBox)
val cleaner = createCleaner(funBox) { it.call() }
cleanerWeak = WeakReference(cleaner)
Pair(called, cleaner)
}) { (called, cleaner) ->
assertFalse(called.value)
}.result
GC.collect()
worker.execute(TransferMode.SAFE, {}) { GC.collect() }.result
performGCOnCleanerWorker()
assertNull(cleanerWeak!!.value)
assertTrue(called.value)
assertNull(funBoxWeak!!.value)
worker.requestTermination().result
}
@Test
fun testCleanerDestroyWithChild() {
val worker = Worker.start()
val called = AtomicBoolean(false);
var funBoxWeak: WeakReference<FunBox>? = null
var cleanerWeak: WeakReference<Cleaner>? = null
worker.execute(TransferMode.SAFE, {
val funBox = FunBox { called.value = true }.freeze()
funBoxWeak = WeakReference(funBox)
val cleaner = createCleaner(funBox) { it.call() }
cleanerWeak = WeakReference(cleaner)
Pair(called, cleaner)
}) { (called, cleaner) ->
assertFalse(called.value)
}.result
GC.collect()
worker.requestTermination().result
waitWorkerTermination(worker)
performGCOnCleanerWorker() // Collect cleaners stack
assertNull(cleanerWeak!!.value)
assertTrue(called.value)
assertNull(funBoxWeak!!.value)
}
@Test
fun testCleanerDestroyInMain() {
val worker = Worker.start()
val called = AtomicBoolean(false);
var funBoxWeak: WeakReference<FunBox>? = null
var cleanerWeak: WeakReference<Cleaner>? = null
{
val result = worker.execute(TransferMode.SAFE, { called }) { called ->
val funBox = FunBox { called.value = true }.freeze()
val cleaner = createCleaner(funBox) { it.call() }
Triple(cleaner, WeakReference(funBox), WeakReference(cleaner))
}.result
val cleaner = result.first
funBoxWeak = result.second
cleanerWeak = result.third
assertFalse(called.value)
}()
GC.collect()
worker.execute(TransferMode.SAFE, {}) { GC.collect() }.result
performGCOnCleanerWorker()
assertNull(cleanerWeak!!.value)
assertTrue(called.value)
assertNull(funBoxWeak!!.value)
worker.requestTermination().result
}
@Test
fun testCleanerDestroyShared() {
val worker = Worker.start()
val called = AtomicBoolean(false);
var funBoxWeak: WeakReference<FunBox>? = null
var cleanerWeak: WeakReference<Cleaner>? = null
val cleanerHolder: AtomicReference<Cleaner?> = AtomicReference(null);
{
val funBox = FunBox { called.value = true }.freeze()
funBoxWeak = WeakReference(funBox)
val cleaner = createCleaner(funBox) { it.call() }
cleanerWeak = WeakReference(cleaner)
cleanerHolder.value = cleaner
worker.execute(TransferMode.SAFE, { Pair(called, cleanerHolder) }) { (called, cleanerHolder) ->
cleanerHolder.value = null
assertFalse(called.value)
}.result
}()
GC.collect()
worker.execute(TransferMode.SAFE, {}) { GC.collect() }.result
performGCOnCleanerWorker()
assertNull(cleanerWeak!!.value)
assertTrue(called.value)
assertNull(funBoxWeak!!.value)
worker.requestTermination().result
}
@ThreadLocal
var tlsValue = 11
@Test
fun testCleanerWithTLS() {
val worker = Worker.start()
tlsValue = 12
val value = AtomicInt(0)
worker.execute(TransferMode.SAFE, {value}) {
tlsValue = 13
createCleaner(it) {
it.value = tlsValue
}
Unit
}.result
worker.execute(TransferMode.SAFE, {}) { GC.collect() }.result
performGCOnCleanerWorker()
assertEquals(11, value.value)
worker.requestTermination().result
}
@@ -0,0 +1,9 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
// TODO: remove kotlin_native.io once overrides are in place.
fun main(args : Array<String>) {
println("Hello, world!")
}
@@ -0,0 +1,13 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.basic.empty_substring
import kotlin.test.*
@Test fun runTest() {
val hello = "Hello world"
println(hello.subSequence(1, 1).toString())
}
@@ -0,0 +1,37 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.basic.entry0
fun fail() {
println("Test failed, this is a wrong main() function.")
}
fun main() {
fail()
}
fun <T> main(args: Array<String>) {
fail()
}
fun main(args: Array<Int>) {
fail()
}
fun main(args: Array<String>, second_arg: Int) {
fail()
}
class Foo {
fun main(args: Array<String>) {
fail()
}
}
fun main(args: Array<String>) {
println("Hello.")
}
@@ -0,0 +1,22 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
fun fail() {
println("Test failed, this is a wrong main() function.")
}
fun foo(args: Array<String>) {
println("Hello.")
}
fun bar() {
println("Hello, without args.")
}
fun main(args: Array<String>) {
fail()
}
@@ -0,0 +1,9 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
fun main(args: Array<String>) {
fail()
}
@@ -0,0 +1,3 @@
fun main() {
println("This is main without args")
}
@@ -0,0 +1,22 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.basic.enum_equals
import kotlin.test.*
enum class EnumA {
A, B
}
enum class EnumB {
B
}
fun main() {
println(EnumA.A == EnumA.A)
println(EnumA.A == EnumA.B)
println(EnumA.A == EnumB.B)
}
@@ -0,0 +1,12 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
import kotlin.system.*
fun main(args: Array<String>) {
exitProcess(42)
@Suppress("UNREACHABLE_CODE")
throw RuntimeException("Exit function call returned normally")
}
@@ -0,0 +1,18 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.basic.for0
import kotlin.test.*
@Test fun runTest() {
val byteArray = ByteArray(3)
byteArray[0] = 2
byteArray[1] = 3
byteArray[2] = 4
for (item in byteArray) {
println(item)
}
}
@@ -0,0 +1,26 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.basic.hash0
import kotlin.test.*
@Test fun runTest() {
println(239.hashCode())
println((-1L).hashCode())
println('a'.hashCode())
println(1.0f.hashCode())
println(1.0.hashCode())
println(true.hashCode())
println(false.hashCode())
println(Any().hashCode() != Any().hashCode())
val a = CharArray(5)
a[0] = 'H'
a[1] = 'e'
a[2] = 'l'
a[3] = 'l'
a[4] = 'o'
println("Hello".hashCode() == String(a, 0, 5).hashCode())
}
@@ -0,0 +1,12 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.basic.hello0
import kotlin.test.*
@Test fun runTest() {
println("Hello, world!")
}
@@ -0,0 +1,10 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
// TODO: TestRuner should be able to pass input to stdin
// TODO: remove kotlin_native.io once overrides are in place.
fun main(args: Array<String>) {
print(readLine().toString())
}
@@ -0,0 +1,10 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
// TODO: TestRuner should be able to pass input to stdin
// TODO: remove kotlin_native.io once overrides are in place.
fun main(args : Array<String>) {
print("you entered '" + readLine() + "'")
}
@@ -0,0 +1,16 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.basic.hello3
import kotlin.test.*
@Test fun runTest() {
println(239)
// TODO: enable, once override by name is implemented.
println(true)
println(3.14159)
println('A')
}
@@ -0,0 +1,14 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.basic.hello4
import kotlin.test.*
@Test fun runTest() {
val x = 2
println(if (x == 2) "Hello" else "Привет")
println(if (x == 3) "Bye" else "Пока")
}
@@ -0,0 +1,28 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
import kotlin.test.*
import kotlin.math.*
fun main() {
val hf = hypot(Float.NEGATIVE_INFINITY, Float.NaN)
println("float hypot: $hf ${hf.toRawBits().toString(16)}")
println("Float.NaN: ${Float.NaN.toRawBits().toString(16)}")
println("Float.+Inf: ${Float.POSITIVE_INFINITY} ${Float.POSITIVE_INFINITY.toRawBits().toString(16)}")
println("Float.-Inf: ${Float.NEGATIVE_INFINITY} ${Float.NEGATIVE_INFINITY.toRawBits().toUInt().toString(16)}")
println(Float.POSITIVE_INFINITY == Float.NEGATIVE_INFINITY)
assertEquals(Float.POSITIVE_INFINITY, hypot(Float.NEGATIVE_INFINITY, Float.NaN))
val hd = hypot(Double.NEGATIVE_INFINITY, Double.NaN)
println("Double hypot: $hd ${hd.toRawBits().toString(16)}")
println("Double.NaN: ${Double.NaN.toRawBits().toString(16)}")
println("Double.+Inf: ${Double.POSITIVE_INFINITY} ${Double.POSITIVE_INFINITY.toRawBits().toString(16)}")
println("Double.-Inf: ${Double.NEGATIVE_INFINITY} ${Double.NEGATIVE_INFINITY.toRawBits().toUInt().toString(16)}")
println(Double.POSITIVE_INFINITY == Double.NEGATIVE_INFINITY)
assertEquals(Double.POSITIVE_INFINITY, hypot(Double.NEGATIVE_INFINITY, Double.NaN))
println("hypot NaN, 0: ${hypot(Double.NaN, 0.0).toRawBits().toString(16)}")
assertTrue(hypot(Double.NaN, 0.0).isNaN())
}
@@ -0,0 +1,34 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.basic.ieee754
import kotlin.test.*
@Test fun runTest() {
val v = Float.POSITIVE_INFINITY
val i = v.toInt()
println("$v $i ${v.toShort()} ${i.toShort()}")
val a = 42
val b = Float.MAX_VALUE
println("${a + b}")
val s = Float.NaN.toShort()
println("NAN2SHORT:: $s")
val d: Float = Float.MAX_VALUE
println("MAX2SHORT:: ${d.toShort()}")
val d2i = d.toInt()
println("$d2i ${d2i.toShort()}")
for (f in arrayOf(Float.POSITIVE_INFINITY, Float.MAX_VALUE / 2, Float.MAX_VALUE,
3.14f, Float.NaN, -33333.12312f, Float.MIN_VALUE, Float.NEGATIVE_INFINITY,
-1.2f, -12.6f, 2.3f)) {
println("FLOAT:: $f INT:: ${f.toInt()}")
}
println("OK")
}
@@ -0,0 +1,4 @@
val x = initRuntimeIfNeeded()
fun main() {
}
@@ -0,0 +1,53 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.basic.initializers0
import kotlin.test.*
class A {
init{
println ("A::init")
}
val a = 1
companion object :B(1) {
init {
println ("A::companion")
}
fun foo() {
println("A::companion::foo")
}
}
object AObj : B(){
init {
println("A::Obj")
}
fun foo() {
println("A::AObj::foo")
}
}
}
@Test fun runTest() {
println("main")
A.foo()
A.foo()
A.AObj.foo()
A.AObj.foo()
}
open class B(val a:Int, val b:Int) {
constructor(a:Int):this (a, 0) {
println("B::constructor(" + a.toString()+ ")")
}
constructor():this(0) {
println("B::constructor()")
}
}
@@ -0,0 +1,22 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.basic.initializers1
import kotlin.test.*
class TestClass {
companion object {
init {
println("Init Test")
}
}
}
@Test fun runTest() {
val t1 = TestClass()
val t2 = TestClass()
println("Done")
}
@@ -0,0 +1,22 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
class A(val msg: String) {
init {
println("init $msg")
}
override fun toString(): String = msg
}
val globalValue1 = 1
val globalValue2 = A("globalValue2")
val globalValue3 = A("globalValue3")
fun main(args: Array<String>) {
println(globalValue1.toString())
println(globalValue2.toString())
println(globalValue3.toString())
}
@@ -0,0 +1,16 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.basic.initializers3
import kotlin.test.*
class Foo(val bar: Int)
var x = Foo(42)
@Test fun runTest() {
println(x.bar)
}
@@ -0,0 +1,16 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.basic.initializers4
import kotlin.test.*
const val INT_MAX_POWER_OF_TWO: Int = Int.MAX_VALUE / 2 + 1
val DOUBLE = Double.MAX_VALUE - 1.0
@Test fun runTest() {
println(INT_MAX_POWER_OF_TWO)
println(DOUBLE > 0.0)
}
@@ -0,0 +1,17 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.basic.initializers5
import kotlin.test.*
object A {
val a = 42
val b = A.a
}
@Test fun runTest() {
println(A.b)
}
@@ -0,0 +1,74 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.basic.initializers6
import kotlin.test.*
import kotlin.native.concurrent.*
val aWorkerId = AtomicInt(0)
val bWorkersCount = 3
val aWorkerUnlocker = AtomicInt(0)
val bWorkerUnlocker = AtomicInt(0)
object A {
init {
// Must be called by aWorker only.
assertEquals(aWorkerId.value, Worker.current.id)
// Only allow b workers to run, when a worker has started initialization.
bWorkerUnlocker.increment()
// Only proceed with initialization, when all b workers have started executing.
while (aWorkerUnlocker.value < bWorkersCount) {}
// And now wait a bit, to increase probability of races.
Worker.current.park(100 * 1000L)
}
val a = produceA()
val b = produceB()
}
fun produceA(): String {
// Must've been called by aWorker only.
assertEquals(aWorkerId.value, Worker.current.id)
return "A"
}
fun produceB(): String {
// Must've been called by aWorker only.
assertEquals(aWorkerId.value, Worker.current.id)
// Also check that it's ok to get A.a while initializing A.b.
return "B+${A.a}"
}
@Test fun runTest() {
val aWorker = Worker.start()
aWorkerId.value = aWorker.id
val bWorkers = Array(bWorkersCount, { _ -> Worker.start() })
val aFuture = aWorker.execute(TransferMode.SAFE, {}, {
A.b
})
val bFutures = Array(bWorkers.size, {
bWorkers[it].execute(TransferMode.SAFE, {}, {
// Wait until A has started to initialize.
while (bWorkerUnlocker.value < 1) {}
// Now allow A initialization to continue.
aWorkerUnlocker.increment()
// And this should not've tried to init A itself.
A.a + A.b
})
})
for (future in bFutures) {
assertEquals("AB+A", future.result)
}
assertEquals("B+A", aFuture.result)
for (worker in bWorkers) {
worker.requestTermination().result
}
aWorker.requestTermination().result
}
@@ -0,0 +1,60 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.basic.initializers7
import kotlin.test.*
object A {
init {
assertAUninitialized()
}
val a1 = 7
val a2 = 12
}
// Check that A is initialized dynamically.
fun assertAUninitialized() {
assertEquals(0, A.a1)
assertEquals(0, A.a2)
}
object B {
init {
assertBUninitialized()
}
val b1 = A.a2
val b2 = C.c1
}
// Check that B is initialized dynamically.
fun assertBUninitialized() {
assertEquals(0, B.b1)
assertEquals(0, B.b2)
}
object C {
init {
assertCUninitialized()
}
val c1 = 42
val c2 = A.a1
val c3 = B.b1
val c4 = B.b2
}
// Check that C is initialized dynamically.
fun assertCUninitialized() {
assertEquals(0, C.c1)
assertEquals(0, C.c2)
assertEquals(0, C.c3)
assertEquals(0, C.c4)
}
@Test fun runTest() {
assertEquals(A.a1, C.c2)
assertEquals(A.a2, C.c3)
assertEquals(C.c1, C.c4)
}
@@ -0,0 +1,25 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.basic.interface0
import kotlin.test.*
interface A {
fun b() = c()
fun c()
}
class B(): A {
override fun c() {
println("PASSED")
}
}
@Test fun runTest() {
val a:A = B()
a.b()
}
@@ -0,0 +1,13 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
fun fail() {
println("Test failed, this is a wrong main() function.")
}
fun foo(args: Array<String>) {
println("Hello.")
}
@@ -0,0 +1,12 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.basic.main_exception
import kotlin.test.*
@Test fun runTest() {
throw Error("Hello!")
}
@@ -0,0 +1,63 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.basic.random
import kotlin.collections.*
import kotlin.random.*
import kotlin.system.*
import kotlin.test.*
/**
* Tests that setting the same seed make random generate the same sequence
*/
private inline fun <reified T> testReproducibility(seed: Long, generator: Random.() -> T) {
// Reset seed. This will make Random to start a new sequence
val r1 = Random(seed)
val first = Array<T>(50, { i -> r1.generator() }).toList()
// Reset seed and try again
val r2 = Random(seed)
val second = Array<T>(50, { i -> r2.generator() }).toList()
assertTrue(first == second, "FAIL: got different sequences of generated values " +
"first: $first, second: $second")
}
/**
* Tests that setting seed makes random generate different sequence.
*/
private inline fun <reified T> testDifference(generator: Random.() -> T) {
val r1 = Random(12345678L)
val first = Array<T>(100, { i -> r1.generator() }).toList()
val r2 = Random(87654321L)
val second = Array<T>(100, { i -> r2.generator() }).toList()
assertTrue(first != second, "FAIL: got the same sequence of generated values " +
"first: $first, second: $second")
}
@Test
fun testInts() {
testReproducibility(getTimeMillis(), { nextInt() })
testReproducibility(Long.MAX_VALUE, { nextInt() })
}
@Test
fun testLong() {
testReproducibility(getTimeMillis(), { nextLong() })
testReproducibility(Long.MAX_VALUE, { nextLong() })
}
@Test
fun testDiffInt() = testDifference { nextInt() }
@Test
fun testDiffLong() = testDifference { nextLong() }
@Test
fun testNextInt() {
testReproducibility(getTimeMillis(), { nextInt(1000) })
testReproducibility(1000L, { nextInt(1024) })
}
@@ -0,0 +1,8 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
fun main(args: Array<String>) {
print(readLine()!!.toInt())
}
@@ -0,0 +1,8 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
fun main(args: Array<String>) {
print(readLine()!!)
}
@@ -0,0 +1,104 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.basic.simd
import kotlin.test.*
@Test fun runTest() {
testBoxingSimple()
testBoxing()
testSetGet()
testString()
testOOB()
testEquals()
testHash()
testDefaultValue()
}
class Box<T>(t: T) {
var value = t
}
class UnalignedC(t: Vector128) {
var smth = 1
var value = t
}
fun testBoxingSimple() {
val v = vectorOf(1f, 3.162f, 10f, 31f)
val box: Box<Vector128> = Box<Vector128>(v)
assertEquals(v, box.value, "testBoxingSimple FAILED")
}
fun testBoxing() {
var u = UnalignedC(vectorOf(0, 1, 2, 3))
assertEquals(3, u.value.getIntAt(3))
u.value = vectorOf(0f, 1f, 2f, 3f)
assertEquals(vectorOf(0f, 1f, 2f, 3f), u.value, "testBoxing FAILED")
}
fun testSetGet() {
var v4any = vectorOf(0, 1, 2, 3)
(0 until 4).forEach { assertEquals(it, v4any.getIntAt(it), "testSetGet FAILED for <4 x i32>") }
// type punning: set the variable to another runtime type
val a = arrayOf(1f, 3.162f, 10f, 31f)
v4any = vectorOf(a[0], a[1], a[2], a[3])
(0 until 4).forEach { assertEquals(a[it], v4any.getFloatAt(it), "testSetGet FAILED for <4 x float>") }
}
fun testString() {
val v4i = vectorOf(100, 1024, Int.MAX_VALUE, Int.MIN_VALUE)
assertEquals("(0x64, 0x400, 0x7fffffff, 0x80000000)", v4i.toString(), "testString FAILED")
}
fun testOOB() {
val f = vectorOf(1f, 3.162f, 10f, 31f)
println("f.getByteAt(15) is OK ${f.getByteAt(15)}")
assertFailsWith<IndexOutOfBoundsException>("f.getByteAt(16) should fail") {
f.getByteAt(16)
}
assertFailsWith<IndexOutOfBoundsException>("f.getIntAt(-1) should fail") {
f.getIntAt(-1)
}
assertFailsWith<IndexOutOfBoundsException>("f.getFloatAt(4) should fail") {
f.getFloatAt(4)
}
}
fun testEquals() {
var v1 = vectorOf(-1f, 0f, 0f, -7f)
var v2 = vectorOf(1f, 4f, 3f, 7f)
assertEquals(false, v1 == v2)
assertEquals(false, v1.equals(v2))
assertEquals(false, v1.equals(Any()))
assertEquals(true, v2 == v2)
v1 = v2
assertEquals(true, v1 == v2)
}
fun testHash() {
val h1 = vectorOf(1f, 4f, 3f, 7f).hashCode()
val h2 = vectorOf(3f, 7f, 1f, 4f).hashCode()
assertEquals(false, h1 == h2)
val i = 654687
assertEquals(true, vectorOf(0, 0, i, 0).hashCode() == i.hashCode()) // exploit little endianness
assertEquals(true, vectorOf(1, 0, 0, 0).hashCode() == vectorOf(0, 0, 31, 0).hashCode())
}
private fun funDefaultValue(v: Vector128 = vectorOf(1.0f, 2.0f, 3.0f, 4.0f)) = v
fun testDefaultValue() {
assertEquals(vectorOf(1.0f, 2.0f, 3.0f, 4.0f), funDefaultValue())
}
@@ -0,0 +1,32 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.basic.standard
import kotlin.test.*
class Foo(val bar: Int)
fun <T> assertEquals(actual: T, expected: T) {
if (actual != expected) throw AssertionError("Assertion failed. Expected value: $expected, actual value: $actual")
}
@Test fun runTest() {
try {
TODO()
throw AssertionError("TODO() doesn't throw an exception")
} catch(e: NotImplementedError) {}
val foo = Foo(42)
assertEquals(run { 42 }, 42)
assertEquals(foo.run { bar }, 42)
assertEquals(with(foo) { bar }, 42)
assertEquals(foo.apply { bar }, foo)
assertEquals(foo.also { it.bar }, foo)
assertEquals(foo.let { it.bar }, 42)
var i = 0
repeat(10) { i++ }
assertEquals(i, 10)
}
@@ -0,0 +1,42 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.basic.statements0
import kotlin.test.*
fun simple() {
var a = 238
a++
println(a)
--a
println(a)
}
class Foo() {
val j = 2
var i = 29
fun more() {
i++
}
fun less() {
--i
}
}
fun fields() {
val foo = Foo()
foo.more()
println(foo.i)
foo.less()
println(foo.i)
}
@Test fun runTest() {
simple()
fields()
}
@@ -0,0 +1,17 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.basic.throw0
import kotlin.test.*
@Test fun runTest() {
val cond = 1
if (cond == 2) throw RuntimeException()
if (cond == 3) throw NoSuchElementException("no such element")
if (cond == 4) throw Error("error happens")
println("Done")
}
@@ -0,0 +1,27 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.basic.tostring0
import kotlin.test.*
@Test fun runTest() {
println(127.toByte().toString())
println(255.toByte().toString())
println(239.toShort().toString())
println('A'.toString())
println('Ё'.toString())
println('ト'.toString())
println(1122334455.toString())
println(112233445566778899.toString())
// Here we differ from Java, as have no dtoa() yet.
println(3.14159265358.toString())
// Here we differ from Java, as have no dtoa() yet.
println(1e27.toFloat().toString())
println(1e7.toString())
println(1e-300.toDouble().toString())
println(true.toString())
println(false.toString())
}
@@ -0,0 +1,13 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.basic.tostring1
import kotlin.test.*
@Test fun runTest() {
val hello = "Hello world"
println(hello.subSequence(1, 5).toString())
}
@@ -0,0 +1,19 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.basic.tostring2
import kotlin.test.*
@Test fun runTest() {
val hello = "Hello"
val array = hello.toCharArray()
for (ch in array) {
print(ch)
print(" ")
}
println()
println(String(array, 0, array.size))
}
@@ -0,0 +1,78 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.basic.tostring3
import kotlin.test.*
fun testByte() {
val values = ByteArray(2)
values[0] = Byte.MIN_VALUE
values[1] = Byte.MAX_VALUE
for (v in values) {
println(v)
}
}
fun testShort() {
val values = ShortArray(2)
values[0] = Short.MIN_VALUE
values[1] = Short.MAX_VALUE
for (v in values) {
println(v)
}
}
fun testInt() {
val values = IntArray(2)
values[0] = Int.MIN_VALUE
values[1] = Int.MAX_VALUE
for (v in values) {
println(v)
}
}
fun testLong() {
val values = LongArray(2)
values[0] = Long.MIN_VALUE
values[1] = Long.MAX_VALUE
for (v in values) {
println(v)
}
}
fun testFloat() {
val values = FloatArray(5)
values[0] = Float.MIN_VALUE
values[1] = Float.MAX_VALUE
values[2] = Float.NEGATIVE_INFINITY
values[3] = Float.POSITIVE_INFINITY
values[4] = Float.NaN
for (v in values) {
println(v)
}
}
fun testDouble() {
val values = DoubleArray(5)
values[0] = Double.MIN_VALUE
values[1] = Double.MAX_VALUE
values[2] = Double.NEGATIVE_INFINITY
values[3] = Double.POSITIVE_INFINITY
values[4] = Double.NaN
for (v in values) {
println(v)
}
}
@Test fun runTest() {
testByte()
testShort()
testInt()
testLong()
testFloat()
testDouble()
}
@@ -0,0 +1,42 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.basic.worker_random
import kotlin.native.concurrent.*
import kotlin.collections.*
import kotlin.random.*
import kotlin.system.*
import kotlin.test.*
@Test
fun testRandomWorkers() {
val seed = getTimeMillis()
val workers = Array(5, { _ -> Worker.start() })
val attempts = 3
val results = Array(attempts, { ArrayList<Int>() } )
for (attempt in 0 until attempts) {
// Produce a list of random numbers in each worker
val futures = Array(workers.size, { workerIndex ->
workers[workerIndex].execute(TransferMode.SAFE, { workerIndex }) {
input ->
Array(10, { Random.nextInt() }).toList()
}
})
// Now collect all results into current attempt's list
val futureSet = futures.toSet()
var finished = 0
while (finished < futureSet.size) {
val ready = waitForMultipleFutures(futureSet, 10000)
ready.forEach { results[attempt].addAll(it.result) }
finished += ready.size
}
}
workers.forEach {
it.requestTermination().result
}
}
@@ -0,0 +1,72 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.collections.AbstractMutableCollection
import kotlin.test.*
class TestCollection(): AbstractMutableCollection<Int>() {
companion object {
const val SIZE = 7
}
private val array = IntArray(SIZE)
private var len = 0
override val size: Int
get() = len
override fun add(element: Int): Boolean {
if (len >= SIZE) return false
array[len++] = element
return true
}
override fun iterator(): MutableIterator<Int> = object: MutableIterator<Int> {
var nextIndex = 0
override fun hasNext() = nextIndex < len
override fun next() = array[nextIndex++]
override fun remove() {
if (nextIndex == 0) throw IllegalStateException()
for (i in nextIndex..len - 1) {
array[i - 1] = array[i]
}
len--
nextIndex--
}
}
override fun clear() {
len = 0
}
}
fun assertEquals(a: TestCollection, b: List<Int>) {
if (a.size != b.size) {
throw AssertionError()
}
val aIt = a.iterator()
val bIt = b.iterator()
while (aIt.hasNext()) {
if (aIt.next() != bIt.next()) throw AssertionError("TestCollection contains wrong elements. Expected: $b, actual: $a.")
}
}
@Test fun runTest() {
val c = TestCollection()
if (!c.addAll(listOf(1, 2, 3, 2, 4, 5, 4))) throw AssertionError("addAll is false when it must be true.")
if (c.addAll(listOf(1, 2)) != false) throw AssertionError("addAll is true when it must be false.")
c.removeAll(listOf(1, 2))
assertEquals(c, listOf(3, 4, 5, 4))
c.retainAll(listOf(4, 5))
assertEquals(c, listOf(4, 5, 4))
c.remove(4)
assertEquals(c, listOf(5, 4))
c.clear()
assertEquals(c, listOf())
}
@@ -0,0 +1,456 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.collections.BitSet
import kotlin.test.*
fun assertContainsOnly(bitSet: BitSet, trueBits: Set<Int>, size: Int) {
for (i in 0 until size) {
val expectedBit = i in trueBits
if (bitSet[i] != expectedBit) {
throw AssertionError()
}
}
}
fun assertNotContainsOnly(bitSet: BitSet, falseBits: Set<Int>, size: Int) {
for (i in 0 until size) {
val expectedBit = i !in falseBits
if (bitSet[i] != expectedBit) {
throw AssertionError()
}
}
}
fun assertTrue(str: String, cond: Boolean) { if (!cond) throw AssertionError(str) }
fun assertFalse(str: String, cond: Boolean) { if (cond) throw AssertionError(str) }
fun <T> assertEquals(str: String, a: T, b: T) { if (a != b) throw AssertionError(str) }
fun assertTrue(cond: Boolean) = assertTrue("", cond)
fun assertFalse(cond: Boolean) = assertFalse("", cond)
fun <T> assertEquals(a: T, b: T) = assertEquals("", a, b)
fun fail(): Unit = throw AssertionError()
fun testConstructor() {
var b = BitSet(12)
assertContainsOnly(b, setOf(), 12)
b = BitSet(12) { it == 0 || it in 5..6 || it == 11 }
assertContainsOnly(b, setOf(0, 5, 6, 11), 12)
}
fun testSet() {
var b = BitSet(0)
assertEquals(b.lastTrueIndex, -1)
b = BitSet(2)
// Test set and clear operation for single index.
assertTrue(b.isEmpty)
b.set(0, true)
b.set(3, true)
assertEquals(b.lastTrueIndex, 3)
assertFalse(b.isEmpty)
assertContainsOnly(b, setOf(0, 3), 4)
b.clear()
assertContainsOnly(b, setOf(), 4)
b.set(1)
b.set(5)
assertEquals(b.lastTrueIndex, 5)
assertContainsOnly(b, setOf(1, 5), 6)
b.set(1, false)
b.set(7, false)
assertEquals(b.lastTrueIndex, 5)
assertContainsOnly(b, setOf(5), 8)
b.clear(5)
assertEquals(b.lastTrueIndex, -1)
assertContainsOnly(b, setOf(), 8)
b.set(70)
assertEquals(b.lastTrueIndex, 70)
assertContainsOnly(b, setOf(70), 71)
b.clear(70)
assertEquals(b.lastTrueIndex, -1)
assertContainsOnly(b, setOf(), 71)
// Test set and clear operations for ranges.
// Set false and clear.
b = BitSet(2)
assertContainsOnly(b, setOf(), 2)
b.set(0..70, true)
assertNotContainsOnly(b, setOf(), 71)
b.set(0..2, false)
assertNotContainsOnly(b, setOf(0, 1, 2), 71)
b.set(63..65, false)
assertNotContainsOnly(b, setOf(0, 1, 2, 63, 64, 65), 71)
b.set(68..70, false)
assertNotContainsOnly(b, setOf(0, 1, 2, 63, 64, 65, 68, 69, 70), 71)
b.set(68..72, false)
assertNotContainsOnly(b, setOf(0, 1, 2, 63, 64, 65, 68, 69, 70, 71, 72), 73)
b.set(0..72, false)
assertContainsOnly(b, setOf(), 73)
b.set(0..72)
assertNotContainsOnly(b, setOf(), 73)
b.clear(0..2)
assertNotContainsOnly(b, setOf(0, 1, 2), 73)
b.clear(63..65)
assertNotContainsOnly(b, setOf(0, 1, 2, 63, 64, 65), 73)
b.clear(68..70)
assertNotContainsOnly(b, setOf(0, 1, 2, 63, 64, 65, 68, 69, 70), 73)
b.clear(68..72)
assertNotContainsOnly(b, setOf(0, 1, 2, 63, 64, 65, 68, 69, 70, 71, 72), 73)
b.clear(0..72)
assertContainsOnly(b, setOf(), 73)
// Set true.
b.set(0..2, true)
assertContainsOnly(b, setOf(0, 1, 2), 73)
b.set(63..65, true)
assertContainsOnly(b, setOf(0, 1, 2, 63, 64, 65), 73)
b.set(70..72, true)
assertContainsOnly(b, setOf(0, 1, 2, 63, 64, 65, 70, 71, 72), 73)
b.set(73..74, true)
assertContainsOnly(b, setOf(0, 1, 2, 63, 64, 65, 70, 71, 72, 73, 74), 75)
b.set(0..74, true)
assertNotContainsOnly(b, setOf(), 75)
// Test set and clear for pair of indices.
b = BitSet(2)
assertContainsOnly(b, setOf(), 71)
b.set(0, 71, true)
assertNotContainsOnly(b, setOf(), 71)
b.set(0, 3, false)
assertNotContainsOnly(b, setOf(0, 1, 2), 71)
b.set(63, 66, false)
assertNotContainsOnly(b, setOf(0, 1, 2, 63, 64, 65), 71)
b.set(68, 71, false)
assertNotContainsOnly(b, setOf(0, 1, 2, 63, 64, 65, 68, 69, 70), 71)
b.set(68, 73, false)
assertNotContainsOnly(b, setOf(0, 1, 2, 63, 64, 65, 68, 69, 70, 71, 72), 73)
b.set(0, 73, false)
assertContainsOnly(b, setOf(), 73)
b.set(0, 73)
assertNotContainsOnly(b, setOf(), 73)
b.clear(0, 3)
assertNotContainsOnly(b, setOf(0, 1, 2), 73)
b.clear(63, 66)
assertNotContainsOnly(b, setOf(0, 1, 2, 63, 64, 65), 73)
b.clear(68, 71)
assertNotContainsOnly(b, setOf(0, 1, 2, 63, 64, 65, 68, 69, 70), 73)
b.clear(68, 73)
assertNotContainsOnly(b, setOf(0, 1, 2, 63, 64, 65, 68, 69, 70, 71, 72), 73)
b.clear(0, 73)
assertContainsOnly(b, setOf(), 73)
// Set true.
b.set(0, 3, true)
assertContainsOnly(b, setOf(0, 1, 2), 73)
b.set(63, 66, true)
assertContainsOnly(b, setOf(0, 1, 2, 63, 64, 65), 73)
b.set(70, 73, true)
assertContainsOnly(b, setOf(0, 1, 2, 63, 64, 65, 70, 71, 72), 73)
b.set(73, 75, true)
assertContainsOnly(b, setOf(0, 1, 2, 63, 64, 65, 70, 71, 72, 73, 74), 75)
b.set(0, 75, true)
assertNotContainsOnly(b, setOf(), 75)
// Access to negative elements must cause an exception
try {
b.set(-1)
fail()
} catch(e: IndexOutOfBoundsException) {}
try {
b.clear(-1)
fail()
} catch(e: IndexOutOfBoundsException) {}
try {
b.clear(-1..0)
fail()
} catch(e: IndexOutOfBoundsException) {}
try {
b.set(-1..0)
fail()
} catch(e: IndexOutOfBoundsException) {}
try {
b[-1]
fail()
} catch(e: IndexOutOfBoundsException) {}
}
fun testFlip() {
val b = BitSet(2)
b.set(0, true)
b.set(70, true)
b.set(63..65, true)
assertEquals(b.lastTrueIndex, 70)
// 0 element
assertContainsOnly(b, setOf(0, 63, 64, 65, 70), 71)
b.flip(0)
assertContainsOnly(b, setOf(63, 64, 65, 70), 71)
b.flip(1)
assertContainsOnly(b, setOf(1, 63, 64, 65, 70), 71)
b.flip(0)
assertContainsOnly(b, setOf(0, 1, 63, 64, 65, 70), 71)
// last element
b.flip(70)
assertContainsOnly(b, setOf(0, 1, 63, 64, 65), 71)
b.flip(69)
assertContainsOnly(b, setOf(0, 1, 63, 64, 65, 69), 71)
b.flip(70)
assertContainsOnly(b, setOf(0, 1, 63, 64, 65, 69, 70), 71)
// element in the middle
b.flip(64)
assertContainsOnly(b, setOf(0, 1, 63, 65, 69, 70), 71)
b.flip(65)
assertContainsOnly(b, setOf(0, 1, 63, 69, 70), 71)
b.flip(65)
b.flip(64)
assertContainsOnly(b, setOf(0, 1, 63, 64, 65, 69, 70), 71)
// range in the beginning
b.flip(0..2)
assertContainsOnly(b, setOf(2, 63, 64, 65, 69, 70), 71)
b.flip(0, 3)
assertContainsOnly(b, setOf(0, 1, 63, 64, 65, 69, 70), 71)
// In the end
b.flip(68..70)
assertContainsOnly(b, setOf(0, 1, 63, 64, 65, 68), 71)
b.flip(68, 71)
assertContainsOnly(b, setOf(0, 1, 63, 64, 65, 69, 70), 71)
// In the middle
b.flip(64..66)
assertContainsOnly(b, setOf(0, 1, 63, 66, 69, 70), 71)
b.flip(64, 67)
assertContainsOnly(b, setOf(0, 1, 63, 64, 65, 69, 70), 71)
// Access to a negative element must cause an exception.
try {
b.flip(-1)
fail()
} catch(e: IndexOutOfBoundsException) {}
try {
b.flip(-1..0)
fail()
} catch(e: IndexOutOfBoundsException) {}
}
fun testNextBit() {
val b = BitSet(71)
b.set(0)
b.set(65)
b.set(70)
assertEquals(b.nextSetBit(), 0)
assertEquals(b.nextSetBit(0), 0)
assertEquals(b.nextSetBit(1), 65)
assertEquals(b.nextSetBit(65), 65)
assertEquals(b.nextSetBit(66), 70)
assertEquals(b.nextSetBit(70), 70)
assertEquals(b.nextSetBit(71), -1)
assertEquals(b.previousSetBit(0), 0)
assertEquals(b.previousSetBit(64), 0)
assertEquals(b.previousSetBit(65), 65)
assertEquals(b.previousSetBit(69), 65)
assertEquals(b.previousSetBit(70), 70)
assertEquals(b.previousSetBit(71), 70)
b.clear()
assertEquals(b.nextSetBit(), -1)
assertEquals(b.previousSetBit(70), -1)
b.set(0..70)
assertEquals(b.nextClearBit(), 71)
assertEquals(b.previousClearBit(70), -1)
b.clear(0)
b.clear(65)
b.clear(70)
assertEquals(b.nextClearBit(), 0)
assertEquals(b.nextClearBit(0), 0)
assertEquals(b.nextClearBit(1), 65)
assertEquals(b.nextClearBit(65), 65)
assertEquals(b.nextClearBit(66), 70)
assertEquals(b.nextClearBit(70), 70)
assertEquals(b.nextClearBit(71), 71) // assume that the bitset is extended here (virtually).
assertEquals(b.previousClearBit(0), 0)
assertEquals(b.previousClearBit(64), 0)
assertEquals(b.previousClearBit(65), 65)
assertEquals(b.previousClearBit(69), 65)
assertEquals(b.previousClearBit(70), 70)
assertEquals(b.previousClearBit(71), 71)
// See http://docs.oracle.com/javase/8/docs/api/java/util/BitSet.html#previousClearBit-int-
assertEquals(b.previousClearBit(-1), -1)
assertEquals(b.previousSetBit(-1), -1)
// Test behaviour on the right border of the bit vector.
// We assume that the vector is infinite and have zeros after (size - 1)th bit.
var a = BitSet(64)
assertEquals(a.nextClearBit(63), 63)
assertEquals(a.nextClearBit(64), 64)
assertEquals(a.nextSetBit(63), -1)
assertEquals(a.nextSetBit(64), -1)
a.set(0, 64)
assertEquals(a.nextClearBit(63), 64)
assertEquals(a.nextClearBit(64), 64)
assertEquals(a.nextSetBit(63), 63)
assertEquals(a.nextSetBit(64), -1)
a.clear()
assertEquals(a.previousClearBit(63), 63)
assertEquals(a.previousClearBit(64), 64)
assertEquals(a.previousSetBit(63), -1)
assertEquals(a.previousSetBit(64), -1)
a.set(0, 64)
assertEquals(a.previousClearBit(63), -1)
assertEquals(a.previousClearBit(64), 64)
assertEquals(a.previousSetBit(63), 63)
assertEquals(a.previousSetBit(64), 63)
a = BitSet(0)
assertEquals(a.nextSetBit(0), -1)
assertEquals(a.nextClearBit(0), 0)
assertEquals(a.previousSetBit(0), -1)
assertEquals(a.previousClearBit(0), 0)
// Access to a negative element must cause an exception.
try {
b.previousSetBit(-2)
fail()
} catch(e: IndexOutOfBoundsException) {}
try {
b.previousClearBit(-2)
fail()
} catch(e: IndexOutOfBoundsException) {}
try {
b.nextSetBit(-1)
fail()
} catch(e: IndexOutOfBoundsException) {}
try {
b.nextClearBit(-1)
fail()
} catch(e: IndexOutOfBoundsException) {}
}
fun BitSet.setBits(vararg indices: Int, value: Boolean = true) {
indices.forEach {
set(it, value)
}
}
fun testLogic() {
var b2 = BitSet(76)
b2.setBits(1, 3,
61, 63,
65, 67,
70, 72)
// and
var b1 = BitSet(73)
b1.set(2..3); b1.set(62..63); b1.set(66..67); b1.set(71..72)
b1.and(b2)
assertContainsOnly(b1, setOf(3, 63, 67, 72), 76)
b1 = BitSet(73)
b1.set(2..3); b1.set(62..63); b1.set(66..67); b1.set(71..72)
b1.set(128)
b1.and(b2)
assertContainsOnly(b1, setOf(3, 63, 67, 72), 129)
// or
b1 = BitSet(73)
b1.set(2..3); b1.set(62..63); b1.set(66..67); b1.set(71..72)
b1.or(b2)
assertContainsOnly(b1, setOf(1, 2, 3, 61, 62, 63, 65, 66, 67, 70, 71, 72), 76)
b1 = BitSet(73)
b1.set(2..3); b1.set(62..63); b1.set(66..67); b1.set(71..72)
b1.set(128)
b1.or(b2)
assertContainsOnly(b1, setOf(1, 2, 3, 61, 62, 63, 65, 66, 67, 70, 71, 72, 128), 129)
// xor
b1 = BitSet(73)
b1.set(2..3); b1.set(62..63); b1.set(66..67); b1.set(71..72)
b1.xor(b2)
assertContainsOnly(b1, setOf(1, 2, 61, 62, 65, 66, 70, 71), 76)
b1 = BitSet(73)
b1.set(2..3); b1.set(62..63); b1.set(66..67); b1.set(71..72)
b1.set(128)
b1.xor(b2)
assertContainsOnly(b1, setOf(1, 2, 61, 62, 65, 66, 70, 71, 128), 129)
// andNot
b1 = BitSet(73)
b1.set(2..3); b1.set(62..63); b1.set(66..67); b1.set(71..72)
b1.andNot(b2)
assertContainsOnly(b1, setOf(2, 62, 66, 71), 76)
b1 = BitSet(73)
b1.set(2..3); b1.set(62..63); b1.set(66..67); b1.set(71..72)
b1.set(128)
b1.andNot(b2)
assertContainsOnly(b1, setOf(2, 62, 66, 71, 128), 129)
// intersects
b1 = BitSet(73)
b1.set(0..1); b1.set(62..63); b1.set(64..65); b1.set(71..72)
b2.clear(); b2.set(0)
assertTrue(b1.intersects(b2))
b2.clear(); b2.set(62..65)
assertTrue(b1.intersects(b2))
b2.clear(); b2.set(72)
assertTrue(b1.intersects(b2))
b2.clear()
assertFalse(b1.intersects(b2))
b2.set(128)
assertFalse(b1.intersects(b2))
}
// Based on Harmony tests.
fun testEqualsHashCode() {
// HashCode.
val b = BitSet()
b.set(0..7)
b.clear(2)
b.clear(6)
assertEquals("BitSet returns wrong hash value", 1129, b.hashCode())
b.set(10)
b.clear(3)
assertEquals("BitSet returns wrong hash value", 97, b.hashCode())
// Equals.
val b1 = BitSet()
val b2 = BitSet()
b1.set(0..7)
b2.set(0..7)
assertTrue("Same BitSet returned false", b1 == b1)
assertTrue("Identical BitSet returned false", b1 == b2)
b2.clear(6)
assertFalse("Different BitSets returned true", b1 == b2)
val b3 = BitSet()
b3.set(0..7)
b3.set(128)
assertFalse("Different sized BitSet with higher bit set returned true", b1 == b3)
b3.clear(128)
assertTrue("Different sized BitSet with higher bits not set returned false", b1 == b3)
}
@Test fun runTest() {
testConstructor()
testSet()
testFlip()
testNextBit()
testLogic()
testEqualsHashCode()
}
@@ -0,0 +1,112 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.collections.SortWith
import kotlin.test.*
val correctIncreasing = Comparator<Int> { a, b -> // correct one.
when {
a > b -> 1
a < b -> -1
else -> 0
}
}
val correctDecreasing = Comparator<Int> { a, b -> // correct one.
when {
a < b -> 1
a > b -> -1
else -> 0
}
}
fun Array<Int>.assertSorted(cmp: Comparator<Int>, message: String = "") {
for (i in 1 until size) {
assertTrue(cmp.compare(this[i - 1], this[i]) <= 0, message)
}
}
fun Array<MyComparable>.assertSorted(message: String = "") {
for (i in 1 until size) {
assertTrue(this[i - 1] <= this[i], message)
}
}
data class ComparatorInfo(val name: String, val comparator: Comparator<Int>, val isCorrect: Boolean)
class MyComparable (val value: Int, val comparator: Comparator<Int>): Comparable<MyComparable> {
override fun compareTo(other: MyComparable): Int = comparator.compare(value, other.value)
}
// Assert that the array is sorted in terms of a comparator only for correct/partially correct cases
val comparators = listOf<ComparatorInfo>(
ComparatorInfo("Correct increasing", correctIncreasing , true),
ComparatorInfo("Correct decreasing", correctDecreasing , true),
ComparatorInfo("Incorrect increasing", Comparator { a ,b -> if (a > b) 1 else -1 }, false),
ComparatorInfo("Incorrect decreasing", Comparator { a ,b -> if (a < b) 1 else -1 }, false),
ComparatorInfo("Always 1", Comparator { a ,b -> 1 }, false),
ComparatorInfo("Always -1", Comparator { a ,b -> -1 }, false),
ComparatorInfo("Always 0", Comparator { a ,b -> 0 }, false)
)
val arrays = listOf<Array<Int>>(
arrayOf(),
arrayOf(1),
arrayOf(Int.MIN_VALUE, 0, Int.MAX_VALUE),
arrayOf(Int.MAX_VALUE, 0, Int.MIN_VALUE),
arrayOf(1, 2, 3),
arrayOf(-2, -1, 99, 1, 2),
arrayOf(90, 91, 0, 98, 99),
arrayOf(2, 1, 99, -1, 2),
arrayOf(99, 98, 0, 91, 90),
arrayOf(42, 42, 42),
arrayOf(99, 42, 0, 42, 50),
arrayOf(
100000, 190001, 200002, 200003, 200004, 210005, 220006, 250007, 300008, 310009, 360010, 365011,
380012, 390013, 390014, 399015, 400016, 400017, 400018, 400019, 400020, 400021, 400022, 400023,
400024, 400025, 400026, 450027, 450028, 480029, 480030, 500031, 500032, 500033, 500034, 500035,
500036, 500037, 500038, 500039, 500040, 500041, 500042, 500043, 500044, 500045, 500046, 500047,
500048, 500049, 500050, 500051, 500052, 500053, 505054, 510055, 510056, 510057, 510058, 510059,
510060, 510061, 510062, 510063, 410064, 410065, 511066, 511067, 520068, 520069, 420070, 520071,
530072, 530073, 530074, 430075, 430076, 530077, 540078, 540079, 540080, 540081, 540082, 540083,
540084, 490085, 540086, 540087, 542088, 544089, 546090, 550091, 550092, 550093, 550094, 590095,
590096, 595097, 600098, 600099, 600100, 600101, 600102, 600103, 600104, 550105, 600106, 600107,
600108, 600109, 600110, 610111, 610112, 610113, 620114, 620115, 620116, 620117, 620118, 620119,
640120, 640121, 645122, 645123, 645124, 645125, 645126, 645127, 650128, 700129, 700130
)
)
@Test fun runTest() {
arrays.forEach { array ->
comparators.forEach {
// Test with custom comparator
val arrayUnderTest = array.copyOf()
arrayUnderTest.sortWith(it.comparator)
if (it.isCorrect) {
arrayUnderTest.assertSorted(it.comparator, """
Assert sorted failed for comparator: "${it.name}"
Array: ${array.joinToString()}
Array after sorting: ${arrayUnderTest.joinToString()}
""".trimIndent())
}
// Test of a custom comparable
val comparableArrayUnderTest = Array(array.size) { i ->
MyComparable(array[i], it.comparator)
}
comparableArrayUnderTest.sort()
if (it.isCorrect) {
comparableArrayUnderTest.assertSorted("""
Assert sorted failed for Comparable: "${it.name}"
Array: ${array.joinToString()}
Array after sorting: ${comparableArrayUnderTest.joinToString()}
""".trimIndent())
}
}
}
}
@@ -0,0 +1,38 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.collections.array0
import kotlin.test.*
@Test fun runTest() {
// Create instances of all array types.
val byteArray = ByteArray(5)
println(byteArray.size.toString())
val charArray = CharArray(6)
println(charArray.size.toString())
val shortArray = ShortArray(7)
println(shortArray.size.toString())
val intArray = IntArray(8)
println(intArray.size.toString())
val longArray = LongArray(9)
println(longArray.size.toString())
val floatArray = FloatArray(10)
println(floatArray.size.toString())
val doubleArray = FloatArray(11)
println(doubleArray.size.toString())
val booleanArray = BooleanArray(12)
println(booleanArray.size.toString())
val stringArray = Array<String>(13, { i -> ""})
println(stringArray.size.toString())
}
@@ -0,0 +1,36 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.collections.array1
import kotlin.test.*
@Test fun runTest() {
val byteArray = ByteArray(5)
byteArray[1] = 2
byteArray[3] = 4
println(byteArray[3].toString() + " " + byteArray[1].toString())
val shortArray = ShortArray(2)
shortArray[0] = -1
shortArray[1] = 1
print(shortArray[1].toString())
print(shortArray[0].toString())
println()
val intArray = IntArray(7)
intArray[1] = 9
intArray[3] = 6
print(intArray[3].toString())
print(intArray[1].toString())
println()
val longArray = LongArray(9)
longArray[8] = 8
longArray[3] = 3
print(longArray[3].toString())
print(longArray[8].toString())
println()
}
@@ -0,0 +1,16 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.collections.array2
import kotlin.test.*
@Test fun runTest() {
val byteArray = Array<Byte>(5, { i -> (i * 2).toByte() })
byteArray.map { println(it) }
val intArray = Array<Int>(5, { i -> i * 4 })
println(intArray.sum())
}
@@ -0,0 +1,22 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.collections.array3
import kotlin.test.*
import kotlin.native.*
@Test fun runTest() {
val data = immutableBlobOf(0x1, 0x2, 0x3, 0x7, 0x8, 0x9, 0x80, 0xff)
for (b in data) {
print("$b ")
}
println()
val dataClone = data.toByteArray()
dataClone.map { print("$it ") }
println()
}
@@ -0,0 +1,64 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.collections.array4
import kotlin.test.*
@Test fun runTest() {
assertFailsWith<IllegalArgumentException> {
val a = Array(-2) { "nope" }
println(a)
}
assertFailsWith<IllegalArgumentException> {
val a = ByteArray(-2)
println(a)
}
assertFailsWith<IllegalArgumentException> {
val a = UByteArray(-2)
println(a)
}
assertFailsWith<IllegalArgumentException> {
val a = ShortArray(-2)
println(a)
}
assertFailsWith<IllegalArgumentException> {
val a = UShortArray(-2)
println(a)
}
assertFailsWith<IllegalArgumentException> {
val a = IntArray(-2)
println(a)
}
assertFailsWith<IllegalArgumentException> {
val a = UIntArray(-2)
println(a)
}
assertFailsWith<IllegalArgumentException> {
val a = LongArray(-2)
println(a)
}
assertFailsWith<IllegalArgumentException> {
val a = ULongArray(-2)
println(a)
}
assertFailsWith<IllegalArgumentException> {
val a = FloatArray(-2)
println(a)
}
assertFailsWith<IllegalArgumentException> {
val a = DoubleArray(-2)
println(a)
}
assertFailsWith<IllegalArgumentException> {
val a = BooleanArray(-2)
println(a)
}
assertFailsWith<IllegalArgumentException> {
val a = CharArray(-2)
println(a)
}
println("OK")
}
@@ -0,0 +1,969 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.collections.array5
import kotlin.test.*
import kotlinx.cinterop.*
@Test fun arrayGet() {
val arr = Array(10) { 0 }
assertEquals(0, arr[0])
assertEquals(0, arr[9])
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[10]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[-1]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MAX_VALUE]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MIN_VALUE]
}
}
@Test fun arraySet() {
val arr = Array(10) { 0 }
arr[0] = 1
arr[9] = 1
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[10] = 1
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[-1] = 1
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MAX_VALUE] = 1
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MIN_VALUE] = 1
}
}
@Test fun byteArrayGet() {
val arr = ByteArray(10) { 0 }
assertEquals(0, arr[0])
assertEquals(0, arr[9])
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[10]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[-1]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MAX_VALUE]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MIN_VALUE]
}
}
@Test fun byteArraySet() {
val arr = ByteArray(10) { 0 }
arr[0] = 1
arr[9] = 1
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[10] = 1
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[-1] = 1
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MAX_VALUE] = 1
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MIN_VALUE] = 1
}
}
@Test fun uByteArrayGet() {
val arr = UByteArray(10) { 0U }
assertEquals(0U, arr[0])
assertEquals(0U, arr[9])
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[10]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[-1]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MAX_VALUE]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MIN_VALUE]
}
}
@Test fun uByteArraySet() {
val arr = UByteArray(10) { 0U }
arr[0] = 1U
arr[9] = 1U
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[10] = 1U
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[-1] = 1U
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MAX_VALUE] = 1U
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MIN_VALUE] = 1U
}
}
@Test fun shortArrayGet() {
val arr = ShortArray(10) { 0 }
assertEquals(0, arr[0])
assertEquals(0, arr[9])
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[10]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[-1]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MAX_VALUE]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MIN_VALUE]
}
}
@Test fun shortArraySet() {
val arr = ShortArray(10) { 0 }
arr[0] = 1
arr[9] = 1
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[10] = 1
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[-1] = 1
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MAX_VALUE] = 1
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MIN_VALUE] = 1
}
}
@Test fun uShortArrayGet() {
val arr = UShortArray(10) { 0U }
assertEquals(0U, arr[0])
assertEquals(0U, arr[9])
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[10]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[-1]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MAX_VALUE]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MIN_VALUE]
}
}
@Test fun uShortArraySet() {
val arr = UShortArray(10) { 0U }
arr[0] = 1U
arr[9] = 1U
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[10] = 1U
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[-1] = 1U
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MAX_VALUE] = 1U
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MIN_VALUE] = 1U
}
}
@Test fun intArrayGet() {
val arr = IntArray(10) { 0 }
assertEquals(0, arr[0])
assertEquals(0, arr[9])
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[10]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[-1]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MAX_VALUE]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MIN_VALUE]
}
}
@Test fun intArraySet() {
val arr = IntArray(10) { 0 }
arr[0] = 1
arr[9] = 1
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[10] = 1
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[-1] = 1
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MAX_VALUE] = 1
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MIN_VALUE] = 1
}
}
@Test fun uIntArrayGet() {
val arr = UIntArray(10) { 0U }
assertEquals(0U, arr[0])
assertEquals(0U, arr[9])
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[10]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[-1]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MAX_VALUE]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MIN_VALUE]
}
}
@Test fun uIntArraySet() {
val arr = UIntArray(10) { 0U }
arr[0] = 1U
arr[9] = 1U
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[10] = 1U
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[-1] = 1U
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MAX_VALUE] = 1U
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MIN_VALUE] = 1U
}
}
@Test fun longArrayGet() {
val arr = LongArray(10) { 0 }
assertEquals(0, arr[0])
assertEquals(0, arr[9])
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[10]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[-1]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MAX_VALUE]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MIN_VALUE]
}
}
@Test fun longArraySet() {
val arr = LongArray(10) { 0 }
arr[0] = 1
arr[9] = 1
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[10] = 1
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[-1] = 1
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MAX_VALUE] = 1
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MIN_VALUE] = 1
}
}
@Test fun uLongArrayGet() {
val arr = ULongArray(10) { 0U }
assertEquals(0U, arr[0])
assertEquals(0U, arr[9])
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[10]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[-1]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MAX_VALUE]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MIN_VALUE]
}
}
@Test fun uLongArraySet() {
val arr = ULongArray(10) { 0U }
arr[0] = 1U
arr[9] = 1U
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[10] = 1U
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[-1] = 1U
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MAX_VALUE] = 1U
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MIN_VALUE] = 1U
}
}
@Test fun floatArrayGet() {
val arr = FloatArray(10) { 0.0f }
assertEquals(0.0f, arr[0])
assertEquals(0.0f, arr[9])
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[10]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[-1]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MAX_VALUE]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MIN_VALUE]
}
}
@Test fun floatArraySet() {
val arr = FloatArray(10) { 0.0f }
arr[0] = 1.0f
arr[9] = 1.0f
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[10] = 1.0f
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[-1] = 1.0f
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MAX_VALUE] = 1.0f
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MIN_VALUE] = 1.0f
}
}
@Test fun doubleArrayGet() {
val arr = DoubleArray(10) { 0.0 }
assertEquals(0.0, arr[0])
assertEquals(0.0, arr[9])
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[10]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[-1]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MAX_VALUE]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MIN_VALUE]
}
}
@Test fun doubleArraySet() {
val arr = DoubleArray(10) { 0.0 }
arr[0] = 1.0
arr[9] = 1.0
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[10] = 1.0
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[-1] = 1.0
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MAX_VALUE] = 1.0
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MIN_VALUE] = 1.0
}
}
@Test fun booleanArrayGet() {
val arr = BooleanArray(10) { false }
assertEquals(false, arr[0])
assertEquals(false, arr[9])
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[10]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[-1]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MAX_VALUE]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MIN_VALUE]
}
}
@Test fun booleanArraySet() {
val arr = BooleanArray(10) { false }
arr[0] = true
arr[9] = true
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[10] = true
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[-1] = true
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MAX_VALUE] = true
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MIN_VALUE] = true
}
}
@Test fun charArrayGet() {
val arr = CharArray(10) { '0' }
assertEquals('0', arr[0])
assertEquals('0', arr[9])
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[10]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[-1]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MAX_VALUE]
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MIN_VALUE]
}
}
@Test fun charArraySet() {
val arr = CharArray(10) { '0' }
arr[0] = '1'
arr[9] = '1'
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[10] = '1'
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[-1] = '1'
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MAX_VALUE] = '1'
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr[Int.MIN_VALUE] = '1'
}
}
@Test fun byteArrayGetUByte() {
val arr = ByteArray(10) { 0 }
assertEquals(0U, arr.getUByteAt(0))
assertEquals(0U, arr.getUByteAt(9))
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getUByteAt(10)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getUByteAt(-1)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getUByteAt(Int.MAX_VALUE)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getUByteAt(Int.MIN_VALUE)
}
}
@Test fun byteArraySetUByte() {
val arr = ByteArray(10) { 0 }
arr.setUByteAt(0, 1U)
arr.setUByteAt(9, 1U)
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setUByteAt(10, 1U)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setUByteAt(-1, 1U)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setUByteAt(Int.MAX_VALUE, 1U)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setUByteAt(Int.MIN_VALUE, 1U)
}
}
@Test fun byteArrayGetChar() {
val arr = ByteArray(10) { 0 }
assertEquals(0.toChar(), arr.getCharAt(0))
assertEquals(0.toChar(), arr.getCharAt(8))
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getCharAt(9)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getCharAt(10)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getCharAt(-1)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getCharAt(Int.MAX_VALUE)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getCharAt(Int.MIN_VALUE)
}
}
@Test fun byteArraySetChar() {
val arr = ByteArray(10) { 0 }
arr.setCharAt(0, '1')
arr.setCharAt(8, '1')
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setCharAt(9, '1')
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setCharAt(10, '1')
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setCharAt(-1, '1')
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setCharAt(Int.MAX_VALUE, '1')
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setCharAt(Int.MIN_VALUE, '1')
}
}
@Test fun byteArrayGetShort() {
val arr = ByteArray(10) { 0 }
assertEquals(0, arr.getShortAt(0))
assertEquals(0, arr.getShortAt(8))
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getShortAt(9)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getShortAt(10)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getShortAt(-1)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getShortAt(Int.MAX_VALUE)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getShortAt(Int.MIN_VALUE)
}
}
@Test fun byteArraySetShort() {
val arr = ByteArray(10) { 0 }
arr.setShortAt(0, 0)
arr.setShortAt(8, 0)
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setShortAt(9, 1)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setShortAt(10, 1)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setShortAt(-1, 1)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setShortAt(Int.MAX_VALUE, 1)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setShortAt(Int.MIN_VALUE, 1)
}
}
@Test fun byteArrayGetUShort() {
val arr = ByteArray(10) { 0 }
assertEquals(0U, arr.getUShortAt(0))
assertEquals(0U, arr.getUShortAt(8))
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getUShortAt(9)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getUShortAt(10)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getUShortAt(-1)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getUShortAt(Int.MAX_VALUE)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getUShortAt(Int.MIN_VALUE)
}
}
@Test fun byteArraySetUShort() {
val arr = ByteArray(10) { 0 }
arr.setUShortAt(0, 0U)
arr.setUShortAt(8, 0U)
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setUShortAt(9, 1U)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setUShortAt(10, 1U)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setUShortAt(-1, 1U)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setUShortAt(Int.MAX_VALUE, 1U)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setUShortAt(Int.MIN_VALUE, 1U)
}
}
@Test fun byteArrayGetInt() {
val arr = ByteArray(10) { 0 }
assertEquals(0, arr.getIntAt(0))
assertEquals(0, arr.getIntAt(6))
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getIntAt(7)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getIntAt(10)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getIntAt(-1)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getIntAt(Int.MAX_VALUE)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getIntAt(Int.MIN_VALUE)
}
}
@Test fun byteArraySetInt() {
val arr = ByteArray(10) { 0 }
arr.setIntAt(0, 1)
arr.setIntAt(6, 1)
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setIntAt(7, 1)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setIntAt(10, 1)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setIntAt(-1, 1)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setIntAt(Int.MAX_VALUE, 1)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setIntAt(Int.MIN_VALUE, 1)
}
}
@Test fun byteArrayGetUInt() {
val arr = ByteArray(10) { 0 }
assertEquals(0U, arr.getUIntAt(0))
assertEquals(0U, arr.getUIntAt(6))
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getUIntAt(7)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getUIntAt(10)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getUIntAt(-1)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getUIntAt(Int.MAX_VALUE)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getUIntAt(Int.MIN_VALUE)
}
}
@Test fun byteArraySetUInt() {
val arr = ByteArray(10) { 0 }
arr.setUIntAt(0, 1U)
arr.setUIntAt(6, 1U)
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setUIntAt(7, 1U)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setUIntAt(10, 1U)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setUIntAt(-1, 1U)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setUIntAt(Int.MAX_VALUE, 1U)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setUIntAt(Int.MIN_VALUE, 1U)
}
}
@Test fun byteArrayGetLong() {
val arr = ByteArray(10) { 0 }
assertEquals(0, arr.getLongAt(0))
assertEquals(0, arr.getLongAt(2))
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getLongAt(3)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getLongAt(10)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getLongAt(-1)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getLongAt(Int.MAX_VALUE)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getLongAt(Int.MIN_VALUE)
}
}
@Test fun byteArraySetLong() {
val arr = ByteArray(10) { 0 }
arr.setLongAt(0, 1)
arr.setLongAt(2, 1)
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setLongAt(3, 1)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setLongAt(10, 1)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setLongAt(-1, 1)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setLongAt(Int.MAX_VALUE, 1)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setLongAt(Int.MIN_VALUE, 1)
}
}
@Test fun byteArrayGetULong() {
val arr = ByteArray(10) { 0 }
assertEquals(0U, arr.getULongAt(0))
assertEquals(0U, arr.getULongAt(2))
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getULongAt(3)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getULongAt(10)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getULongAt(-1)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getULongAt(Int.MAX_VALUE)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getULongAt(Int.MIN_VALUE)
}
}
@Test fun byteArraySetULong() {
val arr = ByteArray(10) { 0 }
arr.setULongAt(0, 1U)
arr.setULongAt(2, 1U)
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setULongAt(3, 1U)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setULongAt(10, 1U)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setULongAt(-1, 1U)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setULongAt(Int.MAX_VALUE, 1U)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setULongAt(Int.MIN_VALUE, 1U)
}
}
@Test fun byteArrayGetFloat() {
val arr = ByteArray(10) { 0 }
assertEquals(0.0f, arr.getFloatAt(0))
assertEquals(0.0f, arr.getFloatAt(6))
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getFloatAt(7)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getFloatAt(10)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getFloatAt(-1)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getFloatAt(Int.MAX_VALUE)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getFloatAt(Int.MIN_VALUE)
}
}
@Test fun byteArraySetFloat() {
val arr = ByteArray(10) { 0 }
arr.setFloatAt(0, 1.0f)
arr.setFloatAt(6, 1.0f)
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setFloatAt(7, 1.0f)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setFloatAt(10, 1.0f)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setFloatAt(-1, 1.0f)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setFloatAt(Int.MAX_VALUE, 1.0f)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setFloatAt(Int.MIN_VALUE, 1.0f)
}
}
@Test fun byteArrayGetDouble() {
val arr = ByteArray(10) { 0 }
assertEquals(0.0, arr.getDoubleAt(0))
assertEquals(0.0, arr.getDoubleAt(2))
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getDoubleAt(3)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getDoubleAt(10)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getDoubleAt(-1)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getDoubleAt(Int.MAX_VALUE)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.getDoubleAt(Int.MIN_VALUE)
}
}
@Test fun byteArraySetDouble() {
val arr = ByteArray(10) { 0 }
arr.setDoubleAt(0, 1.0)
arr.setDoubleAt(2, 1.0)
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setDoubleAt(3, 1.0)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setDoubleAt(10, 1.0)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setDoubleAt(-1, 1.0)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setDoubleAt(Int.MAX_VALUE, 1.0)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
arr.setDoubleAt(Int.MIN_VALUE, 1.0)
}
}
@Test fun immutableBlobToByteArray() {
val blob = immutableBlobOf(0, 0)
val arr = blob.toByteArray(0, 1)
assertEquals(1, arr.size)
assertEquals(0, arr[0])
assertFailsWith<ArrayIndexOutOfBoundsException> {
blob.toByteArray(-1, 1)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
blob.toByteArray(0, -1)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
blob.toByteArray(0, 10)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
blob.toByteArray(10, 11)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
blob.toByteArray(10, 1)
}
}
@Test fun immutableBlobToUByteArray() {
val blob = immutableBlobOf(0, 0)
val arr = blob.toUByteArray(0, 1)
assertEquals(1, arr.size)
assertEquals(0U, arr[0])
assertFailsWith<ArrayIndexOutOfBoundsException> {
blob.toUByteArray(-1, 1)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
blob.toUByteArray(0, -1)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
blob.toUByteArray(0, 10)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
blob.toUByteArray(10, 11)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
blob.toUByteArray(10, 1)
}
}
@Test fun immutableBlobAsCPointer() {
val blob = immutableBlobOf(0, 0)
assertEquals(0, blob.asCPointer(0).pointed.value)
assertFailsWith<ArrayIndexOutOfBoundsException> {
blob.asCPointer(10)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
blob.asCPointer(-1)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
blob.asCPointer(Int.MAX_VALUE)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
blob.asCPointer(Int.MIN_VALUE)
}
}
@Test fun immutableBlobAsUCPointer() {
val blob = immutableBlobOf(0, 0)
assertEquals(0U, blob.asUCPointer(0).pointed.value)
assertFailsWith<ArrayIndexOutOfBoundsException> {
blob.asUCPointer(10)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
blob.asUCPointer(-1)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
blob.asUCPointer(Int.MAX_VALUE)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
blob.asUCPointer(Int.MIN_VALUE)
}
}
@@ -0,0 +1,385 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.collections.array_list1
import kotlin.test.*
fun assertTrue(cond: Boolean) {
if (!cond)
println("FAIL")
}
fun assertFalse(cond: Boolean) {
if (cond)
println("FAIL")
}
fun assertEquals(value1: Any?, value2: Any?) {
if (value1 != value2)
throw Error("FAIL " + value1 + " " + value2)
}
fun assertEquals(value1: Int, value2: Int) {
if (value1 != value2)
throw Error("FAIL " + value1 + " " + value2)
}
fun testBasic() {
val a = ArrayList<String>()
assertTrue(a.isEmpty())
assertEquals(0, a.size)
assertTrue(a.add("1"))
assertTrue(a.add("2"))
assertTrue(a.add("3"))
assertFalse(a.isEmpty())
assertEquals(3, a.size)
assertEquals("1", a[0])
assertEquals("2", a[1])
assertEquals("3", a[2])
a[0] = "11"
assertEquals("11", a[0])
assertEquals("11", a.removeAt(0))
assertEquals(2, a.size)
assertEquals("2", a[0])
assertEquals("3", a[1])
a.add(1, "22")
assertEquals(3, a.size)
assertEquals("2", a[0])
assertEquals("22", a[1])
assertEquals("3", a[2])
a.clear()
assertTrue(a.isEmpty())
assertEquals(0, a.size)
}
fun testIterator() {
val a = ArrayList(listOf("1", "2", "3"))
val it = a.iterator()
assertTrue(it.hasNext())
assertEquals("1", it.next())
assertTrue(it.hasNext())
assertEquals("2", it.next())
assertTrue(it.hasNext())
assertEquals("3", it.next())
assertFalse(it.hasNext())
}
fun testContainsAll() {
val a = ArrayList(listOf("1", "2", "3", "4", "5"))
assertFalse(a.containsAll(listOf("6", "7", "8")))
assertFalse(a.containsAll(listOf("5", "6", "7")))
assertFalse(a.containsAll(listOf("4", "5", "6")))
assertTrue(a.containsAll(listOf("3", "4", "5")))
assertTrue(a.containsAll(listOf("2", "3", "4")))
}
fun testRemove() {
val a = ArrayList(listOf("1", "2", "3"))
assertTrue(a.remove("2"))
assertEquals(2, a.size)
assertEquals("1", a[0])
assertEquals("3", a[1])
assertFalse(a.remove("2"))
assertEquals(2, a.size)
assertEquals("1", a[0])
assertEquals("3", a[1])
}
fun testRemoveAll() {
val a = ArrayList(listOf("1", "2", "3", "4", "5", "1"))
assertFalse(a.removeAll(listOf("6", "7", "8")))
assertEquals(listOf("1", "2", "3", "4", "5", "1"), a)
assertTrue(a.removeAll(listOf("5", "3", "1")))
assertEquals(listOf("2", "4"), a)
}
fun testRetainAll() {
val a = ArrayList(listOf("1", "2", "3", "4", "5"))
assertFalse(a.retainAll(listOf("1", "2", "3", "4", "5")))
assertEquals(listOf("1", "2", "3", "4", "5"), a)
assertTrue(a.retainAll(listOf("5", "3", "1")))
assertEquals(listOf("1", "3", "5"), a)
}
fun testEquals() {
val a = ArrayList(listOf("1", "2", "3"))
assertTrue(a == listOf("1", "2", "3"))
assertFalse(a == listOf("2", "3", "1")) // order matters
assertFalse(a == listOf("1", "2", "4"))
assertFalse(a == listOf("1", "2"))
}
fun testHashCode() {
val a = ArrayList(listOf("1", "2", "3"))
assertTrue(a.hashCode() == listOf("1", "2", "3").hashCode())
}
fun testToString() {
val a = ArrayList(listOf("1", "2", "3"))
assertTrue(a.toString() == listOf("1", "2", "3").toString())
}
fun testSubList() {
val a0 = ArrayList(listOf("0", "1", "2", "3", "4"))
val a = a0.subList(1, 4)
assertEquals(3, a.size)
assertEquals("1", a[0])
assertEquals("2", a[1])
assertEquals("3", a[2])
assertTrue(a == listOf("1", "2", "3"))
assertTrue(a.hashCode() == listOf("1", "2", "3").hashCode())
assertTrue(a.toString() == listOf("1", "2", "3").toString())
}
fun testResize() {
val a = ArrayList<String>()
val n = 10000
for (i in 1..n)
assertTrue(a.add(i.toString()))
assertEquals(n, a.size)
for (i in 1..n)
assertEquals(i.toString(), a[i - 1])
a.trimToSize()
assertEquals(n, a.size)
for (i in 1..n)
assertEquals(i.toString(), a[i - 1])
}
fun testSubListContains() {
val a = ArrayList(listOf("1", "2", "3", "4"))
val s = a.subList(1, 3)
assertTrue(a.contains("1"))
assertFalse(s.contains("1"))
assertTrue(a.contains("2"))
assertTrue(s.contains("2"))
assertTrue(a.contains("3"))
assertTrue(s.contains("3"))
assertTrue(a.contains("4"))
assertFalse(s.contains("4"))
}
fun testSubListIndexOf() {
val a = ArrayList(listOf("1", "2", "3", "4", "1"))
val s = a.subList(1, 3)
assertEquals(0, a.indexOf("1"))
assertEquals(-1, s.indexOf("1"))
assertEquals(1, a.indexOf("2"))
assertEquals(0, s.indexOf("2"))
assertEquals(2, a.indexOf("3"))
assertEquals(1, s.indexOf("3"))
assertEquals(3, a.indexOf("4"))
assertEquals(-1, s.indexOf("4"))
}
fun testSubListLastIndexOf() {
val a = ArrayList(listOf("1", "2", "3", "4", "1"))
val s = a.subList(1, 3)
assertEquals(4, a.lastIndexOf("1"))
assertEquals(-1, s.lastIndexOf("1"))
assertEquals(1, a.lastIndexOf("2"))
assertEquals(0, s.lastIndexOf("2"))
assertEquals(2, a.lastIndexOf("3"))
assertEquals(1, s.lastIndexOf("3"))
assertEquals(3, a.lastIndexOf("4"))
assertEquals(-1, s.lastIndexOf("4"))
}
fun testSubListClear() {
val a = ArrayList(listOf("1", "2", "3", "4"))
val s = a.subList(1, 3)
assertEquals(listOf("2", "3"), s)
s.clear()
assertEquals(listOf<String>(), s)
assertEquals(listOf("1", "4"), a)
}
fun testSubListSubListClear() {
val a = ArrayList(listOf("1", "2", "3", "4", "5", "6"))
val s = a.subList(1, 5)
val q = s.subList(1, 3)
assertEquals(listOf("2", "3", "4", "5"), s)
assertEquals(listOf("3", "4"), q)
q.clear()
assertEquals(listOf<String>(), q)
assertEquals(listOf("2", "5"), s)
assertEquals(listOf("1", "2", "5", "6"), a)
}
fun testSubListAdd() {
val a = ArrayList(listOf("1", "2", "3", "4"))
val s = a.subList(1, 3)
assertEquals(listOf("2", "3"), s)
assertTrue(s.add("5"))
assertEquals(listOf("2", "3", "5"), s)
assertEquals(listOf("1", "2", "3", "5", "4"), a)
}
fun testSubListSubListAdd() {
val a = ArrayList(listOf("1", "2", "3", "4", "5", "6"))
val s = a.subList(1, 5)
val q = s.subList(1, 3)
assertEquals(listOf("2", "3", "4", "5"), s)
assertEquals(listOf("3", "4"), q)
assertTrue(q.add("7"))
assertEquals(listOf("3", "4", "7"), q)
assertEquals(listOf("2", "3", "4", "7", "5"), s)
assertEquals(listOf("1", "2", "3", "4", "7", "5", "6"), a)
}
fun testSubListAddAll() {
val a = ArrayList(listOf("1", "2", "3", "4"))
val s = a.subList(1, 3)
assertEquals(listOf("2", "3"), s)
assertTrue(s.addAll(listOf("5", "6")))
assertEquals(listOf("2", "3", "5", "6"), s)
assertEquals(listOf("1", "2", "3", "5", "6", "4"), a)
}
fun testSubListSubListAddAll() {
val a = ArrayList(listOf("1", "2", "3", "4", "5", "6"))
val s = a.subList(1, 5)
val q = s.subList(1, 3)
assertEquals(listOf("2", "3", "4", "5"), s)
assertEquals(listOf("3", "4"), q)
assertTrue(q.addAll(listOf("7", "8")))
assertEquals(listOf("3", "4", "7", "8"), q)
assertEquals(listOf("2", "3", "4", "7", "8", "5"), s)
assertEquals(listOf("1", "2", "3", "4", "7", "8", "5", "6"), a)
}
fun testSubListRemoveAt() {
val a = ArrayList(listOf("1", "2", "3", "4", "5"))
val s = a.subList(1, 4)
assertEquals(listOf("2", "3", "4"), s)
assertEquals("3", s.removeAt(1))
assertEquals(listOf("2", "4"), s)
assertEquals(listOf("1", "2", "4", "5"), a)
}
fun testSubListSubListRemoveAt() {
val a = ArrayList(listOf("1", "2", "3", "4", "5", "6", "7"))
val s = a.subList(1, 6)
val q = s.subList(1, 4)
assertEquals(listOf("2", "3", "4", "5", "6"), s)
assertEquals(listOf("3", "4", "5"), q)
assertEquals("4", q.removeAt(1))
assertEquals(listOf("3", "5"), q)
assertEquals(listOf("2", "3", "5", "6"), s)
assertEquals(listOf("1", "2", "3", "5", "6", "7"), a)
}
fun testSubListRemoveAll() {
val a = ArrayList(listOf("1", "2", "3", "3", "4", "5"))
val s = a.subList(1, 5)
assertEquals(listOf("2", "3", "3", "4"), s)
assertTrue(s.removeAll(listOf("3", "5")))
assertEquals(listOf("2", "4"), s)
assertEquals(listOf("1", "2", "4", "5"), a)
}
fun testSubListSubListRemoveAll() {
val a = ArrayList(listOf("1", "2", "3", "4", "5", "6", "7"))
val s = a.subList(1, 6)
val q = s.subList(1, 4)
assertEquals(listOf("2", "3", "4", "5", "6"), s)
assertEquals(listOf("3", "4", "5"), q)
assertTrue(q.removeAll(listOf("4", "6")))
assertEquals(listOf("3", "5"), q)
assertEquals(listOf("2", "3", "5", "6"), s)
assertEquals(listOf("1", "2", "3", "5", "6", "7"), a)
}
fun testSubListRetainAll() {
val a = ArrayList(listOf("1", "2", "3", "4", "5"))
val s = a.subList(1, 4)
assertEquals(listOf("2", "3", "4"), s)
assertTrue(s.retainAll(listOf("5", "3")))
assertEquals(listOf("3"), s)
assertEquals(listOf("1", "3", "5"), a)
}
fun testSubListSubListRetainAll() {
val a = ArrayList(listOf("1", "2", "3", "4", "5", "6", "7"))
val s = a.subList(1, 6)
val q = s.subList(1, 4)
assertEquals(listOf("2", "3", "4", "5", "6"), s)
assertEquals(listOf("3", "4", "5"), q)
assertTrue(q.retainAll(listOf("5", "3")))
assertEquals(listOf("3", "5"), q)
assertEquals(listOf("2", "3", "5", "6"), s)
assertEquals(listOf("1", "2", "3", "5", "6", "7"), a)
}
fun testIteratorRemove() {
val a = ArrayList(listOf("1", "2", "3", "4", "5"))
val it = a.iterator()
while (it.hasNext())
if (it.next()[0].toInt() % 2 == 0)
it.remove()
assertEquals(listOf("1", "3", "5"), a)
}
fun testIteratorAdd() {
val a = ArrayList(listOf("1", "2", "3", "4", "5"))
val it = a.listIterator()
while (it.hasNext()) {
val next = it.next()
if (next[0].toInt() % 2 == 0)
it.add("-" + next)
}
assertEquals(listOf("1", "2", "-2", "3", "4", "-4", "5"), a)
}
@Test fun runTest() {
testBasic()
testIterator()
testRemove()
testRemoveAll()
testRetainAll()
testEquals()
testHashCode()
testToString()
testSubList()
testResize()
testSubListContains()
testSubListIndexOf()
testSubListLastIndexOf()
testSubListClear()
testSubListSubListClear()
testSubListAdd()
testSubListSubListAdd()
testSubListAddAll()
testSubListSubListAddAll()
testSubListRemoveAt()
testSubListSubListRemoveAt()
testSubListRemoveAll()
testSubListSubListRemoveAll()
testSubListSubListRemoveAll()
testSubListRetainAll()
testSubListSubListRetainAll()
testIteratorRemove()
testIteratorAdd()
println("OK")
}
@@ -0,0 +1,36 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.collections.array_list2
import kotlin.test.*
fun testIteratorNext() {
val a = arrayListOf("1", "2", "3", "4", "5")
val it = a.listIterator()
assertFailsWith<NoSuchElementException> {
while (true) {
it.next()
}
}
}
fun testIteratorPrevious() {
val a = arrayListOf("1", "2", "3", "4", "5")
val it = a.listIterator()
it.next()
assertFailsWith<NoSuchElementException> {
while (true) {
it.previous()
}
}
}
@Test fun runTest() {
testIteratorNext()
testIteratorPrevious()
println("OK")
}
@@ -0,0 +1,275 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.collections.hash_map0
import kotlin.test.*
fun assertTrue(cond: Boolean) {
if (!cond)
println("FAIL")
}
fun assertFalse(cond: Boolean) {
if (cond)
println("FAIL")
}
fun assertEquals(value1: Any?, value2: Any?) {
if (value1 != value2)
println("FAIL")
}
fun assertNotEquals(value1: Any?, value2: Any?) {
if (value1 == value2)
println("FAIL")
}
fun assertEquals(value1: Int, value2: Int) {
if (value1 != value2)
println("FAIL")
}
fun testBasic() {
val m = HashMap<String, String>()
assertTrue(m.isEmpty())
assertEquals(0, m.size)
assertFalse(m.containsKey("1"))
assertFalse(m.containsValue("a"))
assertEquals(null, m.get("1"))
assertEquals(null, m.put("1", "a"))
assertTrue(m.containsKey("1"))
assertTrue(m.containsValue("a"))
assertEquals("a", m.get("1"))
assertFalse(m.isEmpty())
assertEquals(1, m.size)
assertFalse(m.containsKey("2"))
assertFalse(m.containsValue("b"))
assertEquals(null, m.get("2"))
assertEquals(null, m.put("2", "b"))
assertTrue(m.containsKey("1"))
assertTrue(m.containsValue("a"))
assertEquals("a", m.get("1"))
assertTrue(m.containsKey("2"))
assertTrue(m.containsValue("b"))
assertEquals("b", m.get("2"))
assertFalse(m.isEmpty())
assertEquals(2, m.size)
assertEquals("b", m.put("2", "bb"))
assertTrue(m.containsKey("1"))
assertTrue(m.containsValue("a"))
assertEquals("a", m.get("1"))
assertTrue(m.containsKey("2"))
assertTrue(m.containsValue("a"))
assertTrue(m.containsValue("bb"))
assertEquals("bb", m.get("2"))
assertFalse(m.isEmpty())
assertEquals(2, m.size)
assertEquals("a", m.remove("1"))
assertFalse(m.containsKey("1"))
assertFalse(m.containsValue("a"))
assertEquals(null, m.get("1"))
assertTrue(m.containsKey("2"))
assertTrue(m.containsValue("bb"))
assertEquals("bb", m.get("2"))
assertFalse(m.isEmpty())
assertEquals(1, m.size)
assertEquals("bb", m.remove("2"))
assertFalse(m.containsKey("1"))
assertFalse(m.containsValue("a"))
assertEquals(null, m.get("1"))
assertFalse(m.containsKey("2"))
assertFalse(m.containsValue("bb"))
assertEquals(null, m.get("2"))
assertTrue(m.isEmpty())
assertEquals(0, m.size)
}
fun testRehashAndCompact() {
val m = HashMap<String, String>()
for (repeat in 1..10) {
val n = when (repeat) {
1 -> 1000
2 -> 10000
3 -> 10
else -> 100000
}
for (i in 1..n) {
assertFalse(m.containsKey(i.toString()))
assertEquals(null, m.put(i.toString(), "val$i"))
assertTrue(m.containsKey(i.toString()))
assertEquals(i, m.size)
}
for (i in 1..n) {
assertTrue(m.containsKey(i.toString()))
}
for (i in 1..n) {
assertEquals("val$i", m.remove(i.toString()))
assertFalse(m.containsKey(i.toString()))
assertEquals(n - i, m.size)
}
assertTrue(m.isEmpty())
}
}
fun testClear() {
val m = HashMap<String, String>()
for (repeat in 1..10) {
val n = when (repeat) {
1 -> 1000
2 -> 10000
3 -> 10
else -> 100000
}
for (i in 1..n) {
assertFalse(m.containsKey(i.toString()))
assertEquals(null, m.put(i.toString(), "val$i"))
assertTrue(m.containsKey(i.toString()))
assertEquals(i, m.size)
}
for (i in 1..n) {
assertTrue(m.containsKey(i.toString()))
}
m.clear()
assertEquals(0, m.size)
for (i in 1..n) {
assertFalse(m.containsKey(i.toString()))
}
}
}
fun testEquals() {
val expected = mapOf("a" to "1", "b" to "2", "c" to "3")
val m = HashMap(expected)
assertTrue(m == expected)
assertTrue(m == mapOf("b" to "2", "c" to "3", "a" to "1")) // order does not matter
assertFalse(m == mapOf("a" to "1", "b" to "2", "c" to "4"))
assertFalse(m == mapOf("a" to "1", "b" to "2", "c" to "5"))
assertFalse(m == mapOf("a" to "1", "b" to "2"))
assertEquals(m.keys, expected.keys)
assertEquals(m.values.toList(), expected.values.toList())
assertEquals(m.entries, expected.entries)
}
fun testHashCode() {
val expected = mapOf("a" to "1", "b" to "2", "c" to "3")
val m = HashMap(expected)
assertEquals(expected.hashCode(), m.hashCode())
assertEquals(expected.entries.hashCode(), m.entries.hashCode())
assertEquals(expected.keys.hashCode(), m.keys.hashCode())
}
fun testToString() {
val expected = mapOf("a" to "1", "b" to "2", "c" to "3")
val m = HashMap(expected)
assertEquals(expected.toString(), m.toString())
assertEquals(expected.entries.toString(), m.entries.toString())
assertEquals(expected.keys.toString(), m.keys.toString())
assertEquals(expected.values.toString(), m.values.toString())
}
fun testPutEntry() {
val expected = mapOf("a" to "1", "b" to "2", "c" to "3")
val m = HashMap(expected)
val e = expected.entries.iterator().next() as MutableMap.MutableEntry<String, String>
assertTrue(m.entries.contains(e))
assertTrue(m.entries.remove(e))
assertTrue(mapOf("b" to "2", "c" to "3") == m)
assertEquals(null, m.put(e.key, e.value))
assertTrue(expected == m)
assertEquals(e.value, m.put(e.key, e.value))
assertTrue(expected == m)
}
fun testRemoveAllEntries() {
val expected = mapOf("a" to "1", "b" to "2", "c" to "3")
val m = HashMap(expected)
assertFalse(m.entries.removeAll(mapOf("a" to "2", "b" to "3", "c" to "4").entries))
assertEquals(expected, m)
assertTrue(m.entries.removeAll(mapOf("b" to "22", "c" to "3", "d" to "4").entries))
assertNotEquals(expected, m)
assertEquals(mapOf("a" to "1", "b" to "2"), m)
}
fun testRetainAllEntries() {
val expected = mapOf("a" to "1", "b" to "2", "c" to "3")
val m = HashMap(expected)
assertFalse(m.entries.retainAll(expected.entries))
assertEquals(expected, m)
assertTrue(m.entries.retainAll(mapOf("b" to "22", "c" to "3", "d" to "4").entries))
assertEquals(mapOf("c" to "3"), m)
}
fun testContainsAllValues() {
val m = HashMap(mapOf("a" to "1", "b" to "2", "c" to "3"))
assertTrue(m.values.containsAll(listOf("1", "2")))
assertTrue(m.values.containsAll(listOf("1", "2", "3")))
assertFalse(m.values.containsAll(listOf("1", "2", "3", "4")))
assertFalse(m.values.containsAll(listOf("2", "3", "4")))
}
fun testRemoveValue() {
val expected = mapOf("a" to "1", "b" to "2", "c" to "3")
val m = HashMap(expected)
assertFalse(m.values.remove("b"))
assertEquals(expected, m)
assertTrue(m.values.remove("2"))
assertEquals(mapOf("a" to "1", "c" to "3"), m)
}
fun testRemoveAllValues() {
val expected = mapOf("a" to "1", "b" to "2", "c" to "3")
val m = HashMap(expected)
assertFalse(m.values.removeAll(listOf("b", "c")))
assertEquals(expected, m)
assertTrue(m.values.removeAll(listOf("b", "3")))
assertEquals(mapOf("a" to "1", "b" to "2"), m)
}
fun testRetainAllValues() {
val expected = mapOf("a" to "1", "b" to "2", "c" to "3")
val m = HashMap(expected)
assertFalse(m.values.retainAll(listOf("1", "2", "3")))
assertEquals(expected, m)
assertTrue(m.values.retainAll(listOf("1", "2", "c")))
assertEquals(mapOf("a" to "1", "b" to "2"), m)
}
fun testEntriesIteratorSet() {
val expected = mapOf("a" to "1", "b" to "2", "c" to "3")
val m = HashMap(expected)
val it = m.iterator()
while (it.hasNext()) {
val entry = it.next()
entry.setValue(entry.value + "!")
}
assertNotEquals(expected, m)
assertEquals(mapOf("a" to "1!", "b" to "2!", "c" to "3!"), m)
}
@Test fun runTest() {
testBasic()
testRehashAndCompact()
testClear()
testEquals()
testHashCode()
testToString()
testPutEntry()
testRemoveAllEntries()
testRetainAllEntries()
testContainsAllValues()
testRemoveValue()
testRemoveAllValues()
testRetainAllValues()
testEntriesIteratorSet()
//testDegenerateKeys()
println("OK")
}
@@ -0,0 +1,140 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.collections.hash_set0
import kotlin.test.*
fun assertTrue(cond: Boolean) {
if (!cond)
println("FAIL")
}
fun assertFalse(cond: Boolean) {
if (cond)
println("FAIL")
}
fun assertEquals(value1: Any?, value2: Any?) {
if (value1 != value2)
println("FAIL")
}
fun assertEquals(value1: Int, value2: Int) {
if (value1 != value2)
println("FAIL")
}
fun testBasic() {
val a = HashSet<String>()
assertTrue(a.isEmpty())
assertEquals(0, a.size)
assertTrue(a.add("1"))
assertTrue(a.add("2"))
assertTrue(a.add("3"))
assertFalse(a.isEmpty())
assertEquals(3, a.size)
assertTrue(a.contains("1"))
assertTrue(a.contains("2"))
assertTrue(a.contains("3"))
assertFalse(a.contains("4"))
assertTrue(a.remove("1"))
assertEquals(2, a.size)
assertFalse(a.contains("1"))
assertTrue(a.contains("2"))
assertTrue(a.contains("3"))
assertFalse(a.contains("4"))
assertTrue(a.add("4"))
assertEquals(3, a.size)
assertFalse(a.contains("1"))
assertTrue(a.contains("2"))
assertTrue(a.contains("3"))
assertTrue(a.contains("4"))
assertFalse(a.add("4"))
assertEquals(3, a.size)
assertFalse(a.contains("1"))
assertTrue(a.contains("2"))
assertTrue(a.contains("3"))
assertTrue(a.contains("4"))
a.clear()
assertTrue(a.isEmpty())
assertEquals(0, a.size)
assertFalse(a.contains("1"))
assertFalse(a.contains("2"))
assertFalse(a.contains("3"))
assertFalse(a.contains("4"))
}
fun testIterator() {
val s = HashSet(listOf("1", "2", "3"))
val it = s.iterator()
assertTrue(it.hasNext())
assertEquals("1", it.next())
assertTrue(it.hasNext())
assertEquals("2", it.next())
assertTrue(it.hasNext())
assertEquals("3", it.next())
assertFalse(it.hasNext())
}
fun testEquals() {
val s = HashSet(listOf("1", "2", "3"))
assertTrue(s == setOf("1", "2", "3"))
assertTrue(s == setOf("2", "3", "1")) // order does not matter
assertFalse(s == setOf("1", "2", "4"))
assertFalse(s == setOf("1", "2"))
}
fun testHashCode() {
val s = HashSet(listOf("1", "2", "3"))
assertTrue(s.hashCode() == setOf("1", "2", "3").hashCode())
}
fun testToString() {
val s = HashSet(listOf("1", "2", "3"))
assertTrue(s.toString() == setOf("1", "2", "3").toString())
}
fun testContainsAll() {
val s = HashSet(listOf("1", "2", "3", "4", "5"))
assertFalse(s.containsAll(listOf("6", "7", "8")))
assertFalse(s.containsAll(listOf("5", "6", "7")))
assertFalse(s.containsAll(listOf("4", "5", "6")))
assertTrue(s.containsAll(listOf("3", "4", "5")))
assertTrue(s.containsAll(listOf("2", "3", "4")))
}
fun testRemoveAll() {
val s = HashSet(listOf("1", "2", "3", "4", "5", "1"))
assertFalse(s.removeAll(listOf("6", "7", "8")))
assertEquals(setOf("1", "2", "3", "4", "5", "1"), s)
assertTrue(s.removeAll(listOf("5", "3", "1")))
assertEquals(setOf("2", "4"), s)
}
fun testRetainAll() {
val s = HashSet(listOf("1", "2", "3", "4", "5"))
assertFalse(s.retainAll(listOf("1", "2", "3", "4", "5")))
assertEquals(setOf("1", "2", "3", "4", "5"), s)
assertTrue(s.retainAll(listOf("5", "3", "1")))
assertEquals(setOf("1", "3", "5"), s)
}
@Test fun runTest() {
testBasic()
testIterator()
testEquals()
testHashCode()
testToString()
testContainsAll()
testRemoveAll()
testRetainAll()
println("OK")
}
@@ -0,0 +1,24 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.collections.listof0
import kotlin.test.*
@Test fun runTest() {
main(arrayOf("a"))
}
fun main(args : Array<String>) {
val nonConstStr = args[0]
val list = arrayListOf(nonConstStr, "b", "c")
for (element in list) print(element)
println()
list.add("d")
println(list.toString())
val list2 = listOf("n", "s", nonConstStr)
println(list2.toString())
}
@@ -0,0 +1,20 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.collections.moderately_large_array
import kotlin.test.*
@Test fun runTest() {
val a = ByteArray(1000000)
var sum = 0
for (b in a) {
sum += b
}
println(sum)
}
@@ -0,0 +1,20 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.collections.moderately_large_array1
import kotlin.test.*
@Test fun runTest() {
val a = Array<Byte>(100000, { i -> i.toByte()})
var sum = 0
for (b in a) {
sum += b
}
println(sum)
}
@@ -0,0 +1,15 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.collections.range0
import kotlin.test.*
@Test fun runTest() {
for (i in 1..3) print(i)
println()
for (i in 'a'..'d') print(i)
println()
}
@@ -0,0 +1,13 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.collections.sort0
import kotlin.test.*
@Test fun runTest() {
println(arrayOf("x", "a", "b").sorted().toString())
println(intArrayOf(239, 42, -1, 100500, 0).sorted().toString());
}
@@ -0,0 +1,18 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.collections.sort1
import kotlin.test.*
@Test fun runTest() {
val foo = mutableListOf("x", "a", "b")
foo.sort()
println(foo.toString())
var bar = mutableListOf(239, 42, -1, 100500, 0)
bar.sort()
println(bar.toString())
}
@@ -0,0 +1,17 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.collections.stack_array
import kotlin.test.*
@Test fun runTest() {
val array = IntArray(2)
array[0] = 1
array[1] = 2
val check = array is IntArray
println(check)
println(array[0] + array[1])
}
@@ -0,0 +1,30 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.collections.typed_array0
import kotlin.test.*
@Test fun runTest() {
// Those tests assume little endian bit ordering.
val array = ByteArray(42)
array.setLongAt(5, 0x1234_5678_9abc_def0)
expect(0x1234_5678_9abc_def0) { array.getLongAt(5) }
expect(0xdef0.toInt()) { array.getCharAt(5).toInt() }
expect(0x9abc.toShort()) { array.getShortAt(7) }
expect(0x1234_5678) { array.getIntAt(9) }
expect(0xdef0_0000u) { array.getUIntAt(3) }
expect(0xf0_00u) { array.getUShortAt(4) }
expect(0xf0u) { array.getUByteAt(5) }
expect(0x1234_5678_9abcuL) { array.getULongAt(7) }
array.setIntAt(2, 0x40100000)
expect(2.25f) { array.getFloatAt(2) }
array.setLongAt(11, 0x400c_0000_0000_0000)
expect(3.5) { array.getDoubleAt(11) }
println("OK")
}
@@ -0,0 +1,73 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.collections.typed_array1
import kotlin.test.*
import kotlin.native.concurrent.*
@Test fun runTest() {
val array = ByteArray(17)
val results = mutableSetOf<Any>()
var counter = 0
assertFailsWith<ArrayIndexOutOfBoundsException> {
results += array.getShortAt(16)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
results += array.getCharAt(22)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
results += array.getIntAt(15)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
results += array.getLongAt(14)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
results += array.getFloatAt(14)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
results += array.getDoubleAt(13)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
array.setShortAt(16, 2.toShort())
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
array.setCharAt(22, 'a')
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
array.setIntAt(15, 1234)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
array.setLongAt(14, 1.toLong())
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
array.setFloatAt(14, 1.0f)
}
assertFailsWith<ArrayIndexOutOfBoundsException> {
array.setDoubleAt(13, 3.0)
}
expect(0) { results.size }
array.freeze()
assertFailsWith<InvalidMutabilityException> {
array.setShortAt(0, 2.toShort())
}
assertFailsWith<InvalidMutabilityException> {
array.setCharAt(0, 'a')
}
assertFailsWith<InvalidMutabilityException> {
array.setIntAt(0, 2)
}
assertFailsWith<InvalidMutabilityException> {
array.setLongAt(0, 2)
}
assertFailsWith<InvalidMutabilityException> {
array.setFloatAt(0, 1.0f)
}
assertFailsWith<InvalidMutabilityException> {
array.setDoubleAt(0, 1.0)
}
println("OK")
}
@@ -0,0 +1,780 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.concurrent.worker_bound_reference0
import kotlin.test.*
import kotlin.native.concurrent.*
import kotlin.native.internal.GC
import kotlin.native.ref.WeakReference
import kotlin.text.Regex
class A(var a: Int)
@SharedImmutable
val global1: WorkerBoundReference<A> = WorkerBoundReference(A(3))
@Test
fun testGlobal() {
assertEquals(3, global1.value.a)
assertEquals(3, global1.valueOrNull?.a)
val worker = Worker.start()
val future = worker.execute(TransferMode.SAFE, {}) {
global1
}
val value = future.result
assertEquals(3, value.value.a)
assertEquals(3, value.valueOrNull?.a)
worker.requestTermination().result
}
@SharedImmutable
val global2: WorkerBoundReference<A> = WorkerBoundReference(A(3))
@Test
fun testGlobalDenyAccessOnWorker() {
assertEquals(3, global2.value.a)
val worker = Worker.start()
val future = worker.execute(TransferMode.SAFE, {}) {
val local = global2
assertFailsWith<IncorrectDereferenceException> {
local.value
}
assertEquals(null, local.valueOrNull)
Unit
}
future.result
worker.requestTermination().result
}
@SharedImmutable
val global3: WorkerBoundReference<A> = WorkerBoundReference(A(3).freeze())
@Test
fun testGlobalAccessOnWorkerFrozenInitially() {
assertEquals(3, global3.value.a)
assertEquals(3, global3.valueOrNull?.a)
val worker = Worker.start()
val future = worker.execute(TransferMode.SAFE, {}) {
global3.value.a
}
val value = future.result
assertEquals(3, value)
worker.requestTermination().result
}
@SharedImmutable
val global4: WorkerBoundReference<A> = WorkerBoundReference(A(3))
@Test
fun testGlobalAccessOnWorkerFrozenBeforePassing() {
assertEquals(3, global4.value.a)
global4.value.freeze()
val worker = Worker.start()
val future = worker.execute(TransferMode.SAFE, {}) {
global4.value.a
}
val value = future.result
assertEquals(3, value)
worker.requestTermination().result
}
@SharedImmutable
val global5: WorkerBoundReference<A> = WorkerBoundReference(A(3))
@Test
fun testGlobalAccessOnWorkerFrozenBeforeAccess() {
val semaphore: AtomicInt = AtomicInt(0)
assertEquals(3, global5.value.a)
val worker = Worker.start()
val future = worker.execute(TransferMode.SAFE, { semaphore }) { semaphore ->
semaphore.increment()
while (semaphore.value < 2) {
}
global5.value.a
}
while (semaphore.value < 1) {
}
global5.value.freeze()
semaphore.increment()
val value = future.result
assertEquals(3, value)
worker.requestTermination().result
}
@SharedImmutable
val global6: WorkerBoundReference<A> = WorkerBoundReference(A(3))
@Test
fun testGlobalModification() {
val semaphore: AtomicInt = AtomicInt(0)
assertEquals(3, global6.value.a)
val worker = Worker.start()
val future = worker.execute(TransferMode.SAFE, { semaphore }) { semaphore ->
semaphore.increment()
while (semaphore.value < 2) {
}
global6
}
while (semaphore.value < 1) {
}
global6.value.a = 4
semaphore.increment()
val value = future.result
assertEquals(4, value.value.a)
assertEquals(4, value.valueOrNull?.a)
worker.requestTermination().result
}
@SharedImmutable
val global7: WorkerBoundReference<A> = WorkerBoundReference(A(3))
@Test
fun testGlobalGetWorker() {
val ownerId = Worker.current.id
assertEquals(ownerId, global7.worker.id)
val worker = Worker.start()
val future = worker.execute(TransferMode.SAFE, { ownerId }) { ownerId ->
assertEquals(ownerId, global7.worker.id)
Unit
}
future.result
worker.requestTermination().result
}
@Test
fun testLocal() {
val local = WorkerBoundReference(A(3))
assertEquals(3, local.value.a)
assertEquals(3, local.valueOrNull?.a)
}
@Test
fun testLocalFrozen() {
val local = WorkerBoundReference(A(3)).freeze()
assertEquals(3, local.value.a)
assertEquals(3, local.valueOrNull?.a)
val worker = Worker.start()
val future = worker.execute(TransferMode.SAFE, { local }) { local ->
local
}
val value = future.result
assertEquals(3, value.value.a)
assertEquals(3, value.valueOrNull?.a)
worker.requestTermination().result
}
@Test
fun testLocalDenyAccessOnWorkerFrozen() {
val local = WorkerBoundReference(A(3)).freeze()
assertEquals(3, local.value.a)
val worker = Worker.start()
val future = worker.execute(TransferMode.SAFE, { local }) { local ->
assertFailsWith<IncorrectDereferenceException> {
local.value
}
assertEquals(null, local.valueOrNull)
Unit
}
future.result
worker.requestTermination().result
}
@Test
fun testLocalAccessOnWorkerFrozenInitiallyFrozen() {
val local = WorkerBoundReference(A(3).freeze()).freeze()
assertEquals(3, local.value.a)
assertEquals(3, local.valueOrNull?.a)
val worker = Worker.start()
val future = worker.execute(TransferMode.SAFE, { local }) { local ->
local.value.a
}
val value = future.result
assertEquals(3, value)
worker.requestTermination().result
}
@Test
fun testLocalAccessOnWorkerFrozenBeforePassingFrozen() {
val local = WorkerBoundReference(A(3)).freeze()
assertEquals(3, local.value.a)
local.value.freeze()
val worker = Worker.start()
val future = worker.execute(TransferMode.SAFE, { local }) { local ->
local.value.a
}
val value = future.result
assertEquals(3, value)
worker.requestTermination().result
}
@Test
fun testLocalAccessOnWorkerFrozenBeforeAccessFrozen() {
val semaphore: AtomicInt = AtomicInt(0)
val local = WorkerBoundReference(A(3)).freeze()
assertEquals(3, local.value.a)
val worker = Worker.start()
val future = worker.execute(TransferMode.SAFE, { Pair(local, semaphore) }) { (local, semaphore) ->
semaphore.increment()
while (semaphore.value < 2) {
}
local.value.a
}
while (semaphore.value < 1) {
}
local.value.freeze()
semaphore.increment()
val value = future.result
assertEquals(3, value)
worker.requestTermination().result
}
@Test
fun testLocalAccessOnMainThread() {
val worker = Worker.start()
val future = worker.execute(TransferMode.SAFE, {}) {
WorkerBoundReference(A(3))
}
assertEquals(3, future.result.value.a)
worker.requestTermination().result
}
@Test
fun testLocalDenyAccessOnMainThreadFrozen() {
val worker = Worker.start()
val future = worker.execute(TransferMode.SAFE, {}) {
WorkerBoundReference(A(3)).freeze()
}
val value = future.result
assertFailsWith<IncorrectDereferenceException> {
value.value
}
assertEquals(null, value.valueOrNull)
worker.requestTermination().result
}
@Test
fun testLocalModificationFrozen() {
val semaphore: AtomicInt = AtomicInt(0)
val local = WorkerBoundReference(A(3)).freeze()
assertEquals(3, local.value.a)
val worker = Worker.start()
val future = worker.execute(TransferMode.SAFE, { Pair(local, semaphore) }) { (local, semaphore) ->
semaphore.increment()
while (semaphore.value < 2) {
}
local
}
while (semaphore.value < 1) {
}
local.value.a = 4
semaphore.increment()
val value = future.result
assertEquals(4, value.value.a)
assertEquals(4, value.valueOrNull?.a)
worker.requestTermination().result
}
@Test
fun testLocalGetWorkerFrozen() {
val local = WorkerBoundReference(A(3)).freeze()
val ownerId = Worker.current.id
assertEquals(ownerId, local.worker.id)
val worker = Worker.start()
val future = worker.execute(TransferMode.SAFE, { Pair(local, ownerId) }) { (local, ownerId) ->
assertEquals(ownerId, local.worker.id)
Unit
}
future.result
worker.requestTermination().result
}
@Test
fun testLocalForeignGetWorker() {
val worker = Worker.start()
val ownerId = worker.id
val future = worker.execute(TransferMode.SAFE, { ownerId }) { ownerId ->
val local = WorkerBoundReference(A(3))
assertEquals(ownerId, local.worker.id)
local
}
val value = future.result
assertEquals(ownerId, value.worker.id)
worker.requestTermination().result
}
@Test
fun testLocalForeignGetWorkerFrozen() {
val worker = Worker.start()
val ownerId = worker.id
val future = worker.execute(TransferMode.SAFE, { ownerId }) { ownerId ->
val local = WorkerBoundReference(A(3)).freeze()
assertEquals(ownerId, local.worker.id)
local
}
val value = future.result
assertEquals(ownerId, value.worker.id)
worker.requestTermination().result
}
class Wrapper(val ref: WorkerBoundReference<A>)
@Test
fun testLocalWithWrapperFrozen() {
val local = Wrapper(WorkerBoundReference(A(3))).freeze()
assertEquals(3, local.ref.value.a)
val worker = Worker.start()
val future = worker.execute(TransferMode.SAFE, { local }) { local ->
local
}
val value = future.result
assertEquals(3, value.ref.value.a)
worker.requestTermination().result
}
@Test
fun testLocalDenyAccessWithWrapperFrozen() {
val local = Wrapper(WorkerBoundReference(A(3))).freeze()
assertEquals(3, local.ref.value.a)
val worker = Worker.start()
val future = worker.execute(TransferMode.SAFE, { local }) { local ->
assertFailsWith<IncorrectDereferenceException> {
local.ref.value
}
assertEquals(null, local.ref.valueOrNull)
Unit
}
future.result
worker.requestTermination().result
}
fun getOwnerAndWeaks(initial: Int): Triple<FreezableAtomicReference<WorkerBoundReference<A>?>, WeakReference<WorkerBoundReference<A>>, WeakReference<A>> {
val ref = WorkerBoundReference(A(initial))
val refOwner: FreezableAtomicReference<WorkerBoundReference<A>?> = FreezableAtomicReference(ref)
val refWeak = WeakReference(ref)
val refValueWeak = WeakReference(ref.value)
return Triple(refOwner, refWeak, refValueWeak)
}
@Test
fun testCollect() {
val (refOwner, refWeak, refValueWeak) = getOwnerAndWeaks(3)
refOwner.value = null
GC.collect()
// Last reference to WorkerBoundReference is gone, so it and it's referent are destroyed.
assertNull(refWeak.value)
assertNull(refValueWeak.value)
}
fun getOwnerAndWeaksFrozen(initial: Int): Triple<AtomicReference<WorkerBoundReference<A>?>, WeakReference<WorkerBoundReference<A>>, WeakReference<A>> {
val ref = WorkerBoundReference(A(initial)).freeze()
val refOwner: AtomicReference<WorkerBoundReference<A>?> = AtomicReference(ref)
val refWeak = WeakReference(ref)
val refValueWeak = WeakReference(ref.value)
return Triple(refOwner, refWeak, refValueWeak)
}
@Test
fun testCollectFrozen() {
val (refOwner, refWeak, refValueWeak) = getOwnerAndWeaksFrozen(3)
refOwner.value = null
GC.collect()
// Last reference to WorkerBoundReference is gone, so it and it's referent are destroyed.
assertNull(refWeak.value)
assertNull(refValueWeak.value)
}
fun collectInWorkerFrozen(worker: Worker, semaphore: AtomicInt): Pair<WeakReference<A>, Future<Unit>> {
val (refOwner, _, refValueWeak) = getOwnerAndWeaksFrozen(3)
val future = worker.execute(TransferMode.SAFE, { Pair(refOwner, semaphore) }) { (refOwner, semaphore) ->
semaphore.increment()
while (semaphore.value < 2) {
}
refOwner.value = null
GC.collect()
}
while (semaphore.value < 1) {
}
// At this point worker is spinning on semaphore. refOwner still contains reference to
// WorkerBoundReference, so referent is kept alive.
GC.collect()
assertNotNull(refValueWeak.value)
return Pair(refValueWeak, future)
}
@Test
fun testCollectInWorkerFrozen() {
val semaphore: AtomicInt = AtomicInt(0)
val worker = Worker.start()
val (refValueWeak, future) = collectInWorkerFrozen(worker, semaphore)
semaphore.increment()
future.result
// At this point WorkerBoundReference no longer has a reference, so it's referent is destroyed.
GC.collect()
assertNull(refValueWeak.value)
worker.requestTermination().result
}
fun doNotCollectInWorkerFrozen(worker: Worker, semaphore: AtomicInt): Future<WorkerBoundReference<A>> {
val ref = WorkerBoundReference(A(3)).freeze()
return worker.execute(TransferMode.SAFE, { Pair(ref, semaphore) }) { (ref, semaphore) ->
semaphore.increment()
while (semaphore.value < 2) {
}
GC.collect()
ref
}
}
@Test
fun testDoNotCollectInWorkerFrozen() {
val semaphore: AtomicInt = AtomicInt(0)
val worker = Worker.start()
val future = doNotCollectInWorkerFrozen(worker, semaphore)
while (semaphore.value < 1) {
}
GC.collect()
semaphore.increment()
val value = future.result
assertEquals(3, value.value.a)
worker.requestTermination().result
}
class B1 {
lateinit var b2: WorkerBoundReference<B2>
}
data class B2(val b1: WorkerBoundReference<B1>)
fun createCyclicGarbage(): Triple<FreezableAtomicReference<WorkerBoundReference<B1>?>, WeakReference<B1>, WeakReference<B2>> {
val ref1 = WorkerBoundReference(B1())
val ref1Owner: FreezableAtomicReference<WorkerBoundReference<B1>?> = FreezableAtomicReference(ref1)
val ref1Weak = WeakReference(ref1.value)
val ref2 = WorkerBoundReference(B2(ref1))
val ref2Weak = WeakReference(ref2.value)
ref1.value.b2 = ref2
return Triple(ref1Owner, ref1Weak, ref2Weak)
}
@Test
fun collectCyclicGarbage() {
val (ref1Owner, ref1Weak, ref2Weak) = createCyclicGarbage()
ref1Owner.value = null
GC.collect()
assertNull(ref1Weak.value)
assertNull(ref2Weak.value)
}
fun createCyclicGarbageFrozen(): Triple<AtomicReference<WorkerBoundReference<B1>?>, WeakReference<B1>, WeakReference<B2>> {
val ref1 = WorkerBoundReference(B1()).freeze()
val ref1Owner: AtomicReference<WorkerBoundReference<B1>?> = AtomicReference(ref1)
val ref1Weak = WeakReference(ref1.value)
val ref2 = WorkerBoundReference(B2(ref1)).freeze()
val ref2Weak = WeakReference(ref2.value)
ref1.value.b2 = ref2
return Triple(ref1Owner, ref1Weak, ref2Weak)
}
@Test
fun doesNotCollectCyclicGarbageFrozen() {
val (ref1Owner, ref1Weak, ref2Weak) = createCyclicGarbageFrozen()
ref1Owner.value = null
GC.collect()
// If these asserts fail, that means WorkerBoundReference managed to clean up cyclic garbage all by itself.
assertNotNull(ref1Weak.value)
assertNotNull(ref2Weak.value)
}
fun createCrossThreadCyclicGarbageFrozen(
worker: Worker
): Triple<AtomicReference<WorkerBoundReference<B1>?>, WeakReference<B1>, WeakReference<B2>> {
val ref1 = WorkerBoundReference(B1()).freeze()
val ref1Owner: AtomicReference<WorkerBoundReference<B1>?> = AtomicReference(ref1)
val ref1Weak = WeakReference(ref1.value)
val future = worker.execute(TransferMode.SAFE, { ref1 }) { ref1 ->
val ref2 = WorkerBoundReference(B2(ref1)).freeze()
Pair(ref2, WeakReference(ref2.value))
}
val (ref2, ref2Weak) = future.result
ref1.value.b2 = ref2
return Triple(ref1Owner, ref1Weak, ref2Weak)
}
@Test
fun doesNotCollectCrossThreadCyclicGarbageFrozen() {
val worker = Worker.start()
val (ref1Owner, ref1Weak, ref2Weak) = createCrossThreadCyclicGarbageFrozen(worker)
ref1Owner.value = null
GC.collect()
worker.execute(TransferMode.SAFE, {}) { GC.collect() }.result
// If these asserts fail, that means WorkerBoundReference managed to clean up cyclic garbage all by itself.
assertNotNull(ref1Weak.value)
assertNotNull(ref2Weak.value)
worker.requestTermination().result
}
class C1 {
lateinit var c2: AtomicReference<WorkerBoundReference<C2>?>
fun dispose() {
c2.value = null
}
}
data class C2(val c1: AtomicReference<WorkerBoundReference<C1>>)
fun createCyclicGarbageWithAtomicsFrozen(): Triple<AtomicReference<WorkerBoundReference<C1>?>, WeakReference<C1>, WeakReference<C2>> {
val ref1 = WorkerBoundReference(C1()).freeze()
val ref1Weak = WeakReference(ref1.value)
val ref2 = WorkerBoundReference(C2(AtomicReference(ref1))).freeze()
val ref2Weak = WeakReference(ref2.value)
ref1.value.c2 = AtomicReference(ref2)
return Triple(AtomicReference(ref1), ref1Weak, ref2Weak)
}
fun dispose(refOwner: AtomicReference<WorkerBoundReference<C1>?>) {
refOwner.value!!.value.dispose()
refOwner.value = null
}
@Test
fun doesNotCollectCyclicGarbageWithAtomicsFrozen() {
val (ref1Owner, ref1Weak, ref2Weak) = createCyclicGarbageWithAtomicsFrozen()
ref1Owner.value = null
GC.collect()
// If these asserts fail, that means AtomicReference<WorkerBoundReference> managed to clean up cyclic garbage all by itself.
assertNotNull(ref1Weak.value)
assertNotNull(ref2Weak.value)
}
@Test
fun collectCyclicGarbageWithAtomicsFrozen() {
val (ref1Owner, ref1Weak, ref2Weak) = createCyclicGarbageWithAtomicsFrozen()
dispose(ref1Owner)
GC.collect()
assertNull(ref1Weak.value)
assertNull(ref2Weak.value)
}
fun createCrossThreadCyclicGarbageWithAtomicsFrozen(
worker: Worker
): Triple<AtomicReference<WorkerBoundReference<C1>?>, WeakReference<C1>, WeakReference<C2>> {
val ref1 = WorkerBoundReference(C1()).freeze()
val ref1Weak = WeakReference(ref1.value)
val future = worker.execute(TransferMode.SAFE, { ref1 }) { ref1 ->
val ref2 = WorkerBoundReference(C2(AtomicReference(ref1))).freeze()
Pair(ref2, WeakReference(ref2.value))
}
val (ref2, ref2Weak) = future.result
ref1.value.c2 = AtomicReference(ref2)
return Triple(AtomicReference(ref1), ref1Weak, ref2Weak)
}
@Test
fun doesNotCollectCrossThreadCyclicGarbageWithAtomicsFrozen() {
val worker = Worker.start()
val (ref1Owner, ref1Weak, ref2Weak) = createCrossThreadCyclicGarbageWithAtomicsFrozen(worker)
ref1Owner.value = null
GC.collect()
worker.execute(TransferMode.SAFE, {}) { GC.collect() }.result
// If these asserts fail, that means AtomicReference<WorkerBoundReference> managed to clean up cyclic garbage all by itself.
assertNotNull(ref1Weak.value)
assertNotNull(ref2Weak.value)
worker.requestTermination().result
}
@Test
fun collectCrossThreadCyclicGarbageWithAtomicsFrozen() {
val worker = Worker.start()
val (ref1Owner, ref1Weak, ref2Weak) = createCrossThreadCyclicGarbageWithAtomicsFrozen(worker)
dispose(ref1Owner)
// This marks C2 as gone on the main thread
GC.collect()
// This cleans up all the references from the worker thread and destroys C2, but C1 is still alive.
worker.execute(TransferMode.SAFE, {}) { GC.collect() }.result
// And this finally destroys C1
GC.collect()
assertNull(ref1Weak.value)
assertNull(ref2Weak.value)
worker.requestTermination().result
}
@Test
fun concurrentAccessFrozen() {
val workerCount = 10
val workerUnlocker = AtomicInt(0)
val ref = WorkerBoundReference(A(3)).freeze()
assertEquals(3, ref.value.a)
val workers = Array(workerCount) {
Worker.start()
}
val futures = Array(workers.size) {
workers[it].execute(TransferMode.SAFE, { Pair(ref, workerUnlocker) }) { (ref, workerUnlocker) ->
while (workerUnlocker.value < 1) {
}
assertFailsWith<IncorrectDereferenceException> {
ref.value
}
Unit
}
}
workerUnlocker.increment()
for (future in futures) {
future.result
}
for (worker in workers) {
worker.requestTermination().result
}
}
@Test
fun testExceptionMessageFrozen() {
val worker = Worker.start()
val future = worker.execute(TransferMode.SAFE, {}) {
WorkerBoundReference(A(3)).freeze()
}
val value = future.result
val ownerName = worker.name
val messagePattern = Regex("illegal attempt to access non-shared runtime\\.concurrent\\.worker_bound_reference0\\.A@[a-f0-9]+ bound to `$ownerName` from `${Worker.current.name}`")
val exception = assertFailsWith<IncorrectDereferenceException> {
value.value
}
assertTrue(messagePattern matches exception.message!!)
worker.requestTermination().result
}
@Test
fun testDoubleFreeze() {
val ref = WorkerBoundReference(A(3))
val wrapper = Wrapper(ref)
ref.freeze()
ref.freeze()
wrapper.freeze()
}
@Test
fun testDoubleFreezeWithFreezeBlocker() {
val ref = WorkerBoundReference(A(3))
val wrapper = Wrapper(ref)
wrapper.ensureNeverFrozen()
assertFailsWith<FreezingException> {
wrapper.freeze()
}
ref.freeze()
}
@@ -0,0 +1,25 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.exceptions.catch1
import kotlin.test.*
@Test fun runTest() {
try {
println("Before")
foo()
println("After")
} catch (e: Throwable) {
println("Caught Throwable")
}
println("Done")
}
fun foo() {
throw Error("Error happens")
println("After in foo()")
}
@@ -0,0 +1,29 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.exceptions.catch2
import kotlin.test.*
@Test fun runTest() {
try {
println("Before")
foo()
println("After")
} catch (e: Exception) {
println("Caught Exception")
} catch (e: Error) {
println("Caught Error")
} catch (e: Throwable) {
println("Caught Throwable")
}
println("Done")
}
fun foo() {
throw Error("Error happens")
println("After in foo()")
}
@@ -0,0 +1,23 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.exceptions.catch7
import kotlin.test.*
@Test fun runTest() {
try {
foo()
} catch (e: Throwable) {
val message = e.message
if (message != null) {
println(message)
}
}
}
fun foo() {
throw Error("Error happens")
}
@@ -0,0 +1,42 @@
// Checks that on Apple targets first two lines of exception stacktrace of symbolized executable looks like
// "\tat 1 main.kexe\t\t 0x000000010d7cdb4c kfun:package.function(kotlin.Int) + 108 (/path/to/file/name.kt:10:27)\n"
// If test is broken, org.jetbrains.kotlin.idea.filters.KotlinExceptionFilter (in main Kotlin repo) should be updated.
import kotlin.test.*
import kotlin.text.Regex
val EXTENSION = ".kt:"
val LOCATION_PATTERN = Regex("\\d+:\\d+")
fun checkStringFormat(s: String) {
val trimmed = s.trim()
assertTrue(trimmed.endsWith(')'), "Line is not ended with ')'")
assertNotEquals(trimmed.indexOf('('), -1, "No '(' before filename")
val fileName = trimmed.substring(trimmed.lastIndexOf('(') + 1, trimmed.lastIndex)
assertNotEquals(fileName.indexOf(EXTENSION), -1, "Filename 'kt' extension is absent")
val location = fileName.substring(fileName.indexOf(EXTENSION) + EXTENSION.length)
assertTrue(LOCATION_PATTERN.matches(location), "Expected location of form 12:8")
}
fun functionA() {
throw Error("an error")
}
fun functionB() {
functionA()
}
const val depth = 5
fun main(args : Array<String>) {
try {
functionB()
} catch (e: Throwable) {
val stacktrace = e.getStackTrace()
assert(stacktrace.size >= depth)
stacktrace.take(depth).forEach(::checkStringFormat)
}
}
@@ -0,0 +1,22 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
import kotlin.test.*
import kotlin.native.concurrent.*
fun main(args : Array<String>) {
assertFailsWith<InvalidMutabilityException> {
setUnhandledExceptionHook { _ -> println("wrong") }
}
val x = 42
val old = setUnhandledExceptionHook({
throwable: Throwable -> println("value $x: ${throwable::class.simpleName}")
}.freeze())
assertNull(old)
throw Error("an error")
}
@@ -0,0 +1,18 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.exceptions.extend0
import kotlin.test.*
class C : Exception("OK")
@Test fun runTest() {
try {
throw C()
} catch (e: Throwable) {
println(e.message!!)
}
}
@@ -0,0 +1,42 @@
import kotlin.text.Regex
import kotlin.test.*
fun main() {
try {
foo()
} catch (tw:Throwable) {
val stackTrace = tw.getStackTrace()
stackTrace.take(6).forEach(::checkFrame)
}
}
fun foo() {
myRun {
//platform.darwin.NSObject()
throwException()
}
}
inline fun myRun(block: () -> Unit) {
block()
}
fun throwException() {
throw Error()
}
internal val regex = Regex("^(\\d+)\\ +.*/(.*):(\\d+):.*$")
internal val goldValues = arrayOf<Pair<String, Int>?>(
null,
null,
"kt-37572.kt" to 25,
"kt-37572.kt" to 16,
"kt-37572.kt" to 6,
"kt-37572.kt" to 4)
internal fun checkFrame(value:String) {
val (pos, file, line) = regex.find(value)!!.destructured
goldValues[pos.toInt()]?.let{
assertEquals(it.first, file)
assertEquals(it.second, line.toInt())
}
}
@@ -0,0 +1,31 @@
import kotlin.text.Regex
import kotlin.test.*
fun exception() {
error("FAIL!")
}
fun main() {
try {
exception()
}
catch (e:Exception) {
val stackTrace = e.getStackTrace()
stackTrace.take(6).forEach(::checkFrame)
}
}
internal val regex = Regex("^(\\d+)\\ +.*/(.*):(\\d+):.*$")
internal val goldValues = arrayOf<Pair<String, Int>?>(
null,
null,
null,
null,
"stack_trace_inline.kt" to 5,
"stack_trace_inline.kt" to 10)
internal fun checkFrame(value:String) {
val (pos, file, line) = regex.find(value)!!.destructured
goldValues[pos.toInt()]?.let{
assertEquals(it.first, file)
assertEquals(it.second, line.toInt())
}
}
@@ -0,0 +1,19 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.memory.basic0
import kotlin.test.*
class A {
var field: B? = null
}
class B(var field: Int)
@Test fun runTest() {
val a = A()
a.field = B(2)
}
@@ -0,0 +1,190 @@
import kotlin.native.concurrent.*
import kotlin.native.internal.GC
import kotlin.test.*
fun test1() {
val a = AtomicReference<Any?>(null)
val b = AtomicReference<Any?>(null)
a.value = b
b.value = a
}
class Holder(var other: Any?)
fun test2() {
val array = arrayOf(AtomicReference<Any?>(null), AtomicReference<Any?>(null))
val obj1 = Holder(array).freeze()
array[0].value = obj1
}
fun test3() {
val a1 = FreezableAtomicReference<Any?>(null)
val head = Holder(null)
var current = head
repeat(30) {
val next = Holder(null)
current.other = next
current = next
}
a1.value = head
current.other = a1
current.freeze()
}
fun makeIt(): Holder {
val atomic = AtomicReference<Holder?>(null)
val holder = Holder(atomic).freeze()
atomic.value = holder
return holder
}
fun test4() {
val holder = makeIt()
// To clean rc count coming from rememberNewContainer().
kotlin.native.internal.GC.collect()
// Request cyclic collection.
kotlin.native.internal.GC.collectCyclic()
// Ensure we processed delayed release.
repeat(10) {
// Wait a bit and process queue.
Worker.current.park(10)
Worker.current.processQueue()
kotlin.native.internal.GC.collect()
}
val value = @Suppress("UNCHECKED_CAST") (holder.other as? AtomicReference<Holder?>?)
assertTrue(value != null)
assertTrue(value.value == holder)
}
fun createRef(): AtomicReference<Any?> {
val atomic1 = AtomicReference<Any?>(null)
val atomic2 = AtomicReference<Any?>(null)
atomic1.value = atomic2
atomic2.value = atomic1
return atomic1
}
class Holder2(var value: AtomicReference<Any?>) {
fun switch() {
value = value.value as AtomicReference<Any?>
}
}
fun createHolder2() = Holder2(createRef())
fun test5() {
val holder = createHolder2()
kotlin.native.internal.GC.collect()
kotlin.native.internal.GC.collectCyclic()
Worker.current.park(100 * 1000)
holder.switch()
kotlin.native.internal.GC.collect()
Worker.current.park(100 * 1000)
withWorker {
executeAfter(0L, {
kotlin.native.internal.GC.collect()
}.freeze())
}
Worker.current.park(1000)
assertTrue(holder.value.value != null)
}
fun test6() {
val atomic = AtomicReference<Any?>(null)
atomic.value = Pair(atomic, Holder(atomic)).freeze()
}
fun createRoot(): AtomicReference<Any?> {
val ref1 = AtomicReference<Any?>(null)
val ref2 = AtomicReference<Any?>(null)
ref1.value = Holder(ref2).freeze()
ref2.value = Any().freeze()
return ref1
}
fun test7() {
val ref1 = createRoot()
kotlin.native.internal.GC.collect()
kotlin.native.internal.GC.collectCyclic()
Worker.current.park(500 * 1000L)
withWorker {
executeAfter(0L, {}.freeze())
Worker.current.park(500 * 1000L)
val node = ref1.value as Holder
val ref2 = node.other as AtomicReference<Any?>
assertTrue(ref2.value != null)
}
}
fun array(size: Int) = Array<Any?>(size, { null })
fun test8() {
val ref = AtomicReference<Any?>(null)
val obj1 = array(2)
val obj2 = array(1)
val obj3 = array(2)
obj1[0] = obj2
obj1[1] = obj3
obj2[0] = obj3
obj3[0] = obj2
obj3[1] = ref
ref.value = obj1.freeze()
}
fun createNode1(): Holder {
val ref = AtomicReference<Any?>(null)
val node2 = Holder(ref)
val node1 = Holder(node2)
ref.value = node1.freeze()
return node1
}
fun getNode2(): Holder {
val node1 = createNode1()
GC.collect()
return node1.other as Holder
}
fun test9() {
withWorker {
val node2 = getNode2()
executeAfter(10 * 1000L, { GC.collectCyclic() }.freeze())
GC.collect()
Worker.current.park(50 * 1000L)
execute(TransferMode.SAFE, {}, {}).result
val ref = node2.other as AtomicReference<Any?>
assertTrue(ref.value != null)
}
}
fun main() {
kotlin.native.internal.GC.cyclicCollectorEnabled = true
test1()
test2()
test3()
test4()
repeat(10) {
test5()
}
test6()
test7()
test8()
test9()
}
@@ -0,0 +1,16 @@
import kotlin.native.concurrent.*
import kotlin.native.internal.GC
import kotlin.test.*
fun main() {
kotlin.native.internal.GC.cyclicCollectorEnabled = true
repeat(10000) {
// Create atomic cyclic garbage:
val ref = AtomicReference<Any?>(null)
ref.value = ref
}
// main thread will then run cycle collector termination, which involves running it and cleaning everything up.
// 10000 references should hit [kGcThreshold] then.
}
@@ -0,0 +1,193 @@
import kotlin.native.concurrent.*
import kotlin.native.internal.GC
import kotlin.test.*
class Holder(var other: Any?)
class Holder2(var field1: Any?, var field2: Any?)
val <T> Array<T>.description: String
get() {
val result = StringBuilder()
result.append('[')
for (elem in this) {
result.append(elem.toString())
result.append(',')
}
result.append(']')
return result.toString()
}
fun assertArrayEquals(
expected: Array<Any>,
actual: Array<Any>
): Unit {
val lazyMessage: () -> String? = {
"Expected <${expected.description}>, actual <${actual.description}>."
}
asserter.assertTrue(lazyMessage, expected.size == actual.size)
for (i in expected.indices) {
asserter.assertTrue(lazyMessage, expected[i] == actual[i])
}
}
@Test
fun noCycles() {
val atomic1 = AtomicReference<Any?>(null)
val atomic2 = AtomicReference<Any?>(null)
try {
atomic1.value = atomic2
val cycles = GC.detectCycles()!!
assertEquals(0, cycles.size)
assertNull(GC.findCycle(atomic1));
assertNull(GC.findCycle(atomic2));
} finally {
atomic1.value = null
atomic2.value = null
}
}
@Test
fun oneCycle() {
val atomic = AtomicReference<Any?>(null)
try {
atomic.value = atomic
val cycles = GC.detectCycles()!!
assertEquals(1, cycles.size)
assertArrayEquals(arrayOf(atomic, atomic), GC.findCycle(cycles[0])!!)
} finally {
atomic.value = null
}
}
@Test
fun oneCycleWithHolder() {
val atomic = AtomicReference<Any?>(null)
try {
atomic.value = Holder(atomic).freeze()
val cycles = GC.detectCycles()!!
assertEquals(1, cycles.size)
assertArrayEquals(arrayOf(atomic, atomic.value!!, atomic), GC.findCycle(cycles[0])!!)
assertArrayEquals(arrayOf(atomic.value!!, atomic, atomic.value!!), GC.findCycle(atomic.value!!)!!)
} finally {
atomic.value = null
}
}
@Test
fun oneCycleWithArray() {
val array = arrayOf(AtomicReference<Any?>(null), AtomicReference<Any?>(null))
try {
array[0].value = Holder(array).freeze()
val cycles = GC.detectCycles()!!
assertEquals(1, cycles.size)
assertArrayEquals(arrayOf(array[0], array[0].value!!, array, array[0]), GC.findCycle(cycles[0])!!)
} finally {
array[0].value = null
array[1].value = null
}
}
@Test
fun oneCycleWithLongChain() {
val atomic = AtomicReference<Any?>(null)
try {
val head = Holder(null)
var current = head
repeat(30) {
val next = Holder(null)
current.other = next
current = next
}
current.other = atomic
atomic.value = head.freeze()
val cycles = GC.detectCycles()!!
assertEquals(1, cycles.size)
val cycle = GC.findCycle(cycles[0])!!
assertEquals(33, cycle.size)
} finally {
atomic.value = null
}
}
@Test
fun twoCycles() {
val atomic1 = AtomicReference<Any?>(null)
val atomic2 = AtomicReference<Any?>(null)
try {
atomic1.value = atomic2
atomic2.value = atomic1
val cycles = GC.detectCycles()!!
assertEquals(2, cycles.size)
assertArrayEquals(arrayOf(atomic2, atomic1, atomic2), GC.findCycle(cycles[0])!!)
assertArrayEquals(arrayOf(atomic1, atomic2, atomic1), GC.findCycle(cycles[1])!!)
} finally {
atomic1.value = null
atomic2.value = null
}
}
@Test
fun twoCyclesWithHolder() {
val atomic1 = AtomicReference<Any?>(null)
val atomic2 = AtomicReference<Any?>(null)
try {
atomic1.value = atomic2
atomic2.value = Holder(atomic1).freeze()
val cycles = GC.detectCycles()!!
assertEquals(2, cycles.size)
assertArrayEquals(arrayOf(atomic2, atomic2.value!!, atomic1, atomic2), GC.findCycle(cycles[0])!!)
assertArrayEquals(arrayOf(atomic1, atomic2, atomic2.value!!, atomic1), GC.findCycle(cycles[1])!!)
} finally {
atomic1.value = null
atomic2.value = null
}
}
@Test
fun threeSeparateCycles() {
val atomic1 = AtomicReference<Any?>(null)
val atomic2 = AtomicReference<Any?>(null)
val atomic3 = AtomicReference<Any?>(null)
try {
atomic1.value = atomic1
atomic2.value = Holder2(atomic1, atomic2).freeze()
atomic3.value = Holder2(atomic3, atomic1).freeze()
val cycles = GC.detectCycles()!!
assertEquals(3, cycles.size)
assertArrayEquals(arrayOf(atomic3, atomic3.value!!, atomic3), GC.findCycle(cycles[0])!!)
assertArrayEquals(arrayOf(atomic2, atomic2.value!!, atomic2), GC.findCycle(cycles[1])!!)
assertArrayEquals(arrayOf(atomic1, atomic1), GC.findCycle(cycles[2])!!)
} finally {
atomic1.value = null
atomic2.value = null
atomic3.value = null
}
}
@Test
fun noCyclesWithFreezableAtomicReference() {
val atomic = FreezableAtomicReference<Any?>(null)
try {
atomic.value = atomic
val cycles = GC.detectCycles()!!
assertEquals(0, cycles.size)
} finally {
atomic.value = null
}
}
@Test
fun oneCycleWithFrozenFreezableAtomicReference() {
val atomic = FreezableAtomicReference<Any?>(null)
try {
atomic.value = atomic
atomic.freeze()
val cycles = GC.detectCycles()!!
assertEquals(1, cycles.size)
assertArrayEquals(arrayOf(atomic, atomic), GC.findCycle(cycles[0])!!)
} finally {
atomic.value = null
}
}
@@ -0,0 +1,54 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.memory.cycles0
import kotlin.test.*
data class Node(val data: Int, var next: Node?, var prev: Node?, val outer: Node?)
fun makeCycle(len: Int, outer: Node?): Node {
val start = Node(0, null, null, outer)
var prev = start
for (i in 1 .. len - 1) {
prev = Node(i, prev, null, outer)
}
start.next = prev
return start
}
fun makeDoubleCycle(len: Int): Node {
val start = makeCycle(len, null)
var prev = start
var cur = prev.next
while (cur != start) {
cur!!.prev = prev
prev = cur
cur = cur.next
}
start.prev = prev
return start
}
fun createCycles(junk: Node) {
val cycle1 = makeCycle(1, junk)
val cycle2 = makeCycle(2, junk)
val cycle10 = makeCycle(10, junk)
val cycle100 = makeCycle(100, junk)
val dcycle1 = makeDoubleCycle(1)
val dcycle2 = makeDoubleCycle(2)
val dcycle10 = makeDoubleCycle(10)
val dcycle100 = makeDoubleCycle(100)
}
@Test fun runTest() {
// Create outer link from cyclic garbage.
val outer = Node(42, null, null, null)
createCycles(outer)
kotlin.native.internal.GC.collect()
// Ensure outer is not collected.
println(outer.data)
}
@@ -0,0 +1,24 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.memory.cycles1
import kotlin.test.*
import kotlin.native.ref.*
@Test fun runTest() {
// TODO: make it work in relaxed model as well.
if (Platform.memoryModel == MemoryModel.RELAXED) return
val weakRefToTrashCycle = createLoop()
kotlin.native.internal.GC.collect()
assertNull(weakRefToTrashCycle.get())
}
private fun createLoop(): WeakReference<Any> {
val loop = Array<Any?>(1, { null })
loop[0] = loop
return WeakReference(loop)
}
@@ -0,0 +1,62 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.memory.escape0
import kotlin.test.*
//fun foo1(arg: String) : String = foo0(arg)
fun foo1(arg: Any) : Any = foo0(arg)
fun foo0(arg: Any) : Any = Any()
var global : Any = Any()
fun foo0_escape(arg: Any) : Any{
global = arg
return Any()
}
class Node(var previous: Node?)
fun zoo3() : Node {
var current = Node(null)
for (i in 1 .. 5) {
current = Node(current)
}
return current
}
fun zoo4(arg: Int) : Any {
var a = Any()
var b = Any()
var c = Any()
a = b
val x = 3
a = when {
x < arg -> b
else -> c
}
return a
}
fun zoo5(arg: Any) : Any{
foo1(arg)
return arg
}
fun zoo6(arg: Any) : Any {
return zoo7(arg, "foo", 11)
}
fun zoo7(arg1: Any, arg2: Any, selector: Int) : Any {
return if (selector < 2) arg1 else arg2;
}
@Test fun runTest() {
//val z = zoo7(Any(), Any(), 1)
val x = zoo5(Any())
//println(bar(foo1(foo2("")), foo2(foo1(""))))
}
@@ -0,0 +1,23 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.memory.escape1
import kotlin.test.*
class B(val s: String)
class A {
val b = B("zzz")
}
fun foo(): B {
val a = A()
return a.b
}
@Test fun runTest() {
println(foo().s)
}
@@ -0,0 +1,33 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.memory.escape2
import kotlin.test.*
class A(val s: String)
class B {
var a: A? = null
}
class C(val b: B)
fun foo(c: C) {
c.b.a = A("zzz")
}
fun bar(b: B) {
val c = C(b)
foo(c)
}
@ThreadLocal
val global = B()
@Test fun runTest() {
bar(global)
println(global.a!!.s)
}
@@ -0,0 +1,5 @@
import kotlinx.cinterop.*
fun main() {
StableRef.create(Any())
}
@@ -0,0 +1,9 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
fun main(args: Array<String>) {
kotlin.native.internal.GC.collect()
}
@@ -0,0 +1,48 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.memory.stable_ref_cross_thread_check
import kotlin.test.*
import kotlin.native.concurrent.*
import kotlinx.cinterop.*
@Test
fun runTest1() {
val worker = Worker.start()
val future = worker.execute(TransferMode.SAFE, { }) {
StableRef.create(Any())
}
val ref = future.result
assertFailsWith<IncorrectDereferenceException> {
val value = ref.get()
println(value.toString())
}
worker.requestTermination().result
}
@Test
fun runTest2() {
val worker = Worker.start()
val mainThreadRef = StableRef.create(Any())
// Simulate this going through interop as raw C pointer.
val pointerValue: Long = mainThreadRef.asCPointer().toLong()
val future = worker.execute(TransferMode.SAFE, { pointerValue }) {
val pointer: COpaquePointer = it.toCPointer()!!
assertFailsWith<IncorrectDereferenceException> {
// Even attempting to convert a pointer to StableRef should fail.
val otherThreadRef: StableRef<Any> = pointer.asStableRef()
println(otherThreadRef.toString())
}
Unit
}
future.result
worker.requestTermination().result
}
@@ -0,0 +1,25 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.memory.throw_cleanup
import kotlin.test.*
@Test fun runTest() {
foo(false)
try {
foo(true)
} catch (e: Error) {
println("Ok")
}
}
fun foo(b: Boolean): Any {
var result = Any()
if (b) {
throw Error()
}
return result
}
@@ -0,0 +1,62 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.memory.var1
import kotlin.test.*
class Integer(val value: Int) {
operator fun inc() = Integer(value + 1)
}
fun foo(x: Any, y: Any) {
x.use()
y.use()
}
@Test fun runTest1() {
var x = Integer(0)
for (i in 0..1) {
val c = Integer(0)
if (i == 0) x = c
}
// x refcount is 1.
foo(x, ++x)
}
fun Any?.use() {
var x = this
}
@kotlin.native.internal.CanBePrecreated
object CompileTime {
const val int = Int.MIN_VALUE
const val byte = Byte.MIN_VALUE
const val short = Short.MIN_VALUE
const val long = Long.MIN_VALUE
const val boolean = true
const val float = 1.0f
const val double = 1.0
const val char = Char.MIN_VALUE
}
class AClass {
companion object {}
}
@Test fun runTest2() {
assertEquals(Int.MIN_VALUE, CompileTime.int)
assertEquals(Byte.MIN_VALUE, CompileTime.byte)
assertEquals(Short.MIN_VALUE, CompileTime.short)
assertEquals(Long.MIN_VALUE, CompileTime.long)
assertEquals(true, CompileTime.boolean)
assertEquals(1.0f, CompileTime.float)
assertEquals(1.0, CompileTime.double)
assertEquals(Char.MIN_VALUE, CompileTime.char)
}
@@ -0,0 +1,31 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.memory.var2
import kotlin.test.*
@Test fun runTest() {
var x = Any()
for (i in 0..1) {
val c = Any()
if (i == 0) x = c
}
// x refcount is 1.
val y = try {
x
} finally {
x = Any()
}
y.use()
}
fun Any?.use() {
var x = this
}

Some files were not shown because too many files have changed in this diff Show More