Provide protected toArray implementation in AbstractCollection.

Relates to #KT-13898
This commit is contained in:
Ilya Gorbunov
2016-12-24 04:28:32 +03:00
parent bbf61664ea
commit cdfb72ab76
8 changed files with 71 additions and 11 deletions
+17 -1
View File
@@ -27,7 +27,7 @@ public inline fun <T> Collection<T>.toTypedArray(): Array<T> = copyToArray(this)
@JsName("copyToArray")
internal fun <T> copyToArray(collection: Collection<T>): Array<T> {
return if (collection.asDynamic().toArray !== undefined)
collection.asDynamic().toArray()
collection.asDynamic().toArray().unsafeCast<Array<T>>()
else
copyToArrayImpl(collection).unsafeCast<Array<T>>()
}
@@ -41,6 +41,22 @@ internal fun copyToArrayImpl(collection: Collection<*>): Array<Any?> {
return array
}
@JsName("copyToExistingArrayImpl")
internal fun <T> copyToArrayImpl(collection: Collection<*>, array: Array<T>): Array<T> {
if (array.size < collection.size)
return copyToArrayImpl(collection).unsafeCast<Array<T>>()
val iterator = collection.iterator()
var index = 0
while (iterator.hasNext()) {
array[index++] = iterator.next().unsafeCast<T>()
}
if (index < array.size) {
array[index] = null.unsafeCast<T>()
}
return array
}
@library("arrayToString")
internal fun arrayToString(array: Array<*>): String = noImpl
@@ -51,9 +51,6 @@ public abstract class AbstractMutableCollection<E> protected constructor() : Abs
}
}
// TODO: move somehow to AbstractCollection: can't move now, because it cannot be protected on JVM, just public
protected open fun toArray(): Array<Any?> = copyToArrayImpl(this)
open fun toJSON(): Any = this.toArray()
}