stdlib: Provide Collection.toArray() implementation
It also modifies the test for this method to make it to not rely on Kotlin JVM implementation.
This commit is contained in:
@@ -16,6 +16,12 @@
|
||||
|
||||
package kotlin.collections
|
||||
|
||||
/**
|
||||
* Provides a skeletal implementation of the read-only [Collection] interface.
|
||||
*
|
||||
* @param E the type of elements contained in the collection. The collection is covariant on its element type.
|
||||
*/
|
||||
@SinceKotlin("1.1")
|
||||
public abstract class AbstractCollection<out E> protected constructor() : Collection<E> {
|
||||
abstract override val size: Int
|
||||
abstract override fun iterator(): Iterator<E>
|
||||
@@ -31,4 +37,15 @@ public abstract class AbstractCollection<out E> protected constructor() : Collec
|
||||
override fun toString(): String = joinToString(", ", "[", "]") {
|
||||
if (it === this) "(this Collection)" else it.toString()
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns new array of type `Array<Any?>` with the elements of this collection.
|
||||
*/
|
||||
protected open fun toArray(): Array<Any?> = collectionToArray(this)
|
||||
|
||||
/**
|
||||
* Fills the provided [array] or creates new array of the same type
|
||||
* and fills it with the elements of this collection.
|
||||
*/
|
||||
protected open fun <T> toArray(array: Array<T>): Array<T> = collectionToArray(this, array)
|
||||
}
|
||||
|
||||
@@ -55,6 +55,33 @@ fun <E> Array<E>.copyOfNulls(fromIndex: Int, toIndex: Int): Array<E?> {
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies elements of the [collection] into the given [array].
|
||||
* If the array is too small, allocates a new one of collection.size size.
|
||||
* @return [array] with the elements copied from the collection.
|
||||
*/
|
||||
internal fun <E, T> collectionToArray(collection: Collection<E>, array: Array<T>): Array<T> {
|
||||
val toArray = if (collection.size > array.size) {
|
||||
arrayOfUninitializedElements<T>(collection.size)
|
||||
} else {
|
||||
array
|
||||
}
|
||||
var i = 0
|
||||
// TODO: What about a concurrent modification of the collection? Do we need to handle it here?
|
||||
for (v in collection) {
|
||||
toArray[i] = v as T
|
||||
i++
|
||||
}
|
||||
return toArray
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an array of collection.size size and copies elements of the [collection] into it.
|
||||
* @return [array] with the elements copied from the collection.
|
||||
*/
|
||||
internal fun <E> collectionToArray(collection: Collection<E>): Array<E>
|
||||
= collectionToArray(collection, arrayOfUninitializedElements(collection.size))
|
||||
|
||||
/**
|
||||
* Returns new array which is a copy of the original array's range between [fromIndex] (inclusive)
|
||||
* and [toIndex] (exclusive) with new elements filled with **lateinit** _uninitialized_ values.
|
||||
|
||||
Reference in New Issue
Block a user