Reformat stdlib: collections

#KT-5558
This commit is contained in:
Ilya Gorbunov
2018-04-20 21:30:56 +03:00
parent bea94d1d59
commit ad43c0f4cb
34 changed files with 337 additions and 312 deletions
@@ -9,6 +9,7 @@ expect abstract class AbstractMutableList<E> : MutableList<E> {
protected constructor() protected constructor()
// From List // From List
override fun isEmpty(): Boolean override fun isEmpty(): Boolean
override fun contains(element: @UnsafeVariance E): Boolean override fun contains(element: @UnsafeVariance E): Boolean
override fun containsAll(elements: Collection<@UnsafeVariance E>): Boolean override fun containsAll(elements: Collection<@UnsafeVariance E>): Boolean
@@ -16,9 +17,11 @@ expect abstract class AbstractMutableList<E> : MutableList<E> {
override fun lastIndexOf(element: @UnsafeVariance E): Int override fun lastIndexOf(element: @UnsafeVariance E): Int
// From MutableCollection // From MutableCollection
override fun iterator(): MutableIterator<E> override fun iterator(): MutableIterator<E>
// From MutableList // From MutableList
override fun add(element: E): Boolean override fun add(element: E): Boolean
override fun remove(element: E): Boolean override fun remove(element: E): Boolean
override fun addAll(elements: Collection<E>): Boolean override fun addAll(elements: Collection<E>): Boolean
@@ -14,6 +14,7 @@ expect class ArrayList<E> : MutableList<E>, RandomAccess {
fun ensureCapacity(minCapacity: Int) fun ensureCapacity(minCapacity: Int)
// From List // From List
override val size: Int override val size: Int
override fun isEmpty(): Boolean override fun isEmpty(): Boolean
override fun contains(element: @UnsafeVariance E): Boolean override fun contains(element: @UnsafeVariance E): Boolean
@@ -23,9 +24,11 @@ expect class ArrayList<E> : MutableList<E>, RandomAccess {
override fun lastIndexOf(element: @UnsafeVariance E): Int override fun lastIndexOf(element: @UnsafeVariance E): Int
// From MutableCollection // From MutableCollection
override fun iterator(): MutableIterator<E> override fun iterator(): MutableIterator<E>
// From MutableList // From MutableList
override fun add(element: E): Boolean override fun add(element: E): Boolean
override fun remove(element: E): Boolean override fun remove(element: E): Boolean
override fun addAll(elements: Collection<E>): Boolean override fun addAll(elements: Collection<E>): Boolean
@@ -15,8 +15,10 @@ expect inline fun <reified T> Collection<T>.toTypedArray(): Array<T>
@SinceKotlin("1.2") @SinceKotlin("1.2")
expect fun <T> MutableList<T>.fill(value: T): Unit expect fun <T> MutableList<T>.fill(value: T): Unit
@SinceKotlin("1.2") @SinceKotlin("1.2")
expect fun <T> MutableList<T>.shuffle(): Unit expect fun <T> MutableList<T>.shuffle(): Unit
@SinceKotlin("1.2") @SinceKotlin("1.2")
expect fun <T> Iterable<T>.shuffled(): List<T> expect fun <T> Iterable<T>.shuffled(): List<T>
@@ -12,6 +12,7 @@ expect class HashMap<K, V> : MutableMap<K, V> {
constructor(original: Map<out K, V>) constructor(original: Map<out K, V>)
// From Map // From Map
override val size: Int override val size: Int
override fun isEmpty(): Boolean override fun isEmpty(): Boolean
override fun containsKey(key: K): Boolean override fun containsKey(key: K): Boolean
@@ -19,6 +20,7 @@ expect class HashMap<K, V> : MutableMap<K, V> {
override operator fun get(key: K): V? override operator fun get(key: K): V?
// From MutableMap // From MutableMap
override fun put(key: K, value: V): V? override fun put(key: K, value: V): V?
override fun remove(key: K): V? override fun remove(key: K): V?
override fun putAll(from: Map<out K, V>) override fun putAll(from: Map<out K, V>)
@@ -12,12 +12,14 @@ expect class HashSet<E> : MutableSet<E> {
constructor(elements: Collection<E>) constructor(elements: Collection<E>)
// From Set // From Set
override val size: Int override val size: Int
override fun isEmpty(): Boolean override fun isEmpty(): Boolean
override fun contains(element: @UnsafeVariance E): Boolean override fun contains(element: @UnsafeVariance E): Boolean
override fun containsAll(elements: Collection<@UnsafeVariance E>): Boolean override fun containsAll(elements: Collection<@UnsafeVariance E>): Boolean
// From MutableSet // From MutableSet
override fun iterator(): MutableIterator<E> override fun iterator(): MutableIterator<E>
override fun add(element: E): Boolean override fun add(element: E): Boolean
override fun remove(element: E): Boolean override fun remove(element: E): Boolean
@@ -12,6 +12,7 @@ expect class LinkedHashMap<K, V> : MutableMap<K, V> {
constructor(original: Map<out K, V>) constructor(original: Map<out K, V>)
// From Map // From Map
override val size: Int override val size: Int
override fun isEmpty(): Boolean override fun isEmpty(): Boolean
override fun containsKey(key: K): Boolean override fun containsKey(key: K): Boolean
@@ -19,6 +20,7 @@ expect class LinkedHashMap<K, V> : MutableMap<K, V> {
override fun get(key: K): V? override fun get(key: K): V?
// From MutableMap // From MutableMap
override fun put(key: K, value: V): V? override fun put(key: K, value: V): V?
override fun remove(key: K): V? override fun remove(key: K): V?
override fun putAll(from: Map<out K, V>) override fun putAll(from: Map<out K, V>)
@@ -12,12 +12,14 @@ expect class LinkedHashSet<E> : MutableSet<E> {
constructor(elements: Collection<E>) constructor(elements: Collection<E>)
// From Set // From Set
override val size: Int override val size: Int
override fun isEmpty(): Boolean override fun isEmpty(): Boolean
override fun contains(element: @UnsafeVariance E): Boolean override fun contains(element: @UnsafeVariance E): Boolean
override fun containsAll(elements: Collection<@UnsafeVariance E>): Boolean override fun containsAll(elements: Collection<@UnsafeVariance E>): Boolean
// From MutableSet // From MutableSet
override fun iterator(): MutableIterator<E> override fun iterator(): MutableIterator<E>
override fun add(element: E): Boolean override fun add(element: E): Boolean
override fun remove(element: E): Boolean override fun remove(element: E): Boolean
@@ -120,7 +120,7 @@ public actual abstract class AbstractMutableList<E> protected actual constructor
} }
override fun remove() { override fun remove() {
check(last != -1) { "Call next() or previous() before removing element from the iterator."} check(last != -1) { "Call next() or previous() before removing element from the iterator." }
removeAt(last) removeAt(last)
index = last index = last
@@ -158,7 +158,7 @@ public actual abstract class AbstractMutableList<E> protected actual constructor
} }
override fun set(element: E) { override fun set(element: E) {
check(last != -1) { "Call next() or previous() before updating element value with the iterator."} check(last != -1) { "Call next() or previous() before updating element value with the iterator." }
this@AbstractMutableList[last] = element this@AbstractMutableList[last] = element
} }
} }
@@ -46,7 +46,8 @@ public actual abstract class AbstractMutableMap<K, V> protected actual construct
} }
private var _keys: MutableSet<K>? = null private var _keys: MutableSet<K>? = null
override val keys: MutableSet<K> get() { override val keys: MutableSet<K>
get() {
if (_keys == null) { if (_keys == null) {
_keys = object : AbstractMutableSet<K>() { _keys = object : AbstractMutableSet<K>() {
override fun add(element: K): Boolean = throw UnsupportedOperationException("Add is not supported on keys") override fun add(element: K): Boolean = throw UnsupportedOperationException("Add is not supported on keys")
@@ -88,7 +89,8 @@ public actual abstract class AbstractMutableMap<K, V> protected actual construct
} }
private var _values: MutableCollection<V>? = null private var _values: MutableCollection<V>? = null
override val values: MutableCollection<V> get() { override val values: MutableCollection<V>
get() {
if (_values == null) { if (_values == null) {
_values = object : AbstractMutableCollection<V>() { _values = object : AbstractMutableCollection<V>() {
override fun add(element: V): Boolean = throw UnsupportedOperationException("Add is not supported on values") override fun add(element: V): Boolean = throw UnsupportedOperationException("Add is not supported on values")
@@ -113,6 +115,7 @@ public actual abstract class AbstractMutableMap<K, V> protected actual construct
if (other !is Collection<*>) return false if (other !is Collection<*>) return false
return AbstractList.orderedEquals(this, other) return AbstractList.orderedEquals(this, other)
} }
override fun hashCode(): Int = AbstractList.orderedHashCode(this) override fun hashCode(): Int = AbstractList.orderedHashCode(this)
} }
} }
@@ -24,6 +24,7 @@ public actual open class ArrayList<E> internal constructor(private var array: Ar
* @param initialCapacity initial capacity (ignored) * @param initialCapacity initial capacity (ignored)
*/ */
public actual constructor(initialCapacity: Int) : this(emptyArray()) {} public actual constructor(initialCapacity: Int) : this(emptyArray()) {}
/** /**
* Creates an [ArrayList] filled from the [elements] collection. * Creates an [ArrayList] filled from the [elements] collection.
*/ */
@@ -31,6 +32,7 @@ public actual open class ArrayList<E> internal constructor(private var array: Ar
/** Does nothing in this ArrayList implementation. */ /** Does nothing in this ArrayList implementation. */
public actual fun trimToSize() {} public actual fun trimToSize() {}
/** Does nothing in this ArrayList implementation. */ /** Does nothing in this ArrayList implementation. */
public actual fun ensureCapacity(minCapacity: Int) {} public actual fun ensureCapacity(minCapacity: Int) {}
@@ -92,7 +92,8 @@ public actual open class HashMap<K, V> : AbstractMutableMap<K, V>, MutableMap<K,
actual override fun containsValue(value: V): Boolean = internalMap.any { equality.equals(it.value, value) } actual override fun containsValue(value: V): Boolean = internalMap.any { equality.equals(it.value, value) }
private var _entries: MutableSet<MutableMap.MutableEntry<K, V>>? = null private var _entries: MutableSet<MutableMap.MutableEntry<K, V>>? = null
actual override val entries: MutableSet<MutableMap.MutableEntry<K, V>> get() { actual override val entries: MutableSet<MutableMap.MutableEntry<K, V>>
get() {
if (_entries == null) { if (_entries == null) {
_entries = createEntrySet() _entries = createEntrySet()
} }
@@ -36,21 +36,18 @@ internal class InternalHashCodeMap<K, V>(override val equality: EqualityComparat
if (chainOrEntry == null) { if (chainOrEntry == null) {
// This is a new chain, put it to the map. // This is a new chain, put it to the map.
backingMap[hashCode] = SimpleEntry(key, value) backingMap[hashCode] = SimpleEntry(key, value)
} } else {
else {
if (chainOrEntry !is Array<*>) { if (chainOrEntry !is Array<*>) {
// It is an entry // It is an entry
val entry: SimpleEntry<K, V> = chainOrEntry val entry: SimpleEntry<K, V> = chainOrEntry
if (equality.equals(entry.key, key)) { if (equality.equals(entry.key, key)) {
return entry.setValue(value) return entry.setValue(value)
} } else {
else {
backingMap[hashCode] = arrayOf(entry, SimpleEntry(key, value)) backingMap[hashCode] = arrayOf(entry, SimpleEntry(key, value))
size++ size++
return null return null
} }
} } else {
else {
// Chain already exists, perhaps key also exists. // Chain already exists, perhaps key also exists.
val chain: Array<MutableEntry<K, V>> = chainOrEntry val chain: Array<MutableEntry<K, V>> = chainOrEntry
val entry = chain.findEntryInChain(key) val entry = chain.findEntryInChain(key)
@@ -74,12 +71,10 @@ internal class InternalHashCodeMap<K, V>(override val equality: EqualityComparat
deleteProperty(backingMap, hashCode) deleteProperty(backingMap, hashCode)
size-- size--
return entry.value return entry.value
} } else {
else {
return null return null
} }
} } else {
else {
val chain: Array<MutableEntry<K, V>> = chainOrEntry val chain: Array<MutableEntry<K, V>> = chainOrEntry
for (index in chain.indices) { for (index in chain.indices) {
val entry = chain[index] val entry = chain[index]
@@ -116,12 +111,10 @@ internal class InternalHashCodeMap<K, V>(override val equality: EqualityComparat
val entry: MutableEntry<K, V> = chainOrEntry val entry: MutableEntry<K, V> = chainOrEntry
if (equality.equals(entry.key, key)) { if (equality.equals(entry.key, key)) {
return entry return entry
} } else {
else {
return null return null
} }
} } else {
else {
val chain: Array<MutableEntry<K, V>> = chainOrEntry val chain: Array<MutableEntry<K, V>> = chainOrEntry
return chain.findEntryInChain(key) return chain.findEntryInChain(key)
} }
@@ -155,8 +148,7 @@ internal class InternalHashCodeMap<K, V>(override val equality: EqualityComparat
isChain = chainOrEntry is Array<*> isChain = chainOrEntry is Array<*>
itemIndex = 0 itemIndex = 0
return 0 return 0
} } else {
else {
chainOrEntry = null chainOrEntry = null
return 1 return 1
} }
@@ -172,8 +164,7 @@ internal class InternalHashCodeMap<K, V>(override val equality: EqualityComparat
if (!hasNext()) throw NoSuchElementException() if (!hasNext()) throw NoSuchElementException()
val lastEntry = if (isChain) { val lastEntry = if (isChain) {
chainOrEntry.unsafeCast<Array<MutableEntry<K, V>>>()[itemIndex] chainOrEntry.unsafeCast<Array<MutableEntry<K, V>>>()[itemIndex]
} } else {
else {
chainOrEntry.unsafeCast<MutableEntry<K, V>>() chainOrEntry.unsafeCast<MutableEntry<K, V>>()
} }
this.lastEntry = lastEntry this.lastEntry = lastEntry
@@ -52,8 +52,7 @@ internal class InternalStringMap<K, V>(override val equality: EqualityComparator
size++ size++
// structureChanged(host) // structureChanged(host)
return null return null
} } else {
else {
// valueMod++ // valueMod++
return oldValue.unsafeCast<V>() return oldValue.unsafeCast<V>()
} }
@@ -67,8 +66,7 @@ internal class InternalStringMap<K, V>(override val equality: EqualityComparator
size-- size--
// structureChanged(host) // structureChanged(host)
return value.unsafeCast<V>() return value.unsafeCast<V>()
} } else {
else {
// valueMod++ // valueMod++
return null return null
} }
@@ -135,8 +135,7 @@ public actual open class LinkedHashMap<K, V> : HashMap<K, V>, MutableMap<K, V> {
if (this.next === this) { if (this.next === this) {
// if this is single element, remove head // if this is single element, remove head
head = null head = null
} } else {
else {
if (head === this) { if (head === this) {
// if this is first element, move head to next // if this is first element, move head to next
head = next head = next
@@ -225,8 +224,7 @@ public actual open class LinkedHashMap<K, V> : HashMap<K, V>, MutableMap<K, V> {
map.put(key, newEntry) map.put(key, newEntry)
newEntry.addToEnd() newEntry.addToEnd()
return null return null
} } else {
else {
return old.setValue(value) return old.setValue(value)
} }
} }
@@ -29,6 +29,7 @@ public actual open class LinkedHashSet<E> : HashSet<E>, MutableSet<E> {
actual constructor(elements: Collection<E>) : super(LinkedHashMap<E, Any>()) { actual constructor(elements: Collection<E>) : super(LinkedHashMap<E, Any>()) {
addAll(elements) addAll(elements)
} }
/** /**
* Constructs a new empty [LinkedHashSet]. * Constructs a new empty [LinkedHashSet].
* *
@@ -23,6 +23,7 @@ public actual abstract class AbstractMutableList<E> protected actual constructor
* @return the element previously at the specified position. * @return the element previously at the specified position.
*/ */
abstract override fun set(index: Int, element: E): E abstract override fun set(index: Int, element: E): E
/** /**
* Removes an element at the specified [index] from the list. * Removes an element at the specified [index] from the list.
* *
@@ -32,6 +33,7 @@ public actual abstract class AbstractMutableList<E> protected actual constructor
* @return the element that has been removed. * @return the element that has been removed.
*/ */
abstract override fun removeAt(index: Int): E abstract override fun removeAt(index: Int): E
/** /**
* Inserts an element into the list at the specified [index]. * Inserts an element into the list at the specified [index].
* *
@@ -38,8 +38,8 @@ public fun <K, V> mapOf(pair: Pair<K, V>): Map<K, V> = java.util.Collections.sin
*/ */
public inline fun <K, V> ConcurrentMap<K, V>.getOrPut(key: K, defaultValue: () -> V): V { public inline fun <K, V> ConcurrentMap<K, V>.getOrPut(key: K, defaultValue: () -> V): V {
// Do not use computeIfAbsent on JVM8 as it would change locking behavior // Do not use computeIfAbsent on JVM8 as it would change locking behavior
return this.get(key) ?: return this.get(key)
defaultValue().let { default -> this.putIfAbsent(key, default) ?: default } ?: defaultValue().let { default -> this.putIfAbsent(key, default) ?: default }
} }
@@ -57,8 +57,8 @@ public fun <K : Comparable<K>, V> Map<out K, V>.toSortedMap(): SortedMap<K, V> =
* *
* @sample samples.collections.Maps.Transformations.mapToSortedMapWithComparator * @sample samples.collections.Maps.Transformations.mapToSortedMapWithComparator
*/ */
public fun <K, V> Map<out K, V>.toSortedMap(comparator: Comparator<in K>): SortedMap<K, V> public fun <K, V> Map<out K, V>.toSortedMap(comparator: Comparator<in K>): SortedMap<K, V> =
= TreeMap<K, V>(comparator).apply { putAll(this@toSortedMap) } TreeMap<K, V>(comparator).apply { putAll(this@toSortedMap) }
/** /**
* Returns a new [SortedMap] with the specified contents, given as a list of pairs * Returns a new [SortedMap] with the specified contents, given as a list of pairs
@@ -66,8 +66,8 @@ public fun <K, V> Map<out K, V>.toSortedMap(comparator: Comparator<in K>): Sorte
* *
* @sample samples.collections.Maps.Instantiation.sortedMapFromPairs * @sample samples.collections.Maps.Instantiation.sortedMapFromPairs
*/ */
public fun <K : Comparable<K>, V> sortedMapOf(vararg pairs: Pair<K, V>): SortedMap<K, V> public fun <K : Comparable<K>, V> sortedMapOf(vararg pairs: Pair<K, V>): SortedMap<K, V> =
= TreeMap<K, V>().apply { putAll(pairs) } TreeMap<K, V>().apply { putAll(pairs) }
/** /**
@@ -76,8 +76,8 @@ public fun <K : Comparable<K>, V> sortedMapOf(vararg pairs: Pair<K, V>): SortedM
* @sample samples.collections.Maps.Transformations.mapToProperties * @sample samples.collections.Maps.Transformations.mapToProperties
*/ */
@kotlin.internal.InlineOnly @kotlin.internal.InlineOnly
public inline fun Map<String, String>.toProperties(): Properties public inline fun Map<String, String>.toProperties(): Properties =
= Properties().apply { putAll(this@toProperties) } Properties().apply { putAll(this@toProperties) }
// creates a singleton copy of map, if there is specialization available in target platform, otherwise returns itself // creates a singleton copy of map, if there is specialization available in target platform, otherwise returns itself
@@ -85,6 +85,6 @@ public inline fun Map<String, String>.toProperties(): Properties
internal actual inline fun <K, V> Map<K, V>.toSingletonMapOrSelf(): Map<K, V> = toSingletonMap() internal actual inline fun <K, V> Map<K, V>.toSingletonMapOrSelf(): Map<K, V> = toSingletonMap()
// creates a singleton copy of map // creates a singleton copy of map
internal actual fun <K, V> Map<out K, V>.toSingletonMap(): Map<K, V> internal actual fun <K, V> Map<out K, V>.toSingletonMap(): Map<K, V> =
= with (entries.iterator().next()) { java.util.Collections.singletonMap(key, value) } with(entries.iterator().next()) { java.util.Collections.singletonMap(key, value) }
@@ -15,7 +15,7 @@ import kotlin.*
* @sample samples.collections.Sequences.Building.sequenceFromEnumeration * @sample samples.collections.Sequences.Building.sequenceFromEnumeration
*/ */
@kotlin.internal.InlineOnly @kotlin.internal.InlineOnly
public inline fun<T> java.util.Enumeration<T>.asSequence(): Sequence<T> = this.iterator().asSequence() public inline fun <T> java.util.Enumeration<T>.asSequence(): Sequence<T> = this.iterator().asSequence()
internal actual class ConstrainedOnceSequence<T> actual constructor(sequence: Sequence<T>) : Sequence<T> { internal actual class ConstrainedOnceSequence<T> actual constructor(sequence: Sequence<T>) : Sequence<T> {
@@ -7,7 +7,7 @@ package kotlin.collections
/** /**
* Provides a skeletal implementation of the read-only [Collection] interface. * 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. * @param E the type of elements contained in the collection. The collection is covariant on its element type.
*/ */
@SinceKotlin("1.1") @SinceKotlin("1.1")
public abstract class AbstractCollection<out E> protected constructor() : Collection<E> { public abstract class AbstractCollection<out E> protected constructor() : Collection<E> {
@@ -17,7 +17,7 @@ private enum class State {
* A base class to simplify implementing iterators so that implementations only have to implement [computeNext] * A base class to simplify implementing iterators so that implementations only have to implement [computeNext]
* to implement the iterator, calling [done] when the iteration is complete. * to implement the iterator, calling [done] when the iteration is complete.
*/ */
public abstract class AbstractIterator<T>: Iterator<T> { public abstract class AbstractIterator<T> : Iterator<T> {
private var state = State.NotReady private var state = State.NotReady
private var nextValue: T? = null private var nextValue: T? = null
@@ -16,7 +16,7 @@ package kotlin.collections
* *
* @param K the type of map keys. The map is invariant on its key type. * @param K the type of map keys. The map is invariant on its key type.
* @param V the type of map values. The map is covariant on its value type. * @param V the type of map values. The map is covariant on its value type.
*/ */
@SinceKotlin("1.1") @SinceKotlin("1.1")
public abstract class AbstractMap<K, out V> protected constructor() : Map<K, V> { public abstract class AbstractMap<K, out V> protected constructor() : Map<K, V> {
@@ -78,8 +78,8 @@ public abstract class AbstractMap<K, out V> protected constructor() : Map<K, V>
* Accessing this property first time creates a keys view from [entries]. * Accessing this property first time creates a keys view from [entries].
* All subsequent accesses just return the created instance. * All subsequent accesses just return the created instance.
*/ */
private @kotlin.jvm.Volatile var _keys: Set<K>? = null override val keys: Set<K>
override val keys: Set<K> get() { get() {
if (_keys == null) { if (_keys == null) {
_keys = object : AbstractSet<K>() { _keys = object : AbstractSet<K>() {
override operator fun contains(element: K): Boolean = containsKey(element) override operator fun contains(element: K): Boolean = containsKey(element)
@@ -98,6 +98,10 @@ public abstract class AbstractMap<K, out V> protected constructor() : Map<K, V>
return _keys!! return _keys!!
} }
@kotlin.jvm.Volatile
private var _keys: Set<K>? = null
override fun toString(): String = entries.joinToString(", ", "{", "}") { toString(it) } override fun toString(): String = entries.joinToString(", ", "{", "}") { toString(it) }
private fun toString(entry: Map.Entry<K, V>): String = toString(entry.key) + "=" + toString(entry.value) private fun toString(entry: Map.Entry<K, V>): String = toString(entry.key) + "=" + toString(entry.value)
@@ -110,8 +114,8 @@ public abstract class AbstractMap<K, out V> protected constructor() : Map<K, V>
* Accessing this property first time creates a values view from [entries]. * Accessing this property first time creates a values view from [entries].
* All subsequent accesses just return the created instance. * All subsequent accesses just return the created instance.
*/ */
private @kotlin.jvm.Volatile var _values: Collection<V>? = null override val values: Collection<V>
override val values: Collection<V> get() { get() {
if (_values == null) { if (_values == null) {
_values = object : AbstractCollection<V>() { _values = object : AbstractCollection<V>() {
override operator fun contains(element: @UnsafeVariance V): Boolean = containsValue(element) override operator fun contains(element: @UnsafeVariance V): Boolean = containsValue(element)
@@ -130,6 +134,9 @@ public abstract class AbstractMap<K, out V> protected constructor() : Map<K, V>
return _values!! return _values!!
} }
@kotlin.jvm.Volatile
private var _values: Collection<V>? = null
private fun implFindEntry(key: K): Map.Entry<K, V>? = entries.firstOrNull { it.key == key } private fun implFindEntry(key: K): Map.Entry<K, V>? = entries.firstOrNull { it.key == key }
internal companion object { internal companion object {
@@ -10,7 +10,6 @@
package kotlin.collections package kotlin.collections
/** /**
* Returns a single list of all elements from all arrays in the given array. * Returns a single list of all elements from all arrays in the given array.
* @sample samples.collections.Arrays.Transformations.flattenArray * @sample samples.collections.Arrays.Transformations.flattenArray
@@ -53,7 +53,7 @@ internal object EmptyList : List<Nothing>, Serializable, RandomAccess {
internal fun <T> Array<out T>.asCollection(): Collection<T> = ArrayAsCollection(this, isVarargs = false) internal fun <T> Array<out T>.asCollection(): Collection<T> = ArrayAsCollection(this, isVarargs = false)
private class ArrayAsCollection<T>(val values: Array<out T>, val isVarargs: Boolean): Collection<T> { private class ArrayAsCollection<T>(val values: Array<out T>, val isVarargs: Boolean) : Collection<T> {
override val size: Int get() = values.size override val size: Int get() = values.size
override fun isEmpty(): Boolean = values.isEmpty() override fun isEmpty(): Boolean = values.isEmpty()
override fun contains(element: T): Boolean = values.contains(element) override fun contains(element: T): Boolean = values.contains(element)
@@ -102,15 +102,15 @@ public inline fun <T> arrayListOf(): ArrayList<T> = ArrayList()
* Returns a new [MutableList] with the given elements. * Returns a new [MutableList] with the given elements.
* @sample samples.collections.Collections.Lists.mutableList * @sample samples.collections.Collections.Lists.mutableList
*/ */
public fun <T> mutableListOf(vararg elements: T): MutableList<T> public fun <T> mutableListOf(vararg elements: T): MutableList<T> =
= if (elements.size == 0) ArrayList() else ArrayList(ArrayAsCollection(elements, isVarargs = true)) if (elements.size == 0) ArrayList() else ArrayList(ArrayAsCollection(elements, isVarargs = true))
/** /**
* Returns a new [ArrayList] with the given elements. * Returns a new [ArrayList] with the given elements.
* @sample samples.collections.Collections.Lists.arrayList * @sample samples.collections.Collections.Lists.arrayList
*/ */
public fun <T> arrayListOf(vararg elements: T): ArrayList<T> public fun <T> arrayListOf(vararg elements: T): ArrayList<T> =
= if (elements.size == 0) ArrayList() else ArrayList(ArrayAsCollection(elements, isVarargs = true)) if (elements.size == 0) ArrayList() else ArrayList(ArrayAsCollection(elements, isVarargs = true))
/** /**
* Returns a new read-only list either of single given element, if it is not null, or empty list if the element is null. The returned list is serializable (JVM). * Returns a new read-only list either of single given element, if it is not null, or empty list if the element is null. The returned list is serializable (JVM).
@@ -214,7 +214,7 @@ internal fun <T> List<T>.optimizeReadOnlyList() = when (size) {
* @sample samples.collections.Collections.Lists.binarySearchOnComparable * @sample samples.collections.Collections.Lists.binarySearchOnComparable
* @sample samples.collections.Collections.Lists.binarySearchWithBoundaries * @sample samples.collections.Collections.Lists.binarySearchWithBoundaries
*/ */
public fun <T: Comparable<T>> List<T?>.binarySearch(element: T?, fromIndex: Int = 0, toIndex: Int = size): Int { public fun <T : Comparable<T>> List<T?>.binarySearch(element: T?, fromIndex: Int = 0, toIndex: Int = size): Int {
rangeCheck(size, fromIndex, toIndex) rangeCheck(size, fromIndex, toIndex)
var low = fromIndex var low = fromIndex
@@ -287,7 +287,12 @@ public fun <T> List<T>.binarySearch(element: T, comparator: Comparator<in T>, fr
* so that the list (or the specified subrange of list) still remains sorted. * so that the list (or the specified subrange of list) still remains sorted.
* @sample samples.collections.Collections.Lists.binarySearchByKey * @sample samples.collections.Collections.Lists.binarySearchByKey
*/ */
public inline fun <T, K : Comparable<K>> List<T>.binarySearchBy(key: K?, fromIndex: Int = 0, toIndex: Int = size, crossinline selector: (T) -> K?): Int = public inline fun <T, K : Comparable<K>> List<T>.binarySearchBy(
key: K?,
fromIndex: Int = 0,
toIndex: Int = size,
crossinline selector: (T) -> K?
): Int =
binarySearch(fromIndex, toIndex) { compareValues(selector(it), key) } binarySearch(fromIndex, toIndex) { compareValues(selector(it), key) }
// do not introduce this overload --- too rare // do not introduce this overload --- too rare
@@ -4,6 +4,7 @@
*/ */
@file:kotlin.jvm.JvmMultifileClass @file:kotlin.jvm.JvmMultifileClass
@file:kotlin.jvm.JvmName("CollectionsKt") @file:kotlin.jvm.JvmName("CollectionsKt")
package kotlin.collections package kotlin.collections
/** /**
@@ -42,7 +43,7 @@ private fun <T> Collection<T>.safeToConvertToSet() = size > 2 && this is ArrayLi
/** Converts this collection to a set, when it's worth so and it doesn't change contains method behavior. */ /** Converts this collection to a set, when it's worth so and it doesn't change contains method behavior. */
internal fun <T> Iterable<T>.convertToSetForSetOperationWith(source: Iterable<T>): Collection<T> = internal fun <T> Iterable<T>.convertToSetForSetOperationWith(source: Iterable<T>): Collection<T> =
when(this) { when (this) {
is Set -> this is Set -> this
is Collection -> is Collection ->
when { when {
@@ -54,7 +55,7 @@ internal fun <T> Iterable<T>.convertToSetForSetOperationWith(source: Iterable<T>
/** Converts this collection to a set, when it's worth so and it doesn't change contains method behavior. */ /** Converts this collection to a set, when it's worth so and it doesn't change contains method behavior. */
internal fun <T> Iterable<T>.convertToSetForSetOperation(): Collection<T> = internal fun <T> Iterable<T>.convertToSetForSetOperation(): Collection<T> =
when(this) { when (this) {
is Set -> this is Set -> this
is Collection -> if (this.safeToConvertToSet()) toHashSet() else this is Collection -> if (this.safeToConvertToSet()) toHashSet() else this
else -> toHashSet() else -> toHashSet()
@@ -27,7 +27,7 @@ public fun <T> Iterator<T>.withIndex(): Iterator<IndexedValue<T>> = IndexingIter
* Performs the given [operation] on each element of this [Iterator]. * Performs the given [operation] on each element of this [Iterator].
* @sample samples.collections.Iterators.forEachIterator * @sample samples.collections.Iterators.forEachIterator
*/ */
public inline fun <T> Iterator<T>.forEach(operation: (T) -> Unit) : Unit { public inline fun <T> Iterator<T>.forEach(operation: (T) -> Unit): Unit {
for (element in this) operation(element) for (element in this) operation(element)
} }
@@ -4,6 +4,7 @@
*/ */
@file:kotlin.jvm.JvmName("MapAccessorsKt") @file:kotlin.jvm.JvmName("MapAccessorsKt")
package kotlin.collections package kotlin.collections
import kotlin.reflect.KProperty import kotlin.reflect.KProperty
@@ -18,8 +19,8 @@ import kotlin.internal.Exact
* @throws NoSuchElementException when the map doesn't contain value for the property name and doesn't provide an implicit default (see [withDefault]). * @throws NoSuchElementException when the map doesn't contain value for the property name and doesn't provide an implicit default (see [withDefault]).
*/ */
@kotlin.internal.InlineOnly @kotlin.internal.InlineOnly
public inline operator fun <V, V1: V> Map<in String, @Exact V>.getValue(thisRef: Any?, property: KProperty<*>): V1 public inline operator fun <V, V1 : V> Map<in String, @Exact V>.getValue(thisRef: Any?, property: KProperty<*>): V1 =
= @Suppress("UNCHECKED_CAST") (getOrImplicitDefault(property.name) as V1) @Suppress("UNCHECKED_CAST") (getOrImplicitDefault(property.name) as V1)
/** /**
* Returns the value of the property for the given object from this mutable map. * Returns the value of the property for the given object from this mutable map.
@@ -31,15 +32,15 @@ public inline operator fun <V, V1: V> Map<in String, @Exact V>.getValue(thisRef:
*/ */
@kotlin.jvm.JvmName("getVar") @kotlin.jvm.JvmName("getVar")
@kotlin.internal.InlineOnly @kotlin.internal.InlineOnly
public inline operator fun <V, V1: V> MutableMap<in String, out @Exact V>.getValue(thisRef: Any?, property: KProperty<*>): V1 public inline operator fun <V, V1 : V> MutableMap<in String, out @Exact V>.getValue(thisRef: Any?, property: KProperty<*>): V1 =
= @Suppress("UNCHECKED_CAST") (getOrImplicitDefault(property.name) as V1) @Suppress("UNCHECKED_CAST") (getOrImplicitDefault(property.name) as V1)
@Deprecated("Use getValue() with two type parameters instead") @Deprecated("Use getValue() with two type parameters instead")
@kotlin.jvm.JvmName("getVarContravariant") @kotlin.jvm.JvmName("getVarContravariant")
@kotlin.internal.LowPriorityInOverloadResolution @kotlin.internal.LowPriorityInOverloadResolution
@kotlin.internal.InlineOnly @kotlin.internal.InlineOnly
public inline fun <V> MutableMap<in String, in V>.getValue(thisRef: Any?, property: KProperty<*>): V public inline fun <V> MutableMap<in String, in V>.getValue(thisRef: Any?, property: KProperty<*>): V =
= @Suppress("UNCHECKED_CAST") (getOrImplicitDefault(property.name) as V) @Suppress("UNCHECKED_CAST") (getOrImplicitDefault(property.name) as V)
/** /**
* Stores the value of the property for the given object in this mutable map. * Stores the value of the property for the given object in this mutable map.
@@ -54,20 +54,17 @@ public fun <K, V> MutableMap<K, V>.withDefault(defaultValue: (key: K) -> V): Mut
} }
private interface MapWithDefault<K, out V> : Map<K, V> {
private interface MapWithDefault<K, out V>: Map<K, V> {
public val map: Map<K, V> public val map: Map<K, V>
public fun getOrImplicitDefault(key: K): V public fun getOrImplicitDefault(key: K): V
} }
private interface MutableMapWithDefault<K, V>: MutableMap<K, V>, MapWithDefault<K, V> { private interface MutableMapWithDefault<K, V> : MutableMap<K, V>, MapWithDefault<K, V> {
public override val map: MutableMap<K, V> public override val map: MutableMap<K, V>
} }
private class MapWithDefaultImpl<K, out V>(public override val map: Map<K,V>, private val default: (key: K) -> V) : MapWithDefault<K, V> { private class MapWithDefaultImpl<K, out V>(public override val map: Map<K, V>, private val default: (key: K) -> V) : MapWithDefault<K, V> {
override fun equals(other: Any?): Boolean = map.equals(other) override fun equals(other: Any?): Boolean = map.equals(other)
override fun hashCode(): Int = map.hashCode() override fun hashCode(): Int = map.hashCode()
override fun toString(): String = map.toString() override fun toString(): String = map.toString()
@@ -83,7 +80,7 @@ private class MapWithDefaultImpl<K, out V>(public override val map: Map<K,V>, pr
override fun getOrImplicitDefault(key: K): V = map.getOrElseNullable(key, { default(key) }) override fun getOrImplicitDefault(key: K): V = map.getOrElseNullable(key, { default(key) })
} }
private class MutableMapWithDefaultImpl<K, V>(public override val map: MutableMap<K, V>, private val default: (key: K) -> V): MutableMapWithDefault<K, V> { private class MutableMapWithDefaultImpl<K, V>(public override val map: MutableMap<K, V>, private val default: (key: K) -> V) : MutableMapWithDefault<K, V> {
override fun equals(other: Any?): Boolean = map.equals(other) override fun equals(other: Any?): Boolean = map.equals(other)
override fun hashCode(): Int = map.hashCode() override fun hashCode(): Int = map.hashCode()
override fun toString(): String = map.toString() override fun toString(): String = map.toString()
+44 -45
View File
@@ -11,7 +11,7 @@ package kotlin.collections
private object EmptyMap : Map<Any?, Nothing>, Serializable { private object EmptyMap : Map<Any?, Nothing>, Serializable {
private const val serialVersionUID: Long = 8246714829545688274 private const val serialVersionUID: Long = 8246714829545688274
override fun equals(other: Any?): Boolean = other is Map<*,*> && other.isEmpty() override fun equals(other: Any?): Boolean = other is Map<*, *> && other.isEmpty()
override fun hashCode(): Int = 0 override fun hashCode(): Int = 0
override fun toString(): String = "{}" override fun toString(): String = "{}"
@@ -48,7 +48,8 @@ public fun <K, V> emptyMap(): Map<K, V> = @Suppress("UNCHECKED_CAST") (EmptyMap
* *
* @sample samples.collections.Maps.Instantiation.mapFromPairs * @sample samples.collections.Maps.Instantiation.mapFromPairs
*/ */
public fun <K, V> mapOf(vararg pairs: Pair<K, V>): Map<K, V> = if (pairs.size > 0) pairs.toMap(LinkedHashMap(mapCapacity(pairs.size))) else emptyMap() public fun <K, V> mapOf(vararg pairs: Pair<K, V>): Map<K, V> =
if (pairs.size > 0) pairs.toMap(LinkedHashMap(mapCapacity(pairs.size))) else emptyMap()
/** /**
* Returns an empty read-only map. * Returns an empty read-only map.
@@ -80,8 +81,8 @@ public inline fun <K, V> mutableMapOf(): MutableMap<K, V> = LinkedHashMap()
* @sample samples.collections.Maps.Instantiation.mutableMapFromPairs * @sample samples.collections.Maps.Instantiation.mutableMapFromPairs
* @sample samples.collections.Maps.Instantiation.emptyMutableMap * @sample samples.collections.Maps.Instantiation.emptyMutableMap
*/ */
public fun <K, V> mutableMapOf(vararg pairs: Pair<K, V>): MutableMap<K, V> public fun <K, V> mutableMapOf(vararg pairs: Pair<K, V>): MutableMap<K, V> =
= LinkedHashMap<K, V>(mapCapacity(pairs.size)).apply { putAll(pairs) } LinkedHashMap<K, V>(mapCapacity(pairs.size)).apply { putAll(pairs) }
/** /**
* Returns an empty new [HashMap]. * Returns an empty new [HashMap].
@@ -96,8 +97,7 @@ public inline fun <K, V> hashMapOf(): HashMap<K, V> = HashMap<K, V>()
* *
* @sample samples.collections.Maps.Instantiation.hashMapFromPairs * @sample samples.collections.Maps.Instantiation.hashMapFromPairs
*/ */
public fun <K, V> hashMapOf(vararg pairs: Pair<K, V>): HashMap<K, V> public fun <K, V> hashMapOf(vararg pairs: Pair<K, V>): HashMap<K, V> = HashMap<K, V>(mapCapacity(pairs.size)).apply { putAll(pairs) }
= HashMap<K, V>(mapCapacity(pairs.size)).apply { putAll(pairs) }
/** /**
* Returns an empty new [LinkedHashMap]. * Returns an empty new [LinkedHashMap].
@@ -116,8 +116,7 @@ public inline fun <K, V> linkedMapOf(): LinkedHashMap<K, V> = LinkedHashMap<K, V
* *
* @sample samples.collections.Maps.Instantiation.linkedMapFromPairs * @sample samples.collections.Maps.Instantiation.linkedMapFromPairs
*/ */
public fun <K, V> linkedMapOf(vararg pairs: Pair<K, V>): LinkedHashMap<K, V> public fun <K, V> linkedMapOf(vararg pairs: Pair<K, V>): LinkedHashMap<K, V> = pairs.toMap(LinkedHashMap(mapCapacity(pairs.size)))
= pairs.toMap(LinkedHashMap(mapCapacity(pairs.size)))
/** /**
* Calculate the initial capacity of a map, based on Guava's com.google.common.collect.Maps approach. This is equivalent * Calculate the initial capacity of a map, based on Guava's com.google.common.collect.Maps approach. This is equivalent
@@ -145,7 +144,7 @@ public inline fun <K, V> Map<out K, V>.isNotEmpty(): Boolean = !isEmpty()
* Returns the [Map] if its not `null`, or the empty [Map] otherwise. * Returns the [Map] if its not `null`, or the empty [Map] otherwise.
*/ */
@kotlin.internal.InlineOnly @kotlin.internal.InlineOnly
public inline fun <K, V> Map<K, V>?.orEmpty() : Map<K, V> = this ?: emptyMap() public inline fun <K, V> Map<K, V>?.orEmpty(): Map<K, V> = this ?: emptyMap()
/** /**
* Checks if the map contains the given key. * Checks if the map contains the given key.
@@ -153,14 +152,14 @@ public inline fun <K, V> Map<K, V>?.orEmpty() : Map<K, V> = this ?: emptyMap()
* This method allows to use the `x in map` syntax for checking whether an object is contained in the map. * This method allows to use the `x in map` syntax for checking whether an object is contained in the map.
*/ */
@kotlin.internal.InlineOnly @kotlin.internal.InlineOnly
public inline operator fun <@kotlin.internal.OnlyInputTypes K, V> Map<out K, V>.contains(key: K) : Boolean = containsKey(key) public inline operator fun <@kotlin.internal.OnlyInputTypes K, V> Map<out K, V>.contains(key: K): Boolean = containsKey(key)
/** /**
* Returns the value corresponding to the given [key], or `null` if such a key is not present in the map. * Returns the value corresponding to the given [key], or `null` if such a key is not present in the map.
*/ */
@kotlin.internal.InlineOnly @kotlin.internal.InlineOnly
public inline operator fun <@kotlin.internal.OnlyInputTypes K, V> Map<out K, V>.get(key: K): V? public inline operator fun <@kotlin.internal.OnlyInputTypes K, V> Map<out K, V>.get(key: K): V? =
= @Suppress("UNCHECKED_CAST") (this as Map<K, V>).get(key) @Suppress("UNCHECKED_CAST") (this as Map<K, V>).get(key)
/** /**
* Allows to use the index operator for storing values in a mutable map. * Allows to use the index operator for storing values in a mutable map.
@@ -176,8 +175,8 @@ public inline operator fun <K, V> MutableMap<K, V>.set(key: K, value: V): Unit {
* Allows to overcome type-safety restriction of `containsKey` that requires to pass a key of type `K`. * Allows to overcome type-safety restriction of `containsKey` that requires to pass a key of type `K`.
*/ */
@kotlin.internal.InlineOnly @kotlin.internal.InlineOnly
public inline fun <@kotlin.internal.OnlyInputTypes K> Map<out K, *>.containsKey(key: K): Boolean public inline fun <@kotlin.internal.OnlyInputTypes K> Map<out K, *>.containsKey(key: K): Boolean =
= @Suppress("UNCHECKED_CAST") (this as Map<K, *>).containsKey(key) @Suppress("UNCHECKED_CAST") (this as Map<K, *>).containsKey(key)
/** /**
* Returns `true` if the map maps one or more keys to the specified [value]. * Returns `true` if the map maps one or more keys to the specified [value].
@@ -197,8 +196,8 @@ public inline fun <K, @kotlin.internal.OnlyInputTypes V> Map<K, V>.containsValue
* Allows to overcome type-safety restriction of `remove` that requires to pass a key of type `K`. * Allows to overcome type-safety restriction of `remove` that requires to pass a key of type `K`.
*/ */
@kotlin.internal.InlineOnly @kotlin.internal.InlineOnly
public inline fun <@kotlin.internal.OnlyInputTypes K, V> MutableMap<out K, V>.remove(key: K): V? public inline fun <@kotlin.internal.OnlyInputTypes K, V> MutableMap<out K, V>.remove(key: K): V? =
= @Suppress("UNCHECKED_CAST") (this as MutableMap<K, V>).remove(key) @Suppress("UNCHECKED_CAST") (this as MutableMap<K, V>).remove(key)
/** /**
* Returns the key component of the map entry. * Returns the key component of the map entry.
@@ -327,7 +326,7 @@ public fun <K, V> MutableMap<in K, in V>.putAll(pairs: Array<out Pair<K, V>>): U
/** /**
* Puts all the elements of the given collection into this [MutableMap] with the first component in the pair being the key and the second the value. * Puts all the elements of the given collection into this [MutableMap] with the first component in the pair being the key and the second the value.
*/ */
public fun <K, V> MutableMap<in K, in V>.putAll(pairs: Iterable<Pair<K,V>>): Unit { public fun <K, V> MutableMap<in K, in V>.putAll(pairs: Iterable<Pair<K, V>>): Unit {
for ((key, value) in pairs) { for ((key, value) in pairs) {
put(key, value) put(key, value)
} }
@@ -336,7 +335,7 @@ public fun <K, V> MutableMap<in K, in V>.putAll(pairs: Iterable<Pair<K,V>>): Uni
/** /**
* Puts all the elements of the given sequence into this [MutableMap] with the first component in the pair being the key and the second the value. * Puts all the elements of the given sequence into this [MutableMap] with the first component in the pair being the key and the second the value.
*/ */
public fun <K, V> MutableMap<in K, in V>.putAll(pairs: Sequence<Pair<K,V>>): Unit { public fun <K, V> MutableMap<in K, in V>.putAll(pairs: Sequence<Pair<K, V>>): Unit {
for ((key, value) in pairs) { for ((key, value) in pairs) {
put(key, value) put(key, value)
} }
@@ -471,15 +470,15 @@ public fun <K, V> Iterable<Pair<K, V>>.toMap(): Map<K, V> {
/** /**
* Populates and returns the [destination] mutable map with key-value pairs from the given collection of pairs. * Populates and returns the [destination] mutable map with key-value pairs from the given collection of pairs.
*/ */
public fun <K, V, M : MutableMap<in K, in V>> Iterable<Pair<K, V>>.toMap(destination: M): M public fun <K, V, M : MutableMap<in K, in V>> Iterable<Pair<K, V>>.toMap(destination: M): M =
= destination.apply { putAll(this@toMap) } destination.apply { putAll(this@toMap) }
/** /**
* Returns a new map containing all key-value pairs from the given array of pairs. * Returns a new map containing all key-value pairs from the given array of pairs.
* *
* The returned map preserves the entry iteration order of the original array. * The returned map preserves the entry iteration order of the original array.
*/ */
public fun <K, V> Array<out Pair<K, V>>.toMap(): Map<K, V> = when(size) { public fun <K, V> Array<out Pair<K, V>>.toMap(): Map<K, V> = when (size) {
0 -> emptyMap() 0 -> emptyMap()
1 -> mapOf(this[0]) 1 -> mapOf(this[0])
else -> toMap(LinkedHashMap<K, V>(mapCapacity(size))) else -> toMap(LinkedHashMap<K, V>(mapCapacity(size)))
@@ -488,8 +487,8 @@ public fun <K, V> Array<out Pair<K, V>>.toMap(): Map<K, V> = when(size) {
/** /**
* Populates and returns the [destination] mutable map with key-value pairs from the given array of pairs. * Populates and returns the [destination] mutable map with key-value pairs from the given array of pairs.
*/ */
public fun <K, V, M : MutableMap<in K, in V>> Array<out Pair<K, V>>.toMap(destination: M): M public fun <K, V, M : MutableMap<in K, in V>> Array<out Pair<K, V>>.toMap(destination: M): M =
= destination.apply { putAll(this@toMap) } destination.apply { putAll(this@toMap) }
/** /**
* Returns a new map containing all key-value pairs from the given sequence of pairs. * Returns a new map containing all key-value pairs from the given sequence of pairs.
@@ -501,8 +500,8 @@ public fun <K, V> Sequence<Pair<K, V>>.toMap(): Map<K, V> = toMap(LinkedHashMap<
/** /**
* Populates and returns the [destination] mutable map with key-value pairs from the given sequence of pairs. * Populates and returns the [destination] mutable map with key-value pairs from the given sequence of pairs.
*/ */
public fun <K, V, M : MutableMap<in K, in V>> Sequence<Pair<K, V>>.toMap(destination: M): M public fun <K, V, M : MutableMap<in K, in V>> Sequence<Pair<K, V>>.toMap(destination: M): M =
= destination.apply { putAll(this@toMap) } destination.apply { putAll(this@toMap) }
/** /**
* Returns a new read-only map containing all key-value pairs from the original map. * Returns a new read-only map containing all key-value pairs from the original map.
@@ -528,8 +527,8 @@ public fun <K, V> Map<out K, V>.toMutableMap(): MutableMap<K, V> = LinkedHashMap
* Populates and returns the [destination] mutable map with key-value pairs from the given map. * Populates and returns the [destination] mutable map with key-value pairs from the given map.
*/ */
@SinceKotlin("1.1") @SinceKotlin("1.1")
public fun <K, V, M : MutableMap<in K, in V>> Map<out K, V>.toMap(destination: M): M public fun <K, V, M : MutableMap<in K, in V>> Map<out K, V>.toMap(destination: M): M =
= destination.apply { putAll(this@toMap) } destination.apply { putAll(this@toMap) }
/** /**
* Creates a new read-only map by replacing or adding an entry to this map from a given key-value [pair]. * Creates a new read-only map by replacing or adding an entry to this map from a given key-value [pair].
@@ -537,8 +536,8 @@ public fun <K, V, M : MutableMap<in K, in V>> Map<out K, V>.toMap(destination: M
* The returned map preserves the entry iteration order of the original map. * The returned map preserves the entry iteration order of the original map.
* The [pair] is iterated in the end if it has a unique key. * The [pair] is iterated in the end if it has a unique key.
*/ */
public operator fun <K, V> Map<out K, V>.plus(pair: Pair<K, V>): Map<K, V> public operator fun <K, V> Map<out K, V>.plus(pair: Pair<K, V>): Map<K, V> =
= if (this.isEmpty()) mapOf(pair) else LinkedHashMap(this).apply { put(pair.first, pair.second) } if (this.isEmpty()) mapOf(pair) else LinkedHashMap(this).apply { put(pair.first, pair.second) }
/** /**
* Creates a new read-only map by replacing or adding entries to this map from a given collection of key-value [pairs]. * Creates a new read-only map by replacing or adding entries to this map from a given collection of key-value [pairs].
@@ -546,8 +545,8 @@ public operator fun <K, V> Map<out K, V>.plus(pair: Pair<K, V>): Map<K, V>
* The returned map preserves the entry iteration order of the original map. * The returned map preserves the entry iteration order of the original map.
* Those [pairs] with unique keys are iterated in the end in the order of [pairs] collection. * Those [pairs] with unique keys are iterated in the end in the order of [pairs] collection.
*/ */
public operator fun <K, V> Map<out K, V>.plus(pairs: Iterable<Pair<K, V>>): Map<K, V> public operator fun <K, V> Map<out K, V>.plus(pairs: Iterable<Pair<K, V>>): Map<K, V> =
= if (this.isEmpty()) pairs.toMap() else LinkedHashMap(this).apply { putAll(pairs) } if (this.isEmpty()) pairs.toMap() else LinkedHashMap(this).apply { putAll(pairs) }
/** /**
* Creates a new read-only map by replacing or adding entries to this map from a given array of key-value [pairs]. * Creates a new read-only map by replacing or adding entries to this map from a given array of key-value [pairs].
@@ -555,8 +554,8 @@ public operator fun <K, V> Map<out K, V>.plus(pairs: Iterable<Pair<K, V>>): Map<
* The returned map preserves the entry iteration order of the original map. * The returned map preserves the entry iteration order of the original map.
* Those [pairs] with unique keys are iterated in the end in the order of [pairs] array. * Those [pairs] with unique keys are iterated in the end in the order of [pairs] array.
*/ */
public operator fun <K, V> Map<out K, V>.plus(pairs: Array<out Pair<K, V>>): Map<K, V> public operator fun <K, V> Map<out K, V>.plus(pairs: Array<out Pair<K, V>>): Map<K, V> =
= if (this.isEmpty()) pairs.toMap() else LinkedHashMap(this).apply { putAll(pairs) } if (this.isEmpty()) pairs.toMap() else LinkedHashMap(this).apply { putAll(pairs) }
/** /**
* Creates a new read-only map by replacing or adding entries to this map from a given sequence of key-value [pairs]. * Creates a new read-only map by replacing or adding entries to this map from a given sequence of key-value [pairs].
@@ -564,8 +563,8 @@ public operator fun <K, V> Map<out K, V>.plus(pairs: Array<out Pair<K, V>>): Map
* The returned map preserves the entry iteration order of the original map. * The returned map preserves the entry iteration order of the original map.
* Those [pairs] with unique keys are iterated in the end in the order of [pairs] sequence. * Those [pairs] with unique keys are iterated in the end in the order of [pairs] sequence.
*/ */
public operator fun <K, V> Map<out K, V>.plus(pairs: Sequence<Pair<K, V>>): Map<K, V> public operator fun <K, V> Map<out K, V>.plus(pairs: Sequence<Pair<K, V>>): Map<K, V> =
= LinkedHashMap(this).apply { putAll(pairs) }.optimizeReadOnlyMap() LinkedHashMap(this).apply { putAll(pairs) }.optimizeReadOnlyMap()
/** /**
* Creates a new read-only map by replacing or adding entries to this map from another [map]. * Creates a new read-only map by replacing or adding entries to this map from another [map].
@@ -573,8 +572,8 @@ public operator fun <K, V> Map<out K, V>.plus(pairs: Sequence<Pair<K, V>>): Map<
* The returned map preserves the entry iteration order of the original map. * The returned map preserves the entry iteration order of the original map.
* Those entries of another [map] that are missing in this map are iterated in the end in the order of that [map]. * Those entries of another [map] that are missing in this map are iterated in the end in the order of that [map].
*/ */
public operator fun <K, V> Map<out K, V>.plus(map: Map<out K, V>): Map<K, V> public operator fun <K, V> Map<out K, V>.plus(map: Map<out K, V>): Map<K, V> =
= LinkedHashMap(this).apply { putAll(map) } LinkedHashMap(this).apply { putAll(map) }
/** /**
@@ -623,8 +622,8 @@ public inline operator fun <K, V> MutableMap<in K, in V>.plusAssign(map: Map<K,
* The returned map preserves the entry iteration order of the original map. * The returned map preserves the entry iteration order of the original map.
*/ */
@SinceKotlin("1.1") @SinceKotlin("1.1")
public operator fun <K, V> Map<out K, V>.minus(key: K): Map<K, V> public operator fun <K, V> Map<out K, V>.minus(key: K): Map<K, V> =
= this.toMutableMap().apply { minusAssign(key) }.optimizeReadOnlyMap() this.toMutableMap().apply { minusAssign(key) }.optimizeReadOnlyMap()
/** /**
* Returns a map containing all entries of the original map except those entries * Returns a map containing all entries of the original map except those entries
@@ -633,8 +632,8 @@ public operator fun <K, V> Map<out K, V>.minus(key: K): Map<K, V>
* The returned map preserves the entry iteration order of the original map. * The returned map preserves the entry iteration order of the original map.
*/ */
@SinceKotlin("1.1") @SinceKotlin("1.1")
public operator fun <K, V> Map<out K, V>.minus(keys: Iterable<K>): Map<K, V> public operator fun <K, V> Map<out K, V>.minus(keys: Iterable<K>): Map<K, V> =
= this.toMutableMap().apply { minusAssign(keys) }.optimizeReadOnlyMap() this.toMutableMap().apply { minusAssign(keys) }.optimizeReadOnlyMap()
/** /**
* Returns a map containing all entries of the original map except those entries * Returns a map containing all entries of the original map except those entries
@@ -643,8 +642,8 @@ public operator fun <K, V> Map<out K, V>.minus(keys: Iterable<K>): Map<K, V>
* The returned map preserves the entry iteration order of the original map. * The returned map preserves the entry iteration order of the original map.
*/ */
@SinceKotlin("1.1") @SinceKotlin("1.1")
public operator fun <K, V> Map<out K, V>.minus(keys: Array<out K>): Map<K, V> public operator fun <K, V> Map<out K, V>.minus(keys: Array<out K>): Map<K, V> =
= this.toMutableMap().apply { minusAssign(keys) }.optimizeReadOnlyMap() this.toMutableMap().apply { minusAssign(keys) }.optimizeReadOnlyMap()
/** /**
* Returns a map containing all entries of the original map except those entries * Returns a map containing all entries of the original map except those entries
@@ -653,8 +652,8 @@ public operator fun <K, V> Map<out K, V>.minus(keys: Array<out K>): Map<K, V>
* The returned map preserves the entry iteration order of the original map. * The returned map preserves the entry iteration order of the original map.
*/ */
@SinceKotlin("1.1") @SinceKotlin("1.1")
public operator fun <K, V> Map<out K, V>.minus(keys: Sequence<K>): Map<K, V> public operator fun <K, V> Map<out K, V>.minus(keys: Sequence<K>): Map<K, V> =
= this.toMutableMap().apply { minusAssign(keys) }.optimizeReadOnlyMap() this.toMutableMap().apply { minusAssign(keys) }.optimizeReadOnlyMap()
/** /**
* Removes the entry with the given [key] from this mutable map. * Removes the entry with the given [key] from this mutable map.
@@ -17,8 +17,8 @@ package kotlin.collections
* @return `true` if the element has been successfully removed; `false` if it was not present in the collection. * @return `true` if the element has been successfully removed; `false` if it was not present in the collection.
*/ */
@kotlin.internal.InlineOnly @kotlin.internal.InlineOnly
public inline fun <@kotlin.internal.OnlyInputTypes T> MutableCollection<out T>.remove(element: T): Boolean public inline fun <@kotlin.internal.OnlyInputTypes T> MutableCollection<out T>.remove(element: T): Boolean =
= @Suppress("UNCHECKED_CAST") (this as MutableCollection<T>).remove(element) @Suppress("UNCHECKED_CAST") (this as MutableCollection<T>).remove(element)
/** /**
* Removes all of this collection's elements that are also contained in the specified collection. * Removes all of this collection's elements that are also contained in the specified collection.
@@ -28,8 +28,8 @@ public inline fun <@kotlin.internal.OnlyInputTypes T> MutableCollection<out T>.r
* @return `true` if any of the specified elements was removed from the collection, `false` if the collection was not modified. * @return `true` if any of the specified elements was removed from the collection, `false` if the collection was not modified.
*/ */
@kotlin.internal.InlineOnly @kotlin.internal.InlineOnly
public inline fun <@kotlin.internal.OnlyInputTypes T> MutableCollection<out T>.removeAll(elements: Collection<T>): Boolean public inline fun <@kotlin.internal.OnlyInputTypes T> MutableCollection<out T>.removeAll(elements: Collection<T>): Boolean =
= @Suppress("UNCHECKED_CAST") (this as MutableCollection<T>).removeAll(elements) @Suppress("UNCHECKED_CAST") (this as MutableCollection<T>).removeAll(elements)
/** /**
* Retains only the elements in this collection that are contained in the specified collection. * Retains only the elements in this collection that are contained in the specified collection.
@@ -39,8 +39,8 @@ public inline fun <@kotlin.internal.OnlyInputTypes T> MutableCollection<out T>.r
* @return `true` if any element was removed from the collection, `false` if the collection was not modified. * @return `true` if any element was removed from the collection, `false` if the collection was not modified.
*/ */
@kotlin.internal.InlineOnly @kotlin.internal.InlineOnly
public inline fun <@kotlin.internal.OnlyInputTypes T> MutableCollection<out T>.retainAll(elements: Collection<T>): Boolean public inline fun <@kotlin.internal.OnlyInputTypes T> MutableCollection<out T>.retainAll(elements: Collection<T>): Boolean =
= @Suppress("UNCHECKED_CAST") (this as MutableCollection<T>).retainAll(elements) @Suppress("UNCHECKED_CAST") (this as MutableCollection<T>).retainAll(elements)
/** /**
* Removes the element at the specified [index] from this list. * Removes the element at the specified [index] from this list.
@@ -159,7 +159,7 @@ public fun <T> MutableIterable<T>.retainAll(predicate: (T) -> Boolean): Boolean
private fun <T> MutableIterable<T>.filterInPlace(predicate: (T) -> Boolean, predicateResultToRemove: Boolean): Boolean { private fun <T> MutableIterable<T>.filterInPlace(predicate: (T) -> Boolean, predicateResultToRemove: Boolean): Boolean {
var result = false var result = false
with (iterator()) { with(iterator()) {
while (hasNext()) while (hasNext())
if (predicate(next()) == predicateResultToRemove) { if (predicate(next()) == predicateResultToRemove) {
remove() remove()
@@ -199,8 +199,7 @@ private fun <T> MutableList<T>.filterInPlace(predicate: (T) -> Boolean, predicat
removeAt(removeIndex) removeAt(removeIndex)
return true return true
} } else {
else {
return false return false
} }
} }
@@ -27,6 +27,7 @@ private class ReversedList<T>(private val delegate: MutableList<T>) : AbstractMu
delegate.add(reversePositionIndex(index), element) delegate.add(reversePositionIndex(index), element)
} }
} }
private fun List<*>.reverseElementIndex(index: Int) = private fun List<*>.reverseElementIndex(index: Int) =
if (index in 0..lastIndex) lastIndex - index else throw IndexOutOfBoundsException("Element index $index must be in range [${0..lastIndex}].") if (index in 0..lastIndex) lastIndex - index else throw IndexOutOfBoundsException("Element index $index must be in range [${0..lastIndex}].")
@@ -91,12 +91,13 @@ public fun <T, R> Sequence<Pair<T, R>>.unzip(): Pair<List<T>, List<R>> {
* the specified [predicate]. * the specified [predicate].
* *
* @param sendWhen If `true`, values for which the predicate returns `true` are returned. Otherwise, * @param sendWhen If `true`, values for which the predicate returns `true` are returned. Otherwise,
* values for which the predicate returns `false` are returned * values for which the predicate returns `false` are returned
*/ */
internal class FilteringSequence<T>(private val sequence: Sequence<T>, internal class FilteringSequence<T>(
private val sequence: Sequence<T>,
private val sendWhen: Boolean = true, private val sendWhen: Boolean = true,
private val predicate: (T) -> Boolean private val predicate: (T) -> Boolean
) : Sequence<T> { ) : Sequence<T> {
override fun iterator(): Iterator<T> = object : Iterator<T> { override fun iterator(): Iterator<T> = object : Iterator<T> {
val iterator = sequence.iterator() val iterator = sequence.iterator()
@@ -203,10 +204,11 @@ constructor(private val sequence: Sequence<T>) : Sequence<IndexedValue<T>> {
* values as soon as one of the underlying sequences stops returning values. * values as soon as one of the underlying sequences stops returning values.
*/ */
internal class MergingSequence<T1, T2, V> internal class MergingSequence<T1, T2, V>
constructor(private val sequence1: Sequence<T1>, constructor(
private val sequence1: Sequence<T1>,
private val sequence2: Sequence<T2>, private val sequence2: Sequence<T2>,
private val transform: (T1, T2) -> V private val transform: (T1, T2) -> V
) : Sequence<V> { ) : Sequence<V> {
override fun iterator(): Iterator<V> = object : Iterator<V> { override fun iterator(): Iterator<V> = object : Iterator<V> {
val iterator1 = sequence1.iterator() val iterator1 = sequence1.iterator()
val iterator2 = sequence2.iterator() val iterator2 = sequence2.iterator()
@@ -221,11 +223,11 @@ internal class MergingSequence<T1, T2, V>
} }
internal class FlatteningSequence<T, R, E> internal class FlatteningSequence<T, R, E>
constructor( constructor(
private val sequence: Sequence<T>, private val sequence: Sequence<T>,
private val transformer: (T) -> R, private val transformer: (T) -> R,
private val iterator: (R) -> Iterator<E> private val iterator: (R) -> Iterator<E>
) : Sequence<E> { ) : Sequence<E> {
override fun iterator(): Iterator<E> = object : Iterator<E> { override fun iterator(): Iterator<E> = object : Iterator<E> {
val iterator = sequence.iterator() val iterator = sequence.iterator()
var itemIterator: Iterator<E>? = null var itemIterator: Iterator<E>? = null
@@ -273,16 +275,16 @@ internal interface DropTakeSequence<T> : Sequence<T> {
* A sequence that skips [startIndex] values from the underlying [sequence] * A sequence that skips [startIndex] values from the underlying [sequence]
* and stops returning values right before [endIndex], i.e. stops at `endIndex - 1` * and stops returning values right before [endIndex], i.e. stops at `endIndex - 1`
*/ */
internal class SubSequence<T> ( internal class SubSequence<T>(
private val sequence: Sequence<T>, private val sequence: Sequence<T>,
private val startIndex: Int, private val startIndex: Int,
private val endIndex: Int private val endIndex: Int
): Sequence<T>, DropTakeSequence<T> { ) : Sequence<T>, DropTakeSequence<T> {
init { init {
require(startIndex >= 0) { "startIndex should be non-negative, but is $startIndex" } require(startIndex >= 0) { "startIndex should be non-negative, but is $startIndex" }
require(endIndex >= 0) { "endIndex should be non-negative, but is $endIndex" } require(endIndex >= 0) { "endIndex should be non-negative, but is $endIndex" }
require(endIndex >= startIndex) { "endIndex should be not less than startIndex, but was $endIndex < $startIndex"} require(endIndex >= startIndex) { "endIndex should be not less than startIndex, but was $endIndex < $startIndex" }
} }
private val count: Int get() = endIndex - startIndex private val count: Int get() = endIndex - startIndex
@@ -297,7 +299,7 @@ internal class SubSequence<T> (
// Shouldn't be called from constructor to avoid premature iteration // Shouldn't be called from constructor to avoid premature iteration
private fun drop() { private fun drop() {
while(position < startIndex && iterator.hasNext()) { while (position < startIndex && iterator.hasNext()) {
iterator.next() iterator.next()
position++ position++
} }
@@ -322,13 +324,13 @@ internal class SubSequence<T> (
* A sequence that returns at most [count] values from the underlying [sequence], and stops returning values * A sequence that returns at most [count] values from the underlying [sequence], and stops returning values
* as soon as that count is reached. * as soon as that count is reached.
*/ */
internal class TakeSequence<T> ( internal class TakeSequence<T>(
private val sequence: Sequence<T>, private val sequence: Sequence<T>,
private val count: Int private val count: Int
) : Sequence<T>, DropTakeSequence<T> { ) : Sequence<T>, DropTakeSequence<T> {
init { init {
require (count >= 0) { "count must be non-negative, but was $count." } require(count >= 0) { "count must be non-negative, but was $count." }
} }
override fun drop(n: Int): Sequence<T> = if (n >= count) emptySequence() else SubSequence(sequence, n, count) override fun drop(n: Int): Sequence<T> = if (n >= count) emptySequence() else SubSequence(sequence, n, count)
@@ -356,9 +358,10 @@ internal class TakeSequence<T> (
* `true`, and stops returning values once the function returns `false` for the next element. * `true`, and stops returning values once the function returns `false` for the next element.
*/ */
internal class TakeWhileSequence<T> internal class TakeWhileSequence<T>
constructor(private val sequence: Sequence<T>, constructor(
private val sequence: Sequence<T>,
private val predicate: (T) -> Boolean private val predicate: (T) -> Boolean
) : Sequence<T> { ) : Sequence<T> {
override fun iterator(): Iterator<T> = object : Iterator<T> { override fun iterator(): Iterator<T> = object : Iterator<T> {
val iterator = sequence.iterator() val iterator = sequence.iterator()
var nextState: Int = -1 // -1 for unknown, 0 for done, 1 for continue var nextState: Int = -1 // -1 for unknown, 0 for done, 1 for continue
@@ -402,12 +405,12 @@ internal class TakeWhileSequence<T>
* A sequence that skips the specified number of values from the underlying [sequence] and returns * A sequence that skips the specified number of values from the underlying [sequence] and returns
* all values after that. * all values after that.
*/ */
internal class DropSequence<T> ( internal class DropSequence<T>(
private val sequence: Sequence<T>, private val sequence: Sequence<T>,
private val count: Int private val count: Int
) : Sequence<T>, DropTakeSequence<T> { ) : Sequence<T>, DropTakeSequence<T> {
init { init {
require (count >= 0) { "count must be non-negative, but was $count." } require(count >= 0) { "count must be non-negative, but was $count." }
} }
override fun drop(n: Int): Sequence<T> = DropSequence(sequence, count + n) override fun drop(n: Int): Sequence<T> = DropSequence(sequence, count + n)
@@ -442,9 +445,10 @@ internal class DropSequence<T> (
* all values after that. * all values after that.
*/ */
internal class DropWhileSequence<T> internal class DropWhileSequence<T>
constructor(private val sequence: Sequence<T>, constructor(
private val sequence: Sequence<T>,
private val predicate: (T) -> Boolean private val predicate: (T) -> Boolean
) : Sequence<T> { ) : Sequence<T> {
override fun iterator(): Iterator<T> = object : Iterator<T> { override fun iterator(): Iterator<T> = object : Iterator<T> {
val iterator = sequence.iterator() val iterator = sequence.iterator()
@@ -485,11 +489,11 @@ internal class DropWhileSequence<T>
} }
} }
internal class DistinctSequence<T, K>(private val source : Sequence<T>, private val keySelector : (T) -> K) : Sequence<T> { internal class DistinctSequence<T, K>(private val source: Sequence<T>, private val keySelector: (T) -> K) : Sequence<T> {
override fun iterator(): Iterator<T> = DistinctIterator(source.iterator(), keySelector) override fun iterator(): Iterator<T> = DistinctIterator(source.iterator(), keySelector)
} }
private class DistinctIterator<T, K>(private val source : Iterator<T>, private val keySelector : (T) -> K) : AbstractIterator<T>() { private class DistinctIterator<T, K>(private val source: Iterator<T>, private val keySelector: (T) -> K) : AbstractIterator<T>() {
private val observed = HashSet<K>() private val observed = HashSet<K>()
override fun computeNext() { override fun computeNext() {
@@ -508,7 +512,7 @@ private class DistinctIterator<T, K>(private val source : Iterator<T>, private v
} }
private class GeneratorSequence<T: Any>(private val getInitialValue: () -> T?, private val getNextValue: (T) -> T?): Sequence<T> { private class GeneratorSequence<T : Any>(private val getInitialValue: () -> T?, private val getNextValue: (T) -> T?) : Sequence<T> {
override fun iterator(): Iterator<T> = object : Iterator<T> { override fun iterator(): Iterator<T> = object : Iterator<T> {
var nextItem: T? = null var nextItem: T? = null
var nextState: Int = -2 // -2 for initial unknown, -1 for next unknown, 0 for done, 1 for continue var nextState: Int = -2 // -2 for initial unknown, -1 for next unknown, 0 for done, 1 for continue
@@ -553,7 +557,6 @@ public fun <T> Sequence<T>.constrainOnce(): Sequence<T> {
} }
/** /**
* Returns a sequence which invokes the function to calculate the next value on each iteration until the function returns `null`. * Returns a sequence which invokes the function to calculate the next value on each iteration until the function returns `null`.
* *
@@ -601,6 +604,6 @@ public fun <T : Any> generateSequence(seed: T?, nextFunction: (T) -> T?): Sequen
* *
* @sample samples.collections.Sequences.Building.generateSequenceWithLazySeed * @sample samples.collections.Sequences.Building.generateSequenceWithLazySeed
*/ */
public fun <T: Any> generateSequence(seedFunction: () -> T?, nextFunction: (T) -> T?): Sequence<T> = public fun <T : Any> generateSequence(seedFunction: () -> T?, nextFunction: (T) -> T?): Sequence<T> =
GeneratorSequence(seedFunction, nextFunction) GeneratorSequence(seedFunction, nextFunction)
@@ -32,6 +32,7 @@ internal object EmptySet : Set<Nothing>, Serializable {
* @sample samples.collections.Collections.Sets.emptyReadOnlySet * @sample samples.collections.Collections.Sets.emptyReadOnlySet
*/ */
public fun <T> emptySet(): Set<T> = EmptySet public fun <T> emptySet(): Set<T> = EmptySet
/** /**
* Returns a new read-only set with the given elements. * Returns a new read-only set with the given elements.
* Elements of the set are iterated in the order they were specified. * Elements of the set are iterated in the order they were specified.
@@ -86,7 +86,7 @@ internal class MovingSubList<out E>(private val list: List<E>) : AbstractList<E>
* *
* Buffer overflow is not allowed so [add] doesn't overwrite tail but raises an exception. * Buffer overflow is not allowed so [add] doesn't overwrite tail but raises an exception.
*/ */
private class RingBuffer<T>(val capacity: Int): AbstractList<T>(), RandomAccess { private class RingBuffer<T>(val capacity: Int) : AbstractList<T>(), RandomAccess {
init { init {
require(capacity >= 0) { "ring buffer capacity should not be negative but it is $capacity" } require(capacity >= 0) { "ring buffer capacity should not be negative but it is $capacity" }
} }