From ad43c0f4cb04c72d190e2f1a9baf8a5778e3b70a Mon Sep 17 00:00:00 2001 From: Ilya Gorbunov Date: Fri, 20 Apr 2018 21:30:56 +0300 Subject: [PATCH] Reformat stdlib: collections #KT-5558 --- .../kotlin/collections/AbstractMutableList.kt | 3 + .../src/kotlin/collections/ArrayList.kt | 3 + .../src/kotlin/collections/CollectionsH.kt | 2 + .../common/src/kotlin/collections/HashMap.kt | 2 + .../common/src/kotlin/collections/HashSet.kt | 2 + .../src/kotlin/collections/LinkedHashMap.kt | 2 + .../src/kotlin/collections/LinkedHashSet.kt | 2 + .../kotlin/collections/AbstractMutableList.kt | 4 +- .../kotlin/collections/AbstractMutableMap.kt | 99 ++++++++++--------- .../js/src/kotlin/collections/ArrayList.kt | 2 + .../js/src/kotlin/collections/HashMap.kt | 11 ++- .../kotlin/collections/InternalHashCodeMap.kt | 29 ++---- .../kotlin/collections/InternalStringMap.kt | 6 +- .../src/kotlin/collections/LinkedHashMap.kt | 8 +- .../src/kotlin/collections/LinkedHashSet.kt | 1 + .../kotlin/collections/AbstractMutableList.kt | 2 + .../jvm/src/kotlin/collections/MapsJVM.kt | 20 ++-- .../src/kotlin/collections/SequencesJVM.kt | 2 +- .../kotlin/collections/AbstractCollection.kt | 4 +- .../kotlin/collections/AbstractIterator.kt | 2 +- .../src/kotlin/collections/AbstractMap.kt | 65 ++++++------ .../stdlib/src/kotlin/collections/Arrays.kt | 1 - .../src/kotlin/collections/Collections.kt | 21 ++-- .../stdlib/src/kotlin/collections/Grouping.kt | 66 ++++++------- .../src/kotlin/collections/Iterables.kt | 29 +++--- .../src/kotlin/collections/Iterators.kt | 2 +- .../src/kotlin/collections/MapAccessors.kt | 13 +-- .../src/kotlin/collections/MapWithDefault.kt | 27 +++-- .../stdlib/src/kotlin/collections/Maps.kt | 89 +++++++++-------- .../kotlin/collections/MutableCollections.kt | 17 ++-- .../src/kotlin/collections/ReversedViews.kt | 5 +- .../src/kotlin/collections/Sequences.kt | 81 +++++++-------- .../stdlib/src/kotlin/collections/Sets.kt | 1 + .../src/kotlin/collections/SlidingWindow.kt | 26 ++--- 34 files changed, 337 insertions(+), 312 deletions(-) diff --git a/libraries/stdlib/common/src/kotlin/collections/AbstractMutableList.kt b/libraries/stdlib/common/src/kotlin/collections/AbstractMutableList.kt index a08106a50c7..515fc4775b9 100644 --- a/libraries/stdlib/common/src/kotlin/collections/AbstractMutableList.kt +++ b/libraries/stdlib/common/src/kotlin/collections/AbstractMutableList.kt @@ -9,6 +9,7 @@ expect abstract class AbstractMutableList : MutableList { protected constructor() // From List + override fun isEmpty(): Boolean override fun contains(element: @UnsafeVariance E): Boolean override fun containsAll(elements: Collection<@UnsafeVariance E>): Boolean @@ -16,9 +17,11 @@ expect abstract class AbstractMutableList : MutableList { override fun lastIndexOf(element: @UnsafeVariance E): Int // From MutableCollection + override fun iterator(): MutableIterator // From MutableList + override fun add(element: E): Boolean override fun remove(element: E): Boolean override fun addAll(elements: Collection): Boolean diff --git a/libraries/stdlib/common/src/kotlin/collections/ArrayList.kt b/libraries/stdlib/common/src/kotlin/collections/ArrayList.kt index 1bb91ad4f7d..6e4ab65ea59 100644 --- a/libraries/stdlib/common/src/kotlin/collections/ArrayList.kt +++ b/libraries/stdlib/common/src/kotlin/collections/ArrayList.kt @@ -14,6 +14,7 @@ expect class ArrayList : MutableList, RandomAccess { fun ensureCapacity(minCapacity: Int) // From List + override val size: Int override fun isEmpty(): Boolean override fun contains(element: @UnsafeVariance E): Boolean @@ -23,9 +24,11 @@ expect class ArrayList : MutableList, RandomAccess { override fun lastIndexOf(element: @UnsafeVariance E): Int // From MutableCollection + override fun iterator(): MutableIterator // From MutableList + override fun add(element: E): Boolean override fun remove(element: E): Boolean override fun addAll(elements: Collection): Boolean diff --git a/libraries/stdlib/common/src/kotlin/collections/CollectionsH.kt b/libraries/stdlib/common/src/kotlin/collections/CollectionsH.kt index ece7be90a25..5723caace71 100644 --- a/libraries/stdlib/common/src/kotlin/collections/CollectionsH.kt +++ b/libraries/stdlib/common/src/kotlin/collections/CollectionsH.kt @@ -15,8 +15,10 @@ expect inline fun Collection.toTypedArray(): Array @SinceKotlin("1.2") expect fun MutableList.fill(value: T): Unit + @SinceKotlin("1.2") expect fun MutableList.shuffle(): Unit + @SinceKotlin("1.2") expect fun Iterable.shuffled(): List diff --git a/libraries/stdlib/common/src/kotlin/collections/HashMap.kt b/libraries/stdlib/common/src/kotlin/collections/HashMap.kt index 7fd2ae009b3..f5f7df7b6ba 100644 --- a/libraries/stdlib/common/src/kotlin/collections/HashMap.kt +++ b/libraries/stdlib/common/src/kotlin/collections/HashMap.kt @@ -12,6 +12,7 @@ expect class HashMap : MutableMap { constructor(original: Map) // From Map + override val size: Int override fun isEmpty(): Boolean override fun containsKey(key: K): Boolean @@ -19,6 +20,7 @@ expect class HashMap : MutableMap { override operator fun get(key: K): V? // From MutableMap + override fun put(key: K, value: V): V? override fun remove(key: K): V? override fun putAll(from: Map) diff --git a/libraries/stdlib/common/src/kotlin/collections/HashSet.kt b/libraries/stdlib/common/src/kotlin/collections/HashSet.kt index 999e90d74d7..310180ab554 100644 --- a/libraries/stdlib/common/src/kotlin/collections/HashSet.kt +++ b/libraries/stdlib/common/src/kotlin/collections/HashSet.kt @@ -12,12 +12,14 @@ expect class HashSet : MutableSet { constructor(elements: Collection) // From Set + override val size: Int override fun isEmpty(): Boolean override fun contains(element: @UnsafeVariance E): Boolean override fun containsAll(elements: Collection<@UnsafeVariance E>): Boolean // From MutableSet + override fun iterator(): MutableIterator override fun add(element: E): Boolean override fun remove(element: E): Boolean diff --git a/libraries/stdlib/common/src/kotlin/collections/LinkedHashMap.kt b/libraries/stdlib/common/src/kotlin/collections/LinkedHashMap.kt index cff927fdebf..29ad078b725 100644 --- a/libraries/stdlib/common/src/kotlin/collections/LinkedHashMap.kt +++ b/libraries/stdlib/common/src/kotlin/collections/LinkedHashMap.kt @@ -12,6 +12,7 @@ expect class LinkedHashMap : MutableMap { constructor(original: Map) // From Map + override val size: Int override fun isEmpty(): Boolean override fun containsKey(key: K): Boolean @@ -19,6 +20,7 @@ expect class LinkedHashMap : MutableMap { override fun get(key: K): V? // From MutableMap + override fun put(key: K, value: V): V? override fun remove(key: K): V? override fun putAll(from: Map) diff --git a/libraries/stdlib/common/src/kotlin/collections/LinkedHashSet.kt b/libraries/stdlib/common/src/kotlin/collections/LinkedHashSet.kt index 070b02c18c6..39f14c7a9f2 100644 --- a/libraries/stdlib/common/src/kotlin/collections/LinkedHashSet.kt +++ b/libraries/stdlib/common/src/kotlin/collections/LinkedHashSet.kt @@ -12,12 +12,14 @@ expect class LinkedHashSet : MutableSet { constructor(elements: Collection) // From Set + override val size: Int override fun isEmpty(): Boolean override fun contains(element: @UnsafeVariance E): Boolean override fun containsAll(elements: Collection<@UnsafeVariance E>): Boolean // From MutableSet + override fun iterator(): MutableIterator override fun add(element: E): Boolean override fun remove(element: E): Boolean diff --git a/libraries/stdlib/js/src/kotlin/collections/AbstractMutableList.kt b/libraries/stdlib/js/src/kotlin/collections/AbstractMutableList.kt index cc2e7f63b38..11278919d17 100644 --- a/libraries/stdlib/js/src/kotlin/collections/AbstractMutableList.kt +++ b/libraries/stdlib/js/src/kotlin/collections/AbstractMutableList.kt @@ -120,7 +120,7 @@ public actual abstract class AbstractMutableList protected actual constructor } 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) index = last @@ -158,7 +158,7 @@ public actual abstract class AbstractMutableList protected actual constructor } 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 } } diff --git a/libraries/stdlib/js/src/kotlin/collections/AbstractMutableMap.kt b/libraries/stdlib/js/src/kotlin/collections/AbstractMutableMap.kt index d4fedadd63b..7ace3490a92 100644 --- a/libraries/stdlib/js/src/kotlin/collections/AbstractMutableMap.kt +++ b/libraries/stdlib/js/src/kotlin/collections/AbstractMutableMap.kt @@ -46,38 +46,39 @@ public actual abstract class AbstractMutableMap protected actual construct } private var _keys: MutableSet? = null - override val keys: MutableSet get() { - if (_keys == null) { - _keys = object : AbstractMutableSet() { - override fun add(element: K): Boolean = throw UnsupportedOperationException("Add is not supported on keys") - override fun clear() { - this@AbstractMutableMap.clear() - } - - override operator fun contains(element: K): Boolean = containsKey(element) - - override operator fun iterator(): MutableIterator { - val entryIterator = entries.iterator() - return object : MutableIterator { - override fun hasNext(): Boolean = entryIterator.hasNext() - override fun next(): K = entryIterator.next().key - override fun remove() = entryIterator.remove() + override val keys: MutableSet + get() { + if (_keys == null) { + _keys = object : AbstractMutableSet() { + override fun add(element: K): Boolean = throw UnsupportedOperationException("Add is not supported on keys") + override fun clear() { + this@AbstractMutableMap.clear() } - } - override fun remove(element: K): Boolean { - if (containsKey(element)) { - this@AbstractMutableMap.remove(element) - return true + override operator fun contains(element: K): Boolean = containsKey(element) + + override operator fun iterator(): MutableIterator { + val entryIterator = entries.iterator() + return object : MutableIterator { + override fun hasNext(): Boolean = entryIterator.hasNext() + override fun next(): K = entryIterator.next().key + override fun remove() = entryIterator.remove() + } } - return false - } - override val size: Int get() = this@AbstractMutableMap.size + override fun remove(element: K): Boolean { + if (containsKey(element)) { + this@AbstractMutableMap.remove(element) + return true + } + return false + } + + override val size: Int get() = this@AbstractMutableMap.size + } } + return _keys!! } - return _keys!! - } actual abstract override fun put(key: K, value: V): V? @@ -88,36 +89,38 @@ public actual abstract class AbstractMutableMap protected actual construct } private var _values: MutableCollection? = null - override val values: MutableCollection get() { - if (_values == null) { - _values = object : AbstractMutableCollection() { - override fun add(element: V): Boolean = throw UnsupportedOperationException("Add is not supported on values") - override fun clear() = this@AbstractMutableMap.clear() + override val values: MutableCollection + get() { + if (_values == null) { + _values = object : AbstractMutableCollection() { + override fun add(element: V): Boolean = throw UnsupportedOperationException("Add is not supported on values") + override fun clear() = this@AbstractMutableMap.clear() - override operator fun contains(element: V): Boolean = containsValue(element) + override operator fun contains(element: V): Boolean = containsValue(element) - override operator fun iterator(): MutableIterator { - val entryIterator = entries.iterator() - return object : MutableIterator { - override fun hasNext(): Boolean = entryIterator.hasNext() - override fun next(): V = entryIterator.next().value - override fun remove() = entryIterator.remove() + override operator fun iterator(): MutableIterator { + val entryIterator = entries.iterator() + return object : MutableIterator { + override fun hasNext(): Boolean = entryIterator.hasNext() + override fun next(): V = entryIterator.next().value + override fun remove() = entryIterator.remove() + } } - } - override val size: Int get() = this@AbstractMutableMap.size + override val size: Int get() = this@AbstractMutableMap.size - // TODO: should we implement them this way? Currently it's unspecified in JVM - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other !is Collection<*>) return false - return AbstractList.orderedEquals(this, other) + // TODO: should we implement them this way? Currently it's unspecified in JVM + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other !is Collection<*>) return false + return AbstractList.orderedEquals(this, other) + } + + override fun hashCode(): Int = AbstractList.orderedHashCode(this) } - override fun hashCode(): Int = AbstractList.orderedHashCode(this) } + return _values!! } - return _values!! - } override fun remove(key: K): V? { val iter = entries.iterator() diff --git a/libraries/stdlib/js/src/kotlin/collections/ArrayList.kt b/libraries/stdlib/js/src/kotlin/collections/ArrayList.kt index 433aa792267..582205789bb 100644 --- a/libraries/stdlib/js/src/kotlin/collections/ArrayList.kt +++ b/libraries/stdlib/js/src/kotlin/collections/ArrayList.kt @@ -24,6 +24,7 @@ public actual open class ArrayList internal constructor(private var array: Ar * @param initialCapacity initial capacity (ignored) */ public actual constructor(initialCapacity: Int) : this(emptyArray()) {} + /** * Creates an [ArrayList] filled from the [elements] collection. */ @@ -31,6 +32,7 @@ public actual open class ArrayList internal constructor(private var array: Ar /** Does nothing in this ArrayList implementation. */ public actual fun trimToSize() {} + /** Does nothing in this ArrayList implementation. */ public actual fun ensureCapacity(minCapacity: Int) {} diff --git a/libraries/stdlib/js/src/kotlin/collections/HashMap.kt b/libraries/stdlib/js/src/kotlin/collections/HashMap.kt index 6e2aa9aea79..04b0d4b2079 100644 --- a/libraries/stdlib/js/src/kotlin/collections/HashMap.kt +++ b/libraries/stdlib/js/src/kotlin/collections/HashMap.kt @@ -92,12 +92,13 @@ public actual open class HashMap : AbstractMutableMap, MutableMap>? = null - actual override val entries: MutableSet> get() { - if (_entries == null) { - _entries = createEntrySet() + actual override val entries: MutableSet> + get() { + if (_entries == null) { + _entries = createEntrySet() + } + return _entries!! } - return _entries!! - } protected open fun createEntrySet(): MutableSet> = EntrySet() diff --git a/libraries/stdlib/js/src/kotlin/collections/InternalHashCodeMap.kt b/libraries/stdlib/js/src/kotlin/collections/InternalHashCodeMap.kt index 183c65b2edc..3cadd4809cd 100644 --- a/libraries/stdlib/js/src/kotlin/collections/InternalHashCodeMap.kt +++ b/libraries/stdlib/js/src/kotlin/collections/InternalHashCodeMap.kt @@ -36,21 +36,18 @@ internal class InternalHashCodeMap(override val equality: EqualityComparat if (chainOrEntry == null) { // This is a new chain, put it to the map. backingMap[hashCode] = SimpleEntry(key, value) - } - else { + } else { if (chainOrEntry !is Array<*>) { // It is an entry val entry: SimpleEntry = chainOrEntry if (equality.equals(entry.key, key)) { return entry.setValue(value) - } - else { + } else { backingMap[hashCode] = arrayOf(entry, SimpleEntry(key, value)) size++ return null } - } - else { + } else { // Chain already exists, perhaps key also exists. val chain: Array> = chainOrEntry val entry = chain.findEntryInChain(key) @@ -74,12 +71,10 @@ internal class InternalHashCodeMap(override val equality: EqualityComparat deleteProperty(backingMap, hashCode) size-- return entry.value - } - else { + } else { return null } - } - else { + } else { val chain: Array> = chainOrEntry for (index in chain.indices) { val entry = chain[index] @@ -116,19 +111,17 @@ internal class InternalHashCodeMap(override val equality: EqualityComparat val entry: MutableEntry = chainOrEntry if (equality.equals(entry.key, key)) { return entry - } - else { + } else { return null } - } - else { + } else { val chain: Array> = chainOrEntry return chain.findEntryInChain(key) } } private fun Array>.findEntryInChain(key: K): MutableEntry? = - firstOrNull { entry -> equality.equals(entry.key, key) } + firstOrNull { entry -> equality.equals(entry.key, key) } override fun iterator(): MutableIterator> { @@ -155,8 +148,7 @@ internal class InternalHashCodeMap(override val equality: EqualityComparat isChain = chainOrEntry is Array<*> itemIndex = 0 return 0 - } - else { + } else { chainOrEntry = null return 1 } @@ -172,8 +164,7 @@ internal class InternalHashCodeMap(override val equality: EqualityComparat if (!hasNext()) throw NoSuchElementException() val lastEntry = if (isChain) { chainOrEntry.unsafeCast>>()[itemIndex] - } - else { + } else { chainOrEntry.unsafeCast>() } this.lastEntry = lastEntry diff --git a/libraries/stdlib/js/src/kotlin/collections/InternalStringMap.kt b/libraries/stdlib/js/src/kotlin/collections/InternalStringMap.kt index 2c783264a90..ecff51cc9a3 100644 --- a/libraries/stdlib/js/src/kotlin/collections/InternalStringMap.kt +++ b/libraries/stdlib/js/src/kotlin/collections/InternalStringMap.kt @@ -52,8 +52,7 @@ internal class InternalStringMap(override val equality: EqualityComparator size++ // structureChanged(host) return null - } - else { + } else { // valueMod++ return oldValue.unsafeCast() } @@ -67,8 +66,7 @@ internal class InternalStringMap(override val equality: EqualityComparator size-- // structureChanged(host) return value.unsafeCast() - } - else { + } else { // valueMod++ return null } diff --git a/libraries/stdlib/js/src/kotlin/collections/LinkedHashMap.kt b/libraries/stdlib/js/src/kotlin/collections/LinkedHashMap.kt index 0ba2b0755a8..4093b4ba42f 100644 --- a/libraries/stdlib/js/src/kotlin/collections/LinkedHashMap.kt +++ b/libraries/stdlib/js/src/kotlin/collections/LinkedHashMap.kt @@ -135,8 +135,7 @@ public actual open class LinkedHashMap : HashMap, MutableMap { if (this.next === this) { // if this is single element, remove head head = null - } - else { + } else { if (head === this) { // if this is first element, move head to next head = next @@ -158,7 +157,7 @@ public actual open class LinkedHashMap : HashMap, MutableMap { /** * Constructs an empty [LinkedHashMap] instance. */ - actual constructor() : super() { + actual constructor() : super() { map = HashMap>() } @@ -225,8 +224,7 @@ public actual open class LinkedHashMap : HashMap, MutableMap { map.put(key, newEntry) newEntry.addToEnd() return null - } - else { + } else { return old.setValue(value) } } diff --git a/libraries/stdlib/js/src/kotlin/collections/LinkedHashSet.kt b/libraries/stdlib/js/src/kotlin/collections/LinkedHashSet.kt index 081b0bb9459..a44344363bd 100644 --- a/libraries/stdlib/js/src/kotlin/collections/LinkedHashSet.kt +++ b/libraries/stdlib/js/src/kotlin/collections/LinkedHashSet.kt @@ -29,6 +29,7 @@ public actual open class LinkedHashSet : HashSet, MutableSet { actual constructor(elements: Collection) : super(LinkedHashMap()) { addAll(elements) } + /** * Constructs a new empty [LinkedHashSet]. * diff --git a/libraries/stdlib/jvm/src/kotlin/collections/AbstractMutableList.kt b/libraries/stdlib/jvm/src/kotlin/collections/AbstractMutableList.kt index 690d84f2b02..8bee4efe981 100644 --- a/libraries/stdlib/jvm/src/kotlin/collections/AbstractMutableList.kt +++ b/libraries/stdlib/jvm/src/kotlin/collections/AbstractMutableList.kt @@ -23,6 +23,7 @@ public actual abstract class AbstractMutableList protected actual constructor * @return the element previously at the specified position. */ abstract override fun set(index: Int, element: E): E + /** * Removes an element at the specified [index] from the list. * @@ -32,6 +33,7 @@ public actual abstract class AbstractMutableList protected actual constructor * @return the element that has been removed. */ abstract override fun removeAt(index: Int): E + /** * Inserts an element into the list at the specified [index]. * diff --git a/libraries/stdlib/jvm/src/kotlin/collections/MapsJVM.kt b/libraries/stdlib/jvm/src/kotlin/collections/MapsJVM.kt index a1f074205f6..202ce7a90c2 100644 --- a/libraries/stdlib/jvm/src/kotlin/collections/MapsJVM.kt +++ b/libraries/stdlib/jvm/src/kotlin/collections/MapsJVM.kt @@ -38,8 +38,8 @@ public fun mapOf(pair: Pair): Map = java.util.Collections.sin */ public inline fun ConcurrentMap.getOrPut(key: K, defaultValue: () -> V): V { // Do not use computeIfAbsent on JVM8 as it would change locking behavior - return this.get(key) ?: - defaultValue().let { default -> this.putIfAbsent(key, default) ?: default } + return this.get(key) + ?: defaultValue().let { default -> this.putIfAbsent(key, default) ?: default } } @@ -57,8 +57,8 @@ public fun , V> Map.toSortedMap(): SortedMap = * * @sample samples.collections.Maps.Transformations.mapToSortedMapWithComparator */ -public fun Map.toSortedMap(comparator: Comparator): SortedMap - = TreeMap(comparator).apply { putAll(this@toSortedMap) } +public fun Map.toSortedMap(comparator: Comparator): SortedMap = + TreeMap(comparator).apply { putAll(this@toSortedMap) } /** * Returns a new [SortedMap] with the specified contents, given as a list of pairs @@ -66,8 +66,8 @@ public fun Map.toSortedMap(comparator: Comparator): Sorte * * @sample samples.collections.Maps.Instantiation.sortedMapFromPairs */ -public fun , V> sortedMapOf(vararg pairs: Pair): SortedMap - = TreeMap().apply { putAll(pairs) } +public fun , V> sortedMapOf(vararg pairs: Pair): SortedMap = + TreeMap().apply { putAll(pairs) } /** @@ -76,8 +76,8 @@ public fun , V> sortedMapOf(vararg pairs: Pair): SortedM * @sample samples.collections.Maps.Transformations.mapToProperties */ @kotlin.internal.InlineOnly -public inline fun Map.toProperties(): Properties - = Properties().apply { putAll(this@toProperties) } +public inline fun Map.toProperties(): Properties = + Properties().apply { putAll(this@toProperties) } // 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.toProperties(): Properties internal actual inline fun Map.toSingletonMapOrSelf(): Map = toSingletonMap() // creates a singleton copy of map -internal actual fun Map.toSingletonMap(): Map - = with (entries.iterator().next()) { java.util.Collections.singletonMap(key, value) } +internal actual fun Map.toSingletonMap(): Map = + with(entries.iterator().next()) { java.util.Collections.singletonMap(key, value) } diff --git a/libraries/stdlib/jvm/src/kotlin/collections/SequencesJVM.kt b/libraries/stdlib/jvm/src/kotlin/collections/SequencesJVM.kt index 6dadde6df27..0725869c4fc 100644 --- a/libraries/stdlib/jvm/src/kotlin/collections/SequencesJVM.kt +++ b/libraries/stdlib/jvm/src/kotlin/collections/SequencesJVM.kt @@ -15,7 +15,7 @@ import kotlin.* * @sample samples.collections.Sequences.Building.sequenceFromEnumeration */ @kotlin.internal.InlineOnly -public inline fun java.util.Enumeration.asSequence(): Sequence = this.iterator().asSequence() +public inline fun java.util.Enumeration.asSequence(): Sequence = this.iterator().asSequence() internal actual class ConstrainedOnceSequence actual constructor(sequence: Sequence) : Sequence { diff --git a/libraries/stdlib/src/kotlin/collections/AbstractCollection.kt b/libraries/stdlib/src/kotlin/collections/AbstractCollection.kt index d4a97f3e6c4..0f01306cbd2 100644 --- a/libraries/stdlib/src/kotlin/collections/AbstractCollection.kt +++ b/libraries/stdlib/src/kotlin/collections/AbstractCollection.kt @@ -7,7 +7,7 @@ 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. + * @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 protected constructor() : Collection { @@ -17,7 +17,7 @@ public abstract class AbstractCollection protected constructor() : Collec override fun contains(element: @UnsafeVariance E): Boolean = any { it == element } override fun containsAll(elements: Collection<@UnsafeVariance E>): Boolean = - elements.all { contains(it) } // use when js will support bound refs: elements.all(this::contains) + elements.all { contains(it) } // use when js will support bound refs: elements.all(this::contains) override fun isEmpty(): Boolean = size == 0 diff --git a/libraries/stdlib/src/kotlin/collections/AbstractIterator.kt b/libraries/stdlib/src/kotlin/collections/AbstractIterator.kt index a55241bf7ba..553b22792ed 100644 --- a/libraries/stdlib/src/kotlin/collections/AbstractIterator.kt +++ b/libraries/stdlib/src/kotlin/collections/AbstractIterator.kt @@ -17,7 +17,7 @@ private enum class State { * 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. */ -public abstract class AbstractIterator: Iterator { +public abstract class AbstractIterator : Iterator { private var state = State.NotReady private var nextValue: T? = null diff --git a/libraries/stdlib/src/kotlin/collections/AbstractMap.kt b/libraries/stdlib/src/kotlin/collections/AbstractMap.kt index 21c07380dc5..102131aeaf8 100644 --- a/libraries/stdlib/src/kotlin/collections/AbstractMap.kt +++ b/libraries/stdlib/src/kotlin/collections/AbstractMap.kt @@ -16,7 +16,7 @@ package kotlin.collections * * @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. -*/ + */ @SinceKotlin("1.1") public abstract class AbstractMap protected constructor() : Map { @@ -78,25 +78,29 @@ public abstract class AbstractMap protected constructor() : Map * Accessing this property first time creates a keys view from [entries]. * All subsequent accesses just return the created instance. */ - private @kotlin.jvm.Volatile var _keys: Set? = null - override val keys: Set get() { - if (_keys == null) { - _keys = object : AbstractSet() { - override operator fun contains(element: K): Boolean = containsKey(element) + override val keys: Set + get() { + if (_keys == null) { + _keys = object : AbstractSet() { + override operator fun contains(element: K): Boolean = containsKey(element) - override operator fun iterator(): Iterator { - val entryIterator = entries.iterator() - return object : Iterator { - override fun hasNext(): Boolean = entryIterator.hasNext() - override fun next(): K = entryIterator.next().key + override operator fun iterator(): Iterator { + val entryIterator = entries.iterator() + return object : Iterator { + override fun hasNext(): Boolean = entryIterator.hasNext() + override fun next(): K = entryIterator.next().key + } } - } - override val size: Int get() = this@AbstractMap.size + override val size: Int get() = this@AbstractMap.size + } } + return _keys!! } - return _keys!! - } + + @kotlin.jvm.Volatile + private var _keys: Set? = null + override fun toString(): String = entries.joinToString(", ", "{", "}") { toString(it) } @@ -110,25 +114,28 @@ public abstract class AbstractMap protected constructor() : Map * Accessing this property first time creates a values view from [entries]. * All subsequent accesses just return the created instance. */ - private @kotlin.jvm.Volatile var _values: Collection? = null - override val values: Collection get() { - if (_values == null) { - _values = object : AbstractCollection() { - override operator fun contains(element: @UnsafeVariance V): Boolean = containsValue(element) + override val values: Collection + get() { + if (_values == null) { + _values = object : AbstractCollection() { + override operator fun contains(element: @UnsafeVariance V): Boolean = containsValue(element) - override operator fun iterator(): Iterator { - val entryIterator = entries.iterator() - return object : Iterator { - override fun hasNext(): Boolean = entryIterator.hasNext() - override fun next(): V = entryIterator.next().value + override operator fun iterator(): Iterator { + val entryIterator = entries.iterator() + return object : Iterator { + override fun hasNext(): Boolean = entryIterator.hasNext() + override fun next(): V = entryIterator.next().value + } } - } - override val size: Int get() = this@AbstractMap.size + override val size: Int get() = this@AbstractMap.size + } } + return _values!! } - return _values!! - } + + @kotlin.jvm.Volatile + private var _values: Collection? = null private fun implFindEntry(key: K): Map.Entry? = entries.firstOrNull { it.key == key } diff --git a/libraries/stdlib/src/kotlin/collections/Arrays.kt b/libraries/stdlib/src/kotlin/collections/Arrays.kt index ce50eafb7c0..a3150f3c8ee 100644 --- a/libraries/stdlib/src/kotlin/collections/Arrays.kt +++ b/libraries/stdlib/src/kotlin/collections/Arrays.kt @@ -10,7 +10,6 @@ package kotlin.collections - /** * Returns a single list of all elements from all arrays in the given array. * @sample samples.collections.Arrays.Transformations.flattenArray diff --git a/libraries/stdlib/src/kotlin/collections/Collections.kt b/libraries/stdlib/src/kotlin/collections/Collections.kt index 6994de4c683..7f1202ef524 100644 --- a/libraries/stdlib/src/kotlin/collections/Collections.kt +++ b/libraries/stdlib/src/kotlin/collections/Collections.kt @@ -53,7 +53,7 @@ internal object EmptyList : List, Serializable, RandomAccess { internal fun Array.asCollection(): Collection = ArrayAsCollection(this, isVarargs = false) -private class ArrayAsCollection(val values: Array, val isVarargs: Boolean): Collection { +private class ArrayAsCollection(val values: Array, val isVarargs: Boolean) : Collection { override val size: Int get() = values.size override fun isEmpty(): Boolean = values.isEmpty() override fun contains(element: T): Boolean = values.contains(element) @@ -102,15 +102,15 @@ public inline fun arrayListOf(): ArrayList = ArrayList() * Returns a new [MutableList] with the given elements. * @sample samples.collections.Collections.Lists.mutableList */ -public fun mutableListOf(vararg elements: T): MutableList - = if (elements.size == 0) ArrayList() else ArrayList(ArrayAsCollection(elements, isVarargs = true)) +public fun mutableListOf(vararg elements: T): MutableList = + if (elements.size == 0) ArrayList() else ArrayList(ArrayAsCollection(elements, isVarargs = true)) /** * Returns a new [ArrayList] with the given elements. * @sample samples.collections.Collections.Lists.arrayList */ -public fun arrayListOf(vararg elements: T): ArrayList - = if (elements.size == 0) ArrayList() else ArrayList(ArrayAsCollection(elements, isVarargs = true)) +public fun arrayListOf(vararg elements: T): ArrayList = + 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). @@ -214,7 +214,7 @@ internal fun List.optimizeReadOnlyList() = when (size) { * @sample samples.collections.Collections.Lists.binarySearchOnComparable * @sample samples.collections.Collections.Lists.binarySearchWithBoundaries */ -public fun > List.binarySearch(element: T?, fromIndex: Int = 0, toIndex: Int = size): Int { +public fun > List.binarySearch(element: T?, fromIndex: Int = 0, toIndex: Int = size): Int { rangeCheck(size, fromIndex, toIndex) var low = fromIndex @@ -287,8 +287,13 @@ public fun List.binarySearch(element: T, comparator: Comparator, fr * so that the list (or the specified subrange of list) still remains sorted. * @sample samples.collections.Collections.Lists.binarySearchByKey */ -public inline fun > List.binarySearchBy(key: K?, fromIndex: Int = 0, toIndex: Int = size, crossinline selector: (T) -> K?): Int = - binarySearch(fromIndex, toIndex) { compareValues(selector(it), key) } +public inline fun > List.binarySearchBy( + key: K?, + fromIndex: Int = 0, + toIndex: Int = size, + crossinline selector: (T) -> K? +): Int = + binarySearch(fromIndex, toIndex) { compareValues(selector(it), key) } // do not introduce this overload --- too rare //public fun List.binarySearchBy(key: K, comparator: Comparator, fromIndex: Int = 0, toIndex: Int = size(), selector: (T) -> K): Int = diff --git a/libraries/stdlib/src/kotlin/collections/Grouping.kt b/libraries/stdlib/src/kotlin/collections/Grouping.kt index acaf87dc562..206c5906f83 100644 --- a/libraries/stdlib/src/kotlin/collections/Grouping.kt +++ b/libraries/stdlib/src/kotlin/collections/Grouping.kt @@ -47,7 +47,7 @@ public interface Grouping { */ @SinceKotlin("1.1") public inline fun Grouping.aggregate( - operation: (key: K, accumulator: R?, element: T, first: Boolean) -> R + operation: (key: K, accumulator: R?, element: T, first: Boolean) -> R ): Map { return aggregateTo(mutableMapOf(), operation) } @@ -72,8 +72,8 @@ public inline fun Grouping.aggregate( */ @SinceKotlin("1.1") public inline fun > Grouping.aggregateTo( - destination: M, - operation: (key: K, accumulator: R?, element: T, first: Boolean) -> R + destination: M, + operation: (key: K, accumulator: R?, element: T, first: Boolean) -> R ): M { for (e in this.sourceIterator()) { val key = keyOf(e) @@ -102,11 +102,11 @@ public inline fun > Grouping.aggregateTo( */ @SinceKotlin("1.1") public inline fun Grouping.fold( - initialValueSelector: (key: K, element: T) -> R, - operation: (key: K, accumulator: R, element: T) -> R + initialValueSelector: (key: K, element: T) -> R, + operation: (key: K, accumulator: R, element: T) -> R ): Map = - @Suppress("UNCHECKED_CAST") - aggregate { key, acc, e, first -> operation(key, if (first) initialValueSelector(key, e) else acc as R, e) } + @Suppress("UNCHECKED_CAST") + aggregate { key, acc, e, first -> operation(key, if (first) initialValueSelector(key, e) else acc as R, e) } /** * Groups elements from the [Grouping] source by key and applies [operation] to the elements of each group sequentially, @@ -131,12 +131,12 @@ public inline fun Grouping.fold( */ @SinceKotlin("1.1") public inline fun > Grouping.foldTo( - destination: M, - initialValueSelector: (key: K, element: T) -> R, - operation: (key: K, accumulator: R, element: T) -> R + destination: M, + initialValueSelector: (key: K, element: T) -> R, + operation: (key: K, accumulator: R, element: T) -> R ): M = - @Suppress("UNCHECKED_CAST") - aggregateTo(destination) { key, acc, e, first -> operation(key, if (first) initialValueSelector(key, e) else acc as R, e) } + @Suppress("UNCHECKED_CAST") + aggregateTo(destination) { key, acc, e, first -> operation(key, if (first) initialValueSelector(key, e) else acc as R, e) } /** @@ -152,11 +152,11 @@ public inline fun > Grouping.foldTo( */ @SinceKotlin("1.1") public inline fun Grouping.fold( - initialValue: R, - operation: (accumulator: R, element: T) -> R + initialValue: R, + operation: (accumulator: R, element: T) -> R ): Map = - @Suppress("UNCHECKED_CAST") - aggregate { _, acc, e, first -> operation(if (first) initialValue else acc as R, e) } + @Suppress("UNCHECKED_CAST") + aggregate { _, acc, e, first -> operation(if (first) initialValue else acc as R, e) } /** * Groups elements from the [Grouping] source by key and applies [operation] to the elements of each group sequentially, @@ -175,12 +175,12 @@ public inline fun Grouping.fold( */ @SinceKotlin("1.1") public inline fun > Grouping.foldTo( - destination: M, - initialValue: R, - operation: (accumulator: R, element: T) -> R + destination: M, + initialValue: R, + operation: (accumulator: R, element: T) -> R ): M = - @Suppress("UNCHECKED_CAST") - aggregateTo(destination) { _, acc, e, first -> operation(if (first) initialValue else acc as R, e) } + @Suppress("UNCHECKED_CAST") + aggregateTo(destination) { _, acc, e, first -> operation(if (first) initialValue else acc as R, e) } /** @@ -199,12 +199,12 @@ public inline fun > Grouping.foldTo( */ @SinceKotlin("1.1") public inline fun Grouping.reduce( - operation: (key: K, accumulator: S, element: T) -> S + operation: (key: K, accumulator: S, element: T) -> S ): Map = - aggregate { key, acc, e, first -> - @Suppress("UNCHECKED_CAST") - if (first) e else operation(key, acc as S, e) - } + aggregate { key, acc, e, first -> + @Suppress("UNCHECKED_CAST") + if (first) e else operation(key, acc as S, e) + } /** * Groups elements from the [Grouping] source by key and applies the reducing [operation] to the elements of each group @@ -225,13 +225,13 @@ public inline fun Grouping.reduce( */ @SinceKotlin("1.1") public inline fun > Grouping.reduceTo( - destination: M, - operation: (key: K, accumulator: S, element: T) -> S + destination: M, + operation: (key: K, accumulator: S, element: T) -> S ): M = - aggregateTo(destination) { key, acc, e, first -> - @Suppress("UNCHECKED_CAST") - if (first) e else operation(key, acc as S, e) - } + aggregateTo(destination) { key, acc, e, first -> + @Suppress("UNCHECKED_CAST") + if (first) e else operation(key, acc as S, e) + } /** @@ -246,7 +246,7 @@ public inline fun > Grouping.reduceTo */ @SinceKotlin("1.1") public fun > Grouping.eachCountTo(destination: M): M = - foldTo(destination, 0) { acc, _ -> acc + 1 } + foldTo(destination, 0) { acc, _ -> acc + 1 } /* /** diff --git a/libraries/stdlib/src/kotlin/collections/Iterables.kt b/libraries/stdlib/src/kotlin/collections/Iterables.kt index fc6f51de5b1..d1b00c222ba 100644 --- a/libraries/stdlib/src/kotlin/collections/Iterables.kt +++ b/libraries/stdlib/src/kotlin/collections/Iterables.kt @@ -4,6 +4,7 @@ */ @file:kotlin.jvm.JvmMultifileClass @file:kotlin.jvm.JvmName("CollectionsKt") + package kotlin.collections /** @@ -42,23 +43,23 @@ private fun Collection.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. */ internal fun Iterable.convertToSetForSetOperationWith(source: Iterable): Collection = - when(this) { - is Set -> this - is Collection -> - when { - source is Collection && source.size < 2 -> this - else -> if (this.safeToConvertToSet()) toHashSet() else this - } - else -> toHashSet() - } + when (this) { + is Set -> this + is Collection -> + when { + source is Collection && source.size < 2 -> this + else -> if (this.safeToConvertToSet()) toHashSet() else this + } + else -> toHashSet() + } /** Converts this collection to a set, when it's worth so and it doesn't change contains method behavior. */ internal fun Iterable.convertToSetForSetOperation(): Collection = - when(this) { - is Set -> this - is Collection -> if (this.safeToConvertToSet()) toHashSet() else this - else -> toHashSet() - } + when (this) { + is Set -> this + is Collection -> if (this.safeToConvertToSet()) toHashSet() else this + else -> toHashSet() + } /** diff --git a/libraries/stdlib/src/kotlin/collections/Iterators.kt b/libraries/stdlib/src/kotlin/collections/Iterators.kt index e4eff56c3d0..7455ee2e959 100644 --- a/libraries/stdlib/src/kotlin/collections/Iterators.kt +++ b/libraries/stdlib/src/kotlin/collections/Iterators.kt @@ -27,7 +27,7 @@ public fun Iterator.withIndex(): Iterator> = IndexingIter * Performs the given [operation] on each element of this [Iterator]. * @sample samples.collections.Iterators.forEachIterator */ -public inline fun Iterator.forEach(operation: (T) -> Unit) : Unit { +public inline fun Iterator.forEach(operation: (T) -> Unit): Unit { for (element in this) operation(element) } diff --git a/libraries/stdlib/src/kotlin/collections/MapAccessors.kt b/libraries/stdlib/src/kotlin/collections/MapAccessors.kt index 3f202d9e9a1..c63fb185857 100644 --- a/libraries/stdlib/src/kotlin/collections/MapAccessors.kt +++ b/libraries/stdlib/src/kotlin/collections/MapAccessors.kt @@ -4,6 +4,7 @@ */ @file:kotlin.jvm.JvmName("MapAccessorsKt") + package kotlin.collections 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]). */ @kotlin.internal.InlineOnly -public inline operator fun Map.getValue(thisRef: Any?, property: KProperty<*>): V1 - = @Suppress("UNCHECKED_CAST") (getOrImplicitDefault(property.name) as V1) +public inline operator fun Map.getValue(thisRef: Any?, property: KProperty<*>): V1 = + @Suppress("UNCHECKED_CAST") (getOrImplicitDefault(property.name) as V1) /** * Returns the value of the property for the given object from this mutable map. @@ -31,15 +32,15 @@ public inline operator fun Map.getValue(thisRef: */ @kotlin.jvm.JvmName("getVar") @kotlin.internal.InlineOnly -public inline operator fun MutableMap.getValue(thisRef: Any?, property: KProperty<*>): V1 - = @Suppress("UNCHECKED_CAST") (getOrImplicitDefault(property.name) as V1) +public inline operator fun MutableMap.getValue(thisRef: Any?, property: KProperty<*>): V1 = + @Suppress("UNCHECKED_CAST") (getOrImplicitDefault(property.name) as V1) @Deprecated("Use getValue() with two type parameters instead") @kotlin.jvm.JvmName("getVarContravariant") @kotlin.internal.LowPriorityInOverloadResolution @kotlin.internal.InlineOnly -public inline fun MutableMap.getValue(thisRef: Any?, property: KProperty<*>): V - = @Suppress("UNCHECKED_CAST") (getOrImplicitDefault(property.name) as V) +public inline fun MutableMap.getValue(thisRef: Any?, property: KProperty<*>): V = + @Suppress("UNCHECKED_CAST") (getOrImplicitDefault(property.name) as V) /** * Stores the value of the property for the given object in this mutable map. diff --git a/libraries/stdlib/src/kotlin/collections/MapWithDefault.kt b/libraries/stdlib/src/kotlin/collections/MapWithDefault.kt index afac9f25c26..e04b60b873d 100644 --- a/libraries/stdlib/src/kotlin/collections/MapWithDefault.kt +++ b/libraries/stdlib/src/kotlin/collections/MapWithDefault.kt @@ -33,10 +33,10 @@ internal fun Map.getOrImplicitDefault(key: K): V { * When this map already has an implicit default value provided with a former call to [withDefault], it is being replaced by this call. */ public fun Map.withDefault(defaultValue: (key: K) -> V): Map = - when (this) { - is MapWithDefault -> this.map.withDefault(defaultValue) - else -> MapWithDefaultImpl(this, defaultValue) - } + when (this) { + is MapWithDefault -> this.map.withDefault(defaultValue) + else -> MapWithDefaultImpl(this, defaultValue) + } /** * Returns a wrapper of this mutable map, having the implicit default value provided with the specified function [defaultValue]. @@ -48,26 +48,23 @@ public fun Map.withDefault(defaultValue: (key: K) -> V): Map */ @kotlin.jvm.JvmName("withDefaultMutable") public fun MutableMap.withDefault(defaultValue: (key: K) -> V): MutableMap = - when (this) { - is MutableMapWithDefault -> this.map.withDefault(defaultValue) - else -> MutableMapWithDefaultImpl(this, defaultValue) - } + when (this) { + is MutableMapWithDefault -> this.map.withDefault(defaultValue) + else -> MutableMapWithDefaultImpl(this, defaultValue) + } - - - -private interface MapWithDefault: Map { +private interface MapWithDefault : Map { public val map: Map public fun getOrImplicitDefault(key: K): V } -private interface MutableMapWithDefault: MutableMap, MapWithDefault { +private interface MutableMapWithDefault : MutableMap, MapWithDefault { public override val map: MutableMap } -private class MapWithDefaultImpl(public override val map: Map, private val default: (key: K) -> V) : MapWithDefault { +private class MapWithDefaultImpl(public override val map: Map, private val default: (key: K) -> V) : MapWithDefault { override fun equals(other: Any?): Boolean = map.equals(other) override fun hashCode(): Int = map.hashCode() override fun toString(): String = map.toString() @@ -83,7 +80,7 @@ private class MapWithDefaultImpl(public override val map: Map, pr override fun getOrImplicitDefault(key: K): V = map.getOrElseNullable(key, { default(key) }) } -private class MutableMapWithDefaultImpl(public override val map: MutableMap, private val default: (key: K) -> V): MutableMapWithDefault { +private class MutableMapWithDefaultImpl(public override val map: MutableMap, private val default: (key: K) -> V) : MutableMapWithDefault { override fun equals(other: Any?): Boolean = map.equals(other) override fun hashCode(): Int = map.hashCode() override fun toString(): String = map.toString() diff --git a/libraries/stdlib/src/kotlin/collections/Maps.kt b/libraries/stdlib/src/kotlin/collections/Maps.kt index 7e1c1b0c986..5b0547e158a 100644 --- a/libraries/stdlib/src/kotlin/collections/Maps.kt +++ b/libraries/stdlib/src/kotlin/collections/Maps.kt @@ -11,7 +11,7 @@ package kotlin.collections private object EmptyMap : Map, Serializable { 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 toString(): String = "{}" @@ -48,7 +48,8 @@ public fun emptyMap(): Map = @Suppress("UNCHECKED_CAST") (EmptyMap * * @sample samples.collections.Maps.Instantiation.mapFromPairs */ -public fun mapOf(vararg pairs: Pair): Map = if (pairs.size > 0) pairs.toMap(LinkedHashMap(mapCapacity(pairs.size))) else emptyMap() +public fun mapOf(vararg pairs: Pair): Map = + if (pairs.size > 0) pairs.toMap(LinkedHashMap(mapCapacity(pairs.size))) else emptyMap() /** * Returns an empty read-only map. @@ -80,8 +81,8 @@ public inline fun mutableMapOf(): MutableMap = LinkedHashMap() * @sample samples.collections.Maps.Instantiation.mutableMapFromPairs * @sample samples.collections.Maps.Instantiation.emptyMutableMap */ -public fun mutableMapOf(vararg pairs: Pair): MutableMap - = LinkedHashMap(mapCapacity(pairs.size)).apply { putAll(pairs) } +public fun mutableMapOf(vararg pairs: Pair): MutableMap = + LinkedHashMap(mapCapacity(pairs.size)).apply { putAll(pairs) } /** * Returns an empty new [HashMap]. @@ -96,8 +97,7 @@ public inline fun hashMapOf(): HashMap = HashMap() * * @sample samples.collections.Maps.Instantiation.hashMapFromPairs */ -public fun hashMapOf(vararg pairs: Pair): HashMap - = HashMap(mapCapacity(pairs.size)).apply { putAll(pairs) } +public fun hashMapOf(vararg pairs: Pair): HashMap = HashMap(mapCapacity(pairs.size)).apply { putAll(pairs) } /** * Returns an empty new [LinkedHashMap]. @@ -116,8 +116,7 @@ public inline fun linkedMapOf(): LinkedHashMap = LinkedHashMap linkedMapOf(vararg pairs: Pair): LinkedHashMap - = pairs.toMap(LinkedHashMap(mapCapacity(pairs.size))) +public fun linkedMapOf(vararg pairs: Pair): LinkedHashMap = 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 @@ -145,7 +144,7 @@ public inline fun Map.isNotEmpty(): Boolean = !isEmpty() * Returns the [Map] if its not `null`, or the empty [Map] otherwise. */ @kotlin.internal.InlineOnly -public inline fun Map?.orEmpty() : Map = this ?: emptyMap() +public inline fun Map?.orEmpty(): Map = this ?: emptyMap() /** * Checks if the map contains the given key. @@ -153,14 +152,14 @@ public inline fun Map?.orEmpty() : Map = this ?: emptyMap() * This method allows to use the `x in map` syntax for checking whether an object is contained in the map. */ @kotlin.internal.InlineOnly -public inline operator fun <@kotlin.internal.OnlyInputTypes K, V> Map.contains(key: K) : Boolean = containsKey(key) +public inline operator fun <@kotlin.internal.OnlyInputTypes K, V> Map.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. */ @kotlin.internal.InlineOnly -public inline operator fun <@kotlin.internal.OnlyInputTypes K, V> Map.get(key: K): V? - = @Suppress("UNCHECKED_CAST") (this as Map).get(key) +public inline operator fun <@kotlin.internal.OnlyInputTypes K, V> Map.get(key: K): V? = + @Suppress("UNCHECKED_CAST") (this as Map).get(key) /** * Allows to use the index operator for storing values in a mutable map. @@ -176,8 +175,8 @@ public inline operator fun MutableMap.set(key: K, value: V): Unit { * Allows to overcome type-safety restriction of `containsKey` that requires to pass a key of type `K`. */ @kotlin.internal.InlineOnly -public inline fun <@kotlin.internal.OnlyInputTypes K> Map.containsKey(key: K): Boolean - = @Suppress("UNCHECKED_CAST") (this as Map).containsKey(key) +public inline fun <@kotlin.internal.OnlyInputTypes K> Map.containsKey(key: K): Boolean = + @Suppress("UNCHECKED_CAST") (this as Map).containsKey(key) /** * Returns `true` if the map maps one or more keys to the specified [value]. @@ -197,8 +196,8 @@ public inline fun Map.containsValue * Allows to overcome type-safety restriction of `remove` that requires to pass a key of type `K`. */ @kotlin.internal.InlineOnly -public inline fun <@kotlin.internal.OnlyInputTypes K, V> MutableMap.remove(key: K): V? - = @Suppress("UNCHECKED_CAST") (this as MutableMap).remove(key) +public inline fun <@kotlin.internal.OnlyInputTypes K, V> MutableMap.remove(key: K): V? = + @Suppress("UNCHECKED_CAST") (this as MutableMap).remove(key) /** * Returns the key component of the map entry. @@ -327,7 +326,7 @@ public fun MutableMap.putAll(pairs: Array>): 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. */ -public fun MutableMap.putAll(pairs: Iterable>): Unit { +public fun MutableMap.putAll(pairs: Iterable>): Unit { for ((key, value) in pairs) { put(key, value) } @@ -336,7 +335,7 @@ public fun MutableMap.putAll(pairs: Iterable>): 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. */ -public fun MutableMap.putAll(pairs: Sequence>): Unit { +public fun MutableMap.putAll(pairs: Sequence>): Unit { for ((key, value) in pairs) { put(key, value) } @@ -471,15 +470,15 @@ public fun Iterable>.toMap(): Map { /** * Populates and returns the [destination] mutable map with key-value pairs from the given collection of pairs. */ -public fun > Iterable>.toMap(destination: M): M - = destination.apply { putAll(this@toMap) } +public fun > Iterable>.toMap(destination: M): M = + destination.apply { putAll(this@toMap) } /** * 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. */ -public fun Array>.toMap(): Map = when(size) { +public fun Array>.toMap(): Map = when (size) { 0 -> emptyMap() 1 -> mapOf(this[0]) else -> toMap(LinkedHashMap(mapCapacity(size))) @@ -488,8 +487,8 @@ public fun Array>.toMap(): Map = when(size) { /** * Populates and returns the [destination] mutable map with key-value pairs from the given array of pairs. */ -public fun > Array>.toMap(destination: M): M - = destination.apply { putAll(this@toMap) } +public fun > Array>.toMap(destination: M): M = + destination.apply { putAll(this@toMap) } /** * Returns a new map containing all key-value pairs from the given sequence of pairs. @@ -501,8 +500,8 @@ public fun Sequence>.toMap(): Map = toMap(LinkedHashMap< /** * Populates and returns the [destination] mutable map with key-value pairs from the given sequence of pairs. */ -public fun > Sequence>.toMap(destination: M): M - = destination.apply { putAll(this@toMap) } +public fun > Sequence>.toMap(destination: M): M = + destination.apply { putAll(this@toMap) } /** * Returns a new read-only map containing all key-value pairs from the original map. @@ -528,8 +527,8 @@ public fun Map.toMutableMap(): MutableMap = LinkedHashMap * Populates and returns the [destination] mutable map with key-value pairs from the given map. */ @SinceKotlin("1.1") -public fun > Map.toMap(destination: M): M - = destination.apply { putAll(this@toMap) } +public fun > Map.toMap(destination: M): M = + 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]. @@ -537,8 +536,8 @@ public fun > Map.toMap(destination: M * 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. */ -public operator fun Map.plus(pair: Pair): Map - = if (this.isEmpty()) mapOf(pair) else LinkedHashMap(this).apply { put(pair.first, pair.second) } +public operator fun Map.plus(pair: Pair): Map = + 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]. @@ -546,8 +545,8 @@ public operator fun Map.plus(pair: Pair): 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. */ -public operator fun Map.plus(pairs: Iterable>): Map - = if (this.isEmpty()) pairs.toMap() else LinkedHashMap(this).apply { putAll(pairs) } +public operator fun Map.plus(pairs: Iterable>): Map = + 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]. @@ -555,8 +554,8 @@ public operator fun Map.plus(pairs: Iterable>): 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. */ -public operator fun Map.plus(pairs: Array>): Map - = if (this.isEmpty()) pairs.toMap() else LinkedHashMap(this).apply { putAll(pairs) } +public operator fun Map.plus(pairs: Array>): Map = + 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]. @@ -564,8 +563,8 @@ public operator fun Map.plus(pairs: Array>): 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. */ -public operator fun Map.plus(pairs: Sequence>): Map - = LinkedHashMap(this).apply { putAll(pairs) }.optimizeReadOnlyMap() +public operator fun Map.plus(pairs: Sequence>): Map = + LinkedHashMap(this).apply { putAll(pairs) }.optimizeReadOnlyMap() /** * Creates a new read-only map by replacing or adding entries to this map from another [map]. @@ -573,8 +572,8 @@ public operator fun Map.plus(pairs: Sequence>): 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]. */ -public operator fun Map.plus(map: Map): Map - = LinkedHashMap(this).apply { putAll(map) } +public operator fun Map.plus(map: Map): Map = + LinkedHashMap(this).apply { putAll(map) } /** @@ -623,8 +622,8 @@ public inline operator fun MutableMap.plusAssign(map: Map Map.minus(key: K): Map - = this.toMutableMap().apply { minusAssign(key) }.optimizeReadOnlyMap() +public operator fun Map.minus(key: K): Map = + this.toMutableMap().apply { minusAssign(key) }.optimizeReadOnlyMap() /** * Returns a map containing all entries of the original map except those entries @@ -633,8 +632,8 @@ public operator fun Map.minus(key: K): Map * The returned map preserves the entry iteration order of the original map. */ @SinceKotlin("1.1") -public operator fun Map.minus(keys: Iterable): Map - = this.toMutableMap().apply { minusAssign(keys) }.optimizeReadOnlyMap() +public operator fun Map.minus(keys: Iterable): Map = + this.toMutableMap().apply { minusAssign(keys) }.optimizeReadOnlyMap() /** * Returns a map containing all entries of the original map except those entries @@ -643,8 +642,8 @@ public operator fun Map.minus(keys: Iterable): Map * The returned map preserves the entry iteration order of the original map. */ @SinceKotlin("1.1") -public operator fun Map.minus(keys: Array): Map - = this.toMutableMap().apply { minusAssign(keys) }.optimizeReadOnlyMap() +public operator fun Map.minus(keys: Array): Map = + this.toMutableMap().apply { minusAssign(keys) }.optimizeReadOnlyMap() /** * Returns a map containing all entries of the original map except those entries @@ -653,8 +652,8 @@ public operator fun Map.minus(keys: Array): Map * The returned map preserves the entry iteration order of the original map. */ @SinceKotlin("1.1") -public operator fun Map.minus(keys: Sequence): Map - = this.toMutableMap().apply { minusAssign(keys) }.optimizeReadOnlyMap() +public operator fun Map.minus(keys: Sequence): Map = + this.toMutableMap().apply { minusAssign(keys) }.optimizeReadOnlyMap() /** * Removes the entry with the given [key] from this mutable map. diff --git a/libraries/stdlib/src/kotlin/collections/MutableCollections.kt b/libraries/stdlib/src/kotlin/collections/MutableCollections.kt index 1a889dce985..a9cf4286853 100644 --- a/libraries/stdlib/src/kotlin/collections/MutableCollections.kt +++ b/libraries/stdlib/src/kotlin/collections/MutableCollections.kt @@ -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. */ @kotlin.internal.InlineOnly -public inline fun <@kotlin.internal.OnlyInputTypes T> MutableCollection.remove(element: T): Boolean - = @Suppress("UNCHECKED_CAST") (this as MutableCollection).remove(element) +public inline fun <@kotlin.internal.OnlyInputTypes T> MutableCollection.remove(element: T): Boolean = + @Suppress("UNCHECKED_CAST") (this as MutableCollection).remove(element) /** * 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.r * @return `true` if any of the specified elements was removed from the collection, `false` if the collection was not modified. */ @kotlin.internal.InlineOnly -public inline fun <@kotlin.internal.OnlyInputTypes T> MutableCollection.removeAll(elements: Collection): Boolean - = @Suppress("UNCHECKED_CAST") (this as MutableCollection).removeAll(elements) +public inline fun <@kotlin.internal.OnlyInputTypes T> MutableCollection.removeAll(elements: Collection): Boolean = + @Suppress("UNCHECKED_CAST") (this as MutableCollection).removeAll(elements) /** * 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.r * @return `true` if any element was removed from the collection, `false` if the collection was not modified. */ @kotlin.internal.InlineOnly -public inline fun <@kotlin.internal.OnlyInputTypes T> MutableCollection.retainAll(elements: Collection): Boolean - = @Suppress("UNCHECKED_CAST") (this as MutableCollection).retainAll(elements) +public inline fun <@kotlin.internal.OnlyInputTypes T> MutableCollection.retainAll(elements: Collection): Boolean = + @Suppress("UNCHECKED_CAST") (this as MutableCollection).retainAll(elements) /** * Removes the element at the specified [index] from this list. @@ -159,7 +159,7 @@ public fun MutableIterable.retainAll(predicate: (T) -> Boolean): Boolean private fun MutableIterable.filterInPlace(predicate: (T) -> Boolean, predicateResultToRemove: Boolean): Boolean { var result = false - with (iterator()) { + with(iterator()) { while (hasNext()) if (predicate(next()) == predicateResultToRemove) { remove() @@ -199,8 +199,7 @@ private fun MutableList.filterInPlace(predicate: (T) -> Boolean, predicat removeAt(removeIndex) return true - } - else { + } else { return false } } diff --git a/libraries/stdlib/src/kotlin/collections/ReversedViews.kt b/libraries/stdlib/src/kotlin/collections/ReversedViews.kt index 10b3415ccb1..078d10267f2 100644 --- a/libraries/stdlib/src/kotlin/collections/ReversedViews.kt +++ b/libraries/stdlib/src/kotlin/collections/ReversedViews.kt @@ -27,11 +27,12 @@ private class ReversedList(private val delegate: MutableList) : AbstractMu delegate.add(reversePositionIndex(index), element) } } + 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}].") private fun List<*>.reversePositionIndex(index: Int) = - if (index in 0..size) size - index else throw IndexOutOfBoundsException("Position index $index must be in range [${0..size}].") + if (index in 0..size) size - index else throw IndexOutOfBoundsException("Position index $index must be in range [${0..size}].") /** diff --git a/libraries/stdlib/src/kotlin/collections/Sequences.kt b/libraries/stdlib/src/kotlin/collections/Sequences.kt index 10764461f79..0fe4bc68b29 100644 --- a/libraries/stdlib/src/kotlin/collections/Sequences.kt +++ b/libraries/stdlib/src/kotlin/collections/Sequences.kt @@ -91,12 +91,13 @@ public fun Sequence>.unzip(): Pair, List> { * the specified [predicate]. * * @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(private val sequence: Sequence, - private val sendWhen: Boolean = true, - private val predicate: (T) -> Boolean - ) : Sequence { +internal class FilteringSequence( + private val sequence: Sequence, + private val sendWhen: Boolean = true, + private val predicate: (T) -> Boolean +) : Sequence { override fun iterator(): Iterator = object : Iterator { val iterator = sequence.iterator() @@ -203,10 +204,11 @@ constructor(private val sequence: Sequence) : Sequence> { * values as soon as one of the underlying sequences stops returning values. */ internal class MergingSequence - constructor(private val sequence1: Sequence, - private val sequence2: Sequence, - private val transform: (T1, T2) -> V - ) : Sequence { +constructor( + private val sequence1: Sequence, + private val sequence2: Sequence, + private val transform: (T1, T2) -> V +) : Sequence { override fun iterator(): Iterator = object : Iterator { val iterator1 = sequence1.iterator() val iterator2 = sequence2.iterator() @@ -221,11 +223,11 @@ internal class MergingSequence } internal class FlatteningSequence - constructor( - private val sequence: Sequence, - private val transformer: (T) -> R, - private val iterator: (R) -> Iterator - ) : Sequence { +constructor( + private val sequence: Sequence, + private val transformer: (T) -> R, + private val iterator: (R) -> Iterator +) : Sequence { override fun iterator(): Iterator = object : Iterator { val iterator = sequence.iterator() var itemIterator: Iterator? = null @@ -273,16 +275,16 @@ internal interface DropTakeSequence : Sequence { * A sequence that skips [startIndex] values from the underlying [sequence] * and stops returning values right before [endIndex], i.e. stops at `endIndex - 1` */ -internal class SubSequence ( - private val sequence: Sequence, - private val startIndex: Int, - private val endIndex: Int -): Sequence, DropTakeSequence { +internal class SubSequence( + private val sequence: Sequence, + private val startIndex: Int, + private val endIndex: Int +) : Sequence, DropTakeSequence { init { require(startIndex >= 0) { "startIndex should be non-negative, but is $startIndex" } 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 @@ -297,7 +299,7 @@ internal class SubSequence ( // Shouldn't be called from constructor to avoid premature iteration private fun drop() { - while(position < startIndex && iterator.hasNext()) { + while (position < startIndex && iterator.hasNext()) { iterator.next() position++ } @@ -322,13 +324,13 @@ internal class SubSequence ( * A sequence that returns at most [count] values from the underlying [sequence], and stops returning values * as soon as that count is reached. */ -internal class TakeSequence ( +internal class TakeSequence( private val sequence: Sequence, private val count: Int ) : Sequence, DropTakeSequence { 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 = if (n >= count) emptySequence() else SubSequence(sequence, n, count) @@ -356,9 +358,10 @@ internal class TakeSequence ( * `true`, and stops returning values once the function returns `false` for the next element. */ internal class TakeWhileSequence - constructor(private val sequence: Sequence, - private val predicate: (T) -> Boolean - ) : Sequence { +constructor( + private val sequence: Sequence, + private val predicate: (T) -> Boolean +) : Sequence { override fun iterator(): Iterator = object : Iterator { val iterator = sequence.iterator() var nextState: Int = -1 // -1 for unknown, 0 for done, 1 for continue @@ -402,12 +405,12 @@ internal class TakeWhileSequence * A sequence that skips the specified number of values from the underlying [sequence] and returns * all values after that. */ -internal class DropSequence ( - private val sequence: Sequence, - private val count: Int +internal class DropSequence( + private val sequence: Sequence, + private val count: Int ) : Sequence, DropTakeSequence { 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 = DropSequence(sequence, count + n) @@ -442,9 +445,10 @@ internal class DropSequence ( * all values after that. */ internal class DropWhileSequence - constructor(private val sequence: Sequence, - private val predicate: (T) -> Boolean - ) : Sequence { +constructor( + private val sequence: Sequence, + private val predicate: (T) -> Boolean +) : Sequence { override fun iterator(): Iterator = object : Iterator { val iterator = sequence.iterator() @@ -485,11 +489,11 @@ internal class DropWhileSequence } } -internal class DistinctSequence(private val source : Sequence, private val keySelector : (T) -> K) : Sequence { +internal class DistinctSequence(private val source: Sequence, private val keySelector: (T) -> K) : Sequence { override fun iterator(): Iterator = DistinctIterator(source.iterator(), keySelector) } -private class DistinctIterator(private val source : Iterator, private val keySelector : (T) -> K) : AbstractIterator() { +private class DistinctIterator(private val source: Iterator, private val keySelector: (T) -> K) : AbstractIterator() { private val observed = HashSet() override fun computeNext() { @@ -508,7 +512,7 @@ private class DistinctIterator(private val source : Iterator, private v } -private class GeneratorSequence(private val getInitialValue: () -> T?, private val getNextValue: (T) -> T?): Sequence { +private class GeneratorSequence(private val getInitialValue: () -> T?, private val getNextValue: (T) -> T?) : Sequence { override fun iterator(): Iterator = object : Iterator { var nextItem: T? = null var nextState: Int = -2 // -2 for initial unknown, -1 for next unknown, 0 for done, 1 for continue @@ -553,7 +557,6 @@ public fun Sequence.constrainOnce(): Sequence { } - /** * 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 generateSequence(seed: T?, nextFunction: (T) -> T?): Sequen * * @sample samples.collections.Sequences.Building.generateSequenceWithLazySeed */ -public fun generateSequence(seedFunction: () -> T?, nextFunction: (T) -> T?): Sequence = - GeneratorSequence(seedFunction, nextFunction) +public fun generateSequence(seedFunction: () -> T?, nextFunction: (T) -> T?): Sequence = + GeneratorSequence(seedFunction, nextFunction) diff --git a/libraries/stdlib/src/kotlin/collections/Sets.kt b/libraries/stdlib/src/kotlin/collections/Sets.kt index ce646bb3616..c4036f6749b 100644 --- a/libraries/stdlib/src/kotlin/collections/Sets.kt +++ b/libraries/stdlib/src/kotlin/collections/Sets.kt @@ -32,6 +32,7 @@ internal object EmptySet : Set, Serializable { * @sample samples.collections.Collections.Sets.emptyReadOnlySet */ public fun emptySet(): Set = EmptySet + /** * Returns a new read-only set with the given elements. * Elements of the set are iterated in the order they were specified. diff --git a/libraries/stdlib/src/kotlin/collections/SlidingWindow.kt b/libraries/stdlib/src/kotlin/collections/SlidingWindow.kt index a11ab034574..e707e7d10ad 100644 --- a/libraries/stdlib/src/kotlin/collections/SlidingWindow.kt +++ b/libraries/stdlib/src/kotlin/collections/SlidingWindow.kt @@ -86,7 +86,7 @@ internal class MovingSubList(private val list: List) : AbstractList * * Buffer overflow is not allowed so [add] doesn't overwrite tail but raises an exception. */ -private class RingBuffer(val capacity: Int): AbstractList(), RandomAccess { +private class RingBuffer(val capacity: Int) : AbstractList(), RandomAccess { init { require(capacity >= 0) { "ring buffer capacity should not be negative but it is $capacity" } } @@ -106,25 +106,25 @@ private class RingBuffer(val capacity: Int): AbstractList(), RandomAccess fun isFull() = size == capacity override fun iterator(): Iterator = object : AbstractIterator() { - private var count = size - private var index = startIndex + private var count = size + private var index = startIndex - override fun computeNext() { - if (count == 0) { - done() - } else { - @Suppress("UNCHECKED_CAST") - setNext(buffer[index] as T) - index = index.forward(1) - count-- - } + override fun computeNext() { + if (count == 0) { + done() + } else { + @Suppress("UNCHECKED_CAST") + setNext(buffer[index] as T) + index = index.forward(1) + count-- } + } } @Suppress("UNCHECKED_CAST") override fun toArray(array: Array): Array { val result: Array = - if (array.size < this.size) array.copyOf(this.size) else array as Array + if (array.size < this.size) array.copyOf(this.size) else array as Array val size = this.size