From e37d8174c36c8144e60779bf949e4de2e22072b0 Mon Sep 17 00:00:00 2001 From: Ilya Ryzhenkov Date: Tue, 18 Mar 2014 13:45:31 +0400 Subject: [PATCH] New stdlib generators --- js/js.libraries/src/core/javautil.kt | 2 +- js/js.libraries/src/stdlib/JUMapsCode.kt | 21 - js/js.libraries/src/stdlib/jutilCode.kt | 28 - libraries/stdlib/src/generated/_Aggregates.kt | 2209 ++++++++++++++++ libraries/stdlib/src/generated/_Arrays.kt | 511 +--- .../stdlib/src/generated/_BooleanArrays.kt | 447 ---- libraries/stdlib/src/generated/_ByteArrays.kt | 482 ---- libraries/stdlib/src/generated/_CharArrays.kt | 475 ---- .../stdlib/src/generated/_Collections.kt | 21 - .../stdlib/src/generated/_DoubleArrays.kt | 482 ---- libraries/stdlib/src/generated/_Elements.kt | 2339 +++++++++++++++++ libraries/stdlib/src/generated/_Filtering.kt | 1167 ++++++++ .../stdlib/src/generated/_FloatArrays.kt | 482 ---- libraries/stdlib/src/generated/_Generators.kt | 836 ++++++ libraries/stdlib/src/generated/_Guards.kt | 61 + libraries/stdlib/src/generated/_IntArrays.kt | 482 ---- libraries/stdlib/src/generated/_Iterables.kt | 476 ---- libraries/stdlib/src/generated/_LongArrays.kt | 482 ---- libraries/stdlib/src/generated/_Mapping.kt | 858 ++++++ libraries/stdlib/src/generated/_Numeric.kt | 217 ++ libraries/stdlib/src/generated/_Ordering.kt | 194 ++ .../stdlib/src/generated/_ShortArrays.kt | 482 ---- libraries/stdlib/src/generated/_Snapshots.kt | 720 +++++ libraries/stdlib/src/generated/_SpecialJVM.kt | 361 +++ libraries/stdlib/src/generated/_Strings.kt | 361 +++ libraries/stdlib/src/kotlin/ArraysJVM.kt | 111 - libraries/stdlib/src/kotlin/Deprecated.kt | 73 + libraries/stdlib/src/kotlin/Functions.kt | 12 + .../stdlib/src/kotlin/IterablesSpecial.kt | 77 - libraries/stdlib/src/kotlin/JUtil.kt | 103 - libraries/stdlib/src/kotlin/JUtilJVM.kt | 114 - libraries/stdlib/src/kotlin/Lists.kt | 82 - .../stdlib/src/kotlin/MutableCollections.kt | 15 - libraries/stdlib/src/kotlin/Standard.kt | 53 +- libraries/stdlib/src/kotlin/StandardJVM.kt | 42 +- .../src/kotlin/{ => collections}/Arrays.kt | 6 - .../src/kotlin/collections/ArraysJVM.kt | 37 + .../kotlin/{ => collections}/Exceptions.kt | 0 .../{ => collections}/ImmutableArrayList.kt | 0 .../src/kotlin/collections/Iterators.kt | 15 + .../stdlib/src/kotlin/collections/JUtil.kt | 120 + .../stdlib/src/kotlin/collections/JUtilJVM.kt | 60 + .../src/kotlin/{ => collections}/Maps.kt | 27 +- .../src/kotlin/{ => collections}/MapsJVM.kt | 6 +- .../kotlin/collections/MutableCollections.kt | 16 + .../stdlib/src/kotlin/collections/Stream.kt | 132 + .../{ => collections/iterators}/Iterators.kt | 31 +- .../iterators}/IteratorsJVM.kt | 2 + .../collections/iterators}/_Iterators.kt | 74 +- libraries/stdlib/src/kotlin/dom/Dom.kt | 46 +- libraries/stdlib/src/kotlin/dom/DomJVM.kt | 4 +- libraries/stdlib/src/kotlin/io/Closable.kt | 31 + libraries/stdlib/src/kotlin/io/Files.kt | 6 +- libraries/stdlib/src/kotlin/io/JIO.kt | 172 +- libraries/stdlib/src/kotlin/test/TestJVM.kt | 2 +- .../stdlib/src/kotlin/{ => text}/Char.kt | 2 +- .../stdlib/src/kotlin/{ => text}/Strings.kt | 8 +- .../src/kotlin/{ => text}/StringsJVM.kt | 64 +- libraries/stdlib/test/CollectionApiCheck.kt | 35 - libraries/stdlib/test/CollectionJVMTest.kt | 124 - libraries/stdlib/test/CollectionTest.kt | 492 ---- libraries/stdlib/test/CompareTest.kt | 8 +- .../stdlib/test/EnumerationIteratorTest.kt | 18 - libraries/stdlib/test/ListTest.kt | 79 - libraries/stdlib/test/SetTest.kt | 65 - .../stdlib/test/StandardCollectionTest.kt | 22 - .../test/{ => collections}/ArraysJVMTest.kt | 2 +- .../test/{ => collections}/ArraysTest.kt | 27 +- .../test/collections/CollectionJVMTest.kt | 115 + .../stdlib/test/collections/CollectionTest.kt | 432 +++ .../ImmutableArrayListTest.kt | 2 +- .../test/collections/IterableJVMTests.kt | 9 + .../stdlib/test/collections/IterableTests.kt | 203 ++ .../test/collections/IteratorsJVMTest.kt | 44 + .../stdlib/test/collections/IteratorsTest.kt | 15 + .../test/collections/ListSpecificTest.kt | 33 + .../stdlib/test/{ => collections}/MapTest.kt | 0 .../MutableCollectionsTest.kt | 4 +- .../stdlib/test/collections/StreamTest.kt | 148 ++ .../test/concurrent/SerialFunAndTupleTest.kt | 2 +- .../stdlib/test/concurrent/ThreadTest.kt | 2 +- libraries/stdlib/test/concurrent/TimerTest.kt | 2 +- libraries/stdlib/test/dom/NextSiblingTest.kt | 2 +- libraries/stdlib/test/{ => io}/IoTest.kt | 4 +- libraries/stdlib/test/js/MapJsTest.kt | 4 +- libraries/stdlib/test/js/SetJsTest.kt | 34 +- .../stdlib/test/{ => text}/StringJVMTest.kt | 10 +- .../stdlib/test/{ => text}/StringTest.kt | 2 +- .../stdlib/test/{ => text}/StringUtilTest.kt | 2 +- .../src/generators/GenerateCollections.kt | 35 + .../src/generators/GenerateStandardLib.kt | 38 +- .../src/templates/Aggregates.kt | 399 +++ .../kotlin-stdlib-gen/src/templates/Arrays.kt | 57 +- .../src/templates/Collections.kt | 33 - .../src/templates/Commons.kt | 467 ---- .../src/templates/Elements.kt | 408 +++ .../kotlin-stdlib-gen/src/templates/Engine.kt | 257 +- .../src/templates/Filtering.kt | 266 ++ .../src/templates/Generators.kt | 177 ++ .../kotlin-stdlib-gen/src/templates/Guards.kt | 41 + .../src/templates/Iterables.kt | 308 --- .../src/templates/Iterators.kt | 222 -- .../src/templates/Mapping.kt | 208 ++ .../src/templates/Numeric.kt | 24 + .../src/templates/Ordering.kt | 131 + .../src/templates/Primitives.kt | 47 - .../src/templates/Snapshots.kt | 104 + .../src/templates/SpecialJVM.kt | 94 + .../src/templates/Strings.kt | 56 + 109 files changed, 13317 insertions(+), 7735 deletions(-) delete mode 100644 js/js.libraries/src/stdlib/JUMapsCode.kt create mode 100644 libraries/stdlib/src/generated/_Aggregates.kt delete mode 100644 libraries/stdlib/src/generated/_BooleanArrays.kt delete mode 100644 libraries/stdlib/src/generated/_ByteArrays.kt delete mode 100644 libraries/stdlib/src/generated/_CharArrays.kt delete mode 100644 libraries/stdlib/src/generated/_Collections.kt delete mode 100644 libraries/stdlib/src/generated/_DoubleArrays.kt create mode 100644 libraries/stdlib/src/generated/_Elements.kt create mode 100644 libraries/stdlib/src/generated/_Filtering.kt delete mode 100644 libraries/stdlib/src/generated/_FloatArrays.kt create mode 100644 libraries/stdlib/src/generated/_Generators.kt create mode 100644 libraries/stdlib/src/generated/_Guards.kt delete mode 100644 libraries/stdlib/src/generated/_IntArrays.kt delete mode 100644 libraries/stdlib/src/generated/_Iterables.kt delete mode 100644 libraries/stdlib/src/generated/_LongArrays.kt create mode 100644 libraries/stdlib/src/generated/_Mapping.kt create mode 100644 libraries/stdlib/src/generated/_Numeric.kt create mode 100644 libraries/stdlib/src/generated/_Ordering.kt delete mode 100644 libraries/stdlib/src/generated/_ShortArrays.kt create mode 100644 libraries/stdlib/src/generated/_Snapshots.kt create mode 100644 libraries/stdlib/src/generated/_SpecialJVM.kt create mode 100644 libraries/stdlib/src/generated/_Strings.kt delete mode 100644 libraries/stdlib/src/kotlin/ArraysJVM.kt create mode 100644 libraries/stdlib/src/kotlin/Deprecated.kt create mode 100644 libraries/stdlib/src/kotlin/Functions.kt delete mode 100644 libraries/stdlib/src/kotlin/IterablesSpecial.kt delete mode 100644 libraries/stdlib/src/kotlin/JUtil.kt delete mode 100644 libraries/stdlib/src/kotlin/JUtilJVM.kt delete mode 100644 libraries/stdlib/src/kotlin/Lists.kt delete mode 100644 libraries/stdlib/src/kotlin/MutableCollections.kt rename libraries/stdlib/src/kotlin/{ => collections}/Arrays.kt (75%) create mode 100644 libraries/stdlib/src/kotlin/collections/ArraysJVM.kt rename libraries/stdlib/src/kotlin/{ => collections}/Exceptions.kt (100%) rename libraries/stdlib/src/kotlin/{ => collections}/ImmutableArrayList.kt (100%) create mode 100644 libraries/stdlib/src/kotlin/collections/Iterators.kt create mode 100644 libraries/stdlib/src/kotlin/collections/JUtil.kt create mode 100644 libraries/stdlib/src/kotlin/collections/JUtilJVM.kt rename libraries/stdlib/src/kotlin/{ => collections}/Maps.kt (76%) rename libraries/stdlib/src/kotlin/{ => collections}/MapsJVM.kt (83%) create mode 100644 libraries/stdlib/src/kotlin/collections/MutableCollections.kt create mode 100644 libraries/stdlib/src/kotlin/collections/Stream.kt rename libraries/stdlib/src/kotlin/{ => collections/iterators}/Iterators.kt (86%) rename libraries/stdlib/src/kotlin/{ => collections/iterators}/IteratorsJVM.kt (84%) rename libraries/stdlib/src/{generated => kotlin/collections/iterators}/_Iterators.kt (81%) create mode 100644 libraries/stdlib/src/kotlin/io/Closable.kt rename libraries/stdlib/src/kotlin/{ => text}/Char.kt (95%) rename libraries/stdlib/src/kotlin/{ => text}/Strings.kt (89%) rename libraries/stdlib/src/kotlin/{ => text}/StringsJVM.kt (91%) delete mode 100644 libraries/stdlib/test/CollectionApiCheck.kt delete mode 100644 libraries/stdlib/test/CollectionJVMTest.kt delete mode 100644 libraries/stdlib/test/CollectionTest.kt delete mode 100644 libraries/stdlib/test/EnumerationIteratorTest.kt delete mode 100644 libraries/stdlib/test/ListTest.kt delete mode 100644 libraries/stdlib/test/SetTest.kt delete mode 100644 libraries/stdlib/test/StandardCollectionTest.kt rename libraries/stdlib/test/{ => collections}/ArraysJVMTest.kt (99%) rename libraries/stdlib/test/{ => collections}/ArraysTest.kt (90%) create mode 100644 libraries/stdlib/test/collections/CollectionJVMTest.kt create mode 100644 libraries/stdlib/test/collections/CollectionTest.kt rename libraries/stdlib/test/{ => collections}/ImmutableArrayListTest.kt (98%) create mode 100644 libraries/stdlib/test/collections/IterableJVMTests.kt create mode 100644 libraries/stdlib/test/collections/IterableTests.kt create mode 100644 libraries/stdlib/test/collections/IteratorsJVMTest.kt create mode 100644 libraries/stdlib/test/collections/IteratorsTest.kt create mode 100644 libraries/stdlib/test/collections/ListSpecificTest.kt rename libraries/stdlib/test/{ => collections}/MapTest.kt (100%) rename libraries/stdlib/test/{ => collections}/MutableCollectionsTest.kt (86%) create mode 100644 libraries/stdlib/test/collections/StreamTest.kt rename libraries/stdlib/test/{ => io}/IoTest.kt (98%) rename libraries/stdlib/test/{ => text}/StringJVMTest.kt (98%) rename libraries/stdlib/test/{ => text}/StringTest.kt (98%) rename libraries/stdlib/test/{ => text}/StringUtilTest.kt (93%) create mode 100644 libraries/tools/kotlin-stdlib-gen/src/generators/GenerateCollections.kt create mode 100644 libraries/tools/kotlin-stdlib-gen/src/templates/Aggregates.kt delete mode 100644 libraries/tools/kotlin-stdlib-gen/src/templates/Collections.kt delete mode 100644 libraries/tools/kotlin-stdlib-gen/src/templates/Commons.kt create mode 100644 libraries/tools/kotlin-stdlib-gen/src/templates/Elements.kt create mode 100644 libraries/tools/kotlin-stdlib-gen/src/templates/Filtering.kt create mode 100644 libraries/tools/kotlin-stdlib-gen/src/templates/Generators.kt create mode 100644 libraries/tools/kotlin-stdlib-gen/src/templates/Guards.kt delete mode 100644 libraries/tools/kotlin-stdlib-gen/src/templates/Iterables.kt delete mode 100644 libraries/tools/kotlin-stdlib-gen/src/templates/Iterators.kt create mode 100644 libraries/tools/kotlin-stdlib-gen/src/templates/Mapping.kt create mode 100644 libraries/tools/kotlin-stdlib-gen/src/templates/Numeric.kt create mode 100644 libraries/tools/kotlin-stdlib-gen/src/templates/Ordering.kt delete mode 100644 libraries/tools/kotlin-stdlib-gen/src/templates/Primitives.kt create mode 100644 libraries/tools/kotlin-stdlib-gen/src/templates/Snapshots.kt create mode 100644 libraries/tools/kotlin-stdlib-gen/src/templates/SpecialJVM.kt create mode 100644 libraries/tools/kotlin-stdlib-gen/src/templates/Strings.kt diff --git a/js/js.libraries/src/core/javautil.kt b/js/js.libraries/src/core/javautil.kt index 83771e71776..07454ecc4fd 100644 --- a/js/js.libraries/src/core/javautil.kt +++ b/js/js.libraries/src/core/javautil.kt @@ -67,7 +67,7 @@ public open class LinkedList() : AbstractList() { } library -public open class HashSet() : AbstractCollection(), MutableSet { +public open class HashSet(capacity: Int = 0) : AbstractCollection(), MutableSet { } library diff --git a/js/js.libraries/src/stdlib/JUMapsCode.kt b/js/js.libraries/src/stdlib/JUMapsCode.kt deleted file mode 100644 index 87677f1b3f5..00000000000 --- a/js/js.libraries/src/stdlib/JUMapsCode.kt +++ /dev/null @@ -1,21 +0,0 @@ -package kotlin - -import java.util.HashMap - -/** - * Returns a new [[HashMap]] populated with the given pairs where the first value in each pair - * is the key and the second value is the value - * - * @includeFunctionBody ../../test/MapTest.kt createUsingPairs - */ -public inline fun hashMap(vararg values: Pair): HashMap { - val answer = HashMap() - /** - TODO replace by this simpler call when we can pass vararg values into other methods - answer.putAll(values) - */ - for (v in values) { - answer.put(v.first, v.second) - } - return answer -} \ No newline at end of file diff --git a/js/js.libraries/src/stdlib/jutilCode.kt b/js/js.libraries/src/stdlib/jutilCode.kt index 6e077fc5ac1..f83d8d79d18 100644 --- a/js/js.libraries/src/stdlib/jutilCode.kt +++ b/js/js.libraries/src/stdlib/jutilCode.kt @@ -6,34 +6,6 @@ public inline fun Iterable.toString(): String { return makeString(", ", "[", "]") } -/** Returns a new ArrayList with a variable number of initial elements */ -public inline fun arrayList(vararg values: T) : ArrayList { - val list = ArrayList() - for (value in values) { - list.add(value) - } - return list -} - -/** Returns a new HashSet with a variable number of initial elements */ -public inline fun hashSet(vararg values: T) : HashSet { - val list = HashSet() - for (value in values) { - list.add(value) - } - return list -} - -/** - * Returns a new List containing the results of applying the given *transform* function to each [[Map.Entry]] in this [[Map]] - * - * @includeFunctionBody ../../test/CollectionTest.kt map - */ -public inline fun Map.map(transform: (Map.Entry) -> R) : List { - return mapTo(java.util.ArrayList(), transform) -} - - /** * Returns a new Map containing the results of applying the given *transform* function to each [[Map.Entry]] in this [[Map]] * diff --git a/libraries/stdlib/src/generated/_Aggregates.kt b/libraries/stdlib/src/generated/_Aggregates.kt new file mode 100644 index 00000000000..5275e5bb3e6 --- /dev/null +++ b/libraries/stdlib/src/generated/_Aggregates.kt @@ -0,0 +1,2209 @@ +package kotlin + +// +// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt +// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib +// + +import java.util.* + +/** + * Returns *true* if all elements match the given *predicate* + */ +public inline fun Array.all(predicate: (T) -> Boolean) : Boolean { + for (element in this) if (!predicate(element)) return false + return true + +} + +/** + * Returns *true* if all elements match the given *predicate* + */ +public inline fun BooleanArray.all(predicate: (Boolean) -> Boolean) : Boolean { + for (element in this) if (!predicate(element)) return false + return true + +} + +/** + * Returns *true* if all elements match the given *predicate* + */ +public inline fun ByteArray.all(predicate: (Byte) -> Boolean) : Boolean { + for (element in this) if (!predicate(element)) return false + return true + +} + +/** + * Returns *true* if all elements match the given *predicate* + */ +public inline fun CharArray.all(predicate: (Char) -> Boolean) : Boolean { + for (element in this) if (!predicate(element)) return false + return true + +} + +/** + * Returns *true* if all elements match the given *predicate* + */ +public inline fun DoubleArray.all(predicate: (Double) -> Boolean) : Boolean { + for (element in this) if (!predicate(element)) return false + return true + +} + +/** + * Returns *true* if all elements match the given *predicate* + */ +public inline fun FloatArray.all(predicate: (Float) -> Boolean) : Boolean { + for (element in this) if (!predicate(element)) return false + return true + +} + +/** + * Returns *true* if all elements match the given *predicate* + */ +public inline fun IntArray.all(predicate: (Int) -> Boolean) : Boolean { + for (element in this) if (!predicate(element)) return false + return true + +} + +/** + * Returns *true* if all elements match the given *predicate* + */ +public inline fun LongArray.all(predicate: (Long) -> Boolean) : Boolean { + for (element in this) if (!predicate(element)) return false + return true + +} + +/** + * Returns *true* if all elements match the given *predicate* + */ +public inline fun ShortArray.all(predicate: (Short) -> Boolean) : Boolean { + for (element in this) if (!predicate(element)) return false + return true + +} + +/** + * Returns *true* if all elements match the given *predicate* + */ +public inline fun Iterable.all(predicate: (T) -> Boolean) : Boolean { + for (element in this) if (!predicate(element)) return false + return true + +} + +/** + * Returns *true* if all elements match the given *predicate* + */ +public inline fun Map.all(predicate: (Map.Entry) -> Boolean) : Boolean { + for (element in this) if (!predicate(element)) return false + return true + +} + +/** + * Returns *true* if all elements match the given *predicate* + */ +public inline fun Stream.all(predicate: (T) -> Boolean) : Boolean { + for (element in this) if (!predicate(element)) return false + return true + +} + +/** + * Returns *true* if collection has at least one element + */ +public fun Array.any() : Boolean { + for (element in this) return true + return false + +} + +/** + * Returns *true* if collection has at least one element + */ +public fun BooleanArray.any() : Boolean { + for (element in this) return true + return false + +} + +/** + * Returns *true* if collection has at least one element + */ +public fun ByteArray.any() : Boolean { + for (element in this) return true + return false + +} + +/** + * Returns *true* if collection has at least one element + */ +public fun CharArray.any() : Boolean { + for (element in this) return true + return false + +} + +/** + * Returns *true* if collection has at least one element + */ +public fun DoubleArray.any() : Boolean { + for (element in this) return true + return false + +} + +/** + * Returns *true* if collection has at least one element + */ +public fun FloatArray.any() : Boolean { + for (element in this) return true + return false + +} + +/** + * Returns *true* if collection has at least one element + */ +public fun IntArray.any() : Boolean { + for (element in this) return true + return false + +} + +/** + * Returns *true* if collection has at least one element + */ +public fun LongArray.any() : Boolean { + for (element in this) return true + return false + +} + +/** + * Returns *true* if collection has at least one element + */ +public fun ShortArray.any() : Boolean { + for (element in this) return true + return false + +} + +/** + * Returns *true* if collection has at least one element + */ +public fun Iterable.any() : Boolean { + for (element in this) return true + return false + +} + +/** + * Returns *true* if collection has at least one element + */ +public fun Map.any() : Boolean { + for (element in this) return true + return false + +} + +/** + * Returns *true* if collection has at least one element + */ +public fun Stream.any() : Boolean { + for (element in this) return true + return false + +} + +/** + * Returns *true* if any element matches the given *predicate* + */ +public inline fun Array.any(predicate: (T) -> Boolean) : Boolean { + for (element in this) if (predicate(element)) return true + return false + +} + +/** + * Returns *true* if any element matches the given *predicate* + */ +public inline fun BooleanArray.any(predicate: (Boolean) -> Boolean) : Boolean { + for (element in this) if (predicate(element)) return true + return false + +} + +/** + * Returns *true* if any element matches the given *predicate* + */ +public inline fun ByteArray.any(predicate: (Byte) -> Boolean) : Boolean { + for (element in this) if (predicate(element)) return true + return false + +} + +/** + * Returns *true* if any element matches the given *predicate* + */ +public inline fun CharArray.any(predicate: (Char) -> Boolean) : Boolean { + for (element in this) if (predicate(element)) return true + return false + +} + +/** + * Returns *true* if any element matches the given *predicate* + */ +public inline fun DoubleArray.any(predicate: (Double) -> Boolean) : Boolean { + for (element in this) if (predicate(element)) return true + return false + +} + +/** + * Returns *true* if any element matches the given *predicate* + */ +public inline fun FloatArray.any(predicate: (Float) -> Boolean) : Boolean { + for (element in this) if (predicate(element)) return true + return false + +} + +/** + * Returns *true* if any element matches the given *predicate* + */ +public inline fun IntArray.any(predicate: (Int) -> Boolean) : Boolean { + for (element in this) if (predicate(element)) return true + return false + +} + +/** + * Returns *true* if any element matches the given *predicate* + */ +public inline fun LongArray.any(predicate: (Long) -> Boolean) : Boolean { + for (element in this) if (predicate(element)) return true + return false + +} + +/** + * Returns *true* if any element matches the given *predicate* + */ +public inline fun ShortArray.any(predicate: (Short) -> Boolean) : Boolean { + for (element in this) if (predicate(element)) return true + return false + +} + +/** + * Returns *true* if any element matches the given *predicate* + */ +public inline fun Iterable.any(predicate: (T) -> Boolean) : Boolean { + for (element in this) if (predicate(element)) return true + return false + +} + +/** + * Returns *true* if any element matches the given *predicate* + */ +public inline fun Map.any(predicate: (Map.Entry) -> Boolean) : Boolean { + for (element in this) if (predicate(element)) return true + return false + +} + +/** + * Returns *true* if any element matches the given *predicate* + */ +public inline fun Stream.any(predicate: (T) -> Boolean) : Boolean { + for (element in this) if (predicate(element)) return true + return false + +} + +/** + * Returns the number of elements + */ +public fun Array.count() : Int { + return size +} + +/** + * Returns the number of elements + */ +public fun BooleanArray.count() : Int { + return size +} + +/** + * Returns the number of elements + */ +public fun ByteArray.count() : Int { + return size +} + +/** + * Returns the number of elements + */ +public fun CharArray.count() : Int { + return size +} + +/** + * Returns the number of elements + */ +public fun DoubleArray.count() : Int { + return size +} + +/** + * Returns the number of elements + */ +public fun FloatArray.count() : Int { + return size +} + +/** + * Returns the number of elements + */ +public fun IntArray.count() : Int { + return size +} + +/** + * Returns the number of elements + */ +public fun LongArray.count() : Int { + return size +} + +/** + * Returns the number of elements + */ +public fun ShortArray.count() : Int { + return size +} + +/** + * Returns the number of elements + */ +public fun Collection.count() : Int { + return size +} + +/** + * Returns the number of elements + */ +public fun Iterable.count() : Int { + var count = 0 + for (element in this) count++ + return count + +} + +/** + * Returns the number of elements + */ +public fun Map.count() : Int { + return size +} + +/** + * Returns the number of elements + */ +public fun Stream.count() : Int { + var count = 0 + for (element in this) count++ + return count + +} + +/** + * Returns the number of elements matching the given *predicate* + */ +public inline fun Array.count(predicate: (T) -> Boolean) : Int { + var count = 0 + for (element in this) if (predicate(element)) count++ + return count + +} + +/** + * Returns the number of elements matching the given *predicate* + */ +public inline fun BooleanArray.count(predicate: (Boolean) -> Boolean) : Int { + var count = 0 + for (element in this) if (predicate(element)) count++ + return count + +} + +/** + * Returns the number of elements matching the given *predicate* + */ +public inline fun ByteArray.count(predicate: (Byte) -> Boolean) : Int { + var count = 0 + for (element in this) if (predicate(element)) count++ + return count + +} + +/** + * Returns the number of elements matching the given *predicate* + */ +public inline fun CharArray.count(predicate: (Char) -> Boolean) : Int { + var count = 0 + for (element in this) if (predicate(element)) count++ + return count + +} + +/** + * Returns the number of elements matching the given *predicate* + */ +public inline fun DoubleArray.count(predicate: (Double) -> Boolean) : Int { + var count = 0 + for (element in this) if (predicate(element)) count++ + return count + +} + +/** + * Returns the number of elements matching the given *predicate* + */ +public inline fun FloatArray.count(predicate: (Float) -> Boolean) : Int { + var count = 0 + for (element in this) if (predicate(element)) count++ + return count + +} + +/** + * Returns the number of elements matching the given *predicate* + */ +public inline fun IntArray.count(predicate: (Int) -> Boolean) : Int { + var count = 0 + for (element in this) if (predicate(element)) count++ + return count + +} + +/** + * Returns the number of elements matching the given *predicate* + */ +public inline fun LongArray.count(predicate: (Long) -> Boolean) : Int { + var count = 0 + for (element in this) if (predicate(element)) count++ + return count + +} + +/** + * Returns the number of elements matching the given *predicate* + */ +public inline fun ShortArray.count(predicate: (Short) -> Boolean) : Int { + var count = 0 + for (element in this) if (predicate(element)) count++ + return count + +} + +/** + * Returns the number of elements matching the given *predicate* + */ +public inline fun Iterable.count(predicate: (T) -> Boolean) : Int { + var count = 0 + for (element in this) if (predicate(element)) count++ + return count + +} + +/** + * Returns the number of elements matching the given *predicate* + */ +public inline fun Map.count(predicate: (Map.Entry) -> Boolean) : Int { + var count = 0 + for (element in this) if (predicate(element)) count++ + return count + +} + +/** + * Returns the number of elements matching the given *predicate* + */ +public inline fun Stream.count(predicate: (T) -> Boolean) : Int { + var count = 0 + for (element in this) if (predicate(element)) count++ + return count + +} + +/** + * Accumulates value starting with *initial* value and applying *operation* from left to right to current accumulator value and each element + */ +public inline fun Array.fold(initial: R, operation: (R, T) -> R) : R { + var accumulator = initial + for (element in this) accumulator = operation(accumulator, element) + return accumulator + +} + +/** + * Accumulates value starting with *initial* value and applying *operation* from left to right to current accumulator value and each element + */ +public inline fun BooleanArray.fold(initial: R, operation: (R, Boolean) -> R) : R { + var accumulator = initial + for (element in this) accumulator = operation(accumulator, element) + return accumulator + +} + +/** + * Accumulates value starting with *initial* value and applying *operation* from left to right to current accumulator value and each element + */ +public inline fun ByteArray.fold(initial: R, operation: (R, Byte) -> R) : R { + var accumulator = initial + for (element in this) accumulator = operation(accumulator, element) + return accumulator + +} + +/** + * Accumulates value starting with *initial* value and applying *operation* from left to right to current accumulator value and each element + */ +public inline fun CharArray.fold(initial: R, operation: (R, Char) -> R) : R { + var accumulator = initial + for (element in this) accumulator = operation(accumulator, element) + return accumulator + +} + +/** + * Accumulates value starting with *initial* value and applying *operation* from left to right to current accumulator value and each element + */ +public inline fun DoubleArray.fold(initial: R, operation: (R, Double) -> R) : R { + var accumulator = initial + for (element in this) accumulator = operation(accumulator, element) + return accumulator + +} + +/** + * Accumulates value starting with *initial* value and applying *operation* from left to right to current accumulator value and each element + */ +public inline fun FloatArray.fold(initial: R, operation: (R, Float) -> R) : R { + var accumulator = initial + for (element in this) accumulator = operation(accumulator, element) + return accumulator + +} + +/** + * Accumulates value starting with *initial* value and applying *operation* from left to right to current accumulator value and each element + */ +public inline fun IntArray.fold(initial: R, operation: (R, Int) -> R) : R { + var accumulator = initial + for (element in this) accumulator = operation(accumulator, element) + return accumulator + +} + +/** + * Accumulates value starting with *initial* value and applying *operation* from left to right to current accumulator value and each element + */ +public inline fun LongArray.fold(initial: R, operation: (R, Long) -> R) : R { + var accumulator = initial + for (element in this) accumulator = operation(accumulator, element) + return accumulator + +} + +/** + * Accumulates value starting with *initial* value and applying *operation* from left to right to current accumulator value and each element + */ +public inline fun ShortArray.fold(initial: R, operation: (R, Short) -> R) : R { + var accumulator = initial + for (element in this) accumulator = operation(accumulator, element) + return accumulator + +} + +/** + * Accumulates value starting with *initial* value and applying *operation* from left to right to current accumulator value and each element + */ +public inline fun Iterable.fold(initial: R, operation: (R, T) -> R) : R { + var accumulator = initial + for (element in this) accumulator = operation(accumulator, element) + return accumulator + +} + +/** + * Accumulates value starting with *initial* value and applying *operation* from left to right to current accumulator value and each element + */ +public inline fun Stream.fold(initial: R, operation: (R, T) -> R) : R { + var accumulator = initial + for (element in this) accumulator = operation(accumulator, element) + return accumulator + +} + +/** + * Accumulates value starting with *initial* value and applying *operation* from right to left to each element and current accumulator value + */ +public inline fun Array.foldRight(initial: R, operation: (T, R) -> R) : R { + var index = size - 1 + var accumulator = initial + while (index >= 0) { + accumulator = operation(get(index--), accumulator) + } + return accumulator + +} + +/** + * Accumulates value starting with *initial* value and applying *operation* from right to left to each element and current accumulator value + */ +public inline fun BooleanArray.foldRight(initial: R, operation: (Boolean, R) -> R) : R { + var index = size - 1 + var accumulator = initial + while (index >= 0) { + accumulator = operation(get(index--), accumulator) + } + return accumulator + +} + +/** + * Accumulates value starting with *initial* value and applying *operation* from right to left to each element and current accumulator value + */ +public inline fun ByteArray.foldRight(initial: R, operation: (Byte, R) -> R) : R { + var index = size - 1 + var accumulator = initial + while (index >= 0) { + accumulator = operation(get(index--), accumulator) + } + return accumulator + +} + +/** + * Accumulates value starting with *initial* value and applying *operation* from right to left to each element and current accumulator value + */ +public inline fun CharArray.foldRight(initial: R, operation: (Char, R) -> R) : R { + var index = size - 1 + var accumulator = initial + while (index >= 0) { + accumulator = operation(get(index--), accumulator) + } + return accumulator + +} + +/** + * Accumulates value starting with *initial* value and applying *operation* from right to left to each element and current accumulator value + */ +public inline fun DoubleArray.foldRight(initial: R, operation: (Double, R) -> R) : R { + var index = size - 1 + var accumulator = initial + while (index >= 0) { + accumulator = operation(get(index--), accumulator) + } + return accumulator + +} + +/** + * Accumulates value starting with *initial* value and applying *operation* from right to left to each element and current accumulator value + */ +public inline fun FloatArray.foldRight(initial: R, operation: (Float, R) -> R) : R { + var index = size - 1 + var accumulator = initial + while (index >= 0) { + accumulator = operation(get(index--), accumulator) + } + return accumulator + +} + +/** + * Accumulates value starting with *initial* value and applying *operation* from right to left to each element and current accumulator value + */ +public inline fun IntArray.foldRight(initial: R, operation: (Int, R) -> R) : R { + var index = size - 1 + var accumulator = initial + while (index >= 0) { + accumulator = operation(get(index--), accumulator) + } + return accumulator + +} + +/** + * Accumulates value starting with *initial* value and applying *operation* from right to left to each element and current accumulator value + */ +public inline fun LongArray.foldRight(initial: R, operation: (Long, R) -> R) : R { + var index = size - 1 + var accumulator = initial + while (index >= 0) { + accumulator = operation(get(index--), accumulator) + } + return accumulator + +} + +/** + * Accumulates value starting with *initial* value and applying *operation* from right to left to each element and current accumulator value + */ +public inline fun ShortArray.foldRight(initial: R, operation: (Short, R) -> R) : R { + var index = size - 1 + var accumulator = initial + while (index >= 0) { + accumulator = operation(get(index--), accumulator) + } + return accumulator + +} + +/** + * Accumulates value starting with *initial* value and applying *operation* from right to left to each element and current accumulator value + */ +public inline fun List.foldRight(initial: R, operation: (T, R) -> R) : R { + var index = size - 1 + var accumulator = initial + while (index >= 0) { + accumulator = operation(get(index--), accumulator) + } + return accumulator + +} + +/** + * Performs the given *operation* on each element + */ +public inline fun Array.forEach(operation: (T) -> Unit) : Unit { + for (element in this) operation(element) + +} + +/** + * Performs the given *operation* on each element + */ +public inline fun BooleanArray.forEach(operation: (Boolean) -> Unit) : Unit { + for (element in this) operation(element) + +} + +/** + * Performs the given *operation* on each element + */ +public inline fun ByteArray.forEach(operation: (Byte) -> Unit) : Unit { + for (element in this) operation(element) + +} + +/** + * Performs the given *operation* on each element + */ +public inline fun CharArray.forEach(operation: (Char) -> Unit) : Unit { + for (element in this) operation(element) + +} + +/** + * Performs the given *operation* on each element + */ +public inline fun DoubleArray.forEach(operation: (Double) -> Unit) : Unit { + for (element in this) operation(element) + +} + +/** + * Performs the given *operation* on each element + */ +public inline fun FloatArray.forEach(operation: (Float) -> Unit) : Unit { + for (element in this) operation(element) + +} + +/** + * Performs the given *operation* on each element + */ +public inline fun IntArray.forEach(operation: (Int) -> Unit) : Unit { + for (element in this) operation(element) + +} + +/** + * Performs the given *operation* on each element + */ +public inline fun LongArray.forEach(operation: (Long) -> Unit) : Unit { + for (element in this) operation(element) + +} + +/** + * Performs the given *operation* on each element + */ +public inline fun ShortArray.forEach(operation: (Short) -> Unit) : Unit { + for (element in this) operation(element) + +} + +/** + * Performs the given *operation* on each element + */ +public inline fun Iterable.forEach(operation: (T) -> Unit) : Unit { + for (element in this) operation(element) + +} + +/** + * Performs the given *operation* on each element + */ +public inline fun Map.forEach(operation: (Map.Entry) -> Unit) : Unit { + for (element in this) operation(element) + +} + +/** + * Performs the given *operation* on each element + */ +public inline fun Stream.forEach(operation: (T) -> Unit) : Unit { + for (element in this) operation(element) + +} + +/** + * Returns the largest element or null if there are no elements + */ +public fun > Array.max() : T? { + if (isEmpty()) return null + + var max = this[0] + for (i in 1..lastIndex) { + val e = this[i] + if (max < e) max = e + } + return max + +} + +/** + * Returns the largest element or null if there are no elements + */ +public fun ByteArray.max() : Byte? { + if (isEmpty()) return null + + var max = this[0] + for (i in 1..lastIndex) { + val e = this[i] + if (max < e) max = e + } + return max + +} + +/** + * Returns the largest element or null if there are no elements + */ +public fun CharArray.max() : Char? { + if (isEmpty()) return null + + var max = this[0] + for (i in 1..lastIndex) { + val e = this[i] + if (max < e) max = e + } + return max + +} + +/** + * Returns the largest element or null if there are no elements + */ +public fun DoubleArray.max() : Double? { + if (isEmpty()) return null + + var max = this[0] + for (i in 1..lastIndex) { + val e = this[i] + if (max < e) max = e + } + return max + +} + +/** + * Returns the largest element or null if there are no elements + */ +public fun FloatArray.max() : Float? { + if (isEmpty()) return null + + var max = this[0] + for (i in 1..lastIndex) { + val e = this[i] + if (max < e) max = e + } + return max + +} + +/** + * Returns the largest element or null if there are no elements + */ +public fun IntArray.max() : Int? { + if (isEmpty()) return null + + var max = this[0] + for (i in 1..lastIndex) { + val e = this[i] + if (max < e) max = e + } + return max + +} + +/** + * Returns the largest element or null if there are no elements + */ +public fun LongArray.max() : Long? { + if (isEmpty()) return null + + var max = this[0] + for (i in 1..lastIndex) { + val e = this[i] + if (max < e) max = e + } + return max + +} + +/** + * Returns the largest element or null if there are no elements + */ +public fun ShortArray.max() : Short? { + if (isEmpty()) return null + + var max = this[0] + for (i in 1..lastIndex) { + val e = this[i] + if (max < e) max = e + } + return max + +} + +/** + * Returns the largest element or null if there are no elements + */ +public fun > Iterable.max() : T? { + val iterator = iterator() + if (!iterator.hasNext()) return null + + var max = iterator.next() + while (iterator.hasNext()) { + val e = iterator.next() + if (max < e) max = e + } + return max + +} + +/** + * Returns the largest element or null if there are no elements + */ +public fun > Stream.max() : T? { + val iterator = iterator() + if (!iterator.hasNext()) return null + + var max = iterator.next() + while (iterator.hasNext()) { + val e = iterator.next() + if (max < e) max = e + } + return max + +} + +/** + * Returns the first element yielding the largest value of the given function or null if there are no elements + */ +public inline fun , T: Any> Array.maxBy(f: (T) -> R) : T? { + if (isEmpty()) return null + + var maxElem = this[0] + var maxValue = f(maxElem) + for (i in 1..lastIndex) { + val e = this[i] + val v = f(e) + if (maxValue < v) { + maxElem = e + maxValue = v + } + } + return maxElem + +} + +/** + * Returns the first element yielding the largest value of the given function or null if there are no elements + */ +public inline fun > BooleanArray.maxBy(f: (Boolean) -> R) : Boolean? { + if (isEmpty()) return null + + var maxElem = this[0] + var maxValue = f(maxElem) + for (i in 1..lastIndex) { + val e = this[i] + val v = f(e) + if (maxValue < v) { + maxElem = e + maxValue = v + } + } + return maxElem + +} + +/** + * Returns the first element yielding the largest value of the given function or null if there are no elements + */ +public inline fun > ByteArray.maxBy(f: (Byte) -> R) : Byte? { + if (isEmpty()) return null + + var maxElem = this[0] + var maxValue = f(maxElem) + for (i in 1..lastIndex) { + val e = this[i] + val v = f(e) + if (maxValue < v) { + maxElem = e + maxValue = v + } + } + return maxElem + +} + +/** + * Returns the first element yielding the largest value of the given function or null if there are no elements + */ +public inline fun > CharArray.maxBy(f: (Char) -> R) : Char? { + if (isEmpty()) return null + + var maxElem = this[0] + var maxValue = f(maxElem) + for (i in 1..lastIndex) { + val e = this[i] + val v = f(e) + if (maxValue < v) { + maxElem = e + maxValue = v + } + } + return maxElem + +} + +/** + * Returns the first element yielding the largest value of the given function or null if there are no elements + */ +public inline fun > DoubleArray.maxBy(f: (Double) -> R) : Double? { + if (isEmpty()) return null + + var maxElem = this[0] + var maxValue = f(maxElem) + for (i in 1..lastIndex) { + val e = this[i] + val v = f(e) + if (maxValue < v) { + maxElem = e + maxValue = v + } + } + return maxElem + +} + +/** + * Returns the first element yielding the largest value of the given function or null if there are no elements + */ +public inline fun > FloatArray.maxBy(f: (Float) -> R) : Float? { + if (isEmpty()) return null + + var maxElem = this[0] + var maxValue = f(maxElem) + for (i in 1..lastIndex) { + val e = this[i] + val v = f(e) + if (maxValue < v) { + maxElem = e + maxValue = v + } + } + return maxElem + +} + +/** + * Returns the first element yielding the largest value of the given function or null if there are no elements + */ +public inline fun > IntArray.maxBy(f: (Int) -> R) : Int? { + if (isEmpty()) return null + + var maxElem = this[0] + var maxValue = f(maxElem) + for (i in 1..lastIndex) { + val e = this[i] + val v = f(e) + if (maxValue < v) { + maxElem = e + maxValue = v + } + } + return maxElem + +} + +/** + * Returns the first element yielding the largest value of the given function or null if there are no elements + */ +public inline fun > LongArray.maxBy(f: (Long) -> R) : Long? { + if (isEmpty()) return null + + var maxElem = this[0] + var maxValue = f(maxElem) + for (i in 1..lastIndex) { + val e = this[i] + val v = f(e) + if (maxValue < v) { + maxElem = e + maxValue = v + } + } + return maxElem + +} + +/** + * Returns the first element yielding the largest value of the given function or null if there are no elements + */ +public inline fun > ShortArray.maxBy(f: (Short) -> R) : Short? { + if (isEmpty()) return null + + var maxElem = this[0] + var maxValue = f(maxElem) + for (i in 1..lastIndex) { + val e = this[i] + val v = f(e) + if (maxValue < v) { + maxElem = e + maxValue = v + } + } + return maxElem + +} + +/** + * Returns the first element yielding the largest value of the given function or null if there are no elements + */ +public inline fun , T: Any> Iterable.maxBy(f: (T) -> R) : T? { + val iterator = iterator() + if (!iterator.hasNext()) return null + + var maxElem = iterator.next() + var maxValue = f(maxElem) + while (iterator.hasNext()) { + val e = iterator.next() + val v = f(e) + if (maxValue < v) { + maxElem = e + maxValue = v + } + } + return maxElem + +} + +/** + * Returns the first element yielding the largest value of the given function or null if there are no elements + */ +public inline fun , T: Any> Stream.maxBy(f: (T) -> R) : T? { + val iterator = iterator() + if (!iterator.hasNext()) return null + + var maxElem = iterator.next() + var maxValue = f(maxElem) + while (iterator.hasNext()) { + val e = iterator.next() + val v = f(e) + if (maxValue < v) { + maxElem = e + maxValue = v + } + } + return maxElem + +} + +/** + * Returns the first element yielding the largest value of the given function or null if there are no elements + */ +public inline fun > Map.maxBy(f: (Map.Entry) -> R) : Map.Entry? { + val iterator = iterator() + if (!iterator.hasNext()) return null + + var maxElem = iterator.next() + var maxValue = f(maxElem) + while (iterator.hasNext()) { + val e = iterator.next() + val v = f(e) + if (maxValue < v) { + maxElem = e + maxValue = v + } + } + return maxElem + +} + +/** + * Returns the smallest element or null if there are no elements + */ +public fun > Array.min() : T? { + if (isEmpty()) return null + var min = this[0] + for (i in 1..lastIndex) { + val e = this[i] + if (min > e) min = e + } + return min + +} + +/** + * Returns the smallest element or null if there are no elements + */ +public fun ByteArray.min() : Byte? { + if (isEmpty()) return null + var min = this[0] + for (i in 1..lastIndex) { + val e = this[i] + if (min > e) min = e + } + return min + +} + +/** + * Returns the smallest element or null if there are no elements + */ +public fun CharArray.min() : Char? { + if (isEmpty()) return null + var min = this[0] + for (i in 1..lastIndex) { + val e = this[i] + if (min > e) min = e + } + return min + +} + +/** + * Returns the smallest element or null if there are no elements + */ +public fun DoubleArray.min() : Double? { + if (isEmpty()) return null + var min = this[0] + for (i in 1..lastIndex) { + val e = this[i] + if (min > e) min = e + } + return min + +} + +/** + * Returns the smallest element or null if there are no elements + */ +public fun FloatArray.min() : Float? { + if (isEmpty()) return null + var min = this[0] + for (i in 1..lastIndex) { + val e = this[i] + if (min > e) min = e + } + return min + +} + +/** + * Returns the smallest element or null if there are no elements + */ +public fun IntArray.min() : Int? { + if (isEmpty()) return null + var min = this[0] + for (i in 1..lastIndex) { + val e = this[i] + if (min > e) min = e + } + return min + +} + +/** + * Returns the smallest element or null if there are no elements + */ +public fun LongArray.min() : Long? { + if (isEmpty()) return null + var min = this[0] + for (i in 1..lastIndex) { + val e = this[i] + if (min > e) min = e + } + return min + +} + +/** + * Returns the smallest element or null if there are no elements + */ +public fun ShortArray.min() : Short? { + if (isEmpty()) return null + var min = this[0] + for (i in 1..lastIndex) { + val e = this[i] + if (min > e) min = e + } + return min + +} + +/** + * Returns the smallest element or null if there are no elements + */ +public fun > Iterable.min() : T? { + val iterator = iterator() + if (!iterator.hasNext()) return null + + var min = iterator.next() + while (iterator.hasNext()) { + val e = iterator.next() + if (min > e) min = e + } + return min + +} + +/** + * Returns the smallest element or null if there are no elements + */ +public fun > Stream.min() : T? { + val iterator = iterator() + if (!iterator.hasNext()) return null + + var min = iterator.next() + while (iterator.hasNext()) { + val e = iterator.next() + if (min > e) min = e + } + return min + +} + +/** + * Returns the first element yielding the smallest value of the given function or null if there are no elements + */ +public inline fun , T: Any> Array.minBy(f: (T) -> R) : T? { + if (size == 0) return null + + var minElem = this[0] + var minValue = f(minElem) + for (i in 1..lastIndex) { + val e = this[i] + val v = f(e) + if (minValue > v) { + minElem = e + minValue = v + } + } + return minElem + +} + +/** + * Returns the first element yielding the smallest value of the given function or null if there are no elements + */ +public inline fun > BooleanArray.minBy(f: (Boolean) -> R) : Boolean? { + if (size == 0) return null + + var minElem = this[0] + var minValue = f(minElem) + for (i in 1..lastIndex) { + val e = this[i] + val v = f(e) + if (minValue > v) { + minElem = e + minValue = v + } + } + return minElem + +} + +/** + * Returns the first element yielding the smallest value of the given function or null if there are no elements + */ +public inline fun > ByteArray.minBy(f: (Byte) -> R) : Byte? { + if (size == 0) return null + + var minElem = this[0] + var minValue = f(minElem) + for (i in 1..lastIndex) { + val e = this[i] + val v = f(e) + if (minValue > v) { + minElem = e + minValue = v + } + } + return minElem + +} + +/** + * Returns the first element yielding the smallest value of the given function or null if there are no elements + */ +public inline fun > CharArray.minBy(f: (Char) -> R) : Char? { + if (size == 0) return null + + var minElem = this[0] + var minValue = f(minElem) + for (i in 1..lastIndex) { + val e = this[i] + val v = f(e) + if (minValue > v) { + minElem = e + minValue = v + } + } + return minElem + +} + +/** + * Returns the first element yielding the smallest value of the given function or null if there are no elements + */ +public inline fun > DoubleArray.minBy(f: (Double) -> R) : Double? { + if (size == 0) return null + + var minElem = this[0] + var minValue = f(minElem) + for (i in 1..lastIndex) { + val e = this[i] + val v = f(e) + if (minValue > v) { + minElem = e + minValue = v + } + } + return minElem + +} + +/** + * Returns the first element yielding the smallest value of the given function or null if there are no elements + */ +public inline fun > FloatArray.minBy(f: (Float) -> R) : Float? { + if (size == 0) return null + + var minElem = this[0] + var minValue = f(minElem) + for (i in 1..lastIndex) { + val e = this[i] + val v = f(e) + if (minValue > v) { + minElem = e + minValue = v + } + } + return minElem + +} + +/** + * Returns the first element yielding the smallest value of the given function or null if there are no elements + */ +public inline fun > IntArray.minBy(f: (Int) -> R) : Int? { + if (size == 0) return null + + var minElem = this[0] + var minValue = f(minElem) + for (i in 1..lastIndex) { + val e = this[i] + val v = f(e) + if (minValue > v) { + minElem = e + minValue = v + } + } + return minElem + +} + +/** + * Returns the first element yielding the smallest value of the given function or null if there are no elements + */ +public inline fun > LongArray.minBy(f: (Long) -> R) : Long? { + if (size == 0) return null + + var minElem = this[0] + var minValue = f(minElem) + for (i in 1..lastIndex) { + val e = this[i] + val v = f(e) + if (minValue > v) { + minElem = e + minValue = v + } + } + return minElem + +} + +/** + * Returns the first element yielding the smallest value of the given function or null if there are no elements + */ +public inline fun > ShortArray.minBy(f: (Short) -> R) : Short? { + if (size == 0) return null + + var minElem = this[0] + var minValue = f(minElem) + for (i in 1..lastIndex) { + val e = this[i] + val v = f(e) + if (minValue > v) { + minElem = e + minValue = v + } + } + return minElem + +} + +/** + * Returns the first element yielding the smallest value of the given function or null if there are no elements + */ +public inline fun , T: Any> Iterable.minBy(f: (T) -> R) : T? { + val iterator = iterator() + if (!iterator.hasNext()) return null + + var minElem = iterator.next() + var minValue = f(minElem) + while (iterator.hasNext()) { + val e = iterator.next() + val v = f(e) + if (minValue > v) { + minElem = e + minValue = v + } + } + return minElem + +} + +/** + * Returns the first element yielding the smallest value of the given function or null if there are no elements + */ +public inline fun , T: Any> Stream.minBy(f: (T) -> R) : T? { + val iterator = iterator() + if (!iterator.hasNext()) return null + + var minElem = iterator.next() + var minValue = f(minElem) + while (iterator.hasNext()) { + val e = iterator.next() + val v = f(e) + if (minValue > v) { + minElem = e + minValue = v + } + } + return minElem + +} + +/** + * Returns the first element yielding the smallest value of the given function or null if there are no elements + */ +public inline fun > Map.minBy(f: (Map.Entry) -> R) : Map.Entry? { + val iterator = iterator() + if (!iterator.hasNext()) return null + + var minElem = iterator.next() + var minValue = f(minElem) + while (iterator.hasNext()) { + val e = iterator.next() + val v = f(e) + if (minValue > v) { + minElem = e + minValue = v + } + } + return minElem + +} + +/** + * Returns *true* if collection has no elements + */ +public fun Array.none() : Boolean { + for (element in this) return false + return true + +} + +/** + * Returns *true* if collection has no elements + */ +public fun BooleanArray.none() : Boolean { + for (element in this) return false + return true + +} + +/** + * Returns *true* if collection has no elements + */ +public fun ByteArray.none() : Boolean { + for (element in this) return false + return true + +} + +/** + * Returns *true* if collection has no elements + */ +public fun CharArray.none() : Boolean { + for (element in this) return false + return true + +} + +/** + * Returns *true* if collection has no elements + */ +public fun DoubleArray.none() : Boolean { + for (element in this) return false + return true + +} + +/** + * Returns *true* if collection has no elements + */ +public fun FloatArray.none() : Boolean { + for (element in this) return false + return true + +} + +/** + * Returns *true* if collection has no elements + */ +public fun IntArray.none() : Boolean { + for (element in this) return false + return true + +} + +/** + * Returns *true* if collection has no elements + */ +public fun LongArray.none() : Boolean { + for (element in this) return false + return true + +} + +/** + * Returns *true* if collection has no elements + */ +public fun ShortArray.none() : Boolean { + for (element in this) return false + return true + +} + +/** + * Returns *true* if collection has no elements + */ +public fun Iterable.none() : Boolean { + for (element in this) return false + return true + +} + +/** + * Returns *true* if collection has no elements + */ +public fun Map.none() : Boolean { + for (element in this) return false + return true + +} + +/** + * Returns *true* if collection has no elements + */ +public fun Stream.none() : Boolean { + for (element in this) return false + return true + +} + +/** + * Returns *true* if no elements match the given *predicate* + */ +public inline fun Array.none(predicate: (T) -> Boolean) : Boolean { + for (element in this) if (predicate(element)) return false + return true + +} + +/** + * Returns *true* if no elements match the given *predicate* + */ +public inline fun BooleanArray.none(predicate: (Boolean) -> Boolean) : Boolean { + for (element in this) if (predicate(element)) return false + return true + +} + +/** + * Returns *true* if no elements match the given *predicate* + */ +public inline fun ByteArray.none(predicate: (Byte) -> Boolean) : Boolean { + for (element in this) if (predicate(element)) return false + return true + +} + +/** + * Returns *true* if no elements match the given *predicate* + */ +public inline fun CharArray.none(predicate: (Char) -> Boolean) : Boolean { + for (element in this) if (predicate(element)) return false + return true + +} + +/** + * Returns *true* if no elements match the given *predicate* + */ +public inline fun DoubleArray.none(predicate: (Double) -> Boolean) : Boolean { + for (element in this) if (predicate(element)) return false + return true + +} + +/** + * Returns *true* if no elements match the given *predicate* + */ +public inline fun FloatArray.none(predicate: (Float) -> Boolean) : Boolean { + for (element in this) if (predicate(element)) return false + return true + +} + +/** + * Returns *true* if no elements match the given *predicate* + */ +public inline fun IntArray.none(predicate: (Int) -> Boolean) : Boolean { + for (element in this) if (predicate(element)) return false + return true + +} + +/** + * Returns *true* if no elements match the given *predicate* + */ +public inline fun LongArray.none(predicate: (Long) -> Boolean) : Boolean { + for (element in this) if (predicate(element)) return false + return true + +} + +/** + * Returns *true* if no elements match the given *predicate* + */ +public inline fun ShortArray.none(predicate: (Short) -> Boolean) : Boolean { + for (element in this) if (predicate(element)) return false + return true + +} + +/** + * Returns *true* if no elements match the given *predicate* + */ +public inline fun Iterable.none(predicate: (T) -> Boolean) : Boolean { + for (element in this) if (predicate(element)) return false + return true + +} + +/** + * Returns *true* if no elements match the given *predicate* + */ +public inline fun Map.none(predicate: (Map.Entry) -> Boolean) : Boolean { + for (element in this) if (predicate(element)) return false + return true + +} + +/** + * Returns *true* if no elements match the given *predicate* + */ +public inline fun Stream.none(predicate: (T) -> Boolean) : Boolean { + for (element in this) if (predicate(element)) return false + return true + +} + +/** + * Accumulates value starting with the first element and applying *operation* from left to right to current accumulator value and each element + */ +public inline fun Array.reduce(operation: (T, T) -> T) : T { + val iterator = this.iterator() + if (!iterator.hasNext()) throw UnsupportedOperationException("Empty iterable can't be reduced") + + var accumulator = iterator.next() + while (iterator.hasNext()) { + accumulator = operation(accumulator, iterator.next()) + } + return accumulator + +} + +/** + * Accumulates value starting with the first element and applying *operation* from left to right to current accumulator value and each element + */ +public inline fun BooleanArray.reduce(operation: (Boolean, Boolean) -> Boolean) : Boolean { + val iterator = this.iterator() + if (!iterator.hasNext()) throw UnsupportedOperationException("Empty iterable can't be reduced") + + var accumulator = iterator.next() + while (iterator.hasNext()) { + accumulator = operation(accumulator, iterator.next()) + } + return accumulator + +} + +/** + * Accumulates value starting with the first element and applying *operation* from left to right to current accumulator value and each element + */ +public inline fun ByteArray.reduce(operation: (Byte, Byte) -> Byte) : Byte { + val iterator = this.iterator() + if (!iterator.hasNext()) throw UnsupportedOperationException("Empty iterable can't be reduced") + + var accumulator = iterator.next() + while (iterator.hasNext()) { + accumulator = operation(accumulator, iterator.next()) + } + return accumulator + +} + +/** + * Accumulates value starting with the first element and applying *operation* from left to right to current accumulator value and each element + */ +public inline fun CharArray.reduce(operation: (Char, Char) -> Char) : Char { + val iterator = this.iterator() + if (!iterator.hasNext()) throw UnsupportedOperationException("Empty iterable can't be reduced") + + var accumulator = iterator.next() + while (iterator.hasNext()) { + accumulator = operation(accumulator, iterator.next()) + } + return accumulator + +} + +/** + * Accumulates value starting with the first element and applying *operation* from left to right to current accumulator value and each element + */ +public inline fun DoubleArray.reduce(operation: (Double, Double) -> Double) : Double { + val iterator = this.iterator() + if (!iterator.hasNext()) throw UnsupportedOperationException("Empty iterable can't be reduced") + + var accumulator = iterator.next() + while (iterator.hasNext()) { + accumulator = operation(accumulator, iterator.next()) + } + return accumulator + +} + +/** + * Accumulates value starting with the first element and applying *operation* from left to right to current accumulator value and each element + */ +public inline fun FloatArray.reduce(operation: (Float, Float) -> Float) : Float { + val iterator = this.iterator() + if (!iterator.hasNext()) throw UnsupportedOperationException("Empty iterable can't be reduced") + + var accumulator = iterator.next() + while (iterator.hasNext()) { + accumulator = operation(accumulator, iterator.next()) + } + return accumulator + +} + +/** + * Accumulates value starting with the first element and applying *operation* from left to right to current accumulator value and each element + */ +public inline fun IntArray.reduce(operation: (Int, Int) -> Int) : Int { + val iterator = this.iterator() + if (!iterator.hasNext()) throw UnsupportedOperationException("Empty iterable can't be reduced") + + var accumulator = iterator.next() + while (iterator.hasNext()) { + accumulator = operation(accumulator, iterator.next()) + } + return accumulator + +} + +/** + * Accumulates value starting with the first element and applying *operation* from left to right to current accumulator value and each element + */ +public inline fun LongArray.reduce(operation: (Long, Long) -> Long) : Long { + val iterator = this.iterator() + if (!iterator.hasNext()) throw UnsupportedOperationException("Empty iterable can't be reduced") + + var accumulator = iterator.next() + while (iterator.hasNext()) { + accumulator = operation(accumulator, iterator.next()) + } + return accumulator + +} + +/** + * Accumulates value starting with the first element and applying *operation* from left to right to current accumulator value and each element + */ +public inline fun ShortArray.reduce(operation: (Short, Short) -> Short) : Short { + val iterator = this.iterator() + if (!iterator.hasNext()) throw UnsupportedOperationException("Empty iterable can't be reduced") + + var accumulator = iterator.next() + while (iterator.hasNext()) { + accumulator = operation(accumulator, iterator.next()) + } + return accumulator + +} + +/** + * Accumulates value starting with the first element and applying *operation* from left to right to current accumulator value and each element + */ +public inline fun Iterable.reduce(operation: (T, T) -> T) : T { + val iterator = this.iterator() + if (!iterator.hasNext()) throw UnsupportedOperationException("Empty iterable can't be reduced") + + var accumulator = iterator.next() + while (iterator.hasNext()) { + accumulator = operation(accumulator, iterator.next()) + } + return accumulator + +} + +/** + * Accumulates value starting with the first element and applying *operation* from left to right to current accumulator value and each element + */ +public inline fun Stream.reduce(operation: (T, T) -> T) : T { + val iterator = this.iterator() + if (!iterator.hasNext()) throw UnsupportedOperationException("Empty iterable can't be reduced") + + var accumulator = iterator.next() + while (iterator.hasNext()) { + accumulator = operation(accumulator, iterator.next()) + } + return accumulator + +} + +/** + * Accumulates value starting with last element and applying *operation* from right to left to each element and current accumulator value + */ +public inline fun Array.reduceRight(operation: (T, T) -> T) : T { + var index = size - 1 + if (index < 0) throw UnsupportedOperationException("Empty iterable can't be reduced") + + var accumulator = get(index--) + while (index >= 0) { + accumulator = operation(get(index--), accumulator) + } + + return accumulator + +} + +/** + * Accumulates value starting with last element and applying *operation* from right to left to each element and current accumulator value + */ +public inline fun BooleanArray.reduceRight(operation: (Boolean, Boolean) -> Boolean) : Boolean { + var index = size - 1 + if (index < 0) throw UnsupportedOperationException("Empty iterable can't be reduced") + + var accumulator = get(index--) + while (index >= 0) { + accumulator = operation(get(index--), accumulator) + } + + return accumulator + +} + +/** + * Accumulates value starting with last element and applying *operation* from right to left to each element and current accumulator value + */ +public inline fun ByteArray.reduceRight(operation: (Byte, Byte) -> Byte) : Byte { + var index = size - 1 + if (index < 0) throw UnsupportedOperationException("Empty iterable can't be reduced") + + var accumulator = get(index--) + while (index >= 0) { + accumulator = operation(get(index--), accumulator) + } + + return accumulator + +} + +/** + * Accumulates value starting with last element and applying *operation* from right to left to each element and current accumulator value + */ +public inline fun CharArray.reduceRight(operation: (Char, Char) -> Char) : Char { + var index = size - 1 + if (index < 0) throw UnsupportedOperationException("Empty iterable can't be reduced") + + var accumulator = get(index--) + while (index >= 0) { + accumulator = operation(get(index--), accumulator) + } + + return accumulator + +} + +/** + * Accumulates value starting with last element and applying *operation* from right to left to each element and current accumulator value + */ +public inline fun DoubleArray.reduceRight(operation: (Double, Double) -> Double) : Double { + var index = size - 1 + if (index < 0) throw UnsupportedOperationException("Empty iterable can't be reduced") + + var accumulator = get(index--) + while (index >= 0) { + accumulator = operation(get(index--), accumulator) + } + + return accumulator + +} + +/** + * Accumulates value starting with last element and applying *operation* from right to left to each element and current accumulator value + */ +public inline fun FloatArray.reduceRight(operation: (Float, Float) -> Float) : Float { + var index = size - 1 + if (index < 0) throw UnsupportedOperationException("Empty iterable can't be reduced") + + var accumulator = get(index--) + while (index >= 0) { + accumulator = operation(get(index--), accumulator) + } + + return accumulator + +} + +/** + * Accumulates value starting with last element and applying *operation* from right to left to each element and current accumulator value + */ +public inline fun IntArray.reduceRight(operation: (Int, Int) -> Int) : Int { + var index = size - 1 + if (index < 0) throw UnsupportedOperationException("Empty iterable can't be reduced") + + var accumulator = get(index--) + while (index >= 0) { + accumulator = operation(get(index--), accumulator) + } + + return accumulator + +} + +/** + * Accumulates value starting with last element and applying *operation* from right to left to each element and current accumulator value + */ +public inline fun LongArray.reduceRight(operation: (Long, Long) -> Long) : Long { + var index = size - 1 + if (index < 0) throw UnsupportedOperationException("Empty iterable can't be reduced") + + var accumulator = get(index--) + while (index >= 0) { + accumulator = operation(get(index--), accumulator) + } + + return accumulator + +} + +/** + * Accumulates value starting with last element and applying *operation* from right to left to each element and current accumulator value + */ +public inline fun ShortArray.reduceRight(operation: (Short, Short) -> Short) : Short { + var index = size - 1 + if (index < 0) throw UnsupportedOperationException("Empty iterable can't be reduced") + + var accumulator = get(index--) + while (index >= 0) { + accumulator = operation(get(index--), accumulator) + } + + return accumulator + +} + +/** + * Accumulates value starting with last element and applying *operation* from right to left to each element and current accumulator value + */ +public inline fun List.reduceRight(operation: (T, T) -> T) : T { + var index = size - 1 + if (index < 0) throw UnsupportedOperationException("Empty iterable can't be reduced") + + var accumulator = get(index--) + while (index >= 0) { + accumulator = operation(get(index--), accumulator) + } + + return accumulator + +} + diff --git a/libraries/stdlib/src/generated/_Arrays.kt b/libraries/stdlib/src/generated/_Arrays.kt index 6885247e85f..982face439c 100644 --- a/libraries/stdlib/src/generated/_Arrays.kt +++ b/libraries/stdlib/src/generated/_Arrays.kt @@ -8,531 +8,128 @@ package kotlin import java.util.* /** - * Returns *true* if all elements match the given *predicate* + * Returns true if the array is empty */ -public inline fun Array.all(predicate: (T) -> Boolean) : Boolean { - for (element in this) if (!predicate(element)) return false - return true +public fun Array.isEmpty() : Boolean { + return size == 0 } /** - * Returns *true* if any elements match the given *predicate* + * Returns true if the array is empty */ -public inline fun Array.any(predicate: (T) -> Boolean) : Boolean { - for (element in this) if (predicate(element)) return true - return false +public fun BooleanArray.isEmpty() : Boolean { + return size == 0 } /** - * Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied - * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will - * a special *truncated* separator (which defaults to "..." + * Returns true if the array is empty */ -public fun Array.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit { - buffer.append(prefix) - var count = 0 - for (element in this) { - if (++count > 1) buffer.append(separator) - if (limit < 0 || count <= limit) { - val text = if (element == null) "null" else element.toString() - buffer.append(text) - } else break - } - if (limit >= 0 && count > limit) buffer.append(truncated) - buffer.append(postfix) +public fun ByteArray.isEmpty() : Boolean { + return size == 0 } /** - * Returns the number of elements which match the given *predicate* + * Returns true if the array is empty */ -public inline fun Array.count(predicate: (T) -> Boolean) : Int { - var count = 0 - for (element in this) if (predicate(element)) count++ - return count +public fun CharArray.isEmpty() : Boolean { + return size == 0 } /** - * Returns a list containing everything but the first *n* elements + * Returns true if the array is empty */ -public fun Array.drop(n: Int) : List { - return dropWhile(countTo(n)) +public fun DoubleArray.isEmpty() : Boolean { + return size == 0 } /** - * Returns a list containing the everything but the first elements that satisfy the given *predicate* + * Returns true if the array is empty */ -public inline fun Array.dropWhile(predicate: (T) -> Boolean) : List { - return dropWhileTo(ArrayList(), predicate) +public fun FloatArray.isEmpty() : Boolean { + return size == 0 } /** - * Returns a list containing the everything but the first elements that satisfy the given *predicate* + * Returns true if the array is empty */ -public inline fun > Array.dropWhileTo(result: L, predicate: (T) -> Boolean) : L { - var start = true - for (element in this) { - if (start && predicate(element)) { - // ignore - } else { - start = false - result.add(element) - } - } - return result +public fun IntArray.isEmpty() : Boolean { + return size == 0 } /** - * Returns a list containing all elements which match the given *predicate* + * Returns true if the array is empty */ -public inline fun Array.filter(predicate: (T) -> Boolean) : List { - return filterTo(ArrayList(), predicate) +public fun LongArray.isEmpty() : Boolean { + return size == 0 } /** - * Returns a list containing all elements which do not match the given *predicate* + * Returns true if the array is empty */ -public inline fun Array.filterNot(predicate: (T) -> Boolean) : List { - return filterNotTo(ArrayList(), predicate) +public fun ShortArray.isEmpty() : Boolean { + return size == 0 } /** - * Returns a list containing all the non-*null* elements + * Returns true if the array is not empty */ -public fun Array.filterNotNull() : List { - return filterNotNullTo>(ArrayList()) +public fun Array.isNotEmpty() : Boolean { + return !isEmpty() } /** - * Filters all non-*null* elements into the given list + * Returns true if the array is not empty */ -public fun > Array.filterNotNullTo(result: C) : C { - for (element in this) if (element != null) result.add(element) - return result +public fun BooleanArray.isNotEmpty() : Boolean { + return !isEmpty() } /** - * Returns a list containing all elements which do not match the given *predicate* + * Returns true if the array is not empty */ -public inline fun > Array.filterNotTo(result: C, predicate: (T) -> Boolean) : C { - for (element in this) if (!predicate(element)) result.add(element) - return result +public fun ByteArray.isNotEmpty() : Boolean { + return !isEmpty() } /** - * Filters all elements which match the given predicate into the given list + * Returns true if the array is not empty */ -public inline fun > Array.filterTo(result: C, predicate: (T) -> Boolean) : C { - for (element in this) if (predicate(element)) result.add(element) - return result +public fun CharArray.isNotEmpty() : Boolean { + return !isEmpty() } /** - * Returns the first element which matches the given *predicate* or *null* if none matched + * Returns true if the array is not empty */ -public inline fun Array.find(predicate: (T) -> Boolean) : T? { - for (element in this) if (predicate(element)) return element - return null +public fun DoubleArray.isNotEmpty() : Boolean { + return !isEmpty() } /** - * Returns the result of transforming each element to one or more values which are concatenated together into a single list + * Returns true if the array is not empty */ -public inline fun Array.flatMap(transform: (T)-> Iterable) : List { - return flatMapTo(ArrayList(), transform) +public fun FloatArray.isNotEmpty() : Boolean { + return !isEmpty() } /** - * Returns the result of transforming each element to one or more values which are concatenated together into a single collection + * Returns true if the array is not empty */ -public inline fun > Array.flatMapTo(result: C, transform: (T) -> Iterable) : C { - for (element in this) { - val list = transform(element) - for (r in list) result.add(r) - } - return result +public fun IntArray.isNotEmpty() : Boolean { + return !isEmpty() } /** - * Folds all elements from from left to right with the *initial* value to perform the operation on sequential pairs of elements + * Returns true if the array is not empty */ -public inline fun Array.fold(initial: R, operation: (R, T) -> R) : R { - var answer = initial - for (element in this) answer = operation(answer, element) - return answer +public fun LongArray.isNotEmpty() : Boolean { + return !isEmpty() } /** - * Folds all elements from right to left with the *initial* value to perform the operation on sequential pairs of elements + * Returns true if the array is not empty */ -public inline fun Array.foldRight(initial: R, operation: (T, R) -> R) : R { - var r = initial - var index = size - 1 - - while (index >= 0) { - r = operation(get(index--), r) - } - - return r -} - -/** - * Performs the given *operation* on each element - */ -public inline fun Array.forEach(operation: (T) -> Unit) : Unit { - for (element in this) operation(element) -} - -/** - * Groups the elements in the collection into a new [[Map]] using the supplied *toKey* function to calculate the key to group the elements by - */ -public inline fun Array.groupBy(toKey: (T) -> K) : Map> { - return groupByTo(HashMap>(), toKey) -} - -public inline fun Array.groupByTo(result: MutableMap>, toKey: (T) -> K) : Map> { - for (element in this) { - val key = toKey(element) - val list = result.getOrPut(key) { ArrayList() } - list.add(element) - } - return result -} - -/** - * Returns first index of item, or -1 if the array does not contain item - */ -public fun Array.indexOf(item: T) : Int { - if (item == null) { - for (i in indices) { - if (this[i] == null) { - return i - } - } - } else { - for (i in indices) { - if (item == this[i]) { - return i - } - } - } - return -1 -} - -/** - * Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied. - * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will - * a special *truncated* separator (which defaults to "..." - */ -public fun Array.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String { - val buffer = StringBuilder() - appendString(buffer, separator, prefix, postfix, limit, truncated) - return buffer.toString() -} - -/** - * Returns a new List containing the results of applying the given *transform* function to each element in this collection - */ -public inline fun Array.map(transform : (T) -> R) : List { - return mapTo(ArrayList(), transform) -} - -/** - * Transforms each element of this collection with the given *transform* function and - * adds each return value to the given *results* collection - */ -public inline fun > Array.mapTo(result: C, transform : (T) -> R) : C { - for (item in this) - result.add(transform(item)) - return result -} - -/** - * Returns the largest element or null if there are no elements - */ -public fun > Array.max() : T? { - if (isEmpty()) return null - - var max = this[0] - for (i in 1..lastIndex) { - val e = this[i] - if (max < e) max = e - } - return max -} - -/** - * Returns the first element yielding the largest value of the given function or null if there are no elements - */ -public inline fun , T: Any> Array.maxBy(f: (T) -> R) : T? { - if (isEmpty()) return null - - var maxElem = this[0] - var maxValue = f(maxElem) - for (i in 1..lastIndex) { - val e = this[i] - val v = f(e) - if (maxValue < v) { - maxElem = e - maxValue = v - } - } - return maxElem -} - -/** - * Returns the smallest element or null if there are no elements - */ -public fun > Array.min() : T? { - if (isEmpty()) return null - - var min = this[0] - for (i in 1..lastIndex) { - val e = this[i] - if (min > e) min = e - } - return min -} - -/** - * Returns the first element yielding the smallest value of the given function or null if there are no elements - */ -public inline fun , T: Any> Array.minBy(f: (T) -> R) : T? { - if (size == 0) return null - - var minElem = this[0] - var minValue = f(minElem) - for (i in 1..lastIndex) { - val e = this[i] - val v = f(e) - if (minValue > v) { - minElem = e - minValue = v - } - } - return minElem -} - -/** - * Partitions this collection into a pair of collections - */ -public inline fun Array.partition(predicate: (T) -> Boolean) : Pair, List> { - val first = ArrayList() - val second = ArrayList() - for (element in this) { - if (predicate(element)) { - first.add(element) - } else { - second.add(element) - } - } - return Pair(first, second) -} - -/** - * Creates an [[Iterator]] which iterates over this iterator then the following collection - */ -public fun Array.plus(collection: Iterable) : List { - return plus(collection.iterator()) -} - -/** - * Creates an [[Iterator]] which iterates over this iterator then the given element at the end - */ -public fun Array.plus(element: T) : List { - val answer = ArrayList() - toCollection(answer) - answer.add(element) - return answer -} - -/** - * Creates an [[Iterator]] which iterates over this iterator then the following iterator - */ -public fun Array.plus(iterator: Iterator) : List { - val answer = ArrayList() - toCollection(answer) - for (element in iterator) { - answer.add(element) - } - return answer -} - -/** - * Applies binary operation to all elements of iterable, going from left to right. - * Similar to fold function, but uses the first element as initial value - */ -public inline fun Array.reduce(operation: (T, T) -> T) : T { - val iterator = this.iterator() - if (!iterator.hasNext()) { - throw UnsupportedOperationException("Empty iterable can't be reduced") - } - - var result: T = iterator.next() //compiler doesn't understand that result will initialized anyway - while (iterator.hasNext()) { - result = operation(result, iterator.next()) - } - - return result -} - -/** - * Applies binary operation to all elements of iterable, going from right to left. - * Similar to foldRight function, but uses the last element as initial value - */ -public inline fun Array.reduceRight(operation: (T, T) -> T) : T { - var index = size - 1 - if (index < 0) { - throw UnsupportedOperationException("Empty iterable can't be reduced") - } - - var r = get(index--) - while (index >= 0) { - r = operation(get(index--), r) - } - - return r -} - -/** - * Returns a original Iterable containing all the non-*null* elements, throwing an [[IllegalArgumentException]] if there are any null elements - */ -public fun Array.requireNoNulls() : Array { - for (element in this) { - if (element == null) { - throw IllegalArgumentException("null element found in $this") - } - } - return this as Array -} - -/** - * Reverses the order the elements into a list - */ -public fun Array.reverse() : List { - val list = toCollection(ArrayList()) - Collections.reverse(list) - return list -} - -/** - * Copies all elements into a [[List]] and sorts it by value of compare_function(element) - * E.g. arrayList("two" to 2, "one" to 1).sortBy({it.second}) returns list sorted by second element of pair - */ -public inline fun > Array.sortBy(f: (T) -> R) : List { - val sortedList = toCollection(ArrayList()) - val sortBy: Comparator = comparator {(x: T, y: T) -> - val xr = f(x) - val yr = f(y) - xr.compareTo(yr) - } - java.util.Collections.sort(sortedList, sortBy) - return sortedList -} - -/** - * Returns a list containing the first *n* elements - */ -public fun Array.take(n: Int) : List { - return takeWhile(countTo(n)) -} - -/** - * Returns a list containing the first elements that satisfy the given *predicate* - */ -public inline fun Array.takeWhile(predicate: (T) -> Boolean) : List { - return takeWhileTo(ArrayList(), predicate) -} - -/** - * Returns a list containing the first elements that satisfy the given *predicate* - */ -public inline fun > Array.takeWhileTo(result: C, predicate: (T) -> Boolean) : C { - for (element in this) if (predicate(element)) result.add(element) else break - return result -} - -/** - * Copies all elements into the given collection - */ -public fun > Array.toCollection(result: C) : C { - for (element in this) result.add(element) - return result -} - -/** - * Copies all elements into a [[LinkedList]] - */ -public fun Array.toLinkedList() : LinkedList { - return toCollection(LinkedList()) -} - -/** - * Copies all elements into a [[List]] - */ -public fun Array.toList() : List { - return toCollection(ArrayList()) -} - -/** - * Copies all elements into a [[Set]] - */ -public fun Array.toSet() : Set { - return toCollection(LinkedHashSet()) -} - -/** - * Copies all elements into a [[SortedSet]] - */ -public fun Array.toSortedSet() : SortedSet { - return toCollection(TreeSet()) -} - -/** - * Returns an iterator of Pairs(index, data) - */ -public fun Array.withIndices() : Iterator> { - return IndexIterator(iterator()) -} - -/** - * Sums up the elements - */ -public fun Array.sum() : Int { - return fold(0, {a,b -> a+b}) -} - -/** - * Sums up the elements - */ -public fun Array.sum() : Int { - return fold(0, {a,b -> a+b}) -} - -/** - * Sums up the elements - */ -public fun Array.sum() : Int { - return fold(0, {a,b -> a+b}) -} - -/** - * Sums up the elements - */ -public fun Array.sum() : Long { - return fold(0.toLong(), {a,b -> a+b}) -} - -/** - * Sums up the elements - */ -public fun Array.sum() : Float { - return fold(0.toFloat(), {a,b -> a+b}) -} - -/** - * Sums up the elements - */ -public fun Array.sum() : Double { - return fold(0.0, {a,b -> a+b}) +public fun ShortArray.isNotEmpty() : Boolean { + return !isEmpty() } diff --git a/libraries/stdlib/src/generated/_BooleanArrays.kt b/libraries/stdlib/src/generated/_BooleanArrays.kt deleted file mode 100644 index ae012f75959..00000000000 --- a/libraries/stdlib/src/generated/_BooleanArrays.kt +++ /dev/null @@ -1,447 +0,0 @@ -package kotlin - -// -// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt -// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib -// - -import java.util.* - -/** - * Returns *true* if all elements match the given *predicate* - */ -public inline fun BooleanArray.all(predicate: (Boolean) -> Boolean) : Boolean { - for (element in this) if (!predicate(element)) return false - return true -} - -/** - * Returns *true* if any elements match the given *predicate* - */ -public inline fun BooleanArray.any(predicate: (Boolean) -> Boolean) : Boolean { - for (element in this) if (predicate(element)) return true - return false -} - -/** - * Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied - * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will - * a special *truncated* separator (which defaults to "..." - */ -public fun BooleanArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit { - buffer.append(prefix) - var count = 0 - for (element in this) { - if (++count > 1) buffer.append(separator) - if (limit < 0 || count <= limit) { - val text = if (element == null) "null" else element.toString() - buffer.append(text) - } else break - } - if (limit >= 0 && count > limit) buffer.append(truncated) - buffer.append(postfix) -} - -/** - * Returns the number of elements which match the given *predicate* - */ -public inline fun BooleanArray.count(predicate: (Boolean) -> Boolean) : Int { - var count = 0 - for (element in this) if (predicate(element)) count++ - return count -} - -/** - * Returns a list containing everything but the first *n* elements - */ -public fun BooleanArray.drop(n: Int) : List { - return dropWhile(countTo(n)) -} - -/** - * Returns a list containing the everything but the first elements that satisfy the given *predicate* - */ -public inline fun BooleanArray.dropWhile(predicate: (Boolean) -> Boolean) : List { - return dropWhileTo(ArrayList(), predicate) -} - -/** - * Returns a list containing the everything but the first elements that satisfy the given *predicate* - */ -public inline fun > BooleanArray.dropWhileTo(result: L, predicate: (Boolean) -> Boolean) : L { - var start = true - for (element in this) { - if (start && predicate(element)) { - // ignore - } else { - start = false - result.add(element) - } - } - return result -} - -/** - * Returns a list containing all elements which match the given *predicate* - */ -public inline fun BooleanArray.filter(predicate: (Boolean) -> Boolean) : List { - return filterTo(ArrayList(), predicate) -} - -/** - * Returns a list containing all elements which do not match the given *predicate* - */ -public inline fun BooleanArray.filterNot(predicate: (Boolean) -> Boolean) : List { - return filterNotTo(ArrayList(), predicate) -} - -/** - * Returns a list containing all elements which do not match the given *predicate* - */ -public inline fun > BooleanArray.filterNotTo(result: C, predicate: (Boolean) -> Boolean) : C { - for (element in this) if (!predicate(element)) result.add(element) - return result -} - -/** - * Filters all elements which match the given predicate into the given list - */ -public inline fun > BooleanArray.filterTo(result: C, predicate: (Boolean) -> Boolean) : C { - for (element in this) if (predicate(element)) result.add(element) - return result -} - -/** - * Returns the first element which matches the given *predicate* or *null* if none matched - */ -public inline fun BooleanArray.find(predicate: (Boolean) -> Boolean) : Boolean? { - for (element in this) if (predicate(element)) return element - return null -} - -/** - * Returns the result of transforming each element to one or more values which are concatenated together into a single list - */ -public inline fun BooleanArray.flatMap(transform: (Boolean)-> Iterable) : List { - return flatMapTo(ArrayList(), transform) -} - -/** - * Returns the result of transforming each element to one or more values which are concatenated together into a single collection - */ -public inline fun > BooleanArray.flatMapTo(result: C, transform: (Boolean) -> Iterable) : C { - for (element in this) { - val list = transform(element) - for (r in list) result.add(r) - } - return result -} - -/** - * Folds all elements from from left to right with the *initial* value to perform the operation on sequential pairs of elements - */ -public inline fun BooleanArray.fold(initial: R, operation: (R, Boolean) -> R) : R { - var answer = initial - for (element in this) answer = operation(answer, element) - return answer -} - -/** - * Folds all elements from right to left with the *initial* value to perform the operation on sequential pairs of elements - */ -public inline fun BooleanArray.foldRight(initial: R, operation: (Boolean, R) -> R) : R { - var r = initial - var index = size - 1 - - while (index >= 0) { - r = operation(get(index--), r) - } - - return r -} - -/** - * Performs the given *operation* on each element - */ -public inline fun BooleanArray.forEach(operation: (Boolean) -> Unit) : Unit { - for (element in this) operation(element) -} - -/** - * Groups the elements in the collection into a new [[Map]] using the supplied *toKey* function to calculate the key to group the elements by - */ -public inline fun BooleanArray.groupBy(toKey: (Boolean) -> K) : Map> { - return groupByTo(HashMap>(), toKey) -} - -public inline fun BooleanArray.groupByTo(result: MutableMap>, toKey: (Boolean) -> K) : Map> { - for (element in this) { - val key = toKey(element) - val list = result.getOrPut(key) { ArrayList() } - list.add(element) - } - return result -} - -/** - * Returns first index of item, or -1 if the array does not contain item - */ -public fun BooleanArray.indexOf(item: Boolean) : Int { - for (i in indices) { - if (item == this[i]) { - return i - } - } - return -1 -} - -/** - * Returns true if the array is empty - */ -public fun BooleanArray.isEmpty() : Boolean { - return size == 0 -} - -/** - * Returns true if the array is empty - */ -public fun BooleanArray.isNotEmpty() : Boolean { - return !isEmpty() -} - -/** - * Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied. - * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will - * a special *truncated* separator (which defaults to "..." - */ -public fun BooleanArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String { - val buffer = StringBuilder() - appendString(buffer, separator, prefix, postfix, limit, truncated) - return buffer.toString() -} - -/** - * Returns a new List containing the results of applying the given *transform* function to each element in this collection - */ -public inline fun BooleanArray.map(transform : (Boolean) -> R) : List { - return mapTo(ArrayList(), transform) -} - -/** - * Transforms each element of this collection with the given *transform* function and - * adds each return value to the given *results* collection - */ -public inline fun > BooleanArray.mapTo(result: C, transform : (Boolean) -> R) : C { - for (item in this) - result.add(transform(item)) - return result -} - -/** - * Returns the first element yielding the largest value of the given function or null if there are no elements - */ -public inline fun > BooleanArray.maxBy(f: (Boolean) -> R) : Boolean? { - if (isEmpty()) return null - - var maxElem = this[0] - var maxValue = f(maxElem) - for (i in 1..lastIndex) { - val e = this[i] - val v = f(e) - if (maxValue < v) { - maxElem = e - maxValue = v - } - } - return maxElem -} - -/** - * Returns the first element yielding the smallest value of the given function or null if there are no elements - */ -public inline fun > BooleanArray.minBy(f: (Boolean) -> R) : Boolean? { - if (size == 0) return null - - var minElem = this[0] - var minValue = f(minElem) - for (i in 1..lastIndex) { - val e = this[i] - val v = f(e) - if (minValue > v) { - minElem = e - minValue = v - } - } - return minElem -} - -/** - * Partitions this collection into a pair of collections - */ -public inline fun BooleanArray.partition(predicate: (Boolean) -> Boolean) : Pair, List> { - val first = ArrayList() - val second = ArrayList() - for (element in this) { - if (predicate(element)) { - first.add(element) - } else { - second.add(element) - } - } - return Pair(first, second) -} - -/** - * Creates an [[Iterator]] which iterates over this iterator then the following collection - */ -public fun BooleanArray.plus(collection: Iterable) : List { - return plus(collection.iterator()) -} - -/** - * Creates an [[Iterator]] which iterates over this iterator then the given element at the end - */ -public fun BooleanArray.plus(element: Boolean) : List { - val answer = ArrayList() - toCollection(answer) - answer.add(element) - return answer -} - -/** - * Creates an [[Iterator]] which iterates over this iterator then the following iterator - */ -public fun BooleanArray.plus(iterator: Iterator) : List { - val answer = ArrayList() - toCollection(answer) - for (element in iterator) { - answer.add(element) - } - return answer -} - -/** - * Applies binary operation to all elements of iterable, going from left to right. - * Similar to fold function, but uses the first element as initial value - */ -public inline fun BooleanArray.reduce(operation: (Boolean, Boolean) -> Boolean) : Boolean { - val iterator = this.iterator() - if (!iterator.hasNext()) { - throw UnsupportedOperationException("Empty iterable can't be reduced") - } - - var result: Boolean = iterator.next() //compiler doesn't understand that result will initialized anyway - while (iterator.hasNext()) { - result = operation(result, iterator.next()) - } - - return result -} - -/** - * Applies binary operation to all elements of iterable, going from right to left. - * Similar to foldRight function, but uses the last element as initial value - */ -public inline fun BooleanArray.reduceRight(operation: (Boolean, Boolean) -> Boolean) : Boolean { - var index = size - 1 - if (index < 0) { - throw UnsupportedOperationException("Empty iterable can't be reduced") - } - - var r = get(index--) - while (index >= 0) { - r = operation(get(index--), r) - } - - return r -} - -/** - * Reverses the order the elements into a list - */ -public fun BooleanArray.reverse() : List { - val list = toCollection(ArrayList()) - Collections.reverse(list) - return list -} - -/** - * Copies all elements into a [[List]] and sorts it by value of compare_function(element) - * E.g. arrayList("two" to 2, "one" to 1).sortBy({it.second}) returns list sorted by second element of pair - */ -public inline fun > BooleanArray.sortBy(f: (Boolean) -> R) : List { - val sortedList = toCollection(ArrayList()) - val sortBy: Comparator = comparator {(x: Boolean, y: Boolean) -> - val xr = f(x) - val yr = f(y) - xr.compareTo(yr) - } - java.util.Collections.sort(sortedList, sortBy) - return sortedList -} - -/** - * Returns a list containing the first *n* elements - */ -public fun BooleanArray.take(n: Int) : List { - return takeWhile(countTo(n)) -} - -/** - * Returns a list containing the first elements that satisfy the given *predicate* - */ -public inline fun BooleanArray.takeWhile(predicate: (Boolean) -> Boolean) : List { - return takeWhileTo(ArrayList(), predicate) -} - -/** - * Returns a list containing the first elements that satisfy the given *predicate* - */ -public inline fun > BooleanArray.takeWhileTo(result: C, predicate: (Boolean) -> Boolean) : C { - for (element in this) if (predicate(element)) result.add(element) else break - return result -} - -/** - * Copies all elements into the given collection - */ -public fun > BooleanArray.toCollection(result: C) : C { - for (element in this) result.add(element) - return result -} - -/** - * Copies all elements into a [[LinkedList]] - */ -public fun BooleanArray.toLinkedList() : LinkedList { - return toCollection(LinkedList()) -} - -/** - * Copies all elements into a [[List]] - */ -public fun BooleanArray.toList() : List { - return toCollection(ArrayList()) -} - -/** - * Copies all elements into a [[Set]] - */ -public fun BooleanArray.toSet() : Set { - return toCollection(LinkedHashSet()) -} - -/** - * Copies all elements into a [[SortedSet]] - */ -public fun BooleanArray.toSortedSet() : SortedSet { - return toCollection(TreeSet()) -} - -/** - * Returns an iterator of Pairs(index, data) - */ -public fun BooleanArray.withIndices() : Iterator> { - return IndexIterator(iterator()) -} - diff --git a/libraries/stdlib/src/generated/_ByteArrays.kt b/libraries/stdlib/src/generated/_ByteArrays.kt deleted file mode 100644 index 7fe5d21222a..00000000000 --- a/libraries/stdlib/src/generated/_ByteArrays.kt +++ /dev/null @@ -1,482 +0,0 @@ -package kotlin - -// -// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt -// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib -// - -import java.util.* - -/** - * Returns *true* if all elements match the given *predicate* - */ -public inline fun ByteArray.all(predicate: (Byte) -> Boolean) : Boolean { - for (element in this) if (!predicate(element)) return false - return true -} - -/** - * Returns *true* if any elements match the given *predicate* - */ -public inline fun ByteArray.any(predicate: (Byte) -> Boolean) : Boolean { - for (element in this) if (predicate(element)) return true - return false -} - -/** - * Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied - * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will - * a special *truncated* separator (which defaults to "..." - */ -public fun ByteArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit { - buffer.append(prefix) - var count = 0 - for (element in this) { - if (++count > 1) buffer.append(separator) - if (limit < 0 || count <= limit) { - val text = if (element == null) "null" else element.toString() - buffer.append(text) - } else break - } - if (limit >= 0 && count > limit) buffer.append(truncated) - buffer.append(postfix) -} - -/** - * Returns the number of elements which match the given *predicate* - */ -public inline fun ByteArray.count(predicate: (Byte) -> Boolean) : Int { - var count = 0 - for (element in this) if (predicate(element)) count++ - return count -} - -/** - * Returns a list containing everything but the first *n* elements - */ -public fun ByteArray.drop(n: Int) : List { - return dropWhile(countTo(n)) -} - -/** - * Returns a list containing the everything but the first elements that satisfy the given *predicate* - */ -public inline fun ByteArray.dropWhile(predicate: (Byte) -> Boolean) : List { - return dropWhileTo(ArrayList(), predicate) -} - -/** - * Returns a list containing the everything but the first elements that satisfy the given *predicate* - */ -public inline fun > ByteArray.dropWhileTo(result: L, predicate: (Byte) -> Boolean) : L { - var start = true - for (element in this) { - if (start && predicate(element)) { - // ignore - } else { - start = false - result.add(element) - } - } - return result -} - -/** - * Returns a list containing all elements which match the given *predicate* - */ -public inline fun ByteArray.filter(predicate: (Byte) -> Boolean) : List { - return filterTo(ArrayList(), predicate) -} - -/** - * Returns a list containing all elements which do not match the given *predicate* - */ -public inline fun ByteArray.filterNot(predicate: (Byte) -> Boolean) : List { - return filterNotTo(ArrayList(), predicate) -} - -/** - * Returns a list containing all elements which do not match the given *predicate* - */ -public inline fun > ByteArray.filterNotTo(result: C, predicate: (Byte) -> Boolean) : C { - for (element in this) if (!predicate(element)) result.add(element) - return result -} - -/** - * Filters all elements which match the given predicate into the given list - */ -public inline fun > ByteArray.filterTo(result: C, predicate: (Byte) -> Boolean) : C { - for (element in this) if (predicate(element)) result.add(element) - return result -} - -/** - * Returns the first element which matches the given *predicate* or *null* if none matched - */ -public inline fun ByteArray.find(predicate: (Byte) -> Boolean) : Byte? { - for (element in this) if (predicate(element)) return element - return null -} - -/** - * Returns the result of transforming each element to one or more values which are concatenated together into a single list - */ -public inline fun ByteArray.flatMap(transform: (Byte)-> Iterable) : List { - return flatMapTo(ArrayList(), transform) -} - -/** - * Returns the result of transforming each element to one or more values which are concatenated together into a single collection - */ -public inline fun > ByteArray.flatMapTo(result: C, transform: (Byte) -> Iterable) : C { - for (element in this) { - val list = transform(element) - for (r in list) result.add(r) - } - return result -} - -/** - * Folds all elements from from left to right with the *initial* value to perform the operation on sequential pairs of elements - */ -public inline fun ByteArray.fold(initial: R, operation: (R, Byte) -> R) : R { - var answer = initial - for (element in this) answer = operation(answer, element) - return answer -} - -/** - * Folds all elements from right to left with the *initial* value to perform the operation on sequential pairs of elements - */ -public inline fun ByteArray.foldRight(initial: R, operation: (Byte, R) -> R) : R { - var r = initial - var index = size - 1 - - while (index >= 0) { - r = operation(get(index--), r) - } - - return r -} - -/** - * Performs the given *operation* on each element - */ -public inline fun ByteArray.forEach(operation: (Byte) -> Unit) : Unit { - for (element in this) operation(element) -} - -/** - * Groups the elements in the collection into a new [[Map]] using the supplied *toKey* function to calculate the key to group the elements by - */ -public inline fun ByteArray.groupBy(toKey: (Byte) -> K) : Map> { - return groupByTo(HashMap>(), toKey) -} - -public inline fun ByteArray.groupByTo(result: MutableMap>, toKey: (Byte) -> K) : Map> { - for (element in this) { - val key = toKey(element) - val list = result.getOrPut(key) { ArrayList() } - list.add(element) - } - return result -} - -/** - * Returns first index of item, or -1 if the array does not contain item - */ -public fun ByteArray.indexOf(item: Byte) : Int { - for (i in indices) { - if (item == this[i]) { - return i - } - } - return -1 -} - -/** - * Returns true if the array is empty - */ -public fun ByteArray.isEmpty() : Boolean { - return size == 0 -} - -/** - * Returns true if the array is empty - */ -public fun ByteArray.isNotEmpty() : Boolean { - return !isEmpty() -} - -/** - * Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied. - * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will - * a special *truncated* separator (which defaults to "..." - */ -public fun ByteArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String { - val buffer = StringBuilder() - appendString(buffer, separator, prefix, postfix, limit, truncated) - return buffer.toString() -} - -/** - * Returns a new List containing the results of applying the given *transform* function to each element in this collection - */ -public inline fun ByteArray.map(transform : (Byte) -> R) : List { - return mapTo(ArrayList(), transform) -} - -/** - * Transforms each element of this collection with the given *transform* function and - * adds each return value to the given *results* collection - */ -public inline fun > ByteArray.mapTo(result: C, transform : (Byte) -> R) : C { - for (item in this) - result.add(transform(item)) - return result -} - -/** - * Returns the largest element or null if there are no elements - */ -public fun ByteArray.max() : Byte? { - if (isEmpty()) return null - - var max = this[0] - for (i in 1..lastIndex) { - val e = this[i] - if (max < e) max = e - } - return max -} - -/** - * Returns the first element yielding the largest value of the given function or null if there are no elements - */ -public inline fun > ByteArray.maxBy(f: (Byte) -> R) : Byte? { - if (isEmpty()) return null - - var maxElem = this[0] - var maxValue = f(maxElem) - for (i in 1..lastIndex) { - val e = this[i] - val v = f(e) - if (maxValue < v) { - maxElem = e - maxValue = v - } - } - return maxElem -} - -/** - * Returns the smallest element or null if there are no elements - */ -public fun ByteArray.min() : Byte? { - if (isEmpty()) return null - - var min = this[0] - for (i in 1..lastIndex) { - val e = this[i] - if (min > e) min = e - } - return min -} - -/** - * Returns the first element yielding the smallest value of the given function or null if there are no elements - */ -public inline fun > ByteArray.minBy(f: (Byte) -> R) : Byte? { - if (size == 0) return null - - var minElem = this[0] - var minValue = f(minElem) - for (i in 1..lastIndex) { - val e = this[i] - val v = f(e) - if (minValue > v) { - minElem = e - minValue = v - } - } - return minElem -} - -/** - * Partitions this collection into a pair of collections - */ -public inline fun ByteArray.partition(predicate: (Byte) -> Boolean) : Pair, List> { - val first = ArrayList() - val second = ArrayList() - for (element in this) { - if (predicate(element)) { - first.add(element) - } else { - second.add(element) - } - } - return Pair(first, second) -} - -/** - * Creates an [[Iterator]] which iterates over this iterator then the following collection - */ -public fun ByteArray.plus(collection: Iterable) : List { - return plus(collection.iterator()) -} - -/** - * Creates an [[Iterator]] which iterates over this iterator then the given element at the end - */ -public fun ByteArray.plus(element: Byte) : List { - val answer = ArrayList() - toCollection(answer) - answer.add(element) - return answer -} - -/** - * Creates an [[Iterator]] which iterates over this iterator then the following iterator - */ -public fun ByteArray.plus(iterator: Iterator) : List { - val answer = ArrayList() - toCollection(answer) - for (element in iterator) { - answer.add(element) - } - return answer -} - -/** - * Applies binary operation to all elements of iterable, going from left to right. - * Similar to fold function, but uses the first element as initial value - */ -public inline fun ByteArray.reduce(operation: (Byte, Byte) -> Byte) : Byte { - val iterator = this.iterator() - if (!iterator.hasNext()) { - throw UnsupportedOperationException("Empty iterable can't be reduced") - } - - var result: Byte = iterator.next() //compiler doesn't understand that result will initialized anyway - while (iterator.hasNext()) { - result = operation(result, iterator.next()) - } - - return result -} - -/** - * Applies binary operation to all elements of iterable, going from right to left. - * Similar to foldRight function, but uses the last element as initial value - */ -public inline fun ByteArray.reduceRight(operation: (Byte, Byte) -> Byte) : Byte { - var index = size - 1 - if (index < 0) { - throw UnsupportedOperationException("Empty iterable can't be reduced") - } - - var r = get(index--) - while (index >= 0) { - r = operation(get(index--), r) - } - - return r -} - -/** - * Reverses the order the elements into a list - */ -public fun ByteArray.reverse() : List { - val list = toCollection(ArrayList()) - Collections.reverse(list) - return list -} - -/** - * Copies all elements into a [[List]] and sorts it by value of compare_function(element) - * E.g. arrayList("two" to 2, "one" to 1).sortBy({it.second}) returns list sorted by second element of pair - */ -public inline fun > ByteArray.sortBy(f: (Byte) -> R) : List { - val sortedList = toCollection(ArrayList()) - val sortBy: Comparator = comparator {(x: Byte, y: Byte) -> - val xr = f(x) - val yr = f(y) - xr.compareTo(yr) - } - java.util.Collections.sort(sortedList, sortBy) - return sortedList -} - -/** - * Returns a list containing the first *n* elements - */ -public fun ByteArray.take(n: Int) : List { - return takeWhile(countTo(n)) -} - -/** - * Returns a list containing the first elements that satisfy the given *predicate* - */ -public inline fun ByteArray.takeWhile(predicate: (Byte) -> Boolean) : List { - return takeWhileTo(ArrayList(), predicate) -} - -/** - * Returns a list containing the first elements that satisfy the given *predicate* - */ -public inline fun > ByteArray.takeWhileTo(result: C, predicate: (Byte) -> Boolean) : C { - for (element in this) if (predicate(element)) result.add(element) else break - return result -} - -/** - * Copies all elements into the given collection - */ -public fun > ByteArray.toCollection(result: C) : C { - for (element in this) result.add(element) - return result -} - -/** - * Copies all elements into a [[LinkedList]] - */ -public fun ByteArray.toLinkedList() : LinkedList { - return toCollection(LinkedList()) -} - -/** - * Copies all elements into a [[List]] - */ -public fun ByteArray.toList() : List { - return toCollection(ArrayList()) -} - -/** - * Copies all elements into a [[Set]] - */ -public fun ByteArray.toSet() : Set { - return toCollection(LinkedHashSet()) -} - -/** - * Copies all elements into a [[SortedSet]] - */ -public fun ByteArray.toSortedSet() : SortedSet { - return toCollection(TreeSet()) -} - -/** - * Returns an iterator of Pairs(index, data) - */ -public fun ByteArray.withIndices() : Iterator> { - return IndexIterator(iterator()) -} - -/** - * Sums up the elements - */ -public fun ByteArray.sum() : Int { - return fold(0, {a,b -> a+b}) -} - diff --git a/libraries/stdlib/src/generated/_CharArrays.kt b/libraries/stdlib/src/generated/_CharArrays.kt deleted file mode 100644 index 2e684b9a021..00000000000 --- a/libraries/stdlib/src/generated/_CharArrays.kt +++ /dev/null @@ -1,475 +0,0 @@ -package kotlin - -// -// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt -// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib -// - -import java.util.* - -/** - * Returns *true* if all elements match the given *predicate* - */ -public inline fun CharArray.all(predicate: (Char) -> Boolean) : Boolean { - for (element in this) if (!predicate(element)) return false - return true -} - -/** - * Returns *true* if any elements match the given *predicate* - */ -public inline fun CharArray.any(predicate: (Char) -> Boolean) : Boolean { - for (element in this) if (predicate(element)) return true - return false -} - -/** - * Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied - * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will - * a special *truncated* separator (which defaults to "..." - */ -public fun CharArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit { - buffer.append(prefix) - var count = 0 - for (element in this) { - if (++count > 1) buffer.append(separator) - if (limit < 0 || count <= limit) { - val text = if (element == null) "null" else element.toString() - buffer.append(text) - } else break - } - if (limit >= 0 && count > limit) buffer.append(truncated) - buffer.append(postfix) -} - -/** - * Returns the number of elements which match the given *predicate* - */ -public inline fun CharArray.count(predicate: (Char) -> Boolean) : Int { - var count = 0 - for (element in this) if (predicate(element)) count++ - return count -} - -/** - * Returns a list containing everything but the first *n* elements - */ -public fun CharArray.drop(n: Int) : List { - return dropWhile(countTo(n)) -} - -/** - * Returns a list containing the everything but the first elements that satisfy the given *predicate* - */ -public inline fun CharArray.dropWhile(predicate: (Char) -> Boolean) : List { - return dropWhileTo(ArrayList(), predicate) -} - -/** - * Returns a list containing the everything but the first elements that satisfy the given *predicate* - */ -public inline fun > CharArray.dropWhileTo(result: L, predicate: (Char) -> Boolean) : L { - var start = true - for (element in this) { - if (start && predicate(element)) { - // ignore - } else { - start = false - result.add(element) - } - } - return result -} - -/** - * Returns a list containing all elements which match the given *predicate* - */ -public inline fun CharArray.filter(predicate: (Char) -> Boolean) : List { - return filterTo(ArrayList(), predicate) -} - -/** - * Returns a list containing all elements which do not match the given *predicate* - */ -public inline fun CharArray.filterNot(predicate: (Char) -> Boolean) : List { - return filterNotTo(ArrayList(), predicate) -} - -/** - * Returns a list containing all elements which do not match the given *predicate* - */ -public inline fun > CharArray.filterNotTo(result: C, predicate: (Char) -> Boolean) : C { - for (element in this) if (!predicate(element)) result.add(element) - return result -} - -/** - * Filters all elements which match the given predicate into the given list - */ -public inline fun > CharArray.filterTo(result: C, predicate: (Char) -> Boolean) : C { - for (element in this) if (predicate(element)) result.add(element) - return result -} - -/** - * Returns the first element which matches the given *predicate* or *null* if none matched - */ -public inline fun CharArray.find(predicate: (Char) -> Boolean) : Char? { - for (element in this) if (predicate(element)) return element - return null -} - -/** - * Returns the result of transforming each element to one or more values which are concatenated together into a single list - */ -public inline fun CharArray.flatMap(transform: (Char)-> Iterable) : List { - return flatMapTo(ArrayList(), transform) -} - -/** - * Returns the result of transforming each element to one or more values which are concatenated together into a single collection - */ -public inline fun > CharArray.flatMapTo(result: C, transform: (Char) -> Iterable) : C { - for (element in this) { - val list = transform(element) - for (r in list) result.add(r) - } - return result -} - -/** - * Folds all elements from from left to right with the *initial* value to perform the operation on sequential pairs of elements - */ -public inline fun CharArray.fold(initial: R, operation: (R, Char) -> R) : R { - var answer = initial - for (element in this) answer = operation(answer, element) - return answer -} - -/** - * Folds all elements from right to left with the *initial* value to perform the operation on sequential pairs of elements - */ -public inline fun CharArray.foldRight(initial: R, operation: (Char, R) -> R) : R { - var r = initial - var index = size - 1 - - while (index >= 0) { - r = operation(get(index--), r) - } - - return r -} - -/** - * Performs the given *operation* on each element - */ -public inline fun CharArray.forEach(operation: (Char) -> Unit) : Unit { - for (element in this) operation(element) -} - -/** - * Groups the elements in the collection into a new [[Map]] using the supplied *toKey* function to calculate the key to group the elements by - */ -public inline fun CharArray.groupBy(toKey: (Char) -> K) : Map> { - return groupByTo(HashMap>(), toKey) -} - -public inline fun CharArray.groupByTo(result: MutableMap>, toKey: (Char) -> K) : Map> { - for (element in this) { - val key = toKey(element) - val list = result.getOrPut(key) { ArrayList() } - list.add(element) - } - return result -} - -/** - * Returns first index of item, or -1 if the array does not contain item - */ -public fun CharArray.indexOf(item: Char) : Int { - for (i in indices) { - if (item == this[i]) { - return i - } - } - return -1 -} - -/** - * Returns true if the array is empty - */ -public fun CharArray.isEmpty() : Boolean { - return size == 0 -} - -/** - * Returns true if the array is empty - */ -public fun CharArray.isNotEmpty() : Boolean { - return !isEmpty() -} - -/** - * Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied. - * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will - * a special *truncated* separator (which defaults to "..." - */ -public fun CharArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String { - val buffer = StringBuilder() - appendString(buffer, separator, prefix, postfix, limit, truncated) - return buffer.toString() -} - -/** - * Returns a new List containing the results of applying the given *transform* function to each element in this collection - */ -public inline fun CharArray.map(transform : (Char) -> R) : List { - return mapTo(ArrayList(), transform) -} - -/** - * Transforms each element of this collection with the given *transform* function and - * adds each return value to the given *results* collection - */ -public inline fun > CharArray.mapTo(result: C, transform : (Char) -> R) : C { - for (item in this) - result.add(transform(item)) - return result -} - -/** - * Returns the largest element or null if there are no elements - */ -public fun CharArray.max() : Char? { - if (isEmpty()) return null - - var max = this[0] - for (i in 1..lastIndex) { - val e = this[i] - if (max < e) max = e - } - return max -} - -/** - * Returns the first element yielding the largest value of the given function or null if there are no elements - */ -public inline fun > CharArray.maxBy(f: (Char) -> R) : Char? { - if (isEmpty()) return null - - var maxElem = this[0] - var maxValue = f(maxElem) - for (i in 1..lastIndex) { - val e = this[i] - val v = f(e) - if (maxValue < v) { - maxElem = e - maxValue = v - } - } - return maxElem -} - -/** - * Returns the smallest element or null if there are no elements - */ -public fun CharArray.min() : Char? { - if (isEmpty()) return null - - var min = this[0] - for (i in 1..lastIndex) { - val e = this[i] - if (min > e) min = e - } - return min -} - -/** - * Returns the first element yielding the smallest value of the given function or null if there are no elements - */ -public inline fun > CharArray.minBy(f: (Char) -> R) : Char? { - if (size == 0) return null - - var minElem = this[0] - var minValue = f(minElem) - for (i in 1..lastIndex) { - val e = this[i] - val v = f(e) - if (minValue > v) { - minElem = e - minValue = v - } - } - return minElem -} - -/** - * Partitions this collection into a pair of collections - */ -public inline fun CharArray.partition(predicate: (Char) -> Boolean) : Pair, List> { - val first = ArrayList() - val second = ArrayList() - for (element in this) { - if (predicate(element)) { - first.add(element) - } else { - second.add(element) - } - } - return Pair(first, second) -} - -/** - * Creates an [[Iterator]] which iterates over this iterator then the following collection - */ -public fun CharArray.plus(collection: Iterable) : List { - return plus(collection.iterator()) -} - -/** - * Creates an [[Iterator]] which iterates over this iterator then the given element at the end - */ -public fun CharArray.plus(element: Char) : List { - val answer = ArrayList() - toCollection(answer) - answer.add(element) - return answer -} - -/** - * Creates an [[Iterator]] which iterates over this iterator then the following iterator - */ -public fun CharArray.plus(iterator: Iterator) : List { - val answer = ArrayList() - toCollection(answer) - for (element in iterator) { - answer.add(element) - } - return answer -} - -/** - * Applies binary operation to all elements of iterable, going from left to right. - * Similar to fold function, but uses the first element as initial value - */ -public inline fun CharArray.reduce(operation: (Char, Char) -> Char) : Char { - val iterator = this.iterator() - if (!iterator.hasNext()) { - throw UnsupportedOperationException("Empty iterable can't be reduced") - } - - var result: Char = iterator.next() //compiler doesn't understand that result will initialized anyway - while (iterator.hasNext()) { - result = operation(result, iterator.next()) - } - - return result -} - -/** - * Applies binary operation to all elements of iterable, going from right to left. - * Similar to foldRight function, but uses the last element as initial value - */ -public inline fun CharArray.reduceRight(operation: (Char, Char) -> Char) : Char { - var index = size - 1 - if (index < 0) { - throw UnsupportedOperationException("Empty iterable can't be reduced") - } - - var r = get(index--) - while (index >= 0) { - r = operation(get(index--), r) - } - - return r -} - -/** - * Reverses the order the elements into a list - */ -public fun CharArray.reverse() : List { - val list = toCollection(ArrayList()) - Collections.reverse(list) - return list -} - -/** - * Copies all elements into a [[List]] and sorts it by value of compare_function(element) - * E.g. arrayList("two" to 2, "one" to 1).sortBy({it.second}) returns list sorted by second element of pair - */ -public inline fun > CharArray.sortBy(f: (Char) -> R) : List { - val sortedList = toCollection(ArrayList()) - val sortBy: Comparator = comparator {(x: Char, y: Char) -> - val xr = f(x) - val yr = f(y) - xr.compareTo(yr) - } - java.util.Collections.sort(sortedList, sortBy) - return sortedList -} - -/** - * Returns a list containing the first *n* elements - */ -public fun CharArray.take(n: Int) : List { - return takeWhile(countTo(n)) -} - -/** - * Returns a list containing the first elements that satisfy the given *predicate* - */ -public inline fun CharArray.takeWhile(predicate: (Char) -> Boolean) : List { - return takeWhileTo(ArrayList(), predicate) -} - -/** - * Returns a list containing the first elements that satisfy the given *predicate* - */ -public inline fun > CharArray.takeWhileTo(result: C, predicate: (Char) -> Boolean) : C { - for (element in this) if (predicate(element)) result.add(element) else break - return result -} - -/** - * Copies all elements into the given collection - */ -public fun > CharArray.toCollection(result: C) : C { - for (element in this) result.add(element) - return result -} - -/** - * Copies all elements into a [[LinkedList]] - */ -public fun CharArray.toLinkedList() : LinkedList { - return toCollection(LinkedList()) -} - -/** - * Copies all elements into a [[List]] - */ -public fun CharArray.toList() : List { - return toCollection(ArrayList()) -} - -/** - * Copies all elements into a [[Set]] - */ -public fun CharArray.toSet() : Set { - return toCollection(LinkedHashSet()) -} - -/** - * Copies all elements into a [[SortedSet]] - */ -public fun CharArray.toSortedSet() : SortedSet { - return toCollection(TreeSet()) -} - -/** - * Returns an iterator of Pairs(index, data) - */ -public fun CharArray.withIndices() : Iterator> { - return IndexIterator(iterator()) -} - diff --git a/libraries/stdlib/src/generated/_Collections.kt b/libraries/stdlib/src/generated/_Collections.kt deleted file mode 100644 index 0c80ea0b6e9..00000000000 --- a/libraries/stdlib/src/generated/_Collections.kt +++ /dev/null @@ -1,21 +0,0 @@ -package kotlin - -// -// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt -// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib -// - -import java.util.* - -/** - * Returns a original Iterable containing all the non-*null* elements, throwing an [[IllegalArgumentException]] if there are any null elements - */ -public fun Collection.requireNoNulls() : Collection { - for (element in this) { - if (element == null) { - throw IllegalArgumentException("null element found in $this") - } - } - return this as Collection -} - diff --git a/libraries/stdlib/src/generated/_DoubleArrays.kt b/libraries/stdlib/src/generated/_DoubleArrays.kt deleted file mode 100644 index c8556278992..00000000000 --- a/libraries/stdlib/src/generated/_DoubleArrays.kt +++ /dev/null @@ -1,482 +0,0 @@ -package kotlin - -// -// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt -// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib -// - -import java.util.* - -/** - * Returns *true* if all elements match the given *predicate* - */ -public inline fun DoubleArray.all(predicate: (Double) -> Boolean) : Boolean { - for (element in this) if (!predicate(element)) return false - return true -} - -/** - * Returns *true* if any elements match the given *predicate* - */ -public inline fun DoubleArray.any(predicate: (Double) -> Boolean) : Boolean { - for (element in this) if (predicate(element)) return true - return false -} - -/** - * Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied - * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will - * a special *truncated* separator (which defaults to "..." - */ -public fun DoubleArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit { - buffer.append(prefix) - var count = 0 - for (element in this) { - if (++count > 1) buffer.append(separator) - if (limit < 0 || count <= limit) { - val text = if (element == null) "null" else element.toString() - buffer.append(text) - } else break - } - if (limit >= 0 && count > limit) buffer.append(truncated) - buffer.append(postfix) -} - -/** - * Returns the number of elements which match the given *predicate* - */ -public inline fun DoubleArray.count(predicate: (Double) -> Boolean) : Int { - var count = 0 - for (element in this) if (predicate(element)) count++ - return count -} - -/** - * Returns a list containing everything but the first *n* elements - */ -public fun DoubleArray.drop(n: Int) : List { - return dropWhile(countTo(n)) -} - -/** - * Returns a list containing the everything but the first elements that satisfy the given *predicate* - */ -public inline fun DoubleArray.dropWhile(predicate: (Double) -> Boolean) : List { - return dropWhileTo(ArrayList(), predicate) -} - -/** - * Returns a list containing the everything but the first elements that satisfy the given *predicate* - */ -public inline fun > DoubleArray.dropWhileTo(result: L, predicate: (Double) -> Boolean) : L { - var start = true - for (element in this) { - if (start && predicate(element)) { - // ignore - } else { - start = false - result.add(element) - } - } - return result -} - -/** - * Returns a list containing all elements which match the given *predicate* - */ -public inline fun DoubleArray.filter(predicate: (Double) -> Boolean) : List { - return filterTo(ArrayList(), predicate) -} - -/** - * Returns a list containing all elements which do not match the given *predicate* - */ -public inline fun DoubleArray.filterNot(predicate: (Double) -> Boolean) : List { - return filterNotTo(ArrayList(), predicate) -} - -/** - * Returns a list containing all elements which do not match the given *predicate* - */ -public inline fun > DoubleArray.filterNotTo(result: C, predicate: (Double) -> Boolean) : C { - for (element in this) if (!predicate(element)) result.add(element) - return result -} - -/** - * Filters all elements which match the given predicate into the given list - */ -public inline fun > DoubleArray.filterTo(result: C, predicate: (Double) -> Boolean) : C { - for (element in this) if (predicate(element)) result.add(element) - return result -} - -/** - * Returns the first element which matches the given *predicate* or *null* if none matched - */ -public inline fun DoubleArray.find(predicate: (Double) -> Boolean) : Double? { - for (element in this) if (predicate(element)) return element - return null -} - -/** - * Returns the result of transforming each element to one or more values which are concatenated together into a single list - */ -public inline fun DoubleArray.flatMap(transform: (Double)-> Iterable) : List { - return flatMapTo(ArrayList(), transform) -} - -/** - * Returns the result of transforming each element to one or more values which are concatenated together into a single collection - */ -public inline fun > DoubleArray.flatMapTo(result: C, transform: (Double) -> Iterable) : C { - for (element in this) { - val list = transform(element) - for (r in list) result.add(r) - } - return result -} - -/** - * Folds all elements from from left to right with the *initial* value to perform the operation on sequential pairs of elements - */ -public inline fun DoubleArray.fold(initial: R, operation: (R, Double) -> R) : R { - var answer = initial - for (element in this) answer = operation(answer, element) - return answer -} - -/** - * Folds all elements from right to left with the *initial* value to perform the operation on sequential pairs of elements - */ -public inline fun DoubleArray.foldRight(initial: R, operation: (Double, R) -> R) : R { - var r = initial - var index = size - 1 - - while (index >= 0) { - r = operation(get(index--), r) - } - - return r -} - -/** - * Performs the given *operation* on each element - */ -public inline fun DoubleArray.forEach(operation: (Double) -> Unit) : Unit { - for (element in this) operation(element) -} - -/** - * Groups the elements in the collection into a new [[Map]] using the supplied *toKey* function to calculate the key to group the elements by - */ -public inline fun DoubleArray.groupBy(toKey: (Double) -> K) : Map> { - return groupByTo(HashMap>(), toKey) -} - -public inline fun DoubleArray.groupByTo(result: MutableMap>, toKey: (Double) -> K) : Map> { - for (element in this) { - val key = toKey(element) - val list = result.getOrPut(key) { ArrayList() } - list.add(element) - } - return result -} - -/** - * Returns first index of item, or -1 if the array does not contain item - */ -public fun DoubleArray.indexOf(item: Double) : Int { - for (i in indices) { - if (item == this[i]) { - return i - } - } - return -1 -} - -/** - * Returns true if the array is empty - */ -public fun DoubleArray.isEmpty() : Boolean { - return size == 0 -} - -/** - * Returns true if the array is empty - */ -public fun DoubleArray.isNotEmpty() : Boolean { - return !isEmpty() -} - -/** - * Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied. - * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will - * a special *truncated* separator (which defaults to "..." - */ -public fun DoubleArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String { - val buffer = StringBuilder() - appendString(buffer, separator, prefix, postfix, limit, truncated) - return buffer.toString() -} - -/** - * Returns a new List containing the results of applying the given *transform* function to each element in this collection - */ -public inline fun DoubleArray.map(transform : (Double) -> R) : List { - return mapTo(ArrayList(), transform) -} - -/** - * Transforms each element of this collection with the given *transform* function and - * adds each return value to the given *results* collection - */ -public inline fun > DoubleArray.mapTo(result: C, transform : (Double) -> R) : C { - for (item in this) - result.add(transform(item)) - return result -} - -/** - * Returns the largest element or null if there are no elements - */ -public fun DoubleArray.max() : Double? { - if (isEmpty()) return null - - var max = this[0] - for (i in 1..lastIndex) { - val e = this[i] - if (max < e) max = e - } - return max -} - -/** - * Returns the first element yielding the largest value of the given function or null if there are no elements - */ -public inline fun > DoubleArray.maxBy(f: (Double) -> R) : Double? { - if (isEmpty()) return null - - var maxElem = this[0] - var maxValue = f(maxElem) - for (i in 1..lastIndex) { - val e = this[i] - val v = f(e) - if (maxValue < v) { - maxElem = e - maxValue = v - } - } - return maxElem -} - -/** - * Returns the smallest element or null if there are no elements - */ -public fun DoubleArray.min() : Double? { - if (isEmpty()) return null - - var min = this[0] - for (i in 1..lastIndex) { - val e = this[i] - if (min > e) min = e - } - return min -} - -/** - * Returns the first element yielding the smallest value of the given function or null if there are no elements - */ -public inline fun > DoubleArray.minBy(f: (Double) -> R) : Double? { - if (size == 0) return null - - var minElem = this[0] - var minValue = f(minElem) - for (i in 1..lastIndex) { - val e = this[i] - val v = f(e) - if (minValue > v) { - minElem = e - minValue = v - } - } - return minElem -} - -/** - * Partitions this collection into a pair of collections - */ -public inline fun DoubleArray.partition(predicate: (Double) -> Boolean) : Pair, List> { - val first = ArrayList() - val second = ArrayList() - for (element in this) { - if (predicate(element)) { - first.add(element) - } else { - second.add(element) - } - } - return Pair(first, second) -} - -/** - * Creates an [[Iterator]] which iterates over this iterator then the following collection - */ -public fun DoubleArray.plus(collection: Iterable) : List { - return plus(collection.iterator()) -} - -/** - * Creates an [[Iterator]] which iterates over this iterator then the given element at the end - */ -public fun DoubleArray.plus(element: Double) : List { - val answer = ArrayList() - toCollection(answer) - answer.add(element) - return answer -} - -/** - * Creates an [[Iterator]] which iterates over this iterator then the following iterator - */ -public fun DoubleArray.plus(iterator: Iterator) : List { - val answer = ArrayList() - toCollection(answer) - for (element in iterator) { - answer.add(element) - } - return answer -} - -/** - * Applies binary operation to all elements of iterable, going from left to right. - * Similar to fold function, but uses the first element as initial value - */ -public inline fun DoubleArray.reduce(operation: (Double, Double) -> Double) : Double { - val iterator = this.iterator() - if (!iterator.hasNext()) { - throw UnsupportedOperationException("Empty iterable can't be reduced") - } - - var result: Double = iterator.next() //compiler doesn't understand that result will initialized anyway - while (iterator.hasNext()) { - result = operation(result, iterator.next()) - } - - return result -} - -/** - * Applies binary operation to all elements of iterable, going from right to left. - * Similar to foldRight function, but uses the last element as initial value - */ -public inline fun DoubleArray.reduceRight(operation: (Double, Double) -> Double) : Double { - var index = size - 1 - if (index < 0) { - throw UnsupportedOperationException("Empty iterable can't be reduced") - } - - var r = get(index--) - while (index >= 0) { - r = operation(get(index--), r) - } - - return r -} - -/** - * Reverses the order the elements into a list - */ -public fun DoubleArray.reverse() : List { - val list = toCollection(ArrayList()) - Collections.reverse(list) - return list -} - -/** - * Copies all elements into a [[List]] and sorts it by value of compare_function(element) - * E.g. arrayList("two" to 2, "one" to 1).sortBy({it.second}) returns list sorted by second element of pair - */ -public inline fun > DoubleArray.sortBy(f: (Double) -> R) : List { - val sortedList = toCollection(ArrayList()) - val sortBy: Comparator = comparator {(x: Double, y: Double) -> - val xr = f(x) - val yr = f(y) - xr.compareTo(yr) - } - java.util.Collections.sort(sortedList, sortBy) - return sortedList -} - -/** - * Returns a list containing the first *n* elements - */ -public fun DoubleArray.take(n: Int) : List { - return takeWhile(countTo(n)) -} - -/** - * Returns a list containing the first elements that satisfy the given *predicate* - */ -public inline fun DoubleArray.takeWhile(predicate: (Double) -> Boolean) : List { - return takeWhileTo(ArrayList(), predicate) -} - -/** - * Returns a list containing the first elements that satisfy the given *predicate* - */ -public inline fun > DoubleArray.takeWhileTo(result: C, predicate: (Double) -> Boolean) : C { - for (element in this) if (predicate(element)) result.add(element) else break - return result -} - -/** - * Copies all elements into the given collection - */ -public fun > DoubleArray.toCollection(result: C) : C { - for (element in this) result.add(element) - return result -} - -/** - * Copies all elements into a [[LinkedList]] - */ -public fun DoubleArray.toLinkedList() : LinkedList { - return toCollection(LinkedList()) -} - -/** - * Copies all elements into a [[List]] - */ -public fun DoubleArray.toList() : List { - return toCollection(ArrayList()) -} - -/** - * Copies all elements into a [[Set]] - */ -public fun DoubleArray.toSet() : Set { - return toCollection(LinkedHashSet()) -} - -/** - * Copies all elements into a [[SortedSet]] - */ -public fun DoubleArray.toSortedSet() : SortedSet { - return toCollection(TreeSet()) -} - -/** - * Returns an iterator of Pairs(index, data) - */ -public fun DoubleArray.withIndices() : Iterator> { - return IndexIterator(iterator()) -} - -/** - * Sums up the elements - */ -public fun DoubleArray.sum() : Double { - return fold(0.0, {a,b -> a+b}) -} - diff --git a/libraries/stdlib/src/generated/_Elements.kt b/libraries/stdlib/src/generated/_Elements.kt new file mode 100644 index 00000000000..aae60c9fa60 --- /dev/null +++ b/libraries/stdlib/src/generated/_Elements.kt @@ -0,0 +1,2339 @@ +package kotlin + +// +// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt +// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib +// + +import java.util.* + +/** + * Returns true if *element* is found in the collection + */ +public fun Array.contains(element: T) : Boolean { + return indexOf(element) >= 0 +} + +/** + * Returns true if *element* is found in the collection + */ +public fun BooleanArray.contains(element: Boolean) : Boolean { + return indexOf(element) >= 0 +} + +/** + * Returns true if *element* is found in the collection + */ +public fun ByteArray.contains(element: Byte) : Boolean { + return indexOf(element) >= 0 +} + +/** + * Returns true if *element* is found in the collection + */ +public fun CharArray.contains(element: Char) : Boolean { + return indexOf(element) >= 0 +} + +/** + * Returns true if *element* is found in the collection + */ +public fun DoubleArray.contains(element: Double) : Boolean { + return indexOf(element) >= 0 +} + +/** + * Returns true if *element* is found in the collection + */ +public fun FloatArray.contains(element: Float) : Boolean { + return indexOf(element) >= 0 +} + +/** + * Returns true if *element* is found in the collection + */ +public fun IntArray.contains(element: Int) : Boolean { + return indexOf(element) >= 0 +} + +/** + * Returns true if *element* is found in the collection + */ +public fun LongArray.contains(element: Long) : Boolean { + return indexOf(element) >= 0 +} + +/** + * Returns true if *element* is found in the collection + */ +public fun ShortArray.contains(element: Short) : Boolean { + return indexOf(element) >= 0 +} + +/** + * Returns true if *element* is found in the collection + */ +public fun Iterable.contains(element: T) : Boolean { + return indexOf(element) >= 0 +} + +/** + * Returns true if *element* is found in the collection + */ +public fun Stream.contains(element: T) : Boolean { + return indexOf(element) >= 0 +} + +/** + * Returns element at given *index* + */ +public fun Array.elementAt(index : Int) : T { + return get(index) + +} + +/** + * Returns element at given *index* + */ +public fun BooleanArray.elementAt(index : Int) : Boolean { + return get(index) + +} + +/** + * Returns element at given *index* + */ +public fun ByteArray.elementAt(index : Int) : Byte { + return get(index) + +} + +/** + * Returns element at given *index* + */ +public fun CharArray.elementAt(index : Int) : Char { + return get(index) + +} + +/** + * Returns element at given *index* + */ +public fun DoubleArray.elementAt(index : Int) : Double { + return get(index) + +} + +/** + * Returns element at given *index* + */ +public fun FloatArray.elementAt(index : Int) : Float { + return get(index) + +} + +/** + * Returns element at given *index* + */ +public fun IntArray.elementAt(index : Int) : Int { + return get(index) + +} + +/** + * Returns element at given *index* + */ +public fun LongArray.elementAt(index : Int) : Long { + return get(index) + +} + +/** + * Returns element at given *index* + */ +public fun ShortArray.elementAt(index : Int) : Short { + return get(index) + +} + +/** + * Returns element at given *index* + */ +public fun Iterable.elementAt(index : Int) : T { + if (this is List<*>) + return get(index) as T + val iterator = iterator() + var count = 0 + while (iterator.hasNext()) { + val element = iterator.next() + if (index == count++) + return element + } + throw IndexOutOfBoundsException("Collection doesn't contain element at index") + +} + +/** + * Returns element at given *index* + */ +public fun List.elementAt(index : Int) : T { + return get(index) + +} + +/** + * Returns element at given *index* + */ +public fun Stream.elementAt(index : Int) : T { + val iterator = iterator() + var count = 0 + while (iterator.hasNext()) { + val element = iterator.next() + if (index == count++) + return element + } + throw IndexOutOfBoundsException("Collection doesn't contain element at index") + +} + +/** + * Returns first element + */ +public fun Array.first() : T { + return this[0] + +} + +/** + * Returns first element + */ +public fun BooleanArray.first() : Boolean { + return this[0] + +} + +/** + * Returns first element + */ +public fun ByteArray.first() : Byte { + return this[0] + +} + +/** + * Returns first element + */ +public fun CharArray.first() : Char { + return this[0] + +} + +/** + * Returns first element + */ +public fun DoubleArray.first() : Double { + return this[0] + +} + +/** + * Returns first element + */ +public fun FloatArray.first() : Float { + return this[0] + +} + +/** + * Returns first element + */ +public fun IntArray.first() : Int { + return this[0] + +} + +/** + * Returns first element + */ +public fun LongArray.first() : Long { + return this[0] + +} + +/** + * Returns first element + */ +public fun ShortArray.first() : Short { + return this[0] + +} + +/** + * Returns first element + */ +public fun Iterable.first() : T { + val iterator = iterator() + if (!iterator.hasNext()) + throw IllegalArgumentException("Collection is empty") + return iterator.next() + +} + +/** + * Returns first element + */ +public fun List.first() : T { + return this[0] + +} + +/** + * Returns first element + */ +public fun Stream.first() : T { + val iterator = iterator() + if (!iterator.hasNext()) + throw IllegalArgumentException("Collection is empty") + return iterator.next() + +} + +/** + * Returns first element matching the given *predicate* + */ +public inline fun Array.first(predicate: (T) -> Boolean) : T { + for (element in this) if (predicate(element)) return element + throw IllegalArgumentException("No element matching predicate was found") + +} + +/** + * Returns first element matching the given *predicate* + */ +public inline fun BooleanArray.first(predicate: (Boolean) -> Boolean) : Boolean { + for (element in this) if (predicate(element)) return element + throw IllegalArgumentException("No element matching predicate was found") + +} + +/** + * Returns first element matching the given *predicate* + */ +public inline fun ByteArray.first(predicate: (Byte) -> Boolean) : Byte { + for (element in this) if (predicate(element)) return element + throw IllegalArgumentException("No element matching predicate was found") + +} + +/** + * Returns first element matching the given *predicate* + */ +public inline fun CharArray.first(predicate: (Char) -> Boolean) : Char { + for (element in this) if (predicate(element)) return element + throw IllegalArgumentException("No element matching predicate was found") + +} + +/** + * Returns first element matching the given *predicate* + */ +public inline fun DoubleArray.first(predicate: (Double) -> Boolean) : Double { + for (element in this) if (predicate(element)) return element + throw IllegalArgumentException("No element matching predicate was found") + +} + +/** + * Returns first element matching the given *predicate* + */ +public inline fun FloatArray.first(predicate: (Float) -> Boolean) : Float { + for (element in this) if (predicate(element)) return element + throw IllegalArgumentException("No element matching predicate was found") + +} + +/** + * Returns first element matching the given *predicate* + */ +public inline fun IntArray.first(predicate: (Int) -> Boolean) : Int { + for (element in this) if (predicate(element)) return element + throw IllegalArgumentException("No element matching predicate was found") + +} + +/** + * Returns first element matching the given *predicate* + */ +public inline fun LongArray.first(predicate: (Long) -> Boolean) : Long { + for (element in this) if (predicate(element)) return element + throw IllegalArgumentException("No element matching predicate was found") + +} + +/** + * Returns first element matching the given *predicate* + */ +public inline fun ShortArray.first(predicate: (Short) -> Boolean) : Short { + for (element in this) if (predicate(element)) return element + throw IllegalArgumentException("No element matching predicate was found") + +} + +/** + * Returns first element matching the given *predicate* + */ +public inline fun Iterable.first(predicate: (T) -> Boolean) : T { + for (element in this) if (predicate(element)) return element + throw IllegalArgumentException("No element matching predicate was found") + +} + +/** + * Returns first element matching the given *predicate* + */ +public inline fun Stream.first(predicate: (T) -> Boolean) : T { + for (element in this) if (predicate(element)) return element + throw IllegalArgumentException("No element matching predicate was found") + +} + +/** + * Returns first elementm, or null if collection is empty + */ +public fun Array.firstOrNull() : T? { + return if (size > 0) this[0] else null + +} + +/** + * Returns first elementm, or null if collection is empty + */ +public fun BooleanArray.firstOrNull() : Boolean? { + return if (size > 0) this[0] else null + +} + +/** + * Returns first elementm, or null if collection is empty + */ +public fun ByteArray.firstOrNull() : Byte? { + return if (size > 0) this[0] else null + +} + +/** + * Returns first elementm, or null if collection is empty + */ +public fun CharArray.firstOrNull() : Char? { + return if (size > 0) this[0] else null + +} + +/** + * Returns first elementm, or null if collection is empty + */ +public fun DoubleArray.firstOrNull() : Double? { + return if (size > 0) this[0] else null + +} + +/** + * Returns first elementm, or null if collection is empty + */ +public fun FloatArray.firstOrNull() : Float? { + return if (size > 0) this[0] else null + +} + +/** + * Returns first elementm, or null if collection is empty + */ +public fun IntArray.firstOrNull() : Int? { + return if (size > 0) this[0] else null + +} + +/** + * Returns first elementm, or null if collection is empty + */ +public fun LongArray.firstOrNull() : Long? { + return if (size > 0) this[0] else null + +} + +/** + * Returns first elementm, or null if collection is empty + */ +public fun ShortArray.firstOrNull() : Short? { + return if (size > 0) this[0] else null + +} + +/** + * Returns first elementm, or null if collection is empty + */ +public fun Iterable.firstOrNull() : T? { + val iterator = iterator() + if (!iterator.hasNext()) + return null + return iterator.next() + +} + +/** + * Returns first elementm, or null if collection is empty + */ +public fun List.firstOrNull() : T? { + return if (size > 0) this[0] else null + +} + +/** + * Returns first elementm, or null if collection is empty + */ +public fun Stream.firstOrNull() : T? { + val iterator = iterator() + if (!iterator.hasNext()) + return null + return iterator.next() + +} + +/** + * Returns first element matching the given *predicate*, or *null* if element was not found + */ +public inline fun Array.firstOrNull(predicate: (T) -> Boolean) : T? { + for (element in this) if (predicate(element)) return element + return null + +} + +/** + * Returns first element matching the given *predicate*, or *null* if element was not found + */ +public inline fun BooleanArray.firstOrNull(predicate: (Boolean) -> Boolean) : Boolean? { + for (element in this) if (predicate(element)) return element + return null + +} + +/** + * Returns first element matching the given *predicate*, or *null* if element was not found + */ +public inline fun ByteArray.firstOrNull(predicate: (Byte) -> Boolean) : Byte? { + for (element in this) if (predicate(element)) return element + return null + +} + +/** + * Returns first element matching the given *predicate*, or *null* if element was not found + */ +public inline fun CharArray.firstOrNull(predicate: (Char) -> Boolean) : Char? { + for (element in this) if (predicate(element)) return element + return null + +} + +/** + * Returns first element matching the given *predicate*, or *null* if element was not found + */ +public inline fun DoubleArray.firstOrNull(predicate: (Double) -> Boolean) : Double? { + for (element in this) if (predicate(element)) return element + return null + +} + +/** + * Returns first element matching the given *predicate*, or *null* if element was not found + */ +public inline fun FloatArray.firstOrNull(predicate: (Float) -> Boolean) : Float? { + for (element in this) if (predicate(element)) return element + return null + +} + +/** + * Returns first element matching the given *predicate*, or *null* if element was not found + */ +public inline fun IntArray.firstOrNull(predicate: (Int) -> Boolean) : Int? { + for (element in this) if (predicate(element)) return element + return null + +} + +/** + * Returns first element matching the given *predicate*, or *null* if element was not found + */ +public inline fun LongArray.firstOrNull(predicate: (Long) -> Boolean) : Long? { + for (element in this) if (predicate(element)) return element + return null + +} + +/** + * Returns first element matching the given *predicate*, or *null* if element was not found + */ +public inline fun ShortArray.firstOrNull(predicate: (Short) -> Boolean) : Short? { + for (element in this) if (predicate(element)) return element + return null + +} + +/** + * Returns first element matching the given *predicate*, or *null* if element was not found + */ +public inline fun Iterable.firstOrNull(predicate: (T) -> Boolean) : T? { + for (element in this) if (predicate(element)) return element + return null + +} + +/** + * Returns first element matching the given *predicate*, or *null* if element was not found + */ +public inline fun Stream.firstOrNull(predicate: (T) -> Boolean) : T? { + for (element in this) if (predicate(element)) return element + return null + +} + +/** + * Returns first index of *element*, or -1 if the collection does not contain element + */ +public fun Array.indexOf(element: T) : Int { + if (element == null) { + for (index in indices) { + if (this[index] == null) { + return index + } + } + } else { + for (index in indices) { + if (element == this[index]) { + return index + } + } + } + return -1 + +} + +/** + * Returns first index of *element*, or -1 if the collection does not contain element + */ +public fun BooleanArray.indexOf(element: Boolean) : Int { + for (index in indices) { + if (element == this[index]) { + return index + } + } + return -1 + +} + +/** + * Returns first index of *element*, or -1 if the collection does not contain element + */ +public fun ByteArray.indexOf(element: Byte) : Int { + for (index in indices) { + if (element == this[index]) { + return index + } + } + return -1 + +} + +/** + * Returns first index of *element*, or -1 if the collection does not contain element + */ +public fun CharArray.indexOf(element: Char) : Int { + for (index in indices) { + if (element == this[index]) { + return index + } + } + return -1 + +} + +/** + * Returns first index of *element*, or -1 if the collection does not contain element + */ +public fun DoubleArray.indexOf(element: Double) : Int { + for (index in indices) { + if (element == this[index]) { + return index + } + } + return -1 + +} + +/** + * Returns first index of *element*, or -1 if the collection does not contain element + */ +public fun FloatArray.indexOf(element: Float) : Int { + for (index in indices) { + if (element == this[index]) { + return index + } + } + return -1 + +} + +/** + * Returns first index of *element*, or -1 if the collection does not contain element + */ +public fun IntArray.indexOf(element: Int) : Int { + for (index in indices) { + if (element == this[index]) { + return index + } + } + return -1 + +} + +/** + * Returns first index of *element*, or -1 if the collection does not contain element + */ +public fun LongArray.indexOf(element: Long) : Int { + for (index in indices) { + if (element == this[index]) { + return index + } + } + return -1 + +} + +/** + * Returns first index of *element*, or -1 if the collection does not contain element + */ +public fun ShortArray.indexOf(element: Short) : Int { + for (index in indices) { + if (element == this[index]) { + return index + } + } + return -1 + +} + +/** + * Returns first index of *element*, or -1 if the collection does not contain element + */ +public fun Iterable.indexOf(element: T) : Int { + var index = 0 + for (item in this) { + if (element == item) + return index + index++ + } + return -1 + +} + +/** + * Returns first index of *element*, or -1 if the collection does not contain element + */ +public fun Stream.indexOf(element: T) : Int { + var index = 0 + for (item in this) { + if (element == item) + return index + index++ + } + return -1 + +} + +/** + * Returns last element + */ +public fun Array.last() : T { + if (size == 0) + throw IllegalArgumentException("Collection is empty") + return this[size - 1] + +} + +/** + * Returns last element + */ +public fun BooleanArray.last() : Boolean { + if (size == 0) + throw IllegalArgumentException("Collection is empty") + return this[size - 1] + +} + +/** + * Returns last element + */ +public fun ByteArray.last() : Byte { + if (size == 0) + throw IllegalArgumentException("Collection is empty") + return this[size - 1] + +} + +/** + * Returns last element + */ +public fun CharArray.last() : Char { + if (size == 0) + throw IllegalArgumentException("Collection is empty") + return this[size - 1] + +} + +/** + * Returns last element + */ +public fun DoubleArray.last() : Double { + if (size == 0) + throw IllegalArgumentException("Collection is empty") + return this[size - 1] + +} + +/** + * Returns last element + */ +public fun FloatArray.last() : Float { + if (size == 0) + throw IllegalArgumentException("Collection is empty") + return this[size - 1] + +} + +/** + * Returns last element + */ +public fun IntArray.last() : Int { + if (size == 0) + throw IllegalArgumentException("Collection is empty") + return this[size - 1] + +} + +/** + * Returns last element + */ +public fun LongArray.last() : Long { + if (size == 0) + throw IllegalArgumentException("Collection is empty") + return this[size - 1] + +} + +/** + * Returns last element + */ +public fun ShortArray.last() : Short { + if (size == 0) + throw IllegalArgumentException("Collection is empty") + return this[size - 1] + +} + +/** + * Returns last element + */ +public fun Iterable.last() : T { + when (this) { + is List<*> -> return this[size - 1] as T + else -> { + val iterator = iterator() + if (!iterator.hasNext()) + throw IllegalArgumentException("Collection is empty") + var last = iterator.next() + while (iterator.hasNext()) + last = iterator.next() + return last + } + } + +} + +/** + * Returns last element + */ +public fun List.last() : T { + if (size == 0) + throw IllegalArgumentException("Collection is empty") + return this[size - 1] + +} + +/** + * Returns last element + */ +public fun Stream.last() : T { + when (this) { + is List<*> -> return this[size - 1] as T + else -> { + val iterator = iterator() + if (!iterator.hasNext()) + throw IllegalArgumentException("Collection is empty") + var last = iterator.next() + while (iterator.hasNext()) + last = iterator.next() + return last + } + } + +} + +/** + * Returns last element matching the given *predicate* + */ +public fun Array.last(predicate: (T) -> Boolean) : T { + fun first(it : Iterator) : T { + for (element in it) if (predicate(element)) return element + throw IllegalArgumentException("Collection doesn't contain any element matching predicate") + } + val iterator = iterator() + var last = first(iterator) + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + last = element + } + return last + +} + +/** + * Returns last element matching the given *predicate* + */ +public fun BooleanArray.last(predicate: (Boolean) -> Boolean) : Boolean { + fun first(it : Iterator) : Boolean { + for (element in it) if (predicate(element)) return element + throw IllegalArgumentException("Collection doesn't contain any element matching predicate") + } + val iterator = iterator() + var last = first(iterator) + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + last = element + } + return last + +} + +/** + * Returns last element matching the given *predicate* + */ +public fun ByteArray.last(predicate: (Byte) -> Boolean) : Byte { + fun first(it : Iterator) : Byte { + for (element in it) if (predicate(element)) return element + throw IllegalArgumentException("Collection doesn't contain any element matching predicate") + } + val iterator = iterator() + var last = first(iterator) + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + last = element + } + return last + +} + +/** + * Returns last element matching the given *predicate* + */ +public fun CharArray.last(predicate: (Char) -> Boolean) : Char { + fun first(it : Iterator) : Char { + for (element in it) if (predicate(element)) return element + throw IllegalArgumentException("Collection doesn't contain any element matching predicate") + } + val iterator = iterator() + var last = first(iterator) + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + last = element + } + return last + +} + +/** + * Returns last element matching the given *predicate* + */ +public fun DoubleArray.last(predicate: (Double) -> Boolean) : Double { + fun first(it : Iterator) : Double { + for (element in it) if (predicate(element)) return element + throw IllegalArgumentException("Collection doesn't contain any element matching predicate") + } + val iterator = iterator() + var last = first(iterator) + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + last = element + } + return last + +} + +/** + * Returns last element matching the given *predicate* + */ +public fun FloatArray.last(predicate: (Float) -> Boolean) : Float { + fun first(it : Iterator) : Float { + for (element in it) if (predicate(element)) return element + throw IllegalArgumentException("Collection doesn't contain any element matching predicate") + } + val iterator = iterator() + var last = first(iterator) + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + last = element + } + return last + +} + +/** + * Returns last element matching the given *predicate* + */ +public fun IntArray.last(predicate: (Int) -> Boolean) : Int { + fun first(it : Iterator) : Int { + for (element in it) if (predicate(element)) return element + throw IllegalArgumentException("Collection doesn't contain any element matching predicate") + } + val iterator = iterator() + var last = first(iterator) + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + last = element + } + return last + +} + +/** + * Returns last element matching the given *predicate* + */ +public fun LongArray.last(predicate: (Long) -> Boolean) : Long { + fun first(it : Iterator) : Long { + for (element in it) if (predicate(element)) return element + throw IllegalArgumentException("Collection doesn't contain any element matching predicate") + } + val iterator = iterator() + var last = first(iterator) + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + last = element + } + return last + +} + +/** + * Returns last element matching the given *predicate* + */ +public fun ShortArray.last(predicate: (Short) -> Boolean) : Short { + fun first(it : Iterator) : Short { + for (element in it) if (predicate(element)) return element + throw IllegalArgumentException("Collection doesn't contain any element matching predicate") + } + val iterator = iterator() + var last = first(iterator) + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + last = element + } + return last + +} + +/** + * Returns last element matching the given *predicate* + */ +public fun Iterable.last(predicate: (T) -> Boolean) : T { + fun first(it : Iterator) : T { + for (element in it) if (predicate(element)) return element + throw IllegalArgumentException("Collection doesn't contain any element matching predicate") + } + val iterator = iterator() + var last = first(iterator) + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + last = element + } + return last + +} + +/** + * Returns last element matching the given *predicate* + */ +public fun Stream.last(predicate: (T) -> Boolean) : T { + fun first(it : Iterator) : T { + for (element in it) if (predicate(element)) return element + throw IllegalArgumentException("Collection doesn't contain any element matching predicate") + } + val iterator = iterator() + var last = first(iterator) + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + last = element + } + return last + +} + +/** + * Returns last index of *element*, or -1 if the collection does not contain element + */ +public fun Array.lastIndexOf(element: T) : Int { + if (element == null) { + for (index in indices.reverse()) { + if (this[index] == null) { + return index + } + } + } else { + for (index in indices.reverse()) { + if (element == this[index]) { + return index + } + } + } + return -1 + +} + +/** + * Returns last index of *element*, or -1 if the collection does not contain element + */ +public fun BooleanArray.lastIndexOf(element: Boolean) : Int { + for (index in indices.reverse()) { + if (element == this[index]) { + return index + } + } + return -1 + +} + +/** + * Returns last index of *element*, or -1 if the collection does not contain element + */ +public fun ByteArray.lastIndexOf(element: Byte) : Int { + for (index in indices.reverse()) { + if (element == this[index]) { + return index + } + } + return -1 + +} + +/** + * Returns last index of *element*, or -1 if the collection does not contain element + */ +public fun CharArray.lastIndexOf(element: Char) : Int { + for (index in indices.reverse()) { + if (element == this[index]) { + return index + } + } + return -1 + +} + +/** + * Returns last index of *element*, or -1 if the collection does not contain element + */ +public fun DoubleArray.lastIndexOf(element: Double) : Int { + for (index in indices.reverse()) { + if (element == this[index]) { + return index + } + } + return -1 + +} + +/** + * Returns last index of *element*, or -1 if the collection does not contain element + */ +public fun FloatArray.lastIndexOf(element: Float) : Int { + for (index in indices.reverse()) { + if (element == this[index]) { + return index + } + } + return -1 + +} + +/** + * Returns last index of *element*, or -1 if the collection does not contain element + */ +public fun IntArray.lastIndexOf(element: Int) : Int { + for (index in indices.reverse()) { + if (element == this[index]) { + return index + } + } + return -1 + +} + +/** + * Returns last index of *element*, or -1 if the collection does not contain element + */ +public fun LongArray.lastIndexOf(element: Long) : Int { + for (index in indices.reverse()) { + if (element == this[index]) { + return index + } + } + return -1 + +} + +/** + * Returns last index of *element*, or -1 if the collection does not contain element + */ +public fun ShortArray.lastIndexOf(element: Short) : Int { + for (index in indices.reverse()) { + if (element == this[index]) { + return index + } + } + return -1 + +} + +/** + * Returns last index of *element*, or -1 if the collection does not contain element + */ +public fun Iterable.lastIndexOf(element: T) : Int { + var lastIndex = -1 + var index = 0 + for (item in this) { + if (element == item) + lastIndex = index + index++ + } + return lastIndex + +} + +/** + * Returns last index of *element*, or -1 if the collection does not contain element + */ +public fun List.lastIndexOf(element: T) : Int { + if (element == null) { + for (index in indices.reverse()) { + if (this[index] == null) { + return index + } + } + } else { + for (index in indices.reverse()) { + if (element == this[index]) { + return index + } + } + } + return -1 + +} + +/** + * Returns last index of *element*, or -1 if the collection does not contain element + */ +public fun Stream.lastIndexOf(element: T) : Int { + var lastIndex = -1 + var index = 0 + for (item in this) { + if (element == item) + lastIndex = index + index++ + } + return lastIndex + +} + +/** + * Returns last element, or null if collection is empty + */ +public fun Array.lastOrNull() : T? { + return if (size > 0) this[size - 1] else null + +} + +/** + * Returns last element, or null if collection is empty + */ +public fun BooleanArray.lastOrNull() : Boolean? { + return if (size > 0) this[size - 1] else null + +} + +/** + * Returns last element, or null if collection is empty + */ +public fun ByteArray.lastOrNull() : Byte? { + return if (size > 0) this[size - 1] else null + +} + +/** + * Returns last element, or null if collection is empty + */ +public fun CharArray.lastOrNull() : Char? { + return if (size > 0) this[size - 1] else null + +} + +/** + * Returns last element, or null if collection is empty + */ +public fun DoubleArray.lastOrNull() : Double? { + return if (size > 0) this[size - 1] else null + +} + +/** + * Returns last element, or null if collection is empty + */ +public fun FloatArray.lastOrNull() : Float? { + return if (size > 0) this[size - 1] else null + +} + +/** + * Returns last element, or null if collection is empty + */ +public fun IntArray.lastOrNull() : Int? { + return if (size > 0) this[size - 1] else null + +} + +/** + * Returns last element, or null if collection is empty + */ +public fun LongArray.lastOrNull() : Long? { + return if (size > 0) this[size - 1] else null + +} + +/** + * Returns last element, or null if collection is empty + */ +public fun ShortArray.lastOrNull() : Short? { + return if (size > 0) this[size - 1] else null + +} + +/** + * Returns last element, or null if collection is empty + */ +public fun Iterable.lastOrNull() : T? { + when (this) { + is List<*> -> return if (size > 0) this[size - 1] as T else null + else -> { + val iterator = iterator() + if (!iterator.hasNext()) + return null + var last = iterator.next() + while (iterator.hasNext()) + last = iterator.next() + return last + } + } + +} + +/** + * Returns last element, or null if collection is empty + */ +public fun List.lastOrNull() : T? { + return if (size > 0) this[size - 1] else null + +} + +/** + * Returns last element, or null if collection is empty + */ +public fun Stream.lastOrNull() : T? { + when (this) { + is List<*> -> return if (size > 0) this[size - 1] as T else null + else -> { + val iterator = iterator() + if (!iterator.hasNext()) + return null + var last = iterator.next() + while (iterator.hasNext()) + last = iterator.next() + return last + } + } + +} + +/** + * Returns last element matching the given *predicate*, or null if element was not found + */ +public fun Array.lastOrNull(predicate: (T) -> Boolean) : T? { + fun first(it : Iterator) : T? { + for (element in it) if (predicate(element)) return element + return null + } + val iterator = iterator() + var last = first(iterator) + if (last == null) + return null + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + last = element + } + return last + +} + +/** + * Returns last element matching the given *predicate*, or null if element was not found + */ +public fun BooleanArray.lastOrNull(predicate: (Boolean) -> Boolean) : Boolean? { + fun first(it : Iterator) : Boolean? { + for (element in it) if (predicate(element)) return element + return null + } + val iterator = iterator() + var last = first(iterator) + if (last == null) + return null + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + last = element + } + return last + +} + +/** + * Returns last element matching the given *predicate*, or null if element was not found + */ +public fun ByteArray.lastOrNull(predicate: (Byte) -> Boolean) : Byte? { + fun first(it : Iterator) : Byte? { + for (element in it) if (predicate(element)) return element + return null + } + val iterator = iterator() + var last = first(iterator) + if (last == null) + return null + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + last = element + } + return last + +} + +/** + * Returns last element matching the given *predicate*, or null if element was not found + */ +public fun CharArray.lastOrNull(predicate: (Char) -> Boolean) : Char? { + fun first(it : Iterator) : Char? { + for (element in it) if (predicate(element)) return element + return null + } + val iterator = iterator() + var last = first(iterator) + if (last == null) + return null + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + last = element + } + return last + +} + +/** + * Returns last element matching the given *predicate*, or null if element was not found + */ +public fun DoubleArray.lastOrNull(predicate: (Double) -> Boolean) : Double? { + fun first(it : Iterator) : Double? { + for (element in it) if (predicate(element)) return element + return null + } + val iterator = iterator() + var last = first(iterator) + if (last == null) + return null + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + last = element + } + return last + +} + +/** + * Returns last element matching the given *predicate*, or null if element was not found + */ +public fun FloatArray.lastOrNull(predicate: (Float) -> Boolean) : Float? { + fun first(it : Iterator) : Float? { + for (element in it) if (predicate(element)) return element + return null + } + val iterator = iterator() + var last = first(iterator) + if (last == null) + return null + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + last = element + } + return last + +} + +/** + * Returns last element matching the given *predicate*, or null if element was not found + */ +public fun IntArray.lastOrNull(predicate: (Int) -> Boolean) : Int? { + fun first(it : Iterator) : Int? { + for (element in it) if (predicate(element)) return element + return null + } + val iterator = iterator() + var last = first(iterator) + if (last == null) + return null + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + last = element + } + return last + +} + +/** + * Returns last element matching the given *predicate*, or null if element was not found + */ +public fun LongArray.lastOrNull(predicate: (Long) -> Boolean) : Long? { + fun first(it : Iterator) : Long? { + for (element in it) if (predicate(element)) return element + return null + } + val iterator = iterator() + var last = first(iterator) + if (last == null) + return null + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + last = element + } + return last + +} + +/** + * Returns last element matching the given *predicate*, or null if element was not found + */ +public fun ShortArray.lastOrNull(predicate: (Short) -> Boolean) : Short? { + fun first(it : Iterator) : Short? { + for (element in it) if (predicate(element)) return element + return null + } + val iterator = iterator() + var last = first(iterator) + if (last == null) + return null + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + last = element + } + return last + +} + +/** + * Returns last element matching the given *predicate*, or null if element was not found + */ +public fun Iterable.lastOrNull(predicate: (T) -> Boolean) : T? { + fun first(it : Iterator) : T? { + for (element in it) if (predicate(element)) return element + return null + } + val iterator = iterator() + var last = first(iterator) + if (last == null) + return null + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + last = element + } + return last + +} + +/** + * Returns last element matching the given *predicate*, or null if element was not found + */ +public fun Stream.lastOrNull(predicate: (T) -> Boolean) : T? { + fun first(it : Iterator) : T? { + for (element in it) if (predicate(element)) return element + return null + } + val iterator = iterator() + var last = first(iterator) + if (last == null) + return null + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + last = element + } + return last + +} + +/** + * Returns single element, or throws exception if there is no or more than one element + */ +public fun Array.single() : T { + if (size != 1) + throw IllegalArgumentException("Collection has $size elements") + return this[0] + +} + +/** + * Returns single element, or throws exception if there is no or more than one element + */ +public fun BooleanArray.single() : Boolean { + if (size != 1) + throw IllegalArgumentException("Collection has $size elements") + return this[0] + +} + +/** + * Returns single element, or throws exception if there is no or more than one element + */ +public fun ByteArray.single() : Byte { + if (size != 1) + throw IllegalArgumentException("Collection has $size elements") + return this[0] + +} + +/** + * Returns single element, or throws exception if there is no or more than one element + */ +public fun CharArray.single() : Char { + if (size != 1) + throw IllegalArgumentException("Collection has $size elements") + return this[0] + +} + +/** + * Returns single element, or throws exception if there is no or more than one element + */ +public fun DoubleArray.single() : Double { + if (size != 1) + throw IllegalArgumentException("Collection has $size elements") + return this[0] + +} + +/** + * Returns single element, or throws exception if there is no or more than one element + */ +public fun FloatArray.single() : Float { + if (size != 1) + throw IllegalArgumentException("Collection has $size elements") + return this[0] + +} + +/** + * Returns single element, or throws exception if there is no or more than one element + */ +public fun IntArray.single() : Int { + if (size != 1) + throw IllegalArgumentException("Collection has $size elements") + return this[0] + +} + +/** + * Returns single element, or throws exception if there is no or more than one element + */ +public fun LongArray.single() : Long { + if (size != 1) + throw IllegalArgumentException("Collection has $size elements") + return this[0] + +} + +/** + * Returns single element, or throws exception if there is no or more than one element + */ +public fun ShortArray.single() : Short { + if (size != 1) + throw IllegalArgumentException("Collection has $size elements") + return this[0] + +} + +/** + * Returns single element, or throws exception if there is no or more than one element + */ +public fun Iterable.single() : T { + when (this) { + is List<*> -> return if (size == 1) this[0] as T else throw IllegalArgumentException("Collection has $size elements") + else -> { + val iterator = iterator() + if (!iterator.hasNext()) + throw IllegalArgumentException("Collection is empty") + var single = iterator.next() + if (iterator.hasNext()) + throw IllegalArgumentException("Collection has more than one element") + return single + } + } + +} + +/** + * Returns single element, or throws exception if there is no or more than one element + */ +public fun Stream.single() : T { + when (this) { + is List<*> -> return if (size == 1) this[0] as T else throw IllegalArgumentException("Collection has $size elements") + else -> { + val iterator = iterator() + if (!iterator.hasNext()) + throw IllegalArgumentException("Collection is empty") + var single = iterator.next() + if (iterator.hasNext()) + throw IllegalArgumentException("Collection has more than one element") + return single + } + } + +} + +/** + * Returns single element matching the given *predicate*, or throws exception if there is no or more than one element + */ +public fun Array.single(predicate: (T) -> Boolean) : T { + fun first(it : Iterator) : T { + for (element in it) if (predicate(element)) return element + throw IllegalArgumentException("Collection doesn't have matching element") + } + val iterator = iterator() + var single = first(iterator) + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + throw IllegalArgumentException("Collection has more than one matching element") + } + return single + +} + +/** + * Returns single element matching the given *predicate*, or throws exception if there is no or more than one element + */ +public fun BooleanArray.single(predicate: (Boolean) -> Boolean) : Boolean { + fun first(it : Iterator) : Boolean { + for (element in it) if (predicate(element)) return element + throw IllegalArgumentException("Collection doesn't have matching element") + } + val iterator = iterator() + var single = first(iterator) + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + throw IllegalArgumentException("Collection has more than one matching element") + } + return single + +} + +/** + * Returns single element matching the given *predicate*, or throws exception if there is no or more than one element + */ +public fun ByteArray.single(predicate: (Byte) -> Boolean) : Byte { + fun first(it : Iterator) : Byte { + for (element in it) if (predicate(element)) return element + throw IllegalArgumentException("Collection doesn't have matching element") + } + val iterator = iterator() + var single = first(iterator) + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + throw IllegalArgumentException("Collection has more than one matching element") + } + return single + +} + +/** + * Returns single element matching the given *predicate*, or throws exception if there is no or more than one element + */ +public fun CharArray.single(predicate: (Char) -> Boolean) : Char { + fun first(it : Iterator) : Char { + for (element in it) if (predicate(element)) return element + throw IllegalArgumentException("Collection doesn't have matching element") + } + val iterator = iterator() + var single = first(iterator) + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + throw IllegalArgumentException("Collection has more than one matching element") + } + return single + +} + +/** + * Returns single element matching the given *predicate*, or throws exception if there is no or more than one element + */ +public fun DoubleArray.single(predicate: (Double) -> Boolean) : Double { + fun first(it : Iterator) : Double { + for (element in it) if (predicate(element)) return element + throw IllegalArgumentException("Collection doesn't have matching element") + } + val iterator = iterator() + var single = first(iterator) + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + throw IllegalArgumentException("Collection has more than one matching element") + } + return single + +} + +/** + * Returns single element matching the given *predicate*, or throws exception if there is no or more than one element + */ +public fun FloatArray.single(predicate: (Float) -> Boolean) : Float { + fun first(it : Iterator) : Float { + for (element in it) if (predicate(element)) return element + throw IllegalArgumentException("Collection doesn't have matching element") + } + val iterator = iterator() + var single = first(iterator) + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + throw IllegalArgumentException("Collection has more than one matching element") + } + return single + +} + +/** + * Returns single element matching the given *predicate*, or throws exception if there is no or more than one element + */ +public fun IntArray.single(predicate: (Int) -> Boolean) : Int { + fun first(it : Iterator) : Int { + for (element in it) if (predicate(element)) return element + throw IllegalArgumentException("Collection doesn't have matching element") + } + val iterator = iterator() + var single = first(iterator) + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + throw IllegalArgumentException("Collection has more than one matching element") + } + return single + +} + +/** + * Returns single element matching the given *predicate*, or throws exception if there is no or more than one element + */ +public fun LongArray.single(predicate: (Long) -> Boolean) : Long { + fun first(it : Iterator) : Long { + for (element in it) if (predicate(element)) return element + throw IllegalArgumentException("Collection doesn't have matching element") + } + val iterator = iterator() + var single = first(iterator) + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + throw IllegalArgumentException("Collection has more than one matching element") + } + return single + +} + +/** + * Returns single element matching the given *predicate*, or throws exception if there is no or more than one element + */ +public fun ShortArray.single(predicate: (Short) -> Boolean) : Short { + fun first(it : Iterator) : Short { + for (element in it) if (predicate(element)) return element + throw IllegalArgumentException("Collection doesn't have matching element") + } + val iterator = iterator() + var single = first(iterator) + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + throw IllegalArgumentException("Collection has more than one matching element") + } + return single + +} + +/** + * Returns single element matching the given *predicate*, or throws exception if there is no or more than one element + */ +public fun Iterable.single(predicate: (T) -> Boolean) : T { + fun first(it : Iterator) : T { + for (element in it) if (predicate(element)) return element + throw IllegalArgumentException("Collection doesn't have matching element") + } + val iterator = iterator() + var single = first(iterator) + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + throw IllegalArgumentException("Collection has more than one matching element") + } + return single + +} + +/** + * Returns single element matching the given *predicate*, or throws exception if there is no or more than one element + */ +public fun Stream.single(predicate: (T) -> Boolean) : T { + fun first(it : Iterator) : T { + for (element in it) if (predicate(element)) return element + throw IllegalArgumentException("Collection doesn't have matching element") + } + val iterator = iterator() + var single = first(iterator) + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + throw IllegalArgumentException("Collection has more than one matching element") + } + return single + +} + +/** + * Returns single element, or null if collection is empty, or throws exception if there is more than one element + */ +public fun Array.singleOrNull() : T? { + if (size == 0) + return null + if (size != 1) + throw IllegalArgumentException("Collection has $size elements") + return this[0] + +} + +/** + * Returns single element, or null if collection is empty, or throws exception if there is more than one element + */ +public fun BooleanArray.singleOrNull() : Boolean? { + if (size == 0) + return null + if (size != 1) + throw IllegalArgumentException("Collection has $size elements") + return this[0] + +} + +/** + * Returns single element, or null if collection is empty, or throws exception if there is more than one element + */ +public fun ByteArray.singleOrNull() : Byte? { + if (size == 0) + return null + if (size != 1) + throw IllegalArgumentException("Collection has $size elements") + return this[0] + +} + +/** + * Returns single element, or null if collection is empty, or throws exception if there is more than one element + */ +public fun CharArray.singleOrNull() : Char? { + if (size == 0) + return null + if (size != 1) + throw IllegalArgumentException("Collection has $size elements") + return this[0] + +} + +/** + * Returns single element, or null if collection is empty, or throws exception if there is more than one element + */ +public fun DoubleArray.singleOrNull() : Double? { + if (size == 0) + return null + if (size != 1) + throw IllegalArgumentException("Collection has $size elements") + return this[0] + +} + +/** + * Returns single element, or null if collection is empty, or throws exception if there is more than one element + */ +public fun FloatArray.singleOrNull() : Float? { + if (size == 0) + return null + if (size != 1) + throw IllegalArgumentException("Collection has $size elements") + return this[0] + +} + +/** + * Returns single element, or null if collection is empty, or throws exception if there is more than one element + */ +public fun IntArray.singleOrNull() : Int? { + if (size == 0) + return null + if (size != 1) + throw IllegalArgumentException("Collection has $size elements") + return this[0] + +} + +/** + * Returns single element, or null if collection is empty, or throws exception if there is more than one element + */ +public fun LongArray.singleOrNull() : Long? { + if (size == 0) + return null + if (size != 1) + throw IllegalArgumentException("Collection has $size elements") + return this[0] + +} + +/** + * Returns single element, or null if collection is empty, or throws exception if there is more than one element + */ +public fun ShortArray.singleOrNull() : Short? { + if (size == 0) + return null + if (size != 1) + throw IllegalArgumentException("Collection has $size elements") + return this[0] + +} + +/** + * Returns single element, or null if collection is empty, or throws exception if there is more than one element + */ +public fun Iterable.singleOrNull() : T? { + when (this) { + is List<*> -> return if (size == 1) this[0] as T else if (size == 0) null else throw IllegalArgumentException("Collection has $size elements") + else -> { + val iterator = iterator() + if (!iterator.hasNext()) + return null + var single = iterator.next() + if (iterator.hasNext()) + throw IllegalArgumentException("Collection has more than one element") + return single + } + } + +} + +/** + * Returns single element, or null if collection is empty, or throws exception if there is more than one element + */ +public fun Stream.singleOrNull() : T? { + when (this) { + is List<*> -> return if (size == 1) this[0] as T else if (size == 0) null else throw IllegalArgumentException("Collection has $size elements") + else -> { + val iterator = iterator() + if (!iterator.hasNext()) + return null + var single = iterator.next() + if (iterator.hasNext()) + throw IllegalArgumentException("Collection has more than one element") + return single + } + } + +} + +/** + * Returns single element matching the given *predicate*, or null if element was not found or more than one elements were found + */ +public fun Array.singleOrNull(predicate: (T) -> Boolean) : T? { + fun first(it : Iterator) : T? { + for (element in it) if (predicate(element)) return element + return null + } + val iterator = iterator() + var single = first(iterator) + if (single == null) + return null + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + throw IllegalArgumentException("Collection has more than one matching element") + } + return single + +} + +/** + * Returns single element matching the given *predicate*, or null if element was not found or more than one elements were found + */ +public fun BooleanArray.singleOrNull(predicate: (Boolean) -> Boolean) : Boolean? { + fun first(it : Iterator) : Boolean? { + for (element in it) if (predicate(element)) return element + return null + } + val iterator = iterator() + var single = first(iterator) + if (single == null) + return null + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + throw IllegalArgumentException("Collection has more than one matching element") + } + return single + +} + +/** + * Returns single element matching the given *predicate*, or null if element was not found or more than one elements were found + */ +public fun ByteArray.singleOrNull(predicate: (Byte) -> Boolean) : Byte? { + fun first(it : Iterator) : Byte? { + for (element in it) if (predicate(element)) return element + return null + } + val iterator = iterator() + var single = first(iterator) + if (single == null) + return null + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + throw IllegalArgumentException("Collection has more than one matching element") + } + return single + +} + +/** + * Returns single element matching the given *predicate*, or null if element was not found or more than one elements were found + */ +public fun CharArray.singleOrNull(predicate: (Char) -> Boolean) : Char? { + fun first(it : Iterator) : Char? { + for (element in it) if (predicate(element)) return element + return null + } + val iterator = iterator() + var single = first(iterator) + if (single == null) + return null + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + throw IllegalArgumentException("Collection has more than one matching element") + } + return single + +} + +/** + * Returns single element matching the given *predicate*, or null if element was not found or more than one elements were found + */ +public fun DoubleArray.singleOrNull(predicate: (Double) -> Boolean) : Double? { + fun first(it : Iterator) : Double? { + for (element in it) if (predicate(element)) return element + return null + } + val iterator = iterator() + var single = first(iterator) + if (single == null) + return null + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + throw IllegalArgumentException("Collection has more than one matching element") + } + return single + +} + +/** + * Returns single element matching the given *predicate*, or null if element was not found or more than one elements were found + */ +public fun FloatArray.singleOrNull(predicate: (Float) -> Boolean) : Float? { + fun first(it : Iterator) : Float? { + for (element in it) if (predicate(element)) return element + return null + } + val iterator = iterator() + var single = first(iterator) + if (single == null) + return null + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + throw IllegalArgumentException("Collection has more than one matching element") + } + return single + +} + +/** + * Returns single element matching the given *predicate*, or null if element was not found or more than one elements were found + */ +public fun IntArray.singleOrNull(predicate: (Int) -> Boolean) : Int? { + fun first(it : Iterator) : Int? { + for (element in it) if (predicate(element)) return element + return null + } + val iterator = iterator() + var single = first(iterator) + if (single == null) + return null + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + throw IllegalArgumentException("Collection has more than one matching element") + } + return single + +} + +/** + * Returns single element matching the given *predicate*, or null if element was not found or more than one elements were found + */ +public fun LongArray.singleOrNull(predicate: (Long) -> Boolean) : Long? { + fun first(it : Iterator) : Long? { + for (element in it) if (predicate(element)) return element + return null + } + val iterator = iterator() + var single = first(iterator) + if (single == null) + return null + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + throw IllegalArgumentException("Collection has more than one matching element") + } + return single + +} + +/** + * Returns single element matching the given *predicate*, or null if element was not found or more than one elements were found + */ +public fun ShortArray.singleOrNull(predicate: (Short) -> Boolean) : Short? { + fun first(it : Iterator) : Short? { + for (element in it) if (predicate(element)) return element + return null + } + val iterator = iterator() + var single = first(iterator) + if (single == null) + return null + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + throw IllegalArgumentException("Collection has more than one matching element") + } + return single + +} + +/** + * Returns single element matching the given *predicate*, or null if element was not found or more than one elements were found + */ +public fun Iterable.singleOrNull(predicate: (T) -> Boolean) : T? { + fun first(it : Iterator) : T? { + for (element in it) if (predicate(element)) return element + return null + } + val iterator = iterator() + var single = first(iterator) + if (single == null) + return null + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + throw IllegalArgumentException("Collection has more than one matching element") + } + return single + +} + +/** + * Returns single element matching the given *predicate*, or null if element was not found or more than one elements were found + */ +public fun Stream.singleOrNull(predicate: (T) -> Boolean) : T? { + fun first(it : Iterator) : T? { + for (element in it) if (predicate(element)) return element + return null + } + val iterator = iterator() + var single = first(iterator) + if (single == null) + return null + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + throw IllegalArgumentException("Collection has more than one matching element") + } + return single + +} + diff --git a/libraries/stdlib/src/generated/_Filtering.kt b/libraries/stdlib/src/generated/_Filtering.kt new file mode 100644 index 00000000000..9dcba9e8c0b --- /dev/null +++ b/libraries/stdlib/src/generated/_Filtering.kt @@ -0,0 +1,1167 @@ +package kotlin + +// +// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt +// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib +// + +import java.util.* + +/** + * Returns a list containing all elements except first *n* elements + */ +public fun Array.drop(n: Int) : List { + if (n >= size) + return ArrayList() + + var count = 0 + val list = ArrayList(size - n) + for (item in this) { + if (count++ >= n) list.add(item) + } + return list + +} + +/** + * Returns a list containing all elements except first *n* elements + */ +public fun BooleanArray.drop(n: Int) : List { + if (n >= size) + return ArrayList() + + var count = 0 + val list = ArrayList(size - n) + for (item in this) { + if (count++ >= n) list.add(item) + } + return list + +} + +/** + * Returns a list containing all elements except first *n* elements + */ +public fun ByteArray.drop(n: Int) : List { + if (n >= size) + return ArrayList() + + var count = 0 + val list = ArrayList(size - n) + for (item in this) { + if (count++ >= n) list.add(item) + } + return list + +} + +/** + * Returns a list containing all elements except first *n* elements + */ +public fun CharArray.drop(n: Int) : List { + if (n >= size) + return ArrayList() + + var count = 0 + val list = ArrayList(size - n) + for (item in this) { + if (count++ >= n) list.add(item) + } + return list + +} + +/** + * Returns a list containing all elements except first *n* elements + */ +public fun DoubleArray.drop(n: Int) : List { + if (n >= size) + return ArrayList() + + var count = 0 + val list = ArrayList(size - n) + for (item in this) { + if (count++ >= n) list.add(item) + } + return list + +} + +/** + * Returns a list containing all elements except first *n* elements + */ +public fun FloatArray.drop(n: Int) : List { + if (n >= size) + return ArrayList() + + var count = 0 + val list = ArrayList(size - n) + for (item in this) { + if (count++ >= n) list.add(item) + } + return list + +} + +/** + * Returns a list containing all elements except first *n* elements + */ +public fun IntArray.drop(n: Int) : List { + if (n >= size) + return ArrayList() + + var count = 0 + val list = ArrayList(size - n) + for (item in this) { + if (count++ >= n) list.add(item) + } + return list + +} + +/** + * Returns a list containing all elements except first *n* elements + */ +public fun LongArray.drop(n: Int) : List { + if (n >= size) + return ArrayList() + + var count = 0 + val list = ArrayList(size - n) + for (item in this) { + if (count++ >= n) list.add(item) + } + return list + +} + +/** + * Returns a list containing all elements except first *n* elements + */ +public fun ShortArray.drop(n: Int) : List { + if (n >= size) + return ArrayList() + + var count = 0 + val list = ArrayList(size - n) + for (item in this) { + if (count++ >= n) list.add(item) + } + return list + +} + +/** + * Returns a list containing all elements except first *n* elements + */ +public fun Collection.drop(n: Int) : List { + if (n >= size) + return ArrayList() + + var count = 0 + val list = ArrayList(size - n) + for (item in this) { + if (count++ >= n) list.add(item) + } + return list + +} + +/** + * Returns a list containing all elements except first *n* elements + */ +public fun Iterable.drop(n: Int) : List { + var count = 0 + val list = ArrayList() + for (item in this) { + if (count++ >= n) list.add(item) + } + return list + +} + +/** + * Returns a stream containing all elements except first *n* elements + */ +public fun Stream.drop(n: Int) : Stream { + var count = 0; + return FilteringStream(this) { count++ >= n } + +} + +/** + * Returns a list containing all elements except first elements that satisfy the given *predicate* + */ +public inline fun Array.dropWhile(predicate: (T)->Boolean) : List { + var yielding = false + val list = ArrayList() + for (item in this) + if (yielding) + list.add(item) + else if(!predicate(item)) { + list.add(item) + yielding = true + } + return list + +} + +/** + * Returns a list containing all elements except first elements that satisfy the given *predicate* + */ +public inline fun BooleanArray.dropWhile(predicate: (Boolean)->Boolean) : List { + var yielding = false + val list = ArrayList() + for (item in this) + if (yielding) + list.add(item) + else if(!predicate(item)) { + list.add(item) + yielding = true + } + return list + +} + +/** + * Returns a list containing all elements except first elements that satisfy the given *predicate* + */ +public inline fun ByteArray.dropWhile(predicate: (Byte)->Boolean) : List { + var yielding = false + val list = ArrayList() + for (item in this) + if (yielding) + list.add(item) + else if(!predicate(item)) { + list.add(item) + yielding = true + } + return list + +} + +/** + * Returns a list containing all elements except first elements that satisfy the given *predicate* + */ +public inline fun CharArray.dropWhile(predicate: (Char)->Boolean) : List { + var yielding = false + val list = ArrayList() + for (item in this) + if (yielding) + list.add(item) + else if(!predicate(item)) { + list.add(item) + yielding = true + } + return list + +} + +/** + * Returns a list containing all elements except first elements that satisfy the given *predicate* + */ +public inline fun DoubleArray.dropWhile(predicate: (Double)->Boolean) : List { + var yielding = false + val list = ArrayList() + for (item in this) + if (yielding) + list.add(item) + else if(!predicate(item)) { + list.add(item) + yielding = true + } + return list + +} + +/** + * Returns a list containing all elements except first elements that satisfy the given *predicate* + */ +public inline fun FloatArray.dropWhile(predicate: (Float)->Boolean) : List { + var yielding = false + val list = ArrayList() + for (item in this) + if (yielding) + list.add(item) + else if(!predicate(item)) { + list.add(item) + yielding = true + } + return list + +} + +/** + * Returns a list containing all elements except first elements that satisfy the given *predicate* + */ +public inline fun IntArray.dropWhile(predicate: (Int)->Boolean) : List { + var yielding = false + val list = ArrayList() + for (item in this) + if (yielding) + list.add(item) + else if(!predicate(item)) { + list.add(item) + yielding = true + } + return list + +} + +/** + * Returns a list containing all elements except first elements that satisfy the given *predicate* + */ +public inline fun LongArray.dropWhile(predicate: (Long)->Boolean) : List { + var yielding = false + val list = ArrayList() + for (item in this) + if (yielding) + list.add(item) + else if(!predicate(item)) { + list.add(item) + yielding = true + } + return list + +} + +/** + * Returns a list containing all elements except first elements that satisfy the given *predicate* + */ +public inline fun ShortArray.dropWhile(predicate: (Short)->Boolean) : List { + var yielding = false + val list = ArrayList() + for (item in this) + if (yielding) + list.add(item) + else if(!predicate(item)) { + list.add(item) + yielding = true + } + return list + +} + +/** + * Returns a list containing all elements except first elements that satisfy the given *predicate* + */ +public inline fun Iterable.dropWhile(predicate: (T)->Boolean) : List { + var yielding = false + val list = ArrayList() + for (item in this) + if (yielding) + list.add(item) + else if(!predicate(item)) { + list.add(item) + yielding = true + } + return list + +} + +/** + * Returns a stream containing all elements except first elements that satisfy the given *predicate* + */ +public fun Stream.dropWhile(predicate: (T)->Boolean) : Stream { + var yielding = false + return FilteringStream(this) { + if (yielding) + true + else if (!predicate(it)) { + yielding = true + true + } else + false + } + +} + +/** + * Returns a list containing all elements matching the given *predicate* + */ +public inline fun Array.filter(predicate: (T)->Boolean) : List { + return filterTo(ArrayList(), predicate) + +} + +/** + * Returns a list containing all elements matching the given *predicate* + */ +public inline fun BooleanArray.filter(predicate: (Boolean)->Boolean) : List { + return filterTo(ArrayList(), predicate) + +} + +/** + * Returns a list containing all elements matching the given *predicate* + */ +public inline fun ByteArray.filter(predicate: (Byte)->Boolean) : List { + return filterTo(ArrayList(), predicate) + +} + +/** + * Returns a list containing all elements matching the given *predicate* + */ +public inline fun CharArray.filter(predicate: (Char)->Boolean) : List { + return filterTo(ArrayList(), predicate) + +} + +/** + * Returns a list containing all elements matching the given *predicate* + */ +public inline fun DoubleArray.filter(predicate: (Double)->Boolean) : List { + return filterTo(ArrayList(), predicate) + +} + +/** + * Returns a list containing all elements matching the given *predicate* + */ +public inline fun FloatArray.filter(predicate: (Float)->Boolean) : List { + return filterTo(ArrayList(), predicate) + +} + +/** + * Returns a list containing all elements matching the given *predicate* + */ +public inline fun IntArray.filter(predicate: (Int)->Boolean) : List { + return filterTo(ArrayList(), predicate) + +} + +/** + * Returns a list containing all elements matching the given *predicate* + */ +public inline fun LongArray.filter(predicate: (Long)->Boolean) : List { + return filterTo(ArrayList(), predicate) + +} + +/** + * Returns a list containing all elements matching the given *predicate* + */ +public inline fun ShortArray.filter(predicate: (Short)->Boolean) : List { + return filterTo(ArrayList(), predicate) + +} + +/** + * Returns a list containing all elements matching the given *predicate* + */ +public inline fun Iterable.filter(predicate: (T)->Boolean) : List { + return filterTo(ArrayList(), predicate) + +} + +/** + * Returns a list containing all elements matching the given *predicate* + */ +public inline fun Map.filter(predicate: (Map.Entry)->Boolean) : List> { + return filterTo(ArrayList>(), predicate) + +} + +/** + * Returns a stream containing all elements matching the given *predicate* + */ +public fun Stream.filter(predicate: (T)->Boolean) : Stream { + return FilteringStream(this, true, predicate) + +} + +/** + * Returns a list containing all elements not matching the given *predicate* + */ +public inline fun Array.filterNot(predicate: (T)->Boolean) : List { + return filterNotTo(ArrayList(), predicate) + +} + +/** + * Returns a list containing all elements not matching the given *predicate* + */ +public inline fun BooleanArray.filterNot(predicate: (Boolean)->Boolean) : List { + return filterNotTo(ArrayList(), predicate) + +} + +/** + * Returns a list containing all elements not matching the given *predicate* + */ +public inline fun ByteArray.filterNot(predicate: (Byte)->Boolean) : List { + return filterNotTo(ArrayList(), predicate) + +} + +/** + * Returns a list containing all elements not matching the given *predicate* + */ +public inline fun CharArray.filterNot(predicate: (Char)->Boolean) : List { + return filterNotTo(ArrayList(), predicate) + +} + +/** + * Returns a list containing all elements not matching the given *predicate* + */ +public inline fun DoubleArray.filterNot(predicate: (Double)->Boolean) : List { + return filterNotTo(ArrayList(), predicate) + +} + +/** + * Returns a list containing all elements not matching the given *predicate* + */ +public inline fun FloatArray.filterNot(predicate: (Float)->Boolean) : List { + return filterNotTo(ArrayList(), predicate) + +} + +/** + * Returns a list containing all elements not matching the given *predicate* + */ +public inline fun IntArray.filterNot(predicate: (Int)->Boolean) : List { + return filterNotTo(ArrayList(), predicate) + +} + +/** + * Returns a list containing all elements not matching the given *predicate* + */ +public inline fun LongArray.filterNot(predicate: (Long)->Boolean) : List { + return filterNotTo(ArrayList(), predicate) + +} + +/** + * Returns a list containing all elements not matching the given *predicate* + */ +public inline fun ShortArray.filterNot(predicate: (Short)->Boolean) : List { + return filterNotTo(ArrayList(), predicate) + +} + +/** + * Returns a list containing all elements not matching the given *predicate* + */ +public inline fun Iterable.filterNot(predicate: (T)->Boolean) : List { + return filterNotTo(ArrayList(), predicate) + +} + +/** + * Returns a list containing all elements not matching the given *predicate* + */ +public inline fun Map.filterNot(predicate: (Map.Entry)->Boolean) : List> { + return filterNotTo(ArrayList>(), predicate) + +} + +/** + * Returns a stream containing all elements not matching the given *predicate* + */ +public fun Stream.filterNot(predicate: (T)->Boolean) : Stream { + return FilteringStream(this, false, predicate) + +} + +/** + * Returns a list containing all elements that are not null + */ +public fun Array.filterNotNull() : List { + return filterNotNullTo(ArrayList()) + +} + +/** + * Returns a list containing all elements that are not null + */ +public fun Iterable.filterNotNull() : List { + return filterNotNullTo(ArrayList()) + +} + +/** + * Returns a stream containing all elements that are not null + */ +public fun Stream.filterNotNull() : Stream { + return FilteringStream(this, false, { it != null }) as Stream + +} + +/** + * Appends all elements that are not null to the given *collection* + */ +public fun , T: Any> Array.filterNotNullTo(collection: C) : C { + for (element in this) if (element != null) collection.add(element) + return collection + +} + +/** + * Appends all elements that are not null to the given *collection* + */ +public fun , T: Any> Iterable.filterNotNullTo(collection: C) : C { + for (element in this) if (element != null) collection.add(element) + return collection + +} + +/** + * Appends all elements that are not null to the given *collection* + */ +public fun , T: Any> Stream.filterNotNullTo(collection: C) : C { + for (element in this) if (element != null) collection.add(element) + return collection + +} + +/** + * Appends all elements not matching the given *predicate* to the given *collection* + */ +public inline fun > Array.filterNotTo(collection: C, predicate: (T) -> Boolean) : C { + for (element in this) if (!predicate(element)) collection.add(element) + return collection + +} + +/** + * Appends all elements not matching the given *predicate* to the given *collection* + */ +public inline fun > BooleanArray.filterNotTo(collection: C, predicate: (Boolean) -> Boolean) : C { + for (element in this) if (!predicate(element)) collection.add(element) + return collection + +} + +/** + * Appends all elements not matching the given *predicate* to the given *collection* + */ +public inline fun > ByteArray.filterNotTo(collection: C, predicate: (Byte) -> Boolean) : C { + for (element in this) if (!predicate(element)) collection.add(element) + return collection + +} + +/** + * Appends all elements not matching the given *predicate* to the given *collection* + */ +public inline fun > CharArray.filterNotTo(collection: C, predicate: (Char) -> Boolean) : C { + for (element in this) if (!predicate(element)) collection.add(element) + return collection + +} + +/** + * Appends all elements not matching the given *predicate* to the given *collection* + */ +public inline fun > DoubleArray.filterNotTo(collection: C, predicate: (Double) -> Boolean) : C { + for (element in this) if (!predicate(element)) collection.add(element) + return collection + +} + +/** + * Appends all elements not matching the given *predicate* to the given *collection* + */ +public inline fun > FloatArray.filterNotTo(collection: C, predicate: (Float) -> Boolean) : C { + for (element in this) if (!predicate(element)) collection.add(element) + return collection + +} + +/** + * Appends all elements not matching the given *predicate* to the given *collection* + */ +public inline fun > IntArray.filterNotTo(collection: C, predicate: (Int) -> Boolean) : C { + for (element in this) if (!predicate(element)) collection.add(element) + return collection + +} + +/** + * Appends all elements not matching the given *predicate* to the given *collection* + */ +public inline fun > LongArray.filterNotTo(collection: C, predicate: (Long) -> Boolean) : C { + for (element in this) if (!predicate(element)) collection.add(element) + return collection + +} + +/** + * Appends all elements not matching the given *predicate* to the given *collection* + */ +public inline fun > ShortArray.filterNotTo(collection: C, predicate: (Short) -> Boolean) : C { + for (element in this) if (!predicate(element)) collection.add(element) + return collection + +} + +/** + * Appends all elements not matching the given *predicate* to the given *collection* + */ +public inline fun > Iterable.filterNotTo(collection: C, predicate: (T) -> Boolean) : C { + for (element in this) if (!predicate(element)) collection.add(element) + return collection + +} + +/** + * Appends all elements not matching the given *predicate* to the given *collection* + */ +public inline fun >> Map.filterNotTo(collection: C, predicate: (Map.Entry) -> Boolean) : C { + for (element in this) if (!predicate(element)) collection.add(element) + return collection + +} + +/** + * Appends all elements not matching the given *predicate* to the given *collection* + */ +public inline fun > Stream.filterNotTo(collection: C, predicate: (T) -> Boolean) : C { + for (element in this) if (!predicate(element)) collection.add(element) + return collection + +} + +/** + * Appends all elements matching the given *predicate* into the given *collection* + */ +public inline fun > Array.filterTo(collection: C, predicate: (T) -> Boolean) : C { + for (element in this) if (predicate(element)) collection.add(element) + return collection + +} + +/** + * Appends all elements matching the given *predicate* into the given *collection* + */ +public inline fun > BooleanArray.filterTo(collection: C, predicate: (Boolean) -> Boolean) : C { + for (element in this) if (predicate(element)) collection.add(element) + return collection + +} + +/** + * Appends all elements matching the given *predicate* into the given *collection* + */ +public inline fun > ByteArray.filterTo(collection: C, predicate: (Byte) -> Boolean) : C { + for (element in this) if (predicate(element)) collection.add(element) + return collection + +} + +/** + * Appends all elements matching the given *predicate* into the given *collection* + */ +public inline fun > CharArray.filterTo(collection: C, predicate: (Char) -> Boolean) : C { + for (element in this) if (predicate(element)) collection.add(element) + return collection + +} + +/** + * Appends all elements matching the given *predicate* into the given *collection* + */ +public inline fun > DoubleArray.filterTo(collection: C, predicate: (Double) -> Boolean) : C { + for (element in this) if (predicate(element)) collection.add(element) + return collection + +} + +/** + * Appends all elements matching the given *predicate* into the given *collection* + */ +public inline fun > FloatArray.filterTo(collection: C, predicate: (Float) -> Boolean) : C { + for (element in this) if (predicate(element)) collection.add(element) + return collection + +} + +/** + * Appends all elements matching the given *predicate* into the given *collection* + */ +public inline fun > IntArray.filterTo(collection: C, predicate: (Int) -> Boolean) : C { + for (element in this) if (predicate(element)) collection.add(element) + return collection + +} + +/** + * Appends all elements matching the given *predicate* into the given *collection* + */ +public inline fun > LongArray.filterTo(collection: C, predicate: (Long) -> Boolean) : C { + for (element in this) if (predicate(element)) collection.add(element) + return collection + +} + +/** + * Appends all elements matching the given *predicate* into the given *collection* + */ +public inline fun > ShortArray.filterTo(collection: C, predicate: (Short) -> Boolean) : C { + for (element in this) if (predicate(element)) collection.add(element) + return collection + +} + +/** + * Appends all elements matching the given *predicate* into the given *collection* + */ +public inline fun > Iterable.filterTo(collection: C, predicate: (T) -> Boolean) : C { + for (element in this) if (predicate(element)) collection.add(element) + return collection + +} + +/** + * Appends all elements matching the given *predicate* into the given *collection* + */ +public inline fun >> Map.filterTo(collection: C, predicate: (Map.Entry) -> Boolean) : C { + for (element in this) if (predicate(element)) collection.add(element) + return collection + +} + +/** + * Appends all elements matching the given *predicate* into the given *collection* + */ +public inline fun > Stream.filterTo(collection: C, predicate: (T) -> Boolean) : C { + for (element in this) if (predicate(element)) collection.add(element) + return collection + +} + +/** + * Returns a list containing first *n* elements + */ +public fun Array.take(n: Int) : List { + var count = 0 + val realN = if (n > size) size else n + val list = ArrayList(realN) + for (item in this) { + if (count++ == realN) + break; + list.add(item) + } + return list + +} + +/** + * Returns a list containing first *n* elements + */ +public fun BooleanArray.take(n: Int) : List { + var count = 0 + val realN = if (n > size) size else n + val list = ArrayList(realN) + for (item in this) { + if (count++ == realN) + break; + list.add(item) + } + return list + +} + +/** + * Returns a list containing first *n* elements + */ +public fun ByteArray.take(n: Int) : List { + var count = 0 + val realN = if (n > size) size else n + val list = ArrayList(realN) + for (item in this) { + if (count++ == realN) + break; + list.add(item) + } + return list + +} + +/** + * Returns a list containing first *n* elements + */ +public fun CharArray.take(n: Int) : List { + var count = 0 + val realN = if (n > size) size else n + val list = ArrayList(realN) + for (item in this) { + if (count++ == realN) + break; + list.add(item) + } + return list + +} + +/** + * Returns a list containing first *n* elements + */ +public fun DoubleArray.take(n: Int) : List { + var count = 0 + val realN = if (n > size) size else n + val list = ArrayList(realN) + for (item in this) { + if (count++ == realN) + break; + list.add(item) + } + return list + +} + +/** + * Returns a list containing first *n* elements + */ +public fun FloatArray.take(n: Int) : List { + var count = 0 + val realN = if (n > size) size else n + val list = ArrayList(realN) + for (item in this) { + if (count++ == realN) + break; + list.add(item) + } + return list + +} + +/** + * Returns a list containing first *n* elements + */ +public fun IntArray.take(n: Int) : List { + var count = 0 + val realN = if (n > size) size else n + val list = ArrayList(realN) + for (item in this) { + if (count++ == realN) + break; + list.add(item) + } + return list + +} + +/** + * Returns a list containing first *n* elements + */ +public fun LongArray.take(n: Int) : List { + var count = 0 + val realN = if (n > size) size else n + val list = ArrayList(realN) + for (item in this) { + if (count++ == realN) + break; + list.add(item) + } + return list + +} + +/** + * Returns a list containing first *n* elements + */ +public fun ShortArray.take(n: Int) : List { + var count = 0 + val realN = if (n > size) size else n + val list = ArrayList(realN) + for (item in this) { + if (count++ == realN) + break; + list.add(item) + } + return list + +} + +/** + * Returns a list containing first *n* elements + */ +public fun Collection.take(n: Int) : List { + var count = 0 + val realN = if (n > size) size else n + val list = ArrayList(realN) + for (item in this) { + if (count++ == realN) + break; + list.add(item) + } + return list + +} + +/** + * Returns a list containing first *n* elements + */ +public fun Iterable.take(n: Int) : List { + var count = 0 + val list = ArrayList(n) + for (item in this) + if (count++ >= n) + list.add(item) + return list + +} + +/** + * Returns a stream containing first *n* elements + */ +public fun Stream.take(n: Int) : Stream { + var count = 0 + return LimitedStream(this) { count++ == n } + +} + +/** + * Returns a list containing first elements satisfying the given *predicate* + */ +public inline fun Array.takeWhile(predicate: (T)->Boolean) : List { + val list = ArrayList() + for (item in this) { + if(!predicate(item)) + break; + list.add(item) + } + return list + +} + +/** + * Returns a list containing first elements satisfying the given *predicate* + */ +public inline fun BooleanArray.takeWhile(predicate: (Boolean)->Boolean) : List { + val list = ArrayList() + for (item in this) { + if(!predicate(item)) + break; + list.add(item) + } + return list + +} + +/** + * Returns a list containing first elements satisfying the given *predicate* + */ +public inline fun ByteArray.takeWhile(predicate: (Byte)->Boolean) : List { + val list = ArrayList() + for (item in this) { + if(!predicate(item)) + break; + list.add(item) + } + return list + +} + +/** + * Returns a list containing first elements satisfying the given *predicate* + */ +public inline fun CharArray.takeWhile(predicate: (Char)->Boolean) : List { + val list = ArrayList() + for (item in this) { + if(!predicate(item)) + break; + list.add(item) + } + return list + +} + +/** + * Returns a list containing first elements satisfying the given *predicate* + */ +public inline fun DoubleArray.takeWhile(predicate: (Double)->Boolean) : List { + val list = ArrayList() + for (item in this) { + if(!predicate(item)) + break; + list.add(item) + } + return list + +} + +/** + * Returns a list containing first elements satisfying the given *predicate* + */ +public inline fun FloatArray.takeWhile(predicate: (Float)->Boolean) : List { + val list = ArrayList() + for (item in this) { + if(!predicate(item)) + break; + list.add(item) + } + return list + +} + +/** + * Returns a list containing first elements satisfying the given *predicate* + */ +public inline fun IntArray.takeWhile(predicate: (Int)->Boolean) : List { + val list = ArrayList() + for (item in this) { + if(!predicate(item)) + break; + list.add(item) + } + return list + +} + +/** + * Returns a list containing first elements satisfying the given *predicate* + */ +public inline fun LongArray.takeWhile(predicate: (Long)->Boolean) : List { + val list = ArrayList() + for (item in this) { + if(!predicate(item)) + break; + list.add(item) + } + return list + +} + +/** + * Returns a list containing first elements satisfying the given *predicate* + */ +public inline fun ShortArray.takeWhile(predicate: (Short)->Boolean) : List { + val list = ArrayList() + for (item in this) { + if(!predicate(item)) + break; + list.add(item) + } + return list + +} + +/** + * Returns a list containing first elements satisfying the given *predicate* + */ +public inline fun Iterable.takeWhile(predicate: (T)->Boolean) : List { + val list = ArrayList() + for (item in this) { + if(!predicate(item)) + break; + list.add(item) + } + return list + +} + +/** + * Returns a stream containing first elements satisfying the given *predicate* + */ +public fun Stream.takeWhile(predicate: (T)->Boolean) : Stream { + return LimitedStream(this, false, predicate) + +} + diff --git a/libraries/stdlib/src/generated/_FloatArrays.kt b/libraries/stdlib/src/generated/_FloatArrays.kt deleted file mode 100644 index db134b7c0a6..00000000000 --- a/libraries/stdlib/src/generated/_FloatArrays.kt +++ /dev/null @@ -1,482 +0,0 @@ -package kotlin - -// -// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt -// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib -// - -import java.util.* - -/** - * Returns *true* if all elements match the given *predicate* - */ -public inline fun FloatArray.all(predicate: (Float) -> Boolean) : Boolean { - for (element in this) if (!predicate(element)) return false - return true -} - -/** - * Returns *true* if any elements match the given *predicate* - */ -public inline fun FloatArray.any(predicate: (Float) -> Boolean) : Boolean { - for (element in this) if (predicate(element)) return true - return false -} - -/** - * Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied - * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will - * a special *truncated* separator (which defaults to "..." - */ -public fun FloatArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit { - buffer.append(prefix) - var count = 0 - for (element in this) { - if (++count > 1) buffer.append(separator) - if (limit < 0 || count <= limit) { - val text = if (element == null) "null" else element.toString() - buffer.append(text) - } else break - } - if (limit >= 0 && count > limit) buffer.append(truncated) - buffer.append(postfix) -} - -/** - * Returns the number of elements which match the given *predicate* - */ -public inline fun FloatArray.count(predicate: (Float) -> Boolean) : Int { - var count = 0 - for (element in this) if (predicate(element)) count++ - return count -} - -/** - * Returns a list containing everything but the first *n* elements - */ -public fun FloatArray.drop(n: Int) : List { - return dropWhile(countTo(n)) -} - -/** - * Returns a list containing the everything but the first elements that satisfy the given *predicate* - */ -public inline fun FloatArray.dropWhile(predicate: (Float) -> Boolean) : List { - return dropWhileTo(ArrayList(), predicate) -} - -/** - * Returns a list containing the everything but the first elements that satisfy the given *predicate* - */ -public inline fun > FloatArray.dropWhileTo(result: L, predicate: (Float) -> Boolean) : L { - var start = true - for (element in this) { - if (start && predicate(element)) { - // ignore - } else { - start = false - result.add(element) - } - } - return result -} - -/** - * Returns a list containing all elements which match the given *predicate* - */ -public inline fun FloatArray.filter(predicate: (Float) -> Boolean) : List { - return filterTo(ArrayList(), predicate) -} - -/** - * Returns a list containing all elements which do not match the given *predicate* - */ -public inline fun FloatArray.filterNot(predicate: (Float) -> Boolean) : List { - return filterNotTo(ArrayList(), predicate) -} - -/** - * Returns a list containing all elements which do not match the given *predicate* - */ -public inline fun > FloatArray.filterNotTo(result: C, predicate: (Float) -> Boolean) : C { - for (element in this) if (!predicate(element)) result.add(element) - return result -} - -/** - * Filters all elements which match the given predicate into the given list - */ -public inline fun > FloatArray.filterTo(result: C, predicate: (Float) -> Boolean) : C { - for (element in this) if (predicate(element)) result.add(element) - return result -} - -/** - * Returns the first element which matches the given *predicate* or *null* if none matched - */ -public inline fun FloatArray.find(predicate: (Float) -> Boolean) : Float? { - for (element in this) if (predicate(element)) return element - return null -} - -/** - * Returns the result of transforming each element to one or more values which are concatenated together into a single list - */ -public inline fun FloatArray.flatMap(transform: (Float)-> Iterable) : List { - return flatMapTo(ArrayList(), transform) -} - -/** - * Returns the result of transforming each element to one or more values which are concatenated together into a single collection - */ -public inline fun > FloatArray.flatMapTo(result: C, transform: (Float) -> Iterable) : C { - for (element in this) { - val list = transform(element) - for (r in list) result.add(r) - } - return result -} - -/** - * Folds all elements from from left to right with the *initial* value to perform the operation on sequential pairs of elements - */ -public inline fun FloatArray.fold(initial: R, operation: (R, Float) -> R) : R { - var answer = initial - for (element in this) answer = operation(answer, element) - return answer -} - -/** - * Folds all elements from right to left with the *initial* value to perform the operation on sequential pairs of elements - */ -public inline fun FloatArray.foldRight(initial: R, operation: (Float, R) -> R) : R { - var r = initial - var index = size - 1 - - while (index >= 0) { - r = operation(get(index--), r) - } - - return r -} - -/** - * Performs the given *operation* on each element - */ -public inline fun FloatArray.forEach(operation: (Float) -> Unit) : Unit { - for (element in this) operation(element) -} - -/** - * Groups the elements in the collection into a new [[Map]] using the supplied *toKey* function to calculate the key to group the elements by - */ -public inline fun FloatArray.groupBy(toKey: (Float) -> K) : Map> { - return groupByTo(HashMap>(), toKey) -} - -public inline fun FloatArray.groupByTo(result: MutableMap>, toKey: (Float) -> K) : Map> { - for (element in this) { - val key = toKey(element) - val list = result.getOrPut(key) { ArrayList() } - list.add(element) - } - return result -} - -/** - * Returns first index of item, or -1 if the array does not contain item - */ -public fun FloatArray.indexOf(item: Float) : Int { - for (i in indices) { - if (item == this[i]) { - return i - } - } - return -1 -} - -/** - * Returns true if the array is empty - */ -public fun FloatArray.isEmpty() : Boolean { - return size == 0 -} - -/** - * Returns true if the array is empty - */ -public fun FloatArray.isNotEmpty() : Boolean { - return !isEmpty() -} - -/** - * Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied. - * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will - * a special *truncated* separator (which defaults to "..." - */ -public fun FloatArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String { - val buffer = StringBuilder() - appendString(buffer, separator, prefix, postfix, limit, truncated) - return buffer.toString() -} - -/** - * Returns a new List containing the results of applying the given *transform* function to each element in this collection - */ -public inline fun FloatArray.map(transform : (Float) -> R) : List { - return mapTo(ArrayList(), transform) -} - -/** - * Transforms each element of this collection with the given *transform* function and - * adds each return value to the given *results* collection - */ -public inline fun > FloatArray.mapTo(result: C, transform : (Float) -> R) : C { - for (item in this) - result.add(transform(item)) - return result -} - -/** - * Returns the largest element or null if there are no elements - */ -public fun FloatArray.max() : Float? { - if (isEmpty()) return null - - var max = this[0] - for (i in 1..lastIndex) { - val e = this[i] - if (max < e) max = e - } - return max -} - -/** - * Returns the first element yielding the largest value of the given function or null if there are no elements - */ -public inline fun > FloatArray.maxBy(f: (Float) -> R) : Float? { - if (isEmpty()) return null - - var maxElem = this[0] - var maxValue = f(maxElem) - for (i in 1..lastIndex) { - val e = this[i] - val v = f(e) - if (maxValue < v) { - maxElem = e - maxValue = v - } - } - return maxElem -} - -/** - * Returns the smallest element or null if there are no elements - */ -public fun FloatArray.min() : Float? { - if (isEmpty()) return null - - var min = this[0] - for (i in 1..lastIndex) { - val e = this[i] - if (min > e) min = e - } - return min -} - -/** - * Returns the first element yielding the smallest value of the given function or null if there are no elements - */ -public inline fun > FloatArray.minBy(f: (Float) -> R) : Float? { - if (size == 0) return null - - var minElem = this[0] - var minValue = f(minElem) - for (i in 1..lastIndex) { - val e = this[i] - val v = f(e) - if (minValue > v) { - minElem = e - minValue = v - } - } - return minElem -} - -/** - * Partitions this collection into a pair of collections - */ -public inline fun FloatArray.partition(predicate: (Float) -> Boolean) : Pair, List> { - val first = ArrayList() - val second = ArrayList() - for (element in this) { - if (predicate(element)) { - first.add(element) - } else { - second.add(element) - } - } - return Pair(first, second) -} - -/** - * Creates an [[Iterator]] which iterates over this iterator then the following collection - */ -public fun FloatArray.plus(collection: Iterable) : List { - return plus(collection.iterator()) -} - -/** - * Creates an [[Iterator]] which iterates over this iterator then the given element at the end - */ -public fun FloatArray.plus(element: Float) : List { - val answer = ArrayList() - toCollection(answer) - answer.add(element) - return answer -} - -/** - * Creates an [[Iterator]] which iterates over this iterator then the following iterator - */ -public fun FloatArray.plus(iterator: Iterator) : List { - val answer = ArrayList() - toCollection(answer) - for (element in iterator) { - answer.add(element) - } - return answer -} - -/** - * Applies binary operation to all elements of iterable, going from left to right. - * Similar to fold function, but uses the first element as initial value - */ -public inline fun FloatArray.reduce(operation: (Float, Float) -> Float) : Float { - val iterator = this.iterator() - if (!iterator.hasNext()) { - throw UnsupportedOperationException("Empty iterable can't be reduced") - } - - var result: Float = iterator.next() //compiler doesn't understand that result will initialized anyway - while (iterator.hasNext()) { - result = operation(result, iterator.next()) - } - - return result -} - -/** - * Applies binary operation to all elements of iterable, going from right to left. - * Similar to foldRight function, but uses the last element as initial value - */ -public inline fun FloatArray.reduceRight(operation: (Float, Float) -> Float) : Float { - var index = size - 1 - if (index < 0) { - throw UnsupportedOperationException("Empty iterable can't be reduced") - } - - var r = get(index--) - while (index >= 0) { - r = operation(get(index--), r) - } - - return r -} - -/** - * Reverses the order the elements into a list - */ -public fun FloatArray.reverse() : List { - val list = toCollection(ArrayList()) - Collections.reverse(list) - return list -} - -/** - * Copies all elements into a [[List]] and sorts it by value of compare_function(element) - * E.g. arrayList("two" to 2, "one" to 1).sortBy({it.second}) returns list sorted by second element of pair - */ -public inline fun > FloatArray.sortBy(f: (Float) -> R) : List { - val sortedList = toCollection(ArrayList()) - val sortBy: Comparator = comparator {(x: Float, y: Float) -> - val xr = f(x) - val yr = f(y) - xr.compareTo(yr) - } - java.util.Collections.sort(sortedList, sortBy) - return sortedList -} - -/** - * Returns a list containing the first *n* elements - */ -public fun FloatArray.take(n: Int) : List { - return takeWhile(countTo(n)) -} - -/** - * Returns a list containing the first elements that satisfy the given *predicate* - */ -public inline fun FloatArray.takeWhile(predicate: (Float) -> Boolean) : List { - return takeWhileTo(ArrayList(), predicate) -} - -/** - * Returns a list containing the first elements that satisfy the given *predicate* - */ -public inline fun > FloatArray.takeWhileTo(result: C, predicate: (Float) -> Boolean) : C { - for (element in this) if (predicate(element)) result.add(element) else break - return result -} - -/** - * Copies all elements into the given collection - */ -public fun > FloatArray.toCollection(result: C) : C { - for (element in this) result.add(element) - return result -} - -/** - * Copies all elements into a [[LinkedList]] - */ -public fun FloatArray.toLinkedList() : LinkedList { - return toCollection(LinkedList()) -} - -/** - * Copies all elements into a [[List]] - */ -public fun FloatArray.toList() : List { - return toCollection(ArrayList()) -} - -/** - * Copies all elements into a [[Set]] - */ -public fun FloatArray.toSet() : Set { - return toCollection(LinkedHashSet()) -} - -/** - * Copies all elements into a [[SortedSet]] - */ -public fun FloatArray.toSortedSet() : SortedSet { - return toCollection(TreeSet()) -} - -/** - * Returns an iterator of Pairs(index, data) - */ -public fun FloatArray.withIndices() : Iterator> { - return IndexIterator(iterator()) -} - -/** - * Sums up the elements - */ -public fun FloatArray.sum() : Float { - return fold(0.toFloat(), {a,b -> a+b}) -} - diff --git a/libraries/stdlib/src/generated/_Generators.kt b/libraries/stdlib/src/generated/_Generators.kt new file mode 100644 index 00000000000..caf7711255a --- /dev/null +++ b/libraries/stdlib/src/generated/_Generators.kt @@ -0,0 +1,836 @@ +package kotlin + +// +// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt +// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib +// + +import java.util.* + +/** + * Splits original collection into pair of collections, + * where *first* collection contains elements for which predicate yielded *true*, + * while *second* collection contains elements for which predicate yielded *false* + */ +public inline fun Array.partition(predicate: (T) -> Boolean) : Pair, List> { + val first = ArrayList() + val second = ArrayList() + for (element in this) { + if (predicate(element)) { + first.add(element) + } else { + second.add(element) + } + } + return Pair(first, second) + +} + +/** + * Splits original collection into pair of collections, + * where *first* collection contains elements for which predicate yielded *true*, + * while *second* collection contains elements for which predicate yielded *false* + */ +public inline fun BooleanArray.partition(predicate: (Boolean) -> Boolean) : Pair, List> { + val first = ArrayList() + val second = ArrayList() + for (element in this) { + if (predicate(element)) { + first.add(element) + } else { + second.add(element) + } + } + return Pair(first, second) + +} + +/** + * Splits original collection into pair of collections, + * where *first* collection contains elements for which predicate yielded *true*, + * while *second* collection contains elements for which predicate yielded *false* + */ +public inline fun ByteArray.partition(predicate: (Byte) -> Boolean) : Pair, List> { + val first = ArrayList() + val second = ArrayList() + for (element in this) { + if (predicate(element)) { + first.add(element) + } else { + second.add(element) + } + } + return Pair(first, second) + +} + +/** + * Splits original collection into pair of collections, + * where *first* collection contains elements for which predicate yielded *true*, + * while *second* collection contains elements for which predicate yielded *false* + */ +public inline fun CharArray.partition(predicate: (Char) -> Boolean) : Pair, List> { + val first = ArrayList() + val second = ArrayList() + for (element in this) { + if (predicate(element)) { + first.add(element) + } else { + second.add(element) + } + } + return Pair(first, second) + +} + +/** + * Splits original collection into pair of collections, + * where *first* collection contains elements for which predicate yielded *true*, + * while *second* collection contains elements for which predicate yielded *false* + */ +public inline fun DoubleArray.partition(predicate: (Double) -> Boolean) : Pair, List> { + val first = ArrayList() + val second = ArrayList() + for (element in this) { + if (predicate(element)) { + first.add(element) + } else { + second.add(element) + } + } + return Pair(first, second) + +} + +/** + * Splits original collection into pair of collections, + * where *first* collection contains elements for which predicate yielded *true*, + * while *second* collection contains elements for which predicate yielded *false* + */ +public inline fun FloatArray.partition(predicate: (Float) -> Boolean) : Pair, List> { + val first = ArrayList() + val second = ArrayList() + for (element in this) { + if (predicate(element)) { + first.add(element) + } else { + second.add(element) + } + } + return Pair(first, second) + +} + +/** + * Splits original collection into pair of collections, + * where *first* collection contains elements for which predicate yielded *true*, + * while *second* collection contains elements for which predicate yielded *false* + */ +public inline fun IntArray.partition(predicate: (Int) -> Boolean) : Pair, List> { + val first = ArrayList() + val second = ArrayList() + for (element in this) { + if (predicate(element)) { + first.add(element) + } else { + second.add(element) + } + } + return Pair(first, second) + +} + +/** + * Splits original collection into pair of collections, + * where *first* collection contains elements for which predicate yielded *true*, + * while *second* collection contains elements for which predicate yielded *false* + */ +public inline fun LongArray.partition(predicate: (Long) -> Boolean) : Pair, List> { + val first = ArrayList() + val second = ArrayList() + for (element in this) { + if (predicate(element)) { + first.add(element) + } else { + second.add(element) + } + } + return Pair(first, second) + +} + +/** + * Splits original collection into pair of collections, + * where *first* collection contains elements for which predicate yielded *true*, + * while *second* collection contains elements for which predicate yielded *false* + */ +public inline fun ShortArray.partition(predicate: (Short) -> Boolean) : Pair, List> { + val first = ArrayList() + val second = ArrayList() + for (element in this) { + if (predicate(element)) { + first.add(element) + } else { + second.add(element) + } + } + return Pair(first, second) + +} + +/** + * Splits original collection into pair of collections, + * where *first* collection contains elements for which predicate yielded *true*, + * while *second* collection contains elements for which predicate yielded *false* + */ +public inline fun Iterable.partition(predicate: (T) -> Boolean) : Pair, List> { + val first = ArrayList() + val second = ArrayList() + for (element in this) { + if (predicate(element)) { + first.add(element) + } else { + second.add(element) + } + } + return Pair(first, second) + +} + +/** + * Splits original collection into pair of collections, + * where *first* collection contains elements for which predicate yielded *true*, + * while *second* collection contains elements for which predicate yielded *false* + */ +public inline fun Stream.partition(predicate: (T) -> Boolean) : Pair, List> { + val first = ArrayList() + val second = ArrayList() + for (element in this) { + if (predicate(element)) { + first.add(element) + } else { + second.add(element) + } + } + return Pair(first, second) + +} + +/** + * Returns a list containing all elements of original collection and then all elements of the given *collection* + */ +public fun Array.plus(array: Array) : List { + val answer = toArrayList() + answer.addAll(array) + return answer + +} + +/** + * Returns a list containing all elements of original collection and then all elements of the given *collection* + */ +public fun BooleanArray.plus(array: Array) : List { + val answer = toArrayList() + answer.addAll(array) + return answer + +} + +/** + * Returns a list containing all elements of original collection and then all elements of the given *collection* + */ +public fun ByteArray.plus(array: Array) : List { + val answer = toArrayList() + answer.addAll(array) + return answer + +} + +/** + * Returns a list containing all elements of original collection and then all elements of the given *collection* + */ +public fun CharArray.plus(array: Array) : List { + val answer = toArrayList() + answer.addAll(array) + return answer + +} + +/** + * Returns a list containing all elements of original collection and then all elements of the given *collection* + */ +public fun DoubleArray.plus(array: Array) : List { + val answer = toArrayList() + answer.addAll(array) + return answer + +} + +/** + * Returns a list containing all elements of original collection and then all elements of the given *collection* + */ +public fun FloatArray.plus(array: Array) : List { + val answer = toArrayList() + answer.addAll(array) + return answer + +} + +/** + * Returns a list containing all elements of original collection and then all elements of the given *collection* + */ +public fun IntArray.plus(array: Array) : List { + val answer = toArrayList() + answer.addAll(array) + return answer + +} + +/** + * Returns a list containing all elements of original collection and then all elements of the given *collection* + */ +public fun LongArray.plus(array: Array) : List { + val answer = toArrayList() + answer.addAll(array) + return answer + +} + +/** + * Returns a list containing all elements of original collection and then all elements of the given *collection* + */ +public fun ShortArray.plus(array: Array) : List { + val answer = toArrayList() + answer.addAll(array) + return answer + +} + +/** + * Returns a list containing all elements of original collection and then all elements of the given *collection* + */ +public fun Iterable.plus(array: Array) : List { + val answer = toArrayList() + answer.addAll(array) + return answer + +} + +/** + * Returns a list containing all elements of original collection and then all elements of the given *collection* + */ +public fun Array.plus(collection: Iterable) : List { + val answer = toArrayList() + answer.addAll(collection) + return answer + +} + +/** + * Returns a list containing all elements of original collection and then all elements of the given *collection* + */ +public fun BooleanArray.plus(collection: Iterable) : List { + val answer = toArrayList() + answer.addAll(collection) + return answer + +} + +/** + * Returns a list containing all elements of original collection and then all elements of the given *collection* + */ +public fun ByteArray.plus(collection: Iterable) : List { + val answer = toArrayList() + answer.addAll(collection) + return answer + +} + +/** + * Returns a list containing all elements of original collection and then all elements of the given *collection* + */ +public fun CharArray.plus(collection: Iterable) : List { + val answer = toArrayList() + answer.addAll(collection) + return answer + +} + +/** + * Returns a list containing all elements of original collection and then all elements of the given *collection* + */ +public fun DoubleArray.plus(collection: Iterable) : List { + val answer = toArrayList() + answer.addAll(collection) + return answer + +} + +/** + * Returns a list containing all elements of original collection and then all elements of the given *collection* + */ +public fun FloatArray.plus(collection: Iterable) : List { + val answer = toArrayList() + answer.addAll(collection) + return answer + +} + +/** + * Returns a list containing all elements of original collection and then all elements of the given *collection* + */ +public fun IntArray.plus(collection: Iterable) : List { + val answer = toArrayList() + answer.addAll(collection) + return answer + +} + +/** + * Returns a list containing all elements of original collection and then all elements of the given *collection* + */ +public fun LongArray.plus(collection: Iterable) : List { + val answer = toArrayList() + answer.addAll(collection) + return answer + +} + +/** + * Returns a list containing all elements of original collection and then all elements of the given *collection* + */ +public fun ShortArray.plus(collection: Iterable) : List { + val answer = toArrayList() + answer.addAll(collection) + return answer + +} + +/** + * Returns a list containing all elements of original collection and then all elements of the given *collection* + */ +public fun Iterable.plus(collection: Iterable) : List { + val answer = toArrayList() + answer.addAll(collection) + return answer + +} + +/** + * Returns a stream containing all elements of original stream and then all elements of the given *collection* + */ +public fun Stream.plus(collection: Iterable) : Stream { + val answer = toArrayList() + answer.addAll(collection) + return answer.stream() + +} + +/** + * Returns a list containing all elements of original collection and then the given element + */ +public fun Array.plus(element: T) : List { + val answer = toArrayList() + answer.add(element) + return answer + +} + +/** + * Returns a list containing all elements of original collection and then the given element + */ +public fun BooleanArray.plus(element: Boolean) : List { + val answer = toArrayList() + answer.add(element) + return answer + +} + +/** + * Returns a list containing all elements of original collection and then the given element + */ +public fun ByteArray.plus(element: Byte) : List { + val answer = toArrayList() + answer.add(element) + return answer + +} + +/** + * Returns a list containing all elements of original collection and then the given element + */ +public fun CharArray.plus(element: Char) : List { + val answer = toArrayList() + answer.add(element) + return answer + +} + +/** + * Returns a list containing all elements of original collection and then the given element + */ +public fun DoubleArray.plus(element: Double) : List { + val answer = toArrayList() + answer.add(element) + return answer + +} + +/** + * Returns a list containing all elements of original collection and then the given element + */ +public fun FloatArray.plus(element: Float) : List { + val answer = toArrayList() + answer.add(element) + return answer + +} + +/** + * Returns a list containing all elements of original collection and then the given element + */ +public fun IntArray.plus(element: Int) : List { + val answer = toArrayList() + answer.add(element) + return answer + +} + +/** + * Returns a list containing all elements of original collection and then the given element + */ +public fun LongArray.plus(element: Long) : List { + val answer = toArrayList() + answer.add(element) + return answer + +} + +/** + * Returns a list containing all elements of original collection and then the given element + */ +public fun ShortArray.plus(element: Short) : List { + val answer = toArrayList() + answer.add(element) + return answer + +} + +/** + * Returns a list containing all elements of original collection and then the given element + */ +public fun Iterable.plus(element: T) : List { + val answer = toArrayList() + answer.add(element) + return answer + +} + +/** + * Returns a stream containing all elements of original stream and then the given element + */ +public fun Stream.plus(element: T) : Stream { + val answer = toArrayList() + answer.add(element) + return answer.stream() + +} + +/** + * Returns a stream containing all elements of original stream and then all elements of the given *stream* + */ +public fun Stream.plus(stream: Stream) : Stream { + val answer = toArrayList() + answer.addAll(stream) + return answer.stream() + +} + +/** + * Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection. + */ +public fun Array.zip(array: Array) : List> { + val first = iterator() + val second = array.iterator() + val list = ArrayList>() + while (first.hasNext() && second.hasNext()) { + list.add(first.next() to second.next()) + } + return list + +} + +/** + * Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection. + */ +public fun BooleanArray.zip(array: Array) : List> { + val first = iterator() + val second = array.iterator() + val list = ArrayList>() + while (first.hasNext() && second.hasNext()) { + list.add(first.next() to second.next()) + } + return list + +} + +/** + * Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection. + */ +public fun ByteArray.zip(array: Array) : List> { + val first = iterator() + val second = array.iterator() + val list = ArrayList>() + while (first.hasNext() && second.hasNext()) { + list.add(first.next() to second.next()) + } + return list + +} + +/** + * Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection. + */ +public fun CharArray.zip(array: Array) : List> { + val first = iterator() + val second = array.iterator() + val list = ArrayList>() + while (first.hasNext() && second.hasNext()) { + list.add(first.next() to second.next()) + } + return list + +} + +/** + * Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection. + */ +public fun DoubleArray.zip(array: Array) : List> { + val first = iterator() + val second = array.iterator() + val list = ArrayList>() + while (first.hasNext() && second.hasNext()) { + list.add(first.next() to second.next()) + } + return list + +} + +/** + * Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection. + */ +public fun FloatArray.zip(array: Array) : List> { + val first = iterator() + val second = array.iterator() + val list = ArrayList>() + while (first.hasNext() && second.hasNext()) { + list.add(first.next() to second.next()) + } + return list + +} + +/** + * Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection. + */ +public fun IntArray.zip(array: Array) : List> { + val first = iterator() + val second = array.iterator() + val list = ArrayList>() + while (first.hasNext() && second.hasNext()) { + list.add(first.next() to second.next()) + } + return list + +} + +/** + * Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection. + */ +public fun LongArray.zip(array: Array) : List> { + val first = iterator() + val second = array.iterator() + val list = ArrayList>() + while (first.hasNext() && second.hasNext()) { + list.add(first.next() to second.next()) + } + return list + +} + +/** + * Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection. + */ +public fun ShortArray.zip(array: Array) : List> { + val first = iterator() + val second = array.iterator() + val list = ArrayList>() + while (first.hasNext() && second.hasNext()) { + list.add(first.next() to second.next()) + } + return list + +} + +/** + * Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection. + */ +public fun Iterable.zip(array: Array) : List> { + val first = iterator() + val second = array.iterator() + val list = ArrayList>() + while (first.hasNext() && second.hasNext()) { + list.add(first.next() to second.next()) + } + return list + +} + +/** + * Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection. + */ +public fun Array.zip(collection: Iterable) : List> { + val first = iterator() + val second = collection.iterator() + val list = ArrayList>() + while (first.hasNext() && second.hasNext()) { + list.add(first.next() to second.next()) + } + return list + +} + +/** + * Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection. + */ +public fun BooleanArray.zip(collection: Iterable) : List> { + val first = iterator() + val second = collection.iterator() + val list = ArrayList>() + while (first.hasNext() && second.hasNext()) { + list.add(first.next() to second.next()) + } + return list + +} + +/** + * Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection. + */ +public fun ByteArray.zip(collection: Iterable) : List> { + val first = iterator() + val second = collection.iterator() + val list = ArrayList>() + while (first.hasNext() && second.hasNext()) { + list.add(first.next() to second.next()) + } + return list + +} + +/** + * Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection. + */ +public fun CharArray.zip(collection: Iterable) : List> { + val first = iterator() + val second = collection.iterator() + val list = ArrayList>() + while (first.hasNext() && second.hasNext()) { + list.add(first.next() to second.next()) + } + return list + +} + +/** + * Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection. + */ +public fun DoubleArray.zip(collection: Iterable) : List> { + val first = iterator() + val second = collection.iterator() + val list = ArrayList>() + while (first.hasNext() && second.hasNext()) { + list.add(first.next() to second.next()) + } + return list + +} + +/** + * Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection. + */ +public fun FloatArray.zip(collection: Iterable) : List> { + val first = iterator() + val second = collection.iterator() + val list = ArrayList>() + while (first.hasNext() && second.hasNext()) { + list.add(first.next() to second.next()) + } + return list + +} + +/** + * Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection. + */ +public fun IntArray.zip(collection: Iterable) : List> { + val first = iterator() + val second = collection.iterator() + val list = ArrayList>() + while (first.hasNext() && second.hasNext()) { + list.add(first.next() to second.next()) + } + return list + +} + +/** + * Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection. + */ +public fun LongArray.zip(collection: Iterable) : List> { + val first = iterator() + val second = collection.iterator() + val list = ArrayList>() + while (first.hasNext() && second.hasNext()) { + list.add(first.next() to second.next()) + } + return list + +} + +/** + * Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection. + */ +public fun ShortArray.zip(collection: Iterable) : List> { + val first = iterator() + val second = collection.iterator() + val list = ArrayList>() + while (first.hasNext() && second.hasNext()) { + list.add(first.next() to second.next()) + } + return list + +} + +/** + * Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection. + */ +public fun Iterable.zip(collection: Iterable) : List> { + val first = iterator() + val second = collection.iterator() + val list = ArrayList>() + while (first.hasNext() && second.hasNext()) { + list.add(first.next() to second.next()) + } + return list + +} + +/** + * Returns a stream of pairs built from elements of both collections with same indexes. List has length of shortest collection. + */ +public fun Stream.zip(stream: Stream) : Stream> { + return ZippingStream(this, stream) + +} + diff --git a/libraries/stdlib/src/generated/_Guards.kt b/libraries/stdlib/src/generated/_Guards.kt new file mode 100644 index 00000000000..b3686bb3958 --- /dev/null +++ b/libraries/stdlib/src/generated/_Guards.kt @@ -0,0 +1,61 @@ +package kotlin + +// +// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt +// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib +// + +import java.util.* + +/** + * Returns an original collection containing all the non-*null* elements, throwing an [[IllegalArgumentException]] if there are any null elements + */ +public fun Array.requireNoNulls() : Array { + for (element in this) { + if (element == null) { + throw IllegalArgumentException("null element found in $this") + } + } + return this as Array + +} + +/** + * Returns an original collection containing all the non-*null* elements, throwing an [[IllegalArgumentException]] if there are any null elements + */ +public fun Iterable.requireNoNulls() : Iterable { + for (element in this) { + if (element == null) { + throw IllegalArgumentException("null element found in $this") + } + } + return this as Iterable + +} + +/** + * Returns an original collection containing all the non-*null* elements, throwing an [[IllegalArgumentException]] if there are any null elements + */ +public fun List.requireNoNulls() : List { + for (element in this) { + if (element == null) { + throw IllegalArgumentException("null element found in $this") + } + } + return this as List + +} + +/** + * Returns an original collection containing all the non-*null* elements, throwing an [[IllegalArgumentException]] if there are any null elements + */ +public fun Stream.requireNoNulls() : Stream { + return FilteringStream(this) { + if (it == null) { + throw IllegalArgumentException("null element found in $this") + } + true + } as Stream + +} + diff --git a/libraries/stdlib/src/generated/_IntArrays.kt b/libraries/stdlib/src/generated/_IntArrays.kt deleted file mode 100644 index 96f82bb1d28..00000000000 --- a/libraries/stdlib/src/generated/_IntArrays.kt +++ /dev/null @@ -1,482 +0,0 @@ -package kotlin - -// -// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt -// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib -// - -import java.util.* - -/** - * Returns *true* if all elements match the given *predicate* - */ -public inline fun IntArray.all(predicate: (Int) -> Boolean) : Boolean { - for (element in this) if (!predicate(element)) return false - return true -} - -/** - * Returns *true* if any elements match the given *predicate* - */ -public inline fun IntArray.any(predicate: (Int) -> Boolean) : Boolean { - for (element in this) if (predicate(element)) return true - return false -} - -/** - * Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied - * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will - * a special *truncated* separator (which defaults to "..." - */ -public fun IntArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit { - buffer.append(prefix) - var count = 0 - for (element in this) { - if (++count > 1) buffer.append(separator) - if (limit < 0 || count <= limit) { - val text = if (element == null) "null" else element.toString() - buffer.append(text) - } else break - } - if (limit >= 0 && count > limit) buffer.append(truncated) - buffer.append(postfix) -} - -/** - * Returns the number of elements which match the given *predicate* - */ -public inline fun IntArray.count(predicate: (Int) -> Boolean) : Int { - var count = 0 - for (element in this) if (predicate(element)) count++ - return count -} - -/** - * Returns a list containing everything but the first *n* elements - */ -public fun IntArray.drop(n: Int) : List { - return dropWhile(countTo(n)) -} - -/** - * Returns a list containing the everything but the first elements that satisfy the given *predicate* - */ -public inline fun IntArray.dropWhile(predicate: (Int) -> Boolean) : List { - return dropWhileTo(ArrayList(), predicate) -} - -/** - * Returns a list containing the everything but the first elements that satisfy the given *predicate* - */ -public inline fun > IntArray.dropWhileTo(result: L, predicate: (Int) -> Boolean) : L { - var start = true - for (element in this) { - if (start && predicate(element)) { - // ignore - } else { - start = false - result.add(element) - } - } - return result -} - -/** - * Returns a list containing all elements which match the given *predicate* - */ -public inline fun IntArray.filter(predicate: (Int) -> Boolean) : List { - return filterTo(ArrayList(), predicate) -} - -/** - * Returns a list containing all elements which do not match the given *predicate* - */ -public inline fun IntArray.filterNot(predicate: (Int) -> Boolean) : List { - return filterNotTo(ArrayList(), predicate) -} - -/** - * Returns a list containing all elements which do not match the given *predicate* - */ -public inline fun > IntArray.filterNotTo(result: C, predicate: (Int) -> Boolean) : C { - for (element in this) if (!predicate(element)) result.add(element) - return result -} - -/** - * Filters all elements which match the given predicate into the given list - */ -public inline fun > IntArray.filterTo(result: C, predicate: (Int) -> Boolean) : C { - for (element in this) if (predicate(element)) result.add(element) - return result -} - -/** - * Returns the first element which matches the given *predicate* or *null* if none matched - */ -public inline fun IntArray.find(predicate: (Int) -> Boolean) : Int? { - for (element in this) if (predicate(element)) return element - return null -} - -/** - * Returns the result of transforming each element to one or more values which are concatenated together into a single list - */ -public inline fun IntArray.flatMap(transform: (Int)-> Iterable) : List { - return flatMapTo(ArrayList(), transform) -} - -/** - * Returns the result of transforming each element to one or more values which are concatenated together into a single collection - */ -public inline fun > IntArray.flatMapTo(result: C, transform: (Int) -> Iterable) : C { - for (element in this) { - val list = transform(element) - for (r in list) result.add(r) - } - return result -} - -/** - * Folds all elements from from left to right with the *initial* value to perform the operation on sequential pairs of elements - */ -public inline fun IntArray.fold(initial: R, operation: (R, Int) -> R) : R { - var answer = initial - for (element in this) answer = operation(answer, element) - return answer -} - -/** - * Folds all elements from right to left with the *initial* value to perform the operation on sequential pairs of elements - */ -public inline fun IntArray.foldRight(initial: R, operation: (Int, R) -> R) : R { - var r = initial - var index = size - 1 - - while (index >= 0) { - r = operation(get(index--), r) - } - - return r -} - -/** - * Performs the given *operation* on each element - */ -public inline fun IntArray.forEach(operation: (Int) -> Unit) : Unit { - for (element in this) operation(element) -} - -/** - * Groups the elements in the collection into a new [[Map]] using the supplied *toKey* function to calculate the key to group the elements by - */ -public inline fun IntArray.groupBy(toKey: (Int) -> K) : Map> { - return groupByTo(HashMap>(), toKey) -} - -public inline fun IntArray.groupByTo(result: MutableMap>, toKey: (Int) -> K) : Map> { - for (element in this) { - val key = toKey(element) - val list = result.getOrPut(key) { ArrayList() } - list.add(element) - } - return result -} - -/** - * Returns first index of item, or -1 if the array does not contain item - */ -public fun IntArray.indexOf(item: Int) : Int { - for (i in indices) { - if (item == this[i]) { - return i - } - } - return -1 -} - -/** - * Returns true if the array is empty - */ -public fun IntArray.isEmpty() : Boolean { - return size == 0 -} - -/** - * Returns true if the array is empty - */ -public fun IntArray.isNotEmpty() : Boolean { - return !isEmpty() -} - -/** - * Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied. - * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will - * a special *truncated* separator (which defaults to "..." - */ -public fun IntArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String { - val buffer = StringBuilder() - appendString(buffer, separator, prefix, postfix, limit, truncated) - return buffer.toString() -} - -/** - * Returns a new List containing the results of applying the given *transform* function to each element in this collection - */ -public inline fun IntArray.map(transform : (Int) -> R) : List { - return mapTo(ArrayList(), transform) -} - -/** - * Transforms each element of this collection with the given *transform* function and - * adds each return value to the given *results* collection - */ -public inline fun > IntArray.mapTo(result: C, transform : (Int) -> R) : C { - for (item in this) - result.add(transform(item)) - return result -} - -/** - * Returns the largest element or null if there are no elements - */ -public fun IntArray.max() : Int? { - if (isEmpty()) return null - - var max = this[0] - for (i in 1..lastIndex) { - val e = this[i] - if (max < e) max = e - } - return max -} - -/** - * Returns the first element yielding the largest value of the given function or null if there are no elements - */ -public inline fun > IntArray.maxBy(f: (Int) -> R) : Int? { - if (isEmpty()) return null - - var maxElem = this[0] - var maxValue = f(maxElem) - for (i in 1..lastIndex) { - val e = this[i] - val v = f(e) - if (maxValue < v) { - maxElem = e - maxValue = v - } - } - return maxElem -} - -/** - * Returns the smallest element or null if there are no elements - */ -public fun IntArray.min() : Int? { - if (isEmpty()) return null - - var min = this[0] - for (i in 1..lastIndex) { - val e = this[i] - if (min > e) min = e - } - return min -} - -/** - * Returns the first element yielding the smallest value of the given function or null if there are no elements - */ -public inline fun > IntArray.minBy(f: (Int) -> R) : Int? { - if (size == 0) return null - - var minElem = this[0] - var minValue = f(minElem) - for (i in 1..lastIndex) { - val e = this[i] - val v = f(e) - if (minValue > v) { - minElem = e - minValue = v - } - } - return minElem -} - -/** - * Partitions this collection into a pair of collections - */ -public inline fun IntArray.partition(predicate: (Int) -> Boolean) : Pair, List> { - val first = ArrayList() - val second = ArrayList() - for (element in this) { - if (predicate(element)) { - first.add(element) - } else { - second.add(element) - } - } - return Pair(first, second) -} - -/** - * Creates an [[Iterator]] which iterates over this iterator then the following collection - */ -public fun IntArray.plus(collection: Iterable) : List { - return plus(collection.iterator()) -} - -/** - * Creates an [[Iterator]] which iterates over this iterator then the given element at the end - */ -public fun IntArray.plus(element: Int) : List { - val answer = ArrayList() - toCollection(answer) - answer.add(element) - return answer -} - -/** - * Creates an [[Iterator]] which iterates over this iterator then the following iterator - */ -public fun IntArray.plus(iterator: Iterator) : List { - val answer = ArrayList() - toCollection(answer) - for (element in iterator) { - answer.add(element) - } - return answer -} - -/** - * Applies binary operation to all elements of iterable, going from left to right. - * Similar to fold function, but uses the first element as initial value - */ -public inline fun IntArray.reduce(operation: (Int, Int) -> Int) : Int { - val iterator = this.iterator() - if (!iterator.hasNext()) { - throw UnsupportedOperationException("Empty iterable can't be reduced") - } - - var result: Int = iterator.next() //compiler doesn't understand that result will initialized anyway - while (iterator.hasNext()) { - result = operation(result, iterator.next()) - } - - return result -} - -/** - * Applies binary operation to all elements of iterable, going from right to left. - * Similar to foldRight function, but uses the last element as initial value - */ -public inline fun IntArray.reduceRight(operation: (Int, Int) -> Int) : Int { - var index = size - 1 - if (index < 0) { - throw UnsupportedOperationException("Empty iterable can't be reduced") - } - - var r = get(index--) - while (index >= 0) { - r = operation(get(index--), r) - } - - return r -} - -/** - * Reverses the order the elements into a list - */ -public fun IntArray.reverse() : List { - val list = toCollection(ArrayList()) - Collections.reverse(list) - return list -} - -/** - * Copies all elements into a [[List]] and sorts it by value of compare_function(element) - * E.g. arrayList("two" to 2, "one" to 1).sortBy({it.second}) returns list sorted by second element of pair - */ -public inline fun > IntArray.sortBy(f: (Int) -> R) : List { - val sortedList = toCollection(ArrayList()) - val sortBy: Comparator = comparator {(x: Int, y: Int) -> - val xr = f(x) - val yr = f(y) - xr.compareTo(yr) - } - java.util.Collections.sort(sortedList, sortBy) - return sortedList -} - -/** - * Returns a list containing the first *n* elements - */ -public fun IntArray.take(n: Int) : List { - return takeWhile(countTo(n)) -} - -/** - * Returns a list containing the first elements that satisfy the given *predicate* - */ -public inline fun IntArray.takeWhile(predicate: (Int) -> Boolean) : List { - return takeWhileTo(ArrayList(), predicate) -} - -/** - * Returns a list containing the first elements that satisfy the given *predicate* - */ -public inline fun > IntArray.takeWhileTo(result: C, predicate: (Int) -> Boolean) : C { - for (element in this) if (predicate(element)) result.add(element) else break - return result -} - -/** - * Copies all elements into the given collection - */ -public fun > IntArray.toCollection(result: C) : C { - for (element in this) result.add(element) - return result -} - -/** - * Copies all elements into a [[LinkedList]] - */ -public fun IntArray.toLinkedList() : LinkedList { - return toCollection(LinkedList()) -} - -/** - * Copies all elements into a [[List]] - */ -public fun IntArray.toList() : List { - return toCollection(ArrayList()) -} - -/** - * Copies all elements into a [[Set]] - */ -public fun IntArray.toSet() : Set { - return toCollection(LinkedHashSet()) -} - -/** - * Copies all elements into a [[SortedSet]] - */ -public fun IntArray.toSortedSet() : SortedSet { - return toCollection(TreeSet()) -} - -/** - * Returns an iterator of Pairs(index, data) - */ -public fun IntArray.withIndices() : Iterator> { - return IndexIterator(iterator()) -} - -/** - * Sums up the elements - */ -public fun IntArray.sum() : Int { - return fold(0, {a,b -> a+b}) -} - diff --git a/libraries/stdlib/src/generated/_Iterables.kt b/libraries/stdlib/src/generated/_Iterables.kt deleted file mode 100644 index a5999f15d1d..00000000000 --- a/libraries/stdlib/src/generated/_Iterables.kt +++ /dev/null @@ -1,476 +0,0 @@ -package kotlin - -// -// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt -// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib -// - -import java.util.* - -/** - * Returns *true* if all elements match the given *predicate* - */ -public inline fun Iterable.all(predicate: (T) -> Boolean) : Boolean { - for (element in this) if (!predicate(element)) return false - return true -} - -/** - * Returns *true* if any elements match the given *predicate* - */ -public inline fun Iterable.any(predicate: (T) -> Boolean) : Boolean { - for (element in this) if (predicate(element)) return true - return false -} - -/** - * Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied - * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will - * a special *truncated* separator (which defaults to "..." - */ -public fun Iterable.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit { - buffer.append(prefix) - var count = 0 - for (element in this) { - if (++count > 1) buffer.append(separator) - if (limit < 0 || count <= limit) { - val text = if (element == null) "null" else element.toString() - buffer.append(text) - } else break - } - if (limit >= 0 && count > limit) buffer.append(truncated) - buffer.append(postfix) -} - -/** - * Returns the number of elements which match the given *predicate* - */ -public inline fun Iterable.count(predicate: (T) -> Boolean) : Int { - var count = 0 - for (element in this) if (predicate(element)) count++ - return count -} - -/** - * Returns a list containing everything but the first *n* elements - */ -public fun Iterable.drop(n: Int) : List { - return dropWhile(countTo(n)) -} - -/** - * Returns a list containing the everything but the first elements that satisfy the given *predicate* - */ -public inline fun Iterable.dropWhile(predicate: (T) -> Boolean) : List { - return dropWhileTo(ArrayList(), predicate) -} - -/** - * Returns a list containing the everything but the first elements that satisfy the given *predicate* - */ -public inline fun > Iterable.dropWhileTo(result: L, predicate: (T) -> Boolean) : L { - var start = true - for (element in this) { - if (start && predicate(element)) { - // ignore - } else { - start = false - result.add(element) - } - } - return result -} - -/** - * Returns a list containing all elements which match the given *predicate* - */ -public inline fun Iterable.filter(predicate: (T) -> Boolean) : List { - return filterTo(ArrayList(), predicate) -} - -/** - * Returns a list containing all elements which do not match the given *predicate* - */ -public inline fun Iterable.filterNot(predicate: (T) -> Boolean) : List { - return filterNotTo(ArrayList(), predicate) -} - -/** - * Returns a list containing all the non-*null* elements - */ -public fun Iterable.filterNotNull() : List { - return filterNotNullTo>(ArrayList()) -} - -/** - * Filters all non-*null* elements into the given list - */ -public fun > Iterable.filterNotNullTo(result: C) : C { - for (element in this) if (element != null) result.add(element) - return result -} - -/** - * Returns a list containing all elements which do not match the given *predicate* - */ -public inline fun > Iterable.filterNotTo(result: C, predicate: (T) -> Boolean) : C { - for (element in this) if (!predicate(element)) result.add(element) - return result -} - -/** - * Filters all elements which match the given predicate into the given list - */ -public inline fun > Iterable.filterTo(result: C, predicate: (T) -> Boolean) : C { - for (element in this) if (predicate(element)) result.add(element) - return result -} - -/** - * Returns the first element which matches the given *predicate* or *null* if none matched - */ -public inline fun Iterable.find(predicate: (T) -> Boolean) : T? { - for (element in this) if (predicate(element)) return element - return null -} - -/** - * Returns the result of transforming each element to one or more values which are concatenated together into a single list - */ -public inline fun Iterable.flatMap(transform: (T)-> Iterable) : List { - return flatMapTo(ArrayList(), transform) -} - -/** - * Returns the result of transforming each element to one or more values which are concatenated together into a single collection - */ -public inline fun > Iterable.flatMapTo(result: C, transform: (T) -> Iterable) : C { - for (element in this) { - val list = transform(element) - for (r in list) result.add(r) - } - return result -} - -/** - * Folds all elements from from left to right with the *initial* value to perform the operation on sequential pairs of elements - */ -public inline fun Iterable.fold(initial: R, operation: (R, T) -> R) : R { - var answer = initial - for (element in this) answer = operation(answer, element) - return answer -} - -/** - * Performs the given *operation* on each element - */ -public inline fun Iterable.forEach(operation: (T) -> Unit) : Unit { - for (element in this) operation(element) -} - -/** - * Groups the elements in the collection into a new [[Map]] using the supplied *toKey* function to calculate the key to group the elements by - */ -public inline fun Iterable.groupBy(toKey: (T) -> K) : Map> { - return groupByTo(HashMap>(), toKey) -} - -public inline fun Iterable.groupByTo(result: MutableMap>, toKey: (T) -> K) : Map> { - for (element in this) { - val key = toKey(element) - val list = result.getOrPut(key) { ArrayList() } - list.add(element) - } - return result -} - -/** - * Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied. - * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will - * a special *truncated* separator (which defaults to "..." - */ -public fun Iterable.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String { - val buffer = StringBuilder() - appendString(buffer, separator, prefix, postfix, limit, truncated) - return buffer.toString() -} - -/** - * Returns a new List containing the results of applying the given *transform* function to each element in this collection - */ -public inline fun Iterable.map(transform : (T) -> R) : List { - return mapTo(ArrayList(), transform) -} - -/** - * Transforms each element of this collection with the given *transform* function and - * adds each return value to the given *results* collection - */ -public inline fun > Iterable.mapTo(result: C, transform : (T) -> R) : C { - for (item in this) - result.add(transform(item)) - return result -} - -/** - * Returns the largest element or null if there are no elements - */ -public fun > Iterable.max() : T? { - val iterator = iterator() - if (!iterator.hasNext()) return null - - var max = iterator.next() - while (iterator.hasNext()) { - val e = iterator.next() - if (max < e) max = e - } - return max -} - -/** - * Returns the first element yielding the largest value of the given function or null if there are no elements - */ -public inline fun , T: Any> Iterable.maxBy(f: (T) -> R) : T? { - val iterator = iterator() - if (!iterator.hasNext()) return null - - var maxElem = iterator.next() - var maxValue = f(maxElem) - while (iterator.hasNext()) { - val e = iterator.next() - val v = f(e) - if (maxValue < v) { - maxElem = e - maxValue = v - } - } - return maxElem -} - -/** - * Returns the smallest element or null if there are no elements - */ -public fun > Iterable.min() : T? { - val iterator = iterator() - if (!iterator.hasNext()) return null - - var min = iterator.next() - while (iterator.hasNext()) { - val e = iterator.next() - if (min > e) min = e - } - return min -} - -/** - * Returns the first element yielding the smallest value of the given function or null if there are no elements - */ -public inline fun , T: Any> Iterable.minBy(f: (T) -> R) : T? { - val iterator = iterator() - if (!iterator.hasNext()) return null - - var minElem = iterator.next() - var minValue = f(minElem) - while (iterator.hasNext()) { - val e = iterator.next() - val v = f(e) - if (minValue > v) { - minElem = e - minValue = v - } - } - return minElem -} - -/** - * Partitions this collection into a pair of collections - */ -public inline fun Iterable.partition(predicate: (T) -> Boolean) : Pair, List> { - val first = ArrayList() - val second = ArrayList() - for (element in this) { - if (predicate(element)) { - first.add(element) - } else { - second.add(element) - } - } - return Pair(first, second) -} - -/** - * Creates an [[Iterator]] which iterates over this iterator then the following collection - */ -public fun Iterable.plus(collection: Iterable) : List { - return plus(collection.iterator()) -} - -/** - * Creates an [[Iterator]] which iterates over this iterator then the given element at the end - */ -public fun Iterable.plus(element: T) : List { - val answer = ArrayList() - toCollection(answer) - answer.add(element) - return answer -} - -/** - * Creates an [[Iterator]] which iterates over this iterator then the following iterator - */ -public fun Iterable.plus(iterator: Iterator) : List { - val answer = ArrayList() - toCollection(answer) - for (element in iterator) { - answer.add(element) - } - return answer -} - -/** - * Applies binary operation to all elements of iterable, going from left to right. - * Similar to fold function, but uses the first element as initial value - */ -public inline fun Iterable.reduce(operation: (T, T) -> T) : T { - val iterator = this.iterator() - if (!iterator.hasNext()) { - throw UnsupportedOperationException("Empty iterable can't be reduced") - } - - var result: T = iterator.next() //compiler doesn't understand that result will initialized anyway - while (iterator.hasNext()) { - result = operation(result, iterator.next()) - } - - return result -} - -/** - * Returns a original Iterable containing all the non-*null* elements, throwing an [[IllegalArgumentException]] if there are any null elements - */ -public fun Iterable.requireNoNulls() : Iterable { - for (element in this) { - if (element == null) { - throw IllegalArgumentException("null element found in $this") - } - } - return this as Iterable -} - -/** - * Reverses the order the elements into a list - */ -public fun Iterable.reverse() : List { - val list = toCollection(ArrayList()) - Collections.reverse(list) - return list -} - -/** - * Copies all elements into a [[List]] and sorts it by value of compare_function(element) - * E.g. arrayList("two" to 2, "one" to 1).sortBy({it.second}) returns list sorted by second element of pair - */ -public inline fun > Iterable.sortBy(f: (T) -> R) : List { - val sortedList = toCollection(ArrayList()) - val sortBy: Comparator = comparator {(x: T, y: T) -> - val xr = f(x) - val yr = f(y) - xr.compareTo(yr) - } - java.util.Collections.sort(sortedList, sortBy) - return sortedList -} - -/** - * Returns a list containing the first *n* elements - */ -public fun Iterable.take(n: Int) : List { - return takeWhile(countTo(n)) -} - -/** - * Returns a list containing the first elements that satisfy the given *predicate* - */ -public inline fun Iterable.takeWhile(predicate: (T) -> Boolean) : List { - return takeWhileTo(ArrayList(), predicate) -} - -/** - * Returns a list containing the first elements that satisfy the given *predicate* - */ -public inline fun > Iterable.takeWhileTo(result: C, predicate: (T) -> Boolean) : C { - for (element in this) if (predicate(element)) result.add(element) else break - return result -} - -/** - * Copies all elements into the given collection - */ -public fun > Iterable.toCollection(result: C) : C { - for (element in this) result.add(element) - return result -} - -/** - * Copies all elements into a [[LinkedList]] - */ -public fun Iterable.toLinkedList() : LinkedList { - return toCollection(LinkedList()) -} - -/** - * Copies all elements into a [[List]] - */ -public fun Iterable.toList() : List { - return toCollection(ArrayList()) -} - -/** - * Copies all elements into a [[Set]] - */ -public fun Iterable.toSet() : Set { - return toCollection(LinkedHashSet()) -} - -/** - * Copies all elements into a [[SortedSet]] - */ -public fun Iterable.toSortedSet() : SortedSet { - return toCollection(TreeSet()) -} - -/** - * Returns an iterator of Pairs(index, data) - */ -public fun Iterable.withIndices() : Iterator> { - return IndexIterator(iterator()) -} - -/** - * Sums up the elements - */ -public fun Iterable.sum() : Int { - return fold(0, {a,b -> a+b}) -} - -/** - * Sums up the elements - */ -public fun Iterable.sum() : Long { - return fold(0.toLong(), {a,b -> a+b}) -} - -/** - * Sums up the elements - */ -public fun Iterable.sum() : Float { - return fold(0.toFloat(), {a,b -> a+b}) -} - -/** - * Sums up the elements - */ -public fun Iterable.sum() : Double { - return fold(0.0, {a,b -> a+b}) -} - diff --git a/libraries/stdlib/src/generated/_LongArrays.kt b/libraries/stdlib/src/generated/_LongArrays.kt deleted file mode 100644 index 26595284b07..00000000000 --- a/libraries/stdlib/src/generated/_LongArrays.kt +++ /dev/null @@ -1,482 +0,0 @@ -package kotlin - -// -// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt -// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib -// - -import java.util.* - -/** - * Returns *true* if all elements match the given *predicate* - */ -public inline fun LongArray.all(predicate: (Long) -> Boolean) : Boolean { - for (element in this) if (!predicate(element)) return false - return true -} - -/** - * Returns *true* if any elements match the given *predicate* - */ -public inline fun LongArray.any(predicate: (Long) -> Boolean) : Boolean { - for (element in this) if (predicate(element)) return true - return false -} - -/** - * Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied - * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will - * a special *truncated* separator (which defaults to "..." - */ -public fun LongArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit { - buffer.append(prefix) - var count = 0 - for (element in this) { - if (++count > 1) buffer.append(separator) - if (limit < 0 || count <= limit) { - val text = if (element == null) "null" else element.toString() - buffer.append(text) - } else break - } - if (limit >= 0 && count > limit) buffer.append(truncated) - buffer.append(postfix) -} - -/** - * Returns the number of elements which match the given *predicate* - */ -public inline fun LongArray.count(predicate: (Long) -> Boolean) : Int { - var count = 0 - for (element in this) if (predicate(element)) count++ - return count -} - -/** - * Returns a list containing everything but the first *n* elements - */ -public fun LongArray.drop(n: Int) : List { - return dropWhile(countTo(n)) -} - -/** - * Returns a list containing the everything but the first elements that satisfy the given *predicate* - */ -public inline fun LongArray.dropWhile(predicate: (Long) -> Boolean) : List { - return dropWhileTo(ArrayList(), predicate) -} - -/** - * Returns a list containing the everything but the first elements that satisfy the given *predicate* - */ -public inline fun > LongArray.dropWhileTo(result: L, predicate: (Long) -> Boolean) : L { - var start = true - for (element in this) { - if (start && predicate(element)) { - // ignore - } else { - start = false - result.add(element) - } - } - return result -} - -/** - * Returns a list containing all elements which match the given *predicate* - */ -public inline fun LongArray.filter(predicate: (Long) -> Boolean) : List { - return filterTo(ArrayList(), predicate) -} - -/** - * Returns a list containing all elements which do not match the given *predicate* - */ -public inline fun LongArray.filterNot(predicate: (Long) -> Boolean) : List { - return filterNotTo(ArrayList(), predicate) -} - -/** - * Returns a list containing all elements which do not match the given *predicate* - */ -public inline fun > LongArray.filterNotTo(result: C, predicate: (Long) -> Boolean) : C { - for (element in this) if (!predicate(element)) result.add(element) - return result -} - -/** - * Filters all elements which match the given predicate into the given list - */ -public inline fun > LongArray.filterTo(result: C, predicate: (Long) -> Boolean) : C { - for (element in this) if (predicate(element)) result.add(element) - return result -} - -/** - * Returns the first element which matches the given *predicate* or *null* if none matched - */ -public inline fun LongArray.find(predicate: (Long) -> Boolean) : Long? { - for (element in this) if (predicate(element)) return element - return null -} - -/** - * Returns the result of transforming each element to one or more values which are concatenated together into a single list - */ -public inline fun LongArray.flatMap(transform: (Long)-> Iterable) : List { - return flatMapTo(ArrayList(), transform) -} - -/** - * Returns the result of transforming each element to one or more values which are concatenated together into a single collection - */ -public inline fun > LongArray.flatMapTo(result: C, transform: (Long) -> Iterable) : C { - for (element in this) { - val list = transform(element) - for (r in list) result.add(r) - } - return result -} - -/** - * Folds all elements from from left to right with the *initial* value to perform the operation on sequential pairs of elements - */ -public inline fun LongArray.fold(initial: R, operation: (R, Long) -> R) : R { - var answer = initial - for (element in this) answer = operation(answer, element) - return answer -} - -/** - * Folds all elements from right to left with the *initial* value to perform the operation on sequential pairs of elements - */ -public inline fun LongArray.foldRight(initial: R, operation: (Long, R) -> R) : R { - var r = initial - var index = size - 1 - - while (index >= 0) { - r = operation(get(index--), r) - } - - return r -} - -/** - * Performs the given *operation* on each element - */ -public inline fun LongArray.forEach(operation: (Long) -> Unit) : Unit { - for (element in this) operation(element) -} - -/** - * Groups the elements in the collection into a new [[Map]] using the supplied *toKey* function to calculate the key to group the elements by - */ -public inline fun LongArray.groupBy(toKey: (Long) -> K) : Map> { - return groupByTo(HashMap>(), toKey) -} - -public inline fun LongArray.groupByTo(result: MutableMap>, toKey: (Long) -> K) : Map> { - for (element in this) { - val key = toKey(element) - val list = result.getOrPut(key) { ArrayList() } - list.add(element) - } - return result -} - -/** - * Returns first index of item, or -1 if the array does not contain item - */ -public fun LongArray.indexOf(item: Long) : Int { - for (i in indices) { - if (item == this[i]) { - return i - } - } - return -1 -} - -/** - * Returns true if the array is empty - */ -public fun LongArray.isEmpty() : Boolean { - return size == 0 -} - -/** - * Returns true if the array is empty - */ -public fun LongArray.isNotEmpty() : Boolean { - return !isEmpty() -} - -/** - * Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied. - * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will - * a special *truncated* separator (which defaults to "..." - */ -public fun LongArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String { - val buffer = StringBuilder() - appendString(buffer, separator, prefix, postfix, limit, truncated) - return buffer.toString() -} - -/** - * Returns a new List containing the results of applying the given *transform* function to each element in this collection - */ -public inline fun LongArray.map(transform : (Long) -> R) : List { - return mapTo(ArrayList(), transform) -} - -/** - * Transforms each element of this collection with the given *transform* function and - * adds each return value to the given *results* collection - */ -public inline fun > LongArray.mapTo(result: C, transform : (Long) -> R) : C { - for (item in this) - result.add(transform(item)) - return result -} - -/** - * Returns the largest element or null if there are no elements - */ -public fun LongArray.max() : Long? { - if (isEmpty()) return null - - var max = this[0] - for (i in 1..lastIndex) { - val e = this[i] - if (max < e) max = e - } - return max -} - -/** - * Returns the first element yielding the largest value of the given function or null if there are no elements - */ -public inline fun > LongArray.maxBy(f: (Long) -> R) : Long? { - if (isEmpty()) return null - - var maxElem = this[0] - var maxValue = f(maxElem) - for (i in 1..lastIndex) { - val e = this[i] - val v = f(e) - if (maxValue < v) { - maxElem = e - maxValue = v - } - } - return maxElem -} - -/** - * Returns the smallest element or null if there are no elements - */ -public fun LongArray.min() : Long? { - if (isEmpty()) return null - - var min = this[0] - for (i in 1..lastIndex) { - val e = this[i] - if (min > e) min = e - } - return min -} - -/** - * Returns the first element yielding the smallest value of the given function or null if there are no elements - */ -public inline fun > LongArray.minBy(f: (Long) -> R) : Long? { - if (size == 0) return null - - var minElem = this[0] - var minValue = f(minElem) - for (i in 1..lastIndex) { - val e = this[i] - val v = f(e) - if (minValue > v) { - minElem = e - minValue = v - } - } - return minElem -} - -/** - * Partitions this collection into a pair of collections - */ -public inline fun LongArray.partition(predicate: (Long) -> Boolean) : Pair, List> { - val first = ArrayList() - val second = ArrayList() - for (element in this) { - if (predicate(element)) { - first.add(element) - } else { - second.add(element) - } - } - return Pair(first, second) -} - -/** - * Creates an [[Iterator]] which iterates over this iterator then the following collection - */ -public fun LongArray.plus(collection: Iterable) : List { - return plus(collection.iterator()) -} - -/** - * Creates an [[Iterator]] which iterates over this iterator then the given element at the end - */ -public fun LongArray.plus(element: Long) : List { - val answer = ArrayList() - toCollection(answer) - answer.add(element) - return answer -} - -/** - * Creates an [[Iterator]] which iterates over this iterator then the following iterator - */ -public fun LongArray.plus(iterator: Iterator) : List { - val answer = ArrayList() - toCollection(answer) - for (element in iterator) { - answer.add(element) - } - return answer -} - -/** - * Applies binary operation to all elements of iterable, going from left to right. - * Similar to fold function, but uses the first element as initial value - */ -public inline fun LongArray.reduce(operation: (Long, Long) -> Long) : Long { - val iterator = this.iterator() - if (!iterator.hasNext()) { - throw UnsupportedOperationException("Empty iterable can't be reduced") - } - - var result: Long = iterator.next() //compiler doesn't understand that result will initialized anyway - while (iterator.hasNext()) { - result = operation(result, iterator.next()) - } - - return result -} - -/** - * Applies binary operation to all elements of iterable, going from right to left. - * Similar to foldRight function, but uses the last element as initial value - */ -public inline fun LongArray.reduceRight(operation: (Long, Long) -> Long) : Long { - var index = size - 1 - if (index < 0) { - throw UnsupportedOperationException("Empty iterable can't be reduced") - } - - var r = get(index--) - while (index >= 0) { - r = operation(get(index--), r) - } - - return r -} - -/** - * Reverses the order the elements into a list - */ -public fun LongArray.reverse() : List { - val list = toCollection(ArrayList()) - Collections.reverse(list) - return list -} - -/** - * Copies all elements into a [[List]] and sorts it by value of compare_function(element) - * E.g. arrayList("two" to 2, "one" to 1).sortBy({it.second}) returns list sorted by second element of pair - */ -public inline fun > LongArray.sortBy(f: (Long) -> R) : List { - val sortedList = toCollection(ArrayList()) - val sortBy: Comparator = comparator {(x: Long, y: Long) -> - val xr = f(x) - val yr = f(y) - xr.compareTo(yr) - } - java.util.Collections.sort(sortedList, sortBy) - return sortedList -} - -/** - * Returns a list containing the first *n* elements - */ -public fun LongArray.take(n: Int) : List { - return takeWhile(countTo(n)) -} - -/** - * Returns a list containing the first elements that satisfy the given *predicate* - */ -public inline fun LongArray.takeWhile(predicate: (Long) -> Boolean) : List { - return takeWhileTo(ArrayList(), predicate) -} - -/** - * Returns a list containing the first elements that satisfy the given *predicate* - */ -public inline fun > LongArray.takeWhileTo(result: C, predicate: (Long) -> Boolean) : C { - for (element in this) if (predicate(element)) result.add(element) else break - return result -} - -/** - * Copies all elements into the given collection - */ -public fun > LongArray.toCollection(result: C) : C { - for (element in this) result.add(element) - return result -} - -/** - * Copies all elements into a [[LinkedList]] - */ -public fun LongArray.toLinkedList() : LinkedList { - return toCollection(LinkedList()) -} - -/** - * Copies all elements into a [[List]] - */ -public fun LongArray.toList() : List { - return toCollection(ArrayList()) -} - -/** - * Copies all elements into a [[Set]] - */ -public fun LongArray.toSet() : Set { - return toCollection(LinkedHashSet()) -} - -/** - * Copies all elements into a [[SortedSet]] - */ -public fun LongArray.toSortedSet() : SortedSet { - return toCollection(TreeSet()) -} - -/** - * Returns an iterator of Pairs(index, data) - */ -public fun LongArray.withIndices() : Iterator> { - return IndexIterator(iterator()) -} - -/** - * Sums up the elements - */ -public fun LongArray.sum() : Long { - return fold(0.toLong(), {a,b -> a+b}) -} - diff --git a/libraries/stdlib/src/generated/_Mapping.kt b/libraries/stdlib/src/generated/_Mapping.kt new file mode 100644 index 00000000000..c51012a638f --- /dev/null +++ b/libraries/stdlib/src/generated/_Mapping.kt @@ -0,0 +1,858 @@ +package kotlin + +// +// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt +// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib +// + +import java.util.* + +/** + * Returns a single list of all elements yielded from results of *transform* function being invoked on each element of original collection + */ +public inline fun Array.flatMap(transform: (T)-> Iterable) : List { + return flatMapTo(ArrayList(), transform) +} + +/** + * Returns a single list of all elements yielded from results of *transform* function being invoked on each element of original collection + */ +public inline fun BooleanArray.flatMap(transform: (Boolean)-> Iterable) : List { + return flatMapTo(ArrayList(), transform) +} + +/** + * Returns a single list of all elements yielded from results of *transform* function being invoked on each element of original collection + */ +public inline fun ByteArray.flatMap(transform: (Byte)-> Iterable) : List { + return flatMapTo(ArrayList(), transform) +} + +/** + * Returns a single list of all elements yielded from results of *transform* function being invoked on each element of original collection + */ +public inline fun CharArray.flatMap(transform: (Char)-> Iterable) : List { + return flatMapTo(ArrayList(), transform) +} + +/** + * Returns a single list of all elements yielded from results of *transform* function being invoked on each element of original collection + */ +public inline fun DoubleArray.flatMap(transform: (Double)-> Iterable) : List { + return flatMapTo(ArrayList(), transform) +} + +/** + * Returns a single list of all elements yielded from results of *transform* function being invoked on each element of original collection + */ +public inline fun FloatArray.flatMap(transform: (Float)-> Iterable) : List { + return flatMapTo(ArrayList(), transform) +} + +/** + * Returns a single list of all elements yielded from results of *transform* function being invoked on each element of original collection + */ +public inline fun IntArray.flatMap(transform: (Int)-> Iterable) : List { + return flatMapTo(ArrayList(), transform) +} + +/** + * Returns a single list of all elements yielded from results of *transform* function being invoked on each element of original collection + */ +public inline fun LongArray.flatMap(transform: (Long)-> Iterable) : List { + return flatMapTo(ArrayList(), transform) +} + +/** + * Returns a single list of all elements yielded from results of *transform* function being invoked on each element of original collection + */ +public inline fun ShortArray.flatMap(transform: (Short)-> Iterable) : List { + return flatMapTo(ArrayList(), transform) +} + +/** + * Returns a single list of all elements yielded from results of *transform* function being invoked on each element of original collection + */ +public inline fun Iterable.flatMap(transform: (T)-> Iterable) : List { + return flatMapTo(ArrayList(), transform) +} + +/** + * Returns a single list of all elements yielded from results of *transform* function being invoked on each element of original collection + */ +public inline fun Map.flatMap(transform: (Map.Entry)-> Iterable) : List { + return flatMapTo(ArrayList(), transform) +} + +/** + * Returns a single stream of all elements streamed from results of *transform* function being invoked on each element of original stream + */ +public fun Stream.flatMap(transform: (T)-> Stream) : Stream { + return FlatteningStream(this, transform) +} + +/** + * Appends all elements yielded from results of *transform* function being invoked on each element of original collection, to the given *collection* + */ +public inline fun > Array.flatMapTo(collection: C, transform: (T) -> Iterable) : C { + for (element in this) { + val list = transform(element) + collection.addAll(list) + } + return collection + +} + +/** + * Appends all elements yielded from results of *transform* function being invoked on each element of original collection, to the given *collection* + */ +public inline fun > BooleanArray.flatMapTo(collection: C, transform: (Boolean) -> Iterable) : C { + for (element in this) { + val list = transform(element) + collection.addAll(list) + } + return collection + +} + +/** + * Appends all elements yielded from results of *transform* function being invoked on each element of original collection, to the given *collection* + */ +public inline fun > ByteArray.flatMapTo(collection: C, transform: (Byte) -> Iterable) : C { + for (element in this) { + val list = transform(element) + collection.addAll(list) + } + return collection + +} + +/** + * Appends all elements yielded from results of *transform* function being invoked on each element of original collection, to the given *collection* + */ +public inline fun > CharArray.flatMapTo(collection: C, transform: (Char) -> Iterable) : C { + for (element in this) { + val list = transform(element) + collection.addAll(list) + } + return collection + +} + +/** + * Appends all elements yielded from results of *transform* function being invoked on each element of original collection, to the given *collection* + */ +public inline fun > DoubleArray.flatMapTo(collection: C, transform: (Double) -> Iterable) : C { + for (element in this) { + val list = transform(element) + collection.addAll(list) + } + return collection + +} + +/** + * Appends all elements yielded from results of *transform* function being invoked on each element of original collection, to the given *collection* + */ +public inline fun > FloatArray.flatMapTo(collection: C, transform: (Float) -> Iterable) : C { + for (element in this) { + val list = transform(element) + collection.addAll(list) + } + return collection + +} + +/** + * Appends all elements yielded from results of *transform* function being invoked on each element of original collection, to the given *collection* + */ +public inline fun > IntArray.flatMapTo(collection: C, transform: (Int) -> Iterable) : C { + for (element in this) { + val list = transform(element) + collection.addAll(list) + } + return collection + +} + +/** + * Appends all elements yielded from results of *transform* function being invoked on each element of original collection, to the given *collection* + */ +public inline fun > LongArray.flatMapTo(collection: C, transform: (Long) -> Iterable) : C { + for (element in this) { + val list = transform(element) + collection.addAll(list) + } + return collection + +} + +/** + * Appends all elements yielded from results of *transform* function being invoked on each element of original collection, to the given *collection* + */ +public inline fun > ShortArray.flatMapTo(collection: C, transform: (Short) -> Iterable) : C { + for (element in this) { + val list = transform(element) + collection.addAll(list) + } + return collection + +} + +/** + * Appends all elements yielded from results of *transform* function being invoked on each element of original collection, to the given *collection* + */ +public inline fun > Iterable.flatMapTo(collection: C, transform: (T) -> Iterable) : C { + for (element in this) { + val list = transform(element) + collection.addAll(list) + } + return collection + +} + +/** + * Appends all elements yielded from results of *transform* function being invoked on each element of original collection, to the given *collection* + */ +public inline fun > Map.flatMapTo(collection: C, transform: (Map.Entry) -> Iterable) : C { + for (element in this) { + val list = transform(element) + collection.addAll(list) + } + return collection + +} + +/** + * Appends all elements yielded from results of *transform* function being invoked on each element of original stream, to the given *collection* + */ +public inline fun > Stream.flatMapTo(collection: C, transform: (T) -> Stream) : C { + for (element in this) { + val list = transform(element) + collection.addAll(list) + } + return collection + +} + +/** + * Returns a map of the elements in original collection grouped by the result of given *toKey* function + */ +public inline fun Array.groupBy(toKey: (T) -> K) : Map> { + return groupByTo(HashMap>(), toKey) +} + +/** + * Returns a map of the elements in original collection grouped by the result of given *toKey* function + */ +public inline fun BooleanArray.groupBy(toKey: (Boolean) -> K) : Map> { + return groupByTo(HashMap>(), toKey) +} + +/** + * Returns a map of the elements in original collection grouped by the result of given *toKey* function + */ +public inline fun ByteArray.groupBy(toKey: (Byte) -> K) : Map> { + return groupByTo(HashMap>(), toKey) +} + +/** + * Returns a map of the elements in original collection grouped by the result of given *toKey* function + */ +public inline fun CharArray.groupBy(toKey: (Char) -> K) : Map> { + return groupByTo(HashMap>(), toKey) +} + +/** + * Returns a map of the elements in original collection grouped by the result of given *toKey* function + */ +public inline fun DoubleArray.groupBy(toKey: (Double) -> K) : Map> { + return groupByTo(HashMap>(), toKey) +} + +/** + * Returns a map of the elements in original collection grouped by the result of given *toKey* function + */ +public inline fun FloatArray.groupBy(toKey: (Float) -> K) : Map> { + return groupByTo(HashMap>(), toKey) +} + +/** + * Returns a map of the elements in original collection grouped by the result of given *toKey* function + */ +public inline fun IntArray.groupBy(toKey: (Int) -> K) : Map> { + return groupByTo(HashMap>(), toKey) +} + +/** + * Returns a map of the elements in original collection grouped by the result of given *toKey* function + */ +public inline fun LongArray.groupBy(toKey: (Long) -> K) : Map> { + return groupByTo(HashMap>(), toKey) +} + +/** + * Returns a map of the elements in original collection grouped by the result of given *toKey* function + */ +public inline fun ShortArray.groupBy(toKey: (Short) -> K) : Map> { + return groupByTo(HashMap>(), toKey) +} + +/** + * Returns a map of the elements in original collection grouped by the result of given *toKey* function + */ +public inline fun Iterable.groupBy(toKey: (T) -> K) : Map> { + return groupByTo(HashMap>(), toKey) +} + +/** + * Returns a map of the elements in original collection grouped by the result of given *toKey* function + */ +public inline fun Map.groupBy(toKey: (Map.Entry) -> K) : Map>> { + return groupByTo(HashMap>>(), toKey) +} + +/** + * Returns a map of the elements in original collection grouped by the result of given *toKey* function + */ +public inline fun Stream.groupBy(toKey: (T) -> K) : Map> { + return groupByTo(HashMap>(), toKey) +} + +/** + * Appends elements from original collection grouped by the result of given *toKey* function to the given *map* + */ +public inline fun Array.groupByTo(map: MutableMap>, toKey: (T) -> K) : Map> { + for (element in this) { + val key = toKey(element) + val list = map.getOrPut(key) { ArrayList() } + list.add(element) + } + return map + +} + +/** + * Appends elements from original collection grouped by the result of given *toKey* function to the given *map* + */ +public inline fun BooleanArray.groupByTo(map: MutableMap>, toKey: (Boolean) -> K) : Map> { + for (element in this) { + val key = toKey(element) + val list = map.getOrPut(key) { ArrayList() } + list.add(element) + } + return map + +} + +/** + * Appends elements from original collection grouped by the result of given *toKey* function to the given *map* + */ +public inline fun ByteArray.groupByTo(map: MutableMap>, toKey: (Byte) -> K) : Map> { + for (element in this) { + val key = toKey(element) + val list = map.getOrPut(key) { ArrayList() } + list.add(element) + } + return map + +} + +/** + * Appends elements from original collection grouped by the result of given *toKey* function to the given *map* + */ +public inline fun CharArray.groupByTo(map: MutableMap>, toKey: (Char) -> K) : Map> { + for (element in this) { + val key = toKey(element) + val list = map.getOrPut(key) { ArrayList() } + list.add(element) + } + return map + +} + +/** + * Appends elements from original collection grouped by the result of given *toKey* function to the given *map* + */ +public inline fun DoubleArray.groupByTo(map: MutableMap>, toKey: (Double) -> K) : Map> { + for (element in this) { + val key = toKey(element) + val list = map.getOrPut(key) { ArrayList() } + list.add(element) + } + return map + +} + +/** + * Appends elements from original collection grouped by the result of given *toKey* function to the given *map* + */ +public inline fun FloatArray.groupByTo(map: MutableMap>, toKey: (Float) -> K) : Map> { + for (element in this) { + val key = toKey(element) + val list = map.getOrPut(key) { ArrayList() } + list.add(element) + } + return map + +} + +/** + * Appends elements from original collection grouped by the result of given *toKey* function to the given *map* + */ +public inline fun IntArray.groupByTo(map: MutableMap>, toKey: (Int) -> K) : Map> { + for (element in this) { + val key = toKey(element) + val list = map.getOrPut(key) { ArrayList() } + list.add(element) + } + return map + +} + +/** + * Appends elements from original collection grouped by the result of given *toKey* function to the given *map* + */ +public inline fun LongArray.groupByTo(map: MutableMap>, toKey: (Long) -> K) : Map> { + for (element in this) { + val key = toKey(element) + val list = map.getOrPut(key) { ArrayList() } + list.add(element) + } + return map + +} + +/** + * Appends elements from original collection grouped by the result of given *toKey* function to the given *map* + */ +public inline fun ShortArray.groupByTo(map: MutableMap>, toKey: (Short) -> K) : Map> { + for (element in this) { + val key = toKey(element) + val list = map.getOrPut(key) { ArrayList() } + list.add(element) + } + return map + +} + +/** + * Appends elements from original collection grouped by the result of given *toKey* function to the given *map* + */ +public inline fun Iterable.groupByTo(map: MutableMap>, toKey: (T) -> K) : Map> { + for (element in this) { + val key = toKey(element) + val list = map.getOrPut(key) { ArrayList() } + list.add(element) + } + return map + +} + +/** + * Appends elements from original collection grouped by the result of given *toKey* function to the given *map* + */ +public inline fun Map.groupByTo(map: MutableMap>>, toKey: (Map.Entry) -> K) : Map>> { + for (element in this) { + val key = toKey(element) + val list = map.getOrPut(key) { ArrayList>() } + list.add(element) + } + return map + +} + +/** + * Appends elements from original collection grouped by the result of given *toKey* function to the given *map* + */ +public inline fun Stream.groupByTo(map: MutableMap>, toKey: (T) -> K) : Map> { + for (element in this) { + val key = toKey(element) + val list = map.getOrPut(key) { ArrayList() } + list.add(element) + } + return map + +} + +/** + * Returns a list containing the results of applying the given *transform* function to each element of the original collection + */ +public inline fun Array.map(transform : (T) -> R) : List { + return mapTo(ArrayList(), transform) +} + +/** + * Returns a list containing the results of applying the given *transform* function to each element of the original collection + */ +public inline fun BooleanArray.map(transform : (Boolean) -> R) : List { + return mapTo(ArrayList(), transform) +} + +/** + * Returns a list containing the results of applying the given *transform* function to each element of the original collection + */ +public inline fun ByteArray.map(transform : (Byte) -> R) : List { + return mapTo(ArrayList(), transform) +} + +/** + * Returns a list containing the results of applying the given *transform* function to each element of the original collection + */ +public inline fun CharArray.map(transform : (Char) -> R) : List { + return mapTo(ArrayList(), transform) +} + +/** + * Returns a list containing the results of applying the given *transform* function to each element of the original collection + */ +public inline fun DoubleArray.map(transform : (Double) -> R) : List { + return mapTo(ArrayList(), transform) +} + +/** + * Returns a list containing the results of applying the given *transform* function to each element of the original collection + */ +public inline fun FloatArray.map(transform : (Float) -> R) : List { + return mapTo(ArrayList(), transform) +} + +/** + * Returns a list containing the results of applying the given *transform* function to each element of the original collection + */ +public inline fun IntArray.map(transform : (Int) -> R) : List { + return mapTo(ArrayList(), transform) +} + +/** + * Returns a list containing the results of applying the given *transform* function to each element of the original collection + */ +public inline fun LongArray.map(transform : (Long) -> R) : List { + return mapTo(ArrayList(), transform) +} + +/** + * Returns a list containing the results of applying the given *transform* function to each element of the original collection + */ +public inline fun ShortArray.map(transform : (Short) -> R) : List { + return mapTo(ArrayList(), transform) +} + +/** + * Returns a list containing the results of applying the given *transform* function to each element of the original collection + */ +public inline fun Iterable.map(transform : (T) -> R) : List { + return mapTo(ArrayList(), transform) +} + +/** + * Returns a list containing the results of applying the given *transform* function to each element of the original collection + */ +public inline fun Map.map(transform : (Map.Entry) -> R) : List { + return mapTo(ArrayList(), transform) +} + +/** + * Returns a stream containing the results of applying the given *transform* function to each element of the original stream + */ +public fun Stream.map(transform : (T) -> R) : Stream { + return TransformingStream(this, transform) +} + +/** + * Returns a list containing the results of applying the given *transform* function to each non-null element of the original collection + */ +public fun Array.mapNotNull(transform : (T) -> R) : List { + return mapNotNullTo(ArrayList(), transform) + +} + +/** + * Returns a list containing the results of applying the given *transform* function to each non-null element of the original collection + */ +public fun Iterable.mapNotNull(transform : (T) -> R) : List { + return mapNotNullTo(ArrayList(), transform) + +} + +/** + * Returns a stream containing the results of applying the given *transform* function to each non-null element of the original stream + */ +public fun Stream.mapNotNull(transform : (T) -> R) : Stream { + return TransformingStream(FilteringStream(this, false, { it != null }) as Stream, transform) + +} + +/** + * Appends transformed non-null elements of original collection using the given *transform* function + * to the given *collection* + */ +public inline fun > Array.mapNotNullTo(collection: C, transform : (T) -> R) : C { + for (element in this) { + if (element != null) { + collection.add(transform(element)) + } + } + return collection + +} + +/** + * Appends transformed non-null elements of original collection using the given *transform* function + * to the given *collection* + */ +public inline fun > Iterable.mapNotNullTo(collection: C, transform : (T) -> R) : C { + for (element in this) { + if (element != null) { + collection.add(transform(element)) + } + } + return collection + +} + +/** + * Appends transformed non-null elements of original collection using the given *transform* function + * to the given *collection* + */ +public inline fun > Stream.mapNotNullTo(collection: C, transform : (T) -> R) : C { + for (element in this) { + if (element != null) { + collection.add(transform(element)) + } + } + return collection + +} + +/** + * Appends transformed elements of original collection using the given *transform* function + * to the given *collection* + */ +public inline fun > Array.mapTo(collection: C, transform : (T) -> R) : C { + for (item in this) + collection.add(transform(item)) + return collection + +} + +/** + * Appends transformed elements of original collection using the given *transform* function + * to the given *collection* + */ +public inline fun > BooleanArray.mapTo(collection: C, transform : (Boolean) -> R) : C { + for (item in this) + collection.add(transform(item)) + return collection + +} + +/** + * Appends transformed elements of original collection using the given *transform* function + * to the given *collection* + */ +public inline fun > ByteArray.mapTo(collection: C, transform : (Byte) -> R) : C { + for (item in this) + collection.add(transform(item)) + return collection + +} + +/** + * Appends transformed elements of original collection using the given *transform* function + * to the given *collection* + */ +public inline fun > CharArray.mapTo(collection: C, transform : (Char) -> R) : C { + for (item in this) + collection.add(transform(item)) + return collection + +} + +/** + * Appends transformed elements of original collection using the given *transform* function + * to the given *collection* + */ +public inline fun > DoubleArray.mapTo(collection: C, transform : (Double) -> R) : C { + for (item in this) + collection.add(transform(item)) + return collection + +} + +/** + * Appends transformed elements of original collection using the given *transform* function + * to the given *collection* + */ +public inline fun > FloatArray.mapTo(collection: C, transform : (Float) -> R) : C { + for (item in this) + collection.add(transform(item)) + return collection + +} + +/** + * Appends transformed elements of original collection using the given *transform* function + * to the given *collection* + */ +public inline fun > IntArray.mapTo(collection: C, transform : (Int) -> R) : C { + for (item in this) + collection.add(transform(item)) + return collection + +} + +/** + * Appends transformed elements of original collection using the given *transform* function + * to the given *collection* + */ +public inline fun > LongArray.mapTo(collection: C, transform : (Long) -> R) : C { + for (item in this) + collection.add(transform(item)) + return collection + +} + +/** + * Appends transformed elements of original collection using the given *transform* function + * to the given *collection* + */ +public inline fun > ShortArray.mapTo(collection: C, transform : (Short) -> R) : C { + for (item in this) + collection.add(transform(item)) + return collection + +} + +/** + * Appends transformed elements of original collection using the given *transform* function + * to the given *collection* + */ +public inline fun > Iterable.mapTo(collection: C, transform : (T) -> R) : C { + for (item in this) + collection.add(transform(item)) + return collection + +} + +/** + * Appends transformed elements of original collection using the given *transform* function + * to the given *collection* + */ +public inline fun > Map.mapTo(collection: C, transform : (Map.Entry) -> R) : C { + for (item in this) + collection.add(transform(item)) + return collection + +} + +/** + * Appends transformed elements of original collection using the given *transform* function + * to the given *collection* + */ +public inline fun > Stream.mapTo(collection: C, transform : (T) -> R) : C { + for (item in this) + collection.add(transform(item)) + return collection + +} + +/** + * Returns a list containing pairs of each element of the original collection and their index + */ +public fun Array.withIndices() : List> { + var index = 0 + return mapTo(ArrayList>(), { index++ to it }) + +} + +/** + * Returns a list containing pairs of each element of the original collection and their index + */ +public fun BooleanArray.withIndices() : List> { + var index = 0 + return mapTo(ArrayList>(), { index++ to it }) + +} + +/** + * Returns a list containing pairs of each element of the original collection and their index + */ +public fun ByteArray.withIndices() : List> { + var index = 0 + return mapTo(ArrayList>(), { index++ to it }) + +} + +/** + * Returns a list containing pairs of each element of the original collection and their index + */ +public fun CharArray.withIndices() : List> { + var index = 0 + return mapTo(ArrayList>(), { index++ to it }) + +} + +/** + * Returns a list containing pairs of each element of the original collection and their index + */ +public fun DoubleArray.withIndices() : List> { + var index = 0 + return mapTo(ArrayList>(), { index++ to it }) + +} + +/** + * Returns a list containing pairs of each element of the original collection and their index + */ +public fun FloatArray.withIndices() : List> { + var index = 0 + return mapTo(ArrayList>(), { index++ to it }) + +} + +/** + * Returns a list containing pairs of each element of the original collection and their index + */ +public fun IntArray.withIndices() : List> { + var index = 0 + return mapTo(ArrayList>(), { index++ to it }) + +} + +/** + * Returns a list containing pairs of each element of the original collection and their index + */ +public fun LongArray.withIndices() : List> { + var index = 0 + return mapTo(ArrayList>(), { index++ to it }) + +} + +/** + * Returns a list containing pairs of each element of the original collection and their index + */ +public fun ShortArray.withIndices() : List> { + var index = 0 + return mapTo(ArrayList>(), { index++ to it }) + +} + +/** + * Returns a list containing pairs of each element of the original collection and their index + */ +public fun Iterable.withIndices() : List> { + var index = 0 + return mapTo(ArrayList>(), { index++ to it }) + +} + +/** + * Returns a stream containing pairs of each element of the original collection and their index + */ +public fun Stream.withIndices() : Stream> { + var index = 0 + return TransformingStream(this, { index++ to it }) + +} + diff --git a/libraries/stdlib/src/generated/_Numeric.kt b/libraries/stdlib/src/generated/_Numeric.kt new file mode 100644 index 00000000000..c8d4ede75b0 --- /dev/null +++ b/libraries/stdlib/src/generated/_Numeric.kt @@ -0,0 +1,217 @@ +package kotlin + +// +// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt +// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib +// + +import java.util.* + +/** + * Returns the sum of all elements in the collection + */ +public fun Iterable.sum() : Int { + val iterator = iterator() + var sum : Int = 0 + while (iterator.hasNext()) { + sum += iterator.next() + } + return sum + +} + +/** + * Returns the sum of all elements in the collection + */ +public fun Iterable.sum() : Long { + val iterator = iterator() + var sum : Long = 0 + while (iterator.hasNext()) { + sum += iterator.next() + } + return sum + +} + +/** + * Returns the sum of all elements in the collection + */ +public fun Iterable.sum() : Double { + val iterator = iterator() + var sum : Double = 0.0 + while (iterator.hasNext()) { + sum += iterator.next() + } + return sum + +} + +/** + * Returns the sum of all elements in the collection + */ +public fun Iterable.sum() : Float { + val iterator = iterator() + var sum : Float = 0.0f + while (iterator.hasNext()) { + sum += iterator.next() + } + return sum + +} + +/** + * Returns the sum of all elements in the collection + */ +public fun Array.sum() : Int { + val iterator = iterator() + var sum : Int = 0 + while (iterator.hasNext()) { + sum += iterator.next() + } + return sum + +} + +/** + * Returns the sum of all elements in the collection + */ +public fun IntArray.sum() : Int { + val iterator = iterator() + var sum : Int = 0 + while (iterator.hasNext()) { + sum += iterator.next() + } + return sum + +} + +/** + * Returns the sum of all elements in the collection + */ +public fun Array.sum() : Long { + val iterator = iterator() + var sum : Long = 0 + while (iterator.hasNext()) { + sum += iterator.next() + } + return sum + +} + +/** + * Returns the sum of all elements in the collection + */ +public fun LongArray.sum() : Long { + val iterator = iterator() + var sum : Long = 0 + while (iterator.hasNext()) { + sum += iterator.next() + } + return sum + +} + +/** + * Returns the sum of all elements in the collection + */ +public fun Array.sum() : Int { + val iterator = iterator() + var sum : Int = 0 + while (iterator.hasNext()) { + sum += iterator.next() + } + return sum + +} + +/** + * Returns the sum of all elements in the collection + */ +public fun ByteArray.sum() : Int { + val iterator = iterator() + var sum : Int = 0 + while (iterator.hasNext()) { + sum += iterator.next() + } + return sum + +} + +/** + * Returns the sum of all elements in the collection + */ +public fun Array.sum() : Int { + val iterator = iterator() + var sum : Int = 0 + while (iterator.hasNext()) { + sum += iterator.next() + } + return sum + +} + +/** + * Returns the sum of all elements in the collection + */ +public fun ShortArray.sum() : Int { + val iterator = iterator() + var sum : Int = 0 + while (iterator.hasNext()) { + sum += iterator.next() + } + return sum + +} + +/** + * Returns the sum of all elements in the collection + */ +public fun Array.sum() : Double { + val iterator = iterator() + var sum : Double = 0.0 + while (iterator.hasNext()) { + sum += iterator.next() + } + return sum + +} + +/** + * Returns the sum of all elements in the collection + */ +public fun DoubleArray.sum() : Double { + val iterator = iterator() + var sum : Double = 0.0 + while (iterator.hasNext()) { + sum += iterator.next() + } + return sum + +} + +/** + * Returns the sum of all elements in the collection + */ +public fun Array.sum() : Float { + val iterator = iterator() + var sum : Float = 0.0f + while (iterator.hasNext()) { + sum += iterator.next() + } + return sum + +} + +/** + * Returns the sum of all elements in the collection + */ +public fun FloatArray.sum() : Float { + val iterator = iterator() + var sum : Float = 0.0f + while (iterator.hasNext()) { + sum += iterator.next() + } + return sum + +} + diff --git a/libraries/stdlib/src/generated/_Ordering.kt b/libraries/stdlib/src/generated/_Ordering.kt new file mode 100644 index 00000000000..5a40c899da7 --- /dev/null +++ b/libraries/stdlib/src/generated/_Ordering.kt @@ -0,0 +1,194 @@ +package kotlin + +// +// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt +// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib +// + +import java.util.* + +/** + * Returns a list with elements in reversed order + */ +public fun Array.reverse() : List { + val list = toArrayList() + Collections.reverse(list) + return list + +} + +/** + * Returns a list with elements in reversed order + */ +public fun BooleanArray.reverse() : List { + val list = toArrayList() + Collections.reverse(list) + return list + +} + +/** + * Returns a list with elements in reversed order + */ +public fun ByteArray.reverse() : List { + val list = toArrayList() + Collections.reverse(list) + return list + +} + +/** + * Returns a list with elements in reversed order + */ +public fun CharArray.reverse() : List { + val list = toArrayList() + Collections.reverse(list) + return list + +} + +/** + * Returns a list with elements in reversed order + */ +public fun DoubleArray.reverse() : List { + val list = toArrayList() + Collections.reverse(list) + return list + +} + +/** + * Returns a list with elements in reversed order + */ +public fun FloatArray.reverse() : List { + val list = toArrayList() + Collections.reverse(list) + return list + +} + +/** + * Returns a list with elements in reversed order + */ +public fun IntArray.reverse() : List { + val list = toArrayList() + Collections.reverse(list) + return list + +} + +/** + * Returns a list with elements in reversed order + */ +public fun LongArray.reverse() : List { + val list = toArrayList() + Collections.reverse(list) + return list + +} + +/** + * Returns a list with elements in reversed order + */ +public fun ShortArray.reverse() : List { + val list = toArrayList() + Collections.reverse(list) + return list + +} + +/** + * Returns a list with elements in reversed order + */ +public fun Iterable.reverse() : List { + val list = toArrayList() + Collections.reverse(list) + return list + +} + +/** + * Returns a sorted list of all elements + */ +public fun > Iterable.sort() : List { + val sortedList = toArrayList() + java.util.Collections.sort(sortedList) + return sortedList + +} + +/** + * Returns a list of all elements, sorted by the specified *comparator* + */ +public fun Array.sortBy(comparator : Comparator) : List { + val sortedList = toArrayList() + java.util.Collections.sort(sortedList, comparator) + return sortedList + +} + +/** + * Returns a list of all elements, sorted by the specified *comparator* + */ +public fun Iterable.sortBy(comparator : Comparator) : List { + val sortedList = toArrayList() + java.util.Collections.sort(sortedList, comparator) + return sortedList + +} + +/** + * Returns a list of all elements, sorted by results of specified *order* function. + */ +public inline fun > Array.sortBy(order: (T) -> R) : List { + val sortedList = toArrayList() + val sortBy: Comparator = comparator {(x: T, y: T) -> order(x).compareTo(order(y))} + java.util.Collections.sort(sortedList, sortBy) + return sortedList + +} + +/** + * Returns a list of all elements, sorted by results of specified *order* function. + */ +public inline fun > Iterable.sortBy(order: (T) -> R) : List { + val sortedList = toArrayList() + val sortBy: Comparator = comparator {(x: T, y: T) -> order(x).compareTo(order(y))} + java.util.Collections.sort(sortedList, sortBy) + return sortedList + +} + +/** + * Returns a sorted list of all elements + */ +public fun > Iterable.sortDescending() : List { + val sortedList = toArrayList() + val sortBy: Comparator = comparator {(x: T, y: T) -> -x.compareTo(y)} + java.util.Collections.sort(sortedList, sortBy) + return sortedList + +} + +/** + * Returns a list of all elements, sorted by results of specified *order* function. + */ +public inline fun > Array.sortDescendingBy(order: (T) -> R) : List { + val sortedList = toArrayList() + val sortBy: Comparator = comparator {(x: T, y: T) -> -order(x).compareTo(order(y))} + java.util.Collections.sort(sortedList, sortBy) + return sortedList + +} + +/** + * Returns a list of all elements, sorted by results of specified *order* function. + */ +public inline fun > Iterable.sortDescendingBy(order: (T) -> R) : List { + val sortedList = toArrayList() + val sortBy: Comparator = comparator {(x: T, y: T) -> -order(x).compareTo(order(y))} + java.util.Collections.sort(sortedList, sortBy) + return sortedList + +} + diff --git a/libraries/stdlib/src/generated/_ShortArrays.kt b/libraries/stdlib/src/generated/_ShortArrays.kt deleted file mode 100644 index e647ecdb3b6..00000000000 --- a/libraries/stdlib/src/generated/_ShortArrays.kt +++ /dev/null @@ -1,482 +0,0 @@ -package kotlin - -// -// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt -// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib -// - -import java.util.* - -/** - * Returns *true* if all elements match the given *predicate* - */ -public inline fun ShortArray.all(predicate: (Short) -> Boolean) : Boolean { - for (element in this) if (!predicate(element)) return false - return true -} - -/** - * Returns *true* if any elements match the given *predicate* - */ -public inline fun ShortArray.any(predicate: (Short) -> Boolean) : Boolean { - for (element in this) if (predicate(element)) return true - return false -} - -/** - * Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied - * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will - * a special *truncated* separator (which defaults to "..." - */ -public fun ShortArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit { - buffer.append(prefix) - var count = 0 - for (element in this) { - if (++count > 1) buffer.append(separator) - if (limit < 0 || count <= limit) { - val text = if (element == null) "null" else element.toString() - buffer.append(text) - } else break - } - if (limit >= 0 && count > limit) buffer.append(truncated) - buffer.append(postfix) -} - -/** - * Returns the number of elements which match the given *predicate* - */ -public inline fun ShortArray.count(predicate: (Short) -> Boolean) : Int { - var count = 0 - for (element in this) if (predicate(element)) count++ - return count -} - -/** - * Returns a list containing everything but the first *n* elements - */ -public fun ShortArray.drop(n: Int) : List { - return dropWhile(countTo(n)) -} - -/** - * Returns a list containing the everything but the first elements that satisfy the given *predicate* - */ -public inline fun ShortArray.dropWhile(predicate: (Short) -> Boolean) : List { - return dropWhileTo(ArrayList(), predicate) -} - -/** - * Returns a list containing the everything but the first elements that satisfy the given *predicate* - */ -public inline fun > ShortArray.dropWhileTo(result: L, predicate: (Short) -> Boolean) : L { - var start = true - for (element in this) { - if (start && predicate(element)) { - // ignore - } else { - start = false - result.add(element) - } - } - return result -} - -/** - * Returns a list containing all elements which match the given *predicate* - */ -public inline fun ShortArray.filter(predicate: (Short) -> Boolean) : List { - return filterTo(ArrayList(), predicate) -} - -/** - * Returns a list containing all elements which do not match the given *predicate* - */ -public inline fun ShortArray.filterNot(predicate: (Short) -> Boolean) : List { - return filterNotTo(ArrayList(), predicate) -} - -/** - * Returns a list containing all elements which do not match the given *predicate* - */ -public inline fun > ShortArray.filterNotTo(result: C, predicate: (Short) -> Boolean) : C { - for (element in this) if (!predicate(element)) result.add(element) - return result -} - -/** - * Filters all elements which match the given predicate into the given list - */ -public inline fun > ShortArray.filterTo(result: C, predicate: (Short) -> Boolean) : C { - for (element in this) if (predicate(element)) result.add(element) - return result -} - -/** - * Returns the first element which matches the given *predicate* or *null* if none matched - */ -public inline fun ShortArray.find(predicate: (Short) -> Boolean) : Short? { - for (element in this) if (predicate(element)) return element - return null -} - -/** - * Returns the result of transforming each element to one or more values which are concatenated together into a single list - */ -public inline fun ShortArray.flatMap(transform: (Short)-> Iterable) : List { - return flatMapTo(ArrayList(), transform) -} - -/** - * Returns the result of transforming each element to one or more values which are concatenated together into a single collection - */ -public inline fun > ShortArray.flatMapTo(result: C, transform: (Short) -> Iterable) : C { - for (element in this) { - val list = transform(element) - for (r in list) result.add(r) - } - return result -} - -/** - * Folds all elements from from left to right with the *initial* value to perform the operation on sequential pairs of elements - */ -public inline fun ShortArray.fold(initial: R, operation: (R, Short) -> R) : R { - var answer = initial - for (element in this) answer = operation(answer, element) - return answer -} - -/** - * Folds all elements from right to left with the *initial* value to perform the operation on sequential pairs of elements - */ -public inline fun ShortArray.foldRight(initial: R, operation: (Short, R) -> R) : R { - var r = initial - var index = size - 1 - - while (index >= 0) { - r = operation(get(index--), r) - } - - return r -} - -/** - * Performs the given *operation* on each element - */ -public inline fun ShortArray.forEach(operation: (Short) -> Unit) : Unit { - for (element in this) operation(element) -} - -/** - * Groups the elements in the collection into a new [[Map]] using the supplied *toKey* function to calculate the key to group the elements by - */ -public inline fun ShortArray.groupBy(toKey: (Short) -> K) : Map> { - return groupByTo(HashMap>(), toKey) -} - -public inline fun ShortArray.groupByTo(result: MutableMap>, toKey: (Short) -> K) : Map> { - for (element in this) { - val key = toKey(element) - val list = result.getOrPut(key) { ArrayList() } - list.add(element) - } - return result -} - -/** - * Returns first index of item, or -1 if the array does not contain item - */ -public fun ShortArray.indexOf(item: Short) : Int { - for (i in indices) { - if (item == this[i]) { - return i - } - } - return -1 -} - -/** - * Returns true if the array is empty - */ -public fun ShortArray.isEmpty() : Boolean { - return size == 0 -} - -/** - * Returns true if the array is empty - */ -public fun ShortArray.isNotEmpty() : Boolean { - return !isEmpty() -} - -/** - * Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied. - * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will - * a special *truncated* separator (which defaults to "..." - */ -public fun ShortArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String { - val buffer = StringBuilder() - appendString(buffer, separator, prefix, postfix, limit, truncated) - return buffer.toString() -} - -/** - * Returns a new List containing the results of applying the given *transform* function to each element in this collection - */ -public inline fun ShortArray.map(transform : (Short) -> R) : List { - return mapTo(ArrayList(), transform) -} - -/** - * Transforms each element of this collection with the given *transform* function and - * adds each return value to the given *results* collection - */ -public inline fun > ShortArray.mapTo(result: C, transform : (Short) -> R) : C { - for (item in this) - result.add(transform(item)) - return result -} - -/** - * Returns the largest element or null if there are no elements - */ -public fun ShortArray.max() : Short? { - if (isEmpty()) return null - - var max = this[0] - for (i in 1..lastIndex) { - val e = this[i] - if (max < e) max = e - } - return max -} - -/** - * Returns the first element yielding the largest value of the given function or null if there are no elements - */ -public inline fun > ShortArray.maxBy(f: (Short) -> R) : Short? { - if (isEmpty()) return null - - var maxElem = this[0] - var maxValue = f(maxElem) - for (i in 1..lastIndex) { - val e = this[i] - val v = f(e) - if (maxValue < v) { - maxElem = e - maxValue = v - } - } - return maxElem -} - -/** - * Returns the smallest element or null if there are no elements - */ -public fun ShortArray.min() : Short? { - if (isEmpty()) return null - - var min = this[0] - for (i in 1..lastIndex) { - val e = this[i] - if (min > e) min = e - } - return min -} - -/** - * Returns the first element yielding the smallest value of the given function or null if there are no elements - */ -public inline fun > ShortArray.minBy(f: (Short) -> R) : Short? { - if (size == 0) return null - - var minElem = this[0] - var minValue = f(minElem) - for (i in 1..lastIndex) { - val e = this[i] - val v = f(e) - if (minValue > v) { - minElem = e - minValue = v - } - } - return minElem -} - -/** - * Partitions this collection into a pair of collections - */ -public inline fun ShortArray.partition(predicate: (Short) -> Boolean) : Pair, List> { - val first = ArrayList() - val second = ArrayList() - for (element in this) { - if (predicate(element)) { - first.add(element) - } else { - second.add(element) - } - } - return Pair(first, second) -} - -/** - * Creates an [[Iterator]] which iterates over this iterator then the following collection - */ -public fun ShortArray.plus(collection: Iterable) : List { - return plus(collection.iterator()) -} - -/** - * Creates an [[Iterator]] which iterates over this iterator then the given element at the end - */ -public fun ShortArray.plus(element: Short) : List { - val answer = ArrayList() - toCollection(answer) - answer.add(element) - return answer -} - -/** - * Creates an [[Iterator]] which iterates over this iterator then the following iterator - */ -public fun ShortArray.plus(iterator: Iterator) : List { - val answer = ArrayList() - toCollection(answer) - for (element in iterator) { - answer.add(element) - } - return answer -} - -/** - * Applies binary operation to all elements of iterable, going from left to right. - * Similar to fold function, but uses the first element as initial value - */ -public inline fun ShortArray.reduce(operation: (Short, Short) -> Short) : Short { - val iterator = this.iterator() - if (!iterator.hasNext()) { - throw UnsupportedOperationException("Empty iterable can't be reduced") - } - - var result: Short = iterator.next() //compiler doesn't understand that result will initialized anyway - while (iterator.hasNext()) { - result = operation(result, iterator.next()) - } - - return result -} - -/** - * Applies binary operation to all elements of iterable, going from right to left. - * Similar to foldRight function, but uses the last element as initial value - */ -public inline fun ShortArray.reduceRight(operation: (Short, Short) -> Short) : Short { - var index = size - 1 - if (index < 0) { - throw UnsupportedOperationException("Empty iterable can't be reduced") - } - - var r = get(index--) - while (index >= 0) { - r = operation(get(index--), r) - } - - return r -} - -/** - * Reverses the order the elements into a list - */ -public fun ShortArray.reverse() : List { - val list = toCollection(ArrayList()) - Collections.reverse(list) - return list -} - -/** - * Copies all elements into a [[List]] and sorts it by value of compare_function(element) - * E.g. arrayList("two" to 2, "one" to 1).sortBy({it.second}) returns list sorted by second element of pair - */ -public inline fun > ShortArray.sortBy(f: (Short) -> R) : List { - val sortedList = toCollection(ArrayList()) - val sortBy: Comparator = comparator {(x: Short, y: Short) -> - val xr = f(x) - val yr = f(y) - xr.compareTo(yr) - } - java.util.Collections.sort(sortedList, sortBy) - return sortedList -} - -/** - * Returns a list containing the first *n* elements - */ -public fun ShortArray.take(n: Int) : List { - return takeWhile(countTo(n)) -} - -/** - * Returns a list containing the first elements that satisfy the given *predicate* - */ -public inline fun ShortArray.takeWhile(predicate: (Short) -> Boolean) : List { - return takeWhileTo(ArrayList(), predicate) -} - -/** - * Returns a list containing the first elements that satisfy the given *predicate* - */ -public inline fun > ShortArray.takeWhileTo(result: C, predicate: (Short) -> Boolean) : C { - for (element in this) if (predicate(element)) result.add(element) else break - return result -} - -/** - * Copies all elements into the given collection - */ -public fun > ShortArray.toCollection(result: C) : C { - for (element in this) result.add(element) - return result -} - -/** - * Copies all elements into a [[LinkedList]] - */ -public fun ShortArray.toLinkedList() : LinkedList { - return toCollection(LinkedList()) -} - -/** - * Copies all elements into a [[List]] - */ -public fun ShortArray.toList() : List { - return toCollection(ArrayList()) -} - -/** - * Copies all elements into a [[Set]] - */ -public fun ShortArray.toSet() : Set { - return toCollection(LinkedHashSet()) -} - -/** - * Copies all elements into a [[SortedSet]] - */ -public fun ShortArray.toSortedSet() : SortedSet { - return toCollection(TreeSet()) -} - -/** - * Returns an iterator of Pairs(index, data) - */ -public fun ShortArray.withIndices() : Iterator> { - return IndexIterator(iterator()) -} - -/** - * Sums up the elements - */ -public fun ShortArray.sum() : Int { - return fold(0, {a,b -> a+b}) -} - diff --git a/libraries/stdlib/src/generated/_Snapshots.kt b/libraries/stdlib/src/generated/_Snapshots.kt new file mode 100644 index 00000000000..1ba2e79513c --- /dev/null +++ b/libraries/stdlib/src/generated/_Snapshots.kt @@ -0,0 +1,720 @@ +package kotlin + +// +// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt +// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib +// + +import java.util.* + +/** + * Returns an ArrayList of all elements + */ +public fun Array.toArrayList() : ArrayList { + val list = ArrayList(size) + for (item in this) list.add(item) + return list + +} + +/** + * Returns an ArrayList of all elements + */ +public fun BooleanArray.toArrayList() : ArrayList { + val list = ArrayList(size) + for (item in this) list.add(item) + return list + +} + +/** + * Returns an ArrayList of all elements + */ +public fun ByteArray.toArrayList() : ArrayList { + val list = ArrayList(size) + for (item in this) list.add(item) + return list + +} + +/** + * Returns an ArrayList of all elements + */ +public fun CharArray.toArrayList() : ArrayList { + val list = ArrayList(size) + for (item in this) list.add(item) + return list + +} + +/** + * Returns an ArrayList of all elements + */ +public fun DoubleArray.toArrayList() : ArrayList { + val list = ArrayList(size) + for (item in this) list.add(item) + return list + +} + +/** + * Returns an ArrayList of all elements + */ +public fun FloatArray.toArrayList() : ArrayList { + val list = ArrayList(size) + for (item in this) list.add(item) + return list + +} + +/** + * Returns an ArrayList of all elements + */ +public fun IntArray.toArrayList() : ArrayList { + val list = ArrayList(size) + for (item in this) list.add(item) + return list + +} + +/** + * Returns an ArrayList of all elements + */ +public fun LongArray.toArrayList() : ArrayList { + val list = ArrayList(size) + for (item in this) list.add(item) + return list + +} + +/** + * Returns an ArrayList of all elements + */ +public fun ShortArray.toArrayList() : ArrayList { + val list = ArrayList(size) + for (item in this) list.add(item) + return list + +} + +/** + * Returns an ArrayList of all elements + */ +public fun Iterable.toArrayList() : ArrayList { + return toCollection(ArrayList()) +} + +/** + * Returns an ArrayList of all elements + */ +public fun Stream.toArrayList() : ArrayList { + return toCollection(ArrayList()) +} + +/** + * Appends all elements to the given *collection* + */ +public fun > Array.toCollection(collection : C) : C { + for (item in this) { + collection.add(item) + } + return collection + +} + +/** + * Appends all elements to the given *collection* + */ +public fun > BooleanArray.toCollection(collection : C) : C { + for (item in this) { + collection.add(item) + } + return collection + +} + +/** + * Appends all elements to the given *collection* + */ +public fun > ByteArray.toCollection(collection : C) : C { + for (item in this) { + collection.add(item) + } + return collection + +} + +/** + * Appends all elements to the given *collection* + */ +public fun > CharArray.toCollection(collection : C) : C { + for (item in this) { + collection.add(item) + } + return collection + +} + +/** + * Appends all elements to the given *collection* + */ +public fun > DoubleArray.toCollection(collection : C) : C { + for (item in this) { + collection.add(item) + } + return collection + +} + +/** + * Appends all elements to the given *collection* + */ +public fun > FloatArray.toCollection(collection : C) : C { + for (item in this) { + collection.add(item) + } + return collection + +} + +/** + * Appends all elements to the given *collection* + */ +public fun > IntArray.toCollection(collection : C) : C { + for (item in this) { + collection.add(item) + } + return collection + +} + +/** + * Appends all elements to the given *collection* + */ +public fun > LongArray.toCollection(collection : C) : C { + for (item in this) { + collection.add(item) + } + return collection + +} + +/** + * Appends all elements to the given *collection* + */ +public fun > ShortArray.toCollection(collection : C) : C { + for (item in this) { + collection.add(item) + } + return collection + +} + +/** + * Appends all elements to the given *collection* + */ +public fun > Iterable.toCollection(collection : C) : C { + for (item in this) { + collection.add(item) + } + return collection + +} + +/** + * Appends all elements to the given *collection* + */ +public fun > Stream.toCollection(collection : C) : C { + for (item in this) { + collection.add(item) + } + return collection + +} + +/** + * Returns a HashSet of all elements + */ +public fun Array.toHashSet() : HashSet { + return toCollection(HashSet()) +} + +/** + * Returns a HashSet of all elements + */ +public fun BooleanArray.toHashSet() : HashSet { + return toCollection(HashSet()) +} + +/** + * Returns a HashSet of all elements + */ +public fun ByteArray.toHashSet() : HashSet { + return toCollection(HashSet()) +} + +/** + * Returns a HashSet of all elements + */ +public fun CharArray.toHashSet() : HashSet { + return toCollection(HashSet()) +} + +/** + * Returns a HashSet of all elements + */ +public fun DoubleArray.toHashSet() : HashSet { + return toCollection(HashSet()) +} + +/** + * Returns a HashSet of all elements + */ +public fun FloatArray.toHashSet() : HashSet { + return toCollection(HashSet()) +} + +/** + * Returns a HashSet of all elements + */ +public fun IntArray.toHashSet() : HashSet { + return toCollection(HashSet()) +} + +/** + * Returns a HashSet of all elements + */ +public fun LongArray.toHashSet() : HashSet { + return toCollection(HashSet()) +} + +/** + * Returns a HashSet of all elements + */ +public fun ShortArray.toHashSet() : HashSet { + return toCollection(HashSet()) +} + +/** + * Returns a HashSet of all elements + */ +public fun Iterable.toHashSet() : HashSet { + return toCollection(HashSet()) +} + +/** + * Returns a HashSet of all elements + */ +public fun Stream.toHashSet() : HashSet { + return toCollection(HashSet()) +} + +/** + * Returns a LinkedList containing all elements + */ +public fun Array.toLinkedList() : LinkedList { + return toCollection(LinkedList()) +} + +/** + * Returns a LinkedList containing all elements + */ +public fun BooleanArray.toLinkedList() : LinkedList { + return toCollection(LinkedList()) +} + +/** + * Returns a LinkedList containing all elements + */ +public fun ByteArray.toLinkedList() : LinkedList { + return toCollection(LinkedList()) +} + +/** + * Returns a LinkedList containing all elements + */ +public fun CharArray.toLinkedList() : LinkedList { + return toCollection(LinkedList()) +} + +/** + * Returns a LinkedList containing all elements + */ +public fun DoubleArray.toLinkedList() : LinkedList { + return toCollection(LinkedList()) +} + +/** + * Returns a LinkedList containing all elements + */ +public fun FloatArray.toLinkedList() : LinkedList { + return toCollection(LinkedList()) +} + +/** + * Returns a LinkedList containing all elements + */ +public fun IntArray.toLinkedList() : LinkedList { + return toCollection(LinkedList()) +} + +/** + * Returns a LinkedList containing all elements + */ +public fun LongArray.toLinkedList() : LinkedList { + return toCollection(LinkedList()) +} + +/** + * Returns a LinkedList containing all elements + */ +public fun ShortArray.toLinkedList() : LinkedList { + return toCollection(LinkedList()) +} + +/** + * Returns a LinkedList containing all elements + */ +public fun Iterable.toLinkedList() : LinkedList { + return toCollection(LinkedList()) +} + +/** + * Returns a LinkedList containing all elements + */ +public fun Stream.toLinkedList() : LinkedList { + return toCollection(LinkedList()) +} + +/** + * Returns a List containing all elements + */ +public fun Array.toList() : List { + return toCollection(ArrayList()) +} + +/** + * Returns a List containing all elements + */ +public fun BooleanArray.toList() : List { + val list = ArrayList(size) + for (item in this) list.add(item) + return list + +} + +/** + * Returns a List containing all elements + */ +public fun ByteArray.toList() : List { + val list = ArrayList(size) + for (item in this) list.add(item) + return list + +} + +/** + * Returns a List containing all elements + */ +public fun CharArray.toList() : List { + val list = ArrayList(size) + for (item in this) list.add(item) + return list + +} + +/** + * Returns a List containing all elements + */ +public fun DoubleArray.toList() : List { + val list = ArrayList(size) + for (item in this) list.add(item) + return list + +} + +/** + * Returns a List containing all elements + */ +public fun FloatArray.toList() : List { + val list = ArrayList(size) + for (item in this) list.add(item) + return list + +} + +/** + * Returns a List containing all elements + */ +public fun IntArray.toList() : List { + val list = ArrayList(size) + for (item in this) list.add(item) + return list + +} + +/** + * Returns a List containing all elements + */ +public fun LongArray.toList() : List { + val list = ArrayList(size) + for (item in this) list.add(item) + return list + +} + +/** + * Returns a List containing all elements + */ +public fun ShortArray.toList() : List { + val list = ArrayList(size) + for (item in this) list.add(item) + return list + +} + +/** + * Returns a List containing all elements + */ +public fun Iterable.toList() : List { + return toCollection(ArrayList()) +} + +/** + * Returns a List containing all elements + */ +public fun Stream.toList() : List { + return toCollection(ArrayList()) +} + +/** + * Returns a Set of all elements + */ +public fun Array.toSet() : Set { + return toCollection(LinkedHashSet()) +} + +/** + * Returns a Set of all elements + */ +public fun BooleanArray.toSet() : Set { + return toCollection(LinkedHashSet()) +} + +/** + * Returns a Set of all elements + */ +public fun ByteArray.toSet() : Set { + return toCollection(LinkedHashSet()) +} + +/** + * Returns a Set of all elements + */ +public fun CharArray.toSet() : Set { + return toCollection(LinkedHashSet()) +} + +/** + * Returns a Set of all elements + */ +public fun DoubleArray.toSet() : Set { + return toCollection(LinkedHashSet()) +} + +/** + * Returns a Set of all elements + */ +public fun FloatArray.toSet() : Set { + return toCollection(LinkedHashSet()) +} + +/** + * Returns a Set of all elements + */ +public fun IntArray.toSet() : Set { + return toCollection(LinkedHashSet()) +} + +/** + * Returns a Set of all elements + */ +public fun LongArray.toSet() : Set { + return toCollection(LinkedHashSet()) +} + +/** + * Returns a Set of all elements + */ +public fun ShortArray.toSet() : Set { + return toCollection(LinkedHashSet()) +} + +/** + * Returns a Set of all elements + */ +public fun Iterable.toSet() : Set { + return toCollection(LinkedHashSet()) +} + +/** + * Returns a Set of all elements + */ +public fun Stream.toSet() : Set { + return toCollection(LinkedHashSet()) +} + +/** + * Returns a sorted list of all elements + */ +public fun > Array.toSortedList() : List { + return toArrayList().sort() +} + +/** + * Returns a sorted list of all elements + */ +public fun BooleanArray.toSortedList() : List { + return toArrayList().sort() +} + +/** + * Returns a sorted list of all elements + */ +public fun ByteArray.toSortedList() : List { + return toArrayList().sort() +} + +/** + * Returns a sorted list of all elements + */ +public fun CharArray.toSortedList() : List { + return toArrayList().sort() +} + +/** + * Returns a sorted list of all elements + */ +public fun DoubleArray.toSortedList() : List { + return toArrayList().sort() +} + +/** + * Returns a sorted list of all elements + */ +public fun FloatArray.toSortedList() : List { + return toArrayList().sort() +} + +/** + * Returns a sorted list of all elements + */ +public fun IntArray.toSortedList() : List { + return toArrayList().sort() +} + +/** + * Returns a sorted list of all elements + */ +public fun LongArray.toSortedList() : List { + return toArrayList().sort() +} + +/** + * Returns a sorted list of all elements + */ +public fun ShortArray.toSortedList() : List { + return toArrayList().sort() +} + +/** + * Returns a sorted list of all elements + */ +public fun > Iterable.toSortedList() : List { + return sort() +} + +/** + * Returns a sorted list of all elements + */ +public fun > Stream.toSortedList() : List { + return toArrayList().sort() +} + +/** + * Returns a SortedSet of all elements + */ +public fun Array.toSortedSet() : SortedSet { + return toCollection(TreeSet()) +} + +/** + * Returns a SortedSet of all elements + */ +public fun BooleanArray.toSortedSet() : SortedSet { + return toCollection(TreeSet()) +} + +/** + * Returns a SortedSet of all elements + */ +public fun ByteArray.toSortedSet() : SortedSet { + return toCollection(TreeSet()) +} + +/** + * Returns a SortedSet of all elements + */ +public fun CharArray.toSortedSet() : SortedSet { + return toCollection(TreeSet()) +} + +/** + * Returns a SortedSet of all elements + */ +public fun DoubleArray.toSortedSet() : SortedSet { + return toCollection(TreeSet()) +} + +/** + * Returns a SortedSet of all elements + */ +public fun FloatArray.toSortedSet() : SortedSet { + return toCollection(TreeSet()) +} + +/** + * Returns a SortedSet of all elements + */ +public fun IntArray.toSortedSet() : SortedSet { + return toCollection(TreeSet()) +} + +/** + * Returns a SortedSet of all elements + */ +public fun LongArray.toSortedSet() : SortedSet { + return toCollection(TreeSet()) +} + +/** + * Returns a SortedSet of all elements + */ +public fun ShortArray.toSortedSet() : SortedSet { + return toCollection(TreeSet()) +} + +/** + * Returns a SortedSet of all elements + */ +public fun Iterable.toSortedSet() : SortedSet { + return toCollection(TreeSet()) +} + +/** + * Returns a SortedSet of all elements + */ +public fun Stream.toSortedSet() : SortedSet { + return toCollection(TreeSet()) +} + diff --git a/libraries/stdlib/src/generated/_SpecialJVM.kt b/libraries/stdlib/src/generated/_SpecialJVM.kt new file mode 100644 index 00000000000..0e64af296fa --- /dev/null +++ b/libraries/stdlib/src/generated/_SpecialJVM.kt @@ -0,0 +1,361 @@ +package kotlin + +// +// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt +// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib +// + +import java.util.* + +/** + * Searches array or range of array for provided element index using binary search algorithm. Array is expected to be sorted. + */ +public fun Array.binarySearch(element: T, fromIndex: Int = 0, toIndex: Int = size - 1) : Int { + return Arrays.binarySearch(this, fromIndex, toIndex, element) +} + +/** + * Searches array or range of array for provided element index using binary search algorithm. Array is expected to be sorted. + */ +public fun ByteArray.binarySearch(element: Byte, fromIndex: Int = 0, toIndex: Int = size - 1) : Int { + return Arrays.binarySearch(this, fromIndex, toIndex, element) +} + +/** + * Searches array or range of array for provided element index using binary search algorithm. Array is expected to be sorted. + */ +public fun CharArray.binarySearch(element: Char, fromIndex: Int = 0, toIndex: Int = size - 1) : Int { + return Arrays.binarySearch(this, fromIndex, toIndex, element) +} + +/** + * Searches array or range of array for provided element index using binary search algorithm. Array is expected to be sorted. + */ +public fun DoubleArray.binarySearch(element: Double, fromIndex: Int = 0, toIndex: Int = size - 1) : Int { + return Arrays.binarySearch(this, fromIndex, toIndex, element) +} + +/** + * Searches array or range of array for provided element index using binary search algorithm. Array is expected to be sorted. + */ +public fun FloatArray.binarySearch(element: Float, fromIndex: Int = 0, toIndex: Int = size - 1) : Int { + return Arrays.binarySearch(this, fromIndex, toIndex, element) +} + +/** + * Searches array or range of array for provided element index using binary search algorithm. Array is expected to be sorted. + */ +public fun IntArray.binarySearch(element: Int, fromIndex: Int = 0, toIndex: Int = size - 1) : Int { + return Arrays.binarySearch(this, fromIndex, toIndex, element) +} + +/** + * Searches array or range of array for provided element index using binary search algorithm. Array is expected to be sorted. + */ +public fun LongArray.binarySearch(element: Long, fromIndex: Int = 0, toIndex: Int = size - 1) : Int { + return Arrays.binarySearch(this, fromIndex, toIndex, element) +} + +/** + * Searches array or range of array for provided element index using binary search algorithm. Array is expected to be sorted. + */ +public fun ShortArray.binarySearch(element: Short, fromIndex: Int = 0, toIndex: Int = size - 1) : Int { + return Arrays.binarySearch(this, fromIndex, toIndex, element) +} + +/** + * Returns new array which is a copy of the riginal array + */ +public fun Array.copyOf(newSize: Int = size) : Array { + return Arrays.copyOf(this, newSize) as Array +} + +/** + * Returns new array which is a copy of the riginal array + */ +public fun BooleanArray.copyOf(newSize: Int = size) : BooleanArray { + return Arrays.copyOf(this, newSize) +} + +/** + * Returns new array which is a copy of the riginal array + */ +public fun ByteArray.copyOf(newSize: Int = size) : ByteArray { + return Arrays.copyOf(this, newSize) +} + +/** + * Returns new array which is a copy of the riginal array + */ +public fun CharArray.copyOf(newSize: Int = size) : CharArray { + return Arrays.copyOf(this, newSize) +} + +/** + * Returns new array which is a copy of the riginal array + */ +public fun DoubleArray.copyOf(newSize: Int = size) : DoubleArray { + return Arrays.copyOf(this, newSize) +} + +/** + * Returns new array which is a copy of the riginal array + */ +public fun FloatArray.copyOf(newSize: Int = size) : FloatArray { + return Arrays.copyOf(this, newSize) +} + +/** + * Returns new array which is a copy of the riginal array + */ +public fun IntArray.copyOf(newSize: Int = size) : IntArray { + return Arrays.copyOf(this, newSize) +} + +/** + * Returns new array which is a copy of the riginal array + */ +public fun LongArray.copyOf(newSize: Int = size) : LongArray { + return Arrays.copyOf(this, newSize) +} + +/** + * Returns new array which is a copy of the riginal array + */ +public fun ShortArray.copyOf(newSize: Int = size) : ShortArray { + return Arrays.copyOf(this, newSize) +} + +/** + * Returns new array which is a copy of range of original array + */ +public fun Array.copyOfRange(from: Int, to: Int) : Array { + return Arrays.copyOfRange(this, from, to) +} + +/** + * Returns new array which is a copy of range of original array + */ +public fun BooleanArray.copyOfRange(from: Int, to: Int) : BooleanArray { + return Arrays.copyOfRange(this, from, to) +} + +/** + * Returns new array which is a copy of range of original array + */ +public fun ByteArray.copyOfRange(from: Int, to: Int) : ByteArray { + return Arrays.copyOfRange(this, from, to) +} + +/** + * Returns new array which is a copy of range of original array + */ +public fun CharArray.copyOfRange(from: Int, to: Int) : CharArray { + return Arrays.copyOfRange(this, from, to) +} + +/** + * Returns new array which is a copy of range of original array + */ +public fun DoubleArray.copyOfRange(from: Int, to: Int) : DoubleArray { + return Arrays.copyOfRange(this, from, to) +} + +/** + * Returns new array which is a copy of range of original array + */ +public fun FloatArray.copyOfRange(from: Int, to: Int) : FloatArray { + return Arrays.copyOfRange(this, from, to) +} + +/** + * Returns new array which is a copy of range of original array + */ +public fun IntArray.copyOfRange(from: Int, to: Int) : IntArray { + return Arrays.copyOfRange(this, from, to) +} + +/** + * Returns new array which is a copy of range of original array + */ +public fun LongArray.copyOfRange(from: Int, to: Int) : LongArray { + return Arrays.copyOfRange(this, from, to) +} + +/** + * Returns new array which is a copy of range of original array + */ +public fun ShortArray.copyOfRange(from: Int, to: Int) : ShortArray { + return Arrays.copyOfRange(this, from, to) +} + +/** + * Fills original array with the provided value + */ +public fun Array.fill(element: T) : Unit { + Arrays.fill(this, element) +} + +/** + * Fills original array with the provided value + */ +public fun BooleanArray.fill(element: Boolean) : Unit { + Arrays.fill(this, element) +} + +/** + * Fills original array with the provided value + */ +public fun ByteArray.fill(element: Byte) : Unit { + Arrays.fill(this, element) +} + +/** + * Fills original array with the provided value + */ +public fun CharArray.fill(element: Char) : Unit { + Arrays.fill(this, element) +} + +/** + * Fills original array with the provided value + */ +public fun DoubleArray.fill(element: Double) : Unit { + Arrays.fill(this, element) +} + +/** + * Fills original array with the provided value + */ +public fun FloatArray.fill(element: Float) : Unit { + Arrays.fill(this, element) +} + +/** + * Fills original array with the provided value + */ +public fun IntArray.fill(element: Int) : Unit { + Arrays.fill(this, element) +} + +/** + * Fills original array with the provided value + */ +public fun LongArray.fill(element: Long) : Unit { + Arrays.fill(this, element) +} + +/** + * Fills original array with the provided value + */ +public fun ShortArray.fill(element: Short) : Unit { + Arrays.fill(this, element) +} + +/** + * Returns a list containing all elements that are instances of specified class + */ +public fun Array.filterIsInstance(klass: Class) : List { + return filterIsInstanceTo(ArrayList(), klass) + +} + +/** + * Returns a list containing all elements that are instances of specified class + */ +public fun Iterable.filterIsInstance(klass: Class) : List { + return filterIsInstanceTo(ArrayList(), klass) + +} + +/** + * Returns a stream containing all elements that are instances of specified class + */ +public fun Stream.filterIsInstance(klass: Class) : Stream { + return FilteringStream(this, true, { klass.isInstance(it) }) + +} + +/** + * Appends all elements that are instances of specified class into the given *collection* + */ +public fun , R: T> Array.filterIsInstanceTo(collection: C, klass: Class) : C { + for (element in this) if (klass.isInstance(element)) collection.add(element as R) + return collection + +} + +/** + * Appends all elements that are instances of specified class into the given *collection* + */ +public fun , R: T> Iterable.filterIsInstanceTo(collection: C, klass: Class) : C { + for (element in this) if (klass.isInstance(element)) collection.add(element as R) + return collection + +} + +/** + * Appends all elements that are instances of specified class into the given *collection* + */ +public fun , R: T> Stream.filterIsInstanceTo(collection: C, klass: Class) : C { + for (element in this) if (klass.isInstance(element)) collection.add(element as R) + return collection + +} + +/** + * Sorts array or range in array inplace + */ +public fun Array.sort(fromIndex : Int = 0, toIndex : Int = size - 1) : Unit { + Arrays.sort(this, fromIndex, toIndex) +} + +/** + * Sorts array or range in array inplace + */ +public fun ByteArray.sort(fromIndex : Int = 0, toIndex : Int = size - 1) : Unit { + Arrays.sort(this, fromIndex, toIndex) +} + +/** + * Sorts array or range in array inplace + */ +public fun CharArray.sort(fromIndex : Int = 0, toIndex : Int = size - 1) : Unit { + Arrays.sort(this, fromIndex, toIndex) +} + +/** + * Sorts array or range in array inplace + */ +public fun DoubleArray.sort(fromIndex : Int = 0, toIndex : Int = size - 1) : Unit { + Arrays.sort(this, fromIndex, toIndex) +} + +/** + * Sorts array or range in array inplace + */ +public fun FloatArray.sort(fromIndex : Int = 0, toIndex : Int = size - 1) : Unit { + Arrays.sort(this, fromIndex, toIndex) +} + +/** + * Sorts array or range in array inplace + */ +public fun IntArray.sort(fromIndex : Int = 0, toIndex : Int = size - 1) : Unit { + Arrays.sort(this, fromIndex, toIndex) +} + +/** + * Sorts array or range in array inplace + */ +public fun LongArray.sort(fromIndex : Int = 0, toIndex : Int = size - 1) : Unit { + Arrays.sort(this, fromIndex, toIndex) +} + +/** + * Sorts array or range in array inplace + */ +public fun ShortArray.sort(fromIndex : Int = 0, toIndex : Int = size - 1) : Unit { + Arrays.sort(this, fromIndex, toIndex) +} + diff --git a/libraries/stdlib/src/generated/_Strings.kt b/libraries/stdlib/src/generated/_Strings.kt new file mode 100644 index 00000000000..14f6820c860 --- /dev/null +++ b/libraries/stdlib/src/generated/_Strings.kt @@ -0,0 +1,361 @@ +package kotlin + +// +// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt +// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib +// + +import java.util.* + +/** + * Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied + * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will + * a special *truncated* separator (which defaults to "..." + */ +public fun Array.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit { + buffer.append(prefix) + var count = 0 + for (element in this) { + if (++count > 1) buffer.append(separator) + if (limit < 0 || count <= limit) { + val text = if (element == null) "null" else element.toString() + buffer.append(text) + } else break + } + if (limit >= 0 && count > limit) buffer.append(truncated) + buffer.append(postfix) + +} + +/** + * Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied + * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will + * a special *truncated* separator (which defaults to "..." + */ +public fun BooleanArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit { + buffer.append(prefix) + var count = 0 + for (element in this) { + if (++count > 1) buffer.append(separator) + if (limit < 0 || count <= limit) { + val text = if (element == null) "null" else element.toString() + buffer.append(text) + } else break + } + if (limit >= 0 && count > limit) buffer.append(truncated) + buffer.append(postfix) + +} + +/** + * Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied + * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will + * a special *truncated* separator (which defaults to "..." + */ +public fun ByteArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit { + buffer.append(prefix) + var count = 0 + for (element in this) { + if (++count > 1) buffer.append(separator) + if (limit < 0 || count <= limit) { + val text = if (element == null) "null" else element.toString() + buffer.append(text) + } else break + } + if (limit >= 0 && count > limit) buffer.append(truncated) + buffer.append(postfix) + +} + +/** + * Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied + * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will + * a special *truncated* separator (which defaults to "..." + */ +public fun CharArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit { + buffer.append(prefix) + var count = 0 + for (element in this) { + if (++count > 1) buffer.append(separator) + if (limit < 0 || count <= limit) { + val text = if (element == null) "null" else element.toString() + buffer.append(text) + } else break + } + if (limit >= 0 && count > limit) buffer.append(truncated) + buffer.append(postfix) + +} + +/** + * Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied + * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will + * a special *truncated* separator (which defaults to "..." + */ +public fun DoubleArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit { + buffer.append(prefix) + var count = 0 + for (element in this) { + if (++count > 1) buffer.append(separator) + if (limit < 0 || count <= limit) { + val text = if (element == null) "null" else element.toString() + buffer.append(text) + } else break + } + if (limit >= 0 && count > limit) buffer.append(truncated) + buffer.append(postfix) + +} + +/** + * Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied + * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will + * a special *truncated* separator (which defaults to "..." + */ +public fun FloatArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit { + buffer.append(prefix) + var count = 0 + for (element in this) { + if (++count > 1) buffer.append(separator) + if (limit < 0 || count <= limit) { + val text = if (element == null) "null" else element.toString() + buffer.append(text) + } else break + } + if (limit >= 0 && count > limit) buffer.append(truncated) + buffer.append(postfix) + +} + +/** + * Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied + * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will + * a special *truncated* separator (which defaults to "..." + */ +public fun IntArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit { + buffer.append(prefix) + var count = 0 + for (element in this) { + if (++count > 1) buffer.append(separator) + if (limit < 0 || count <= limit) { + val text = if (element == null) "null" else element.toString() + buffer.append(text) + } else break + } + if (limit >= 0 && count > limit) buffer.append(truncated) + buffer.append(postfix) + +} + +/** + * Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied + * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will + * a special *truncated* separator (which defaults to "..." + */ +public fun LongArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit { + buffer.append(prefix) + var count = 0 + for (element in this) { + if (++count > 1) buffer.append(separator) + if (limit < 0 || count <= limit) { + val text = if (element == null) "null" else element.toString() + buffer.append(text) + } else break + } + if (limit >= 0 && count > limit) buffer.append(truncated) + buffer.append(postfix) + +} + +/** + * Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied + * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will + * a special *truncated* separator (which defaults to "..." + */ +public fun ShortArray.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit { + buffer.append(prefix) + var count = 0 + for (element in this) { + if (++count > 1) buffer.append(separator) + if (limit < 0 || count <= limit) { + val text = if (element == null) "null" else element.toString() + buffer.append(text) + } else break + } + if (limit >= 0 && count > limit) buffer.append(truncated) + buffer.append(postfix) + +} + +/** + * Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied + * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will + * a special *truncated* separator (which defaults to "..." + */ +public fun Iterable.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit { + buffer.append(prefix) + var count = 0 + for (element in this) { + if (++count > 1) buffer.append(separator) + if (limit < 0 || count <= limit) { + val text = if (element == null) "null" else element.toString() + buffer.append(text) + } else break + } + if (limit >= 0 && count > limit) buffer.append(truncated) + buffer.append(postfix) + +} + +/** + * Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied + * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will + * a special *truncated* separator (which defaults to "..." + */ +public fun Stream.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit { + buffer.append(prefix) + var count = 0 + for (element in this) { + if (++count > 1) buffer.append(separator) + if (limit < 0 || count <= limit) { + val text = if (element == null) "null" else element.toString() + buffer.append(text) + } else break + } + if (limit >= 0 && count > limit) buffer.append(truncated) + buffer.append(postfix) + +} + +/** + * Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied. + * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will + * a special *truncated* separator (which defaults to "..." + */ +public fun Array.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String { + val buffer = StringBuilder() + appendString(buffer, separator, prefix, postfix, limit, truncated) + return buffer.toString() + +} + +/** + * Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied. + * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will + * a special *truncated* separator (which defaults to "..." + */ +public fun BooleanArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String { + val buffer = StringBuilder() + appendString(buffer, separator, prefix, postfix, limit, truncated) + return buffer.toString() + +} + +/** + * Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied. + * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will + * a special *truncated* separator (which defaults to "..." + */ +public fun ByteArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String { + val buffer = StringBuilder() + appendString(buffer, separator, prefix, postfix, limit, truncated) + return buffer.toString() + +} + +/** + * Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied. + * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will + * a special *truncated* separator (which defaults to "..." + */ +public fun CharArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String { + val buffer = StringBuilder() + appendString(buffer, separator, prefix, postfix, limit, truncated) + return buffer.toString() + +} + +/** + * Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied. + * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will + * a special *truncated* separator (which defaults to "..." + */ +public fun DoubleArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String { + val buffer = StringBuilder() + appendString(buffer, separator, prefix, postfix, limit, truncated) + return buffer.toString() + +} + +/** + * Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied. + * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will + * a special *truncated* separator (which defaults to "..." + */ +public fun FloatArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String { + val buffer = StringBuilder() + appendString(buffer, separator, prefix, postfix, limit, truncated) + return buffer.toString() + +} + +/** + * Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied. + * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will + * a special *truncated* separator (which defaults to "..." + */ +public fun IntArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String { + val buffer = StringBuilder() + appendString(buffer, separator, prefix, postfix, limit, truncated) + return buffer.toString() + +} + +/** + * Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied. + * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will + * a special *truncated* separator (which defaults to "..." + */ +public fun LongArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String { + val buffer = StringBuilder() + appendString(buffer, separator, prefix, postfix, limit, truncated) + return buffer.toString() + +} + +/** + * Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied. + * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will + * a special *truncated* separator (which defaults to "..." + */ +public fun ShortArray.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String { + val buffer = StringBuilder() + appendString(buffer, separator, prefix, postfix, limit, truncated) + return buffer.toString() + +} + +/** + * Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied. + * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will + * a special *truncated* separator (which defaults to "..." + */ +public fun Iterable.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String { + val buffer = StringBuilder() + appendString(buffer, separator, prefix, postfix, limit, truncated) + return buffer.toString() + +} + +/** + * Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied. + * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will + * a special *truncated* separator (which defaults to "..." + */ +public fun Stream.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String { + val buffer = StringBuilder() + appendString(buffer, separator, prefix, postfix, limit, truncated) + return buffer.toString() + +} + diff --git a/libraries/stdlib/src/kotlin/ArraysJVM.kt b/libraries/stdlib/src/kotlin/ArraysJVM.kt deleted file mode 100644 index 235576a2241..00000000000 --- a/libraries/stdlib/src/kotlin/ArraysJVM.kt +++ /dev/null @@ -1,111 +0,0 @@ -package kotlin - -import java.io.ByteArrayInputStream -import java.nio.charset.Charset -import java.util.Arrays -import kotlin.jvm.internal.Intrinsic - -// Array "constructor" -[Intrinsic("kotlin.arrays.array")] public fun array(vararg t : T) : Array = t - -// "constructors" for primitive types array -[Intrinsic("kotlin.arrays.array")] public fun doubleArray(vararg content : Double) : DoubleArray = content - -[Intrinsic("kotlin.arrays.array")] public fun floatArray(vararg content : Float) : FloatArray = content - -[Intrinsic("kotlin.arrays.array")] public fun longArray(vararg content : Long) : LongArray = content - -[Intrinsic("kotlin.arrays.array")] public fun intArray(vararg content : Int) : IntArray = content - -[Intrinsic("kotlin.arrays.array")] public fun charArray(vararg content : Char) : CharArray = content - -[Intrinsic("kotlin.arrays.array")] public fun shortArray(vararg content : Short) : ShortArray = content - -[Intrinsic("kotlin.arrays.array")] public fun byteArray(vararg content : Byte) : ByteArray = content - -[Intrinsic("kotlin.arrays.array")] public fun booleanArray(vararg content : Boolean) : BooleanArray = content - -public fun ByteArray.binarySearch(key: Byte) : Int = Arrays.binarySearch(this, key) -public fun ShortArray.binarySearch(key: Short) : Int = Arrays.binarySearch(this, key) -public fun IntArray.binarySearch(key: Int) : Int = Arrays.binarySearch(this, key) -public fun LongArray.binarySearch(key: Long) : Int = Arrays.binarySearch(this, key) -public fun FloatArray.binarySearch(key: Float) : Int = Arrays.binarySearch(this, key) -public fun DoubleArray.binarySearch(key: Double) : Int = Arrays.binarySearch(this, key) -public fun CharArray.binarySearch(key: Char) : Int = Arrays.binarySearch(this, key) - -public fun ByteArray.binarySearch(fromIndex: Int, toIndex: Int, key: Byte) : Int = Arrays.binarySearch(this, fromIndex, toIndex, key) -public fun ShortArray.binarySearch(fromIndex: Int, toIndex: Int, key: Short) : Int = Arrays.binarySearch(this, fromIndex, toIndex, key) -public fun IntArray.binarySearch(fromIndex: Int, toIndex: Int, key: Int) : Int = Arrays.binarySearch(this, fromIndex, toIndex, key) -public fun LongArray.binarySearch(fromIndex: Int, toIndex: Int, key: Long) : Int = Arrays.binarySearch(this, fromIndex, toIndex, key) -public fun FloatArray.binarySearch(fromIndex: Int, toIndex: Int, key: Float) : Int = Arrays.binarySearch(this, fromIndex, toIndex, key) -public fun DoubleArray.binarySearch(fromIndex: Int, toIndex: Int, key: Double) : Int = Arrays.binarySearch(this, fromIndex, toIndex, key) -public fun CharArray.binarySearch(fromIndex: Int, toIndex: Int, key: Char) : Int = Arrays.binarySearch(this, fromIndex, toIndex, key) - -/* -public inline fun Array.binarySearch(key: T, comparator: public fun(T,T):Int) = Arrays.binarySearch(this, key, object: java.util.Comparator { - public override fun compare(a: T, b: T) = comparator(a, b) - - public override fun equals(obj: Any?) = obj.identityEquals(this) -}) -*/ -public fun BooleanArray.fill(value: Boolean) : Unit = Arrays.fill(this, value) -public fun ByteArray.fill(value: Byte) : Unit = Arrays.fill(this, value) -public fun ShortArray.fill(value: Short) : Unit = Arrays.fill(this, value) -public fun IntArray.fill(value: Int) : Unit = Arrays.fill(this, value) -public fun LongArray.fill(value: Long) : Unit = Arrays.fill(this, value) -public fun FloatArray.fill(value: Float) : Unit = Arrays.fill(this, value) -public fun DoubleArray.fill(value: Double) : Unit = Arrays.fill(this, value) -public fun CharArray.fill(value: Char) : Unit = Arrays.fill(this, value) - -public fun Array.fill(value: T) : Unit = Arrays.fill(this, value) - -public fun ByteArray.sort() : Unit = Arrays.sort(this) -public fun ShortArray.sort() : Unit = Arrays.sort(this) -public fun IntArray.sort() : Unit = Arrays.sort(this) -public fun LongArray.sort() : Unit = Arrays.sort(this) -public fun FloatArray.sort() : Unit = Arrays.sort(this) -public fun DoubleArray.sort() : Unit = Arrays.sort(this) -public fun CharArray.sort() : Unit = Arrays.sort(this) - -public fun ByteArray.sort(fromIndex: Int, toIndex: Int) : Unit = Arrays.sort(this, fromIndex, toIndex) -public fun ShortArray.sort(fromIndex: Int, toIndex: Int) : Unit = Arrays.sort(this, fromIndex, toIndex) -public fun IntArray.sort(fromIndex: Int, toIndex: Int) : Unit = Arrays.sort(this, fromIndex, toIndex) -public fun LongArray.sort(fromIndex: Int, toIndex: Int) : Unit = Arrays.sort(this, fromIndex, toIndex) -public fun FloatArray.sort(fromIndex: Int, toIndex: Int) : Unit = Arrays.sort(this, fromIndex, toIndex) -public fun DoubleArray.sort(fromIndex: Int, toIndex: Int) : Unit = Arrays.sort(this, fromIndex, toIndex) -public fun CharArray.sort(fromIndex: Int, toIndex: Int) : Unit = Arrays.sort(this, fromIndex, toIndex) - -public fun BooleanArray.copyOf(newLength: Int = this.size) : BooleanArray = Arrays.copyOf(this, newLength) -public fun ByteArray.copyOf(newLength: Int = this.size) : ByteArray = Arrays.copyOf(this, newLength) -public fun ShortArray.copyOf(newLength: Int = this.size) : ShortArray = Arrays.copyOf(this, newLength) -public fun IntArray.copyOf(newLength: Int = this.size) : IntArray = Arrays.copyOf(this, newLength) -public fun LongArray.copyOf(newLength: Int = this.size) : LongArray = Arrays.copyOf(this, newLength) -public fun FloatArray.copyOf(newLength: Int = this.size) : FloatArray = Arrays.copyOf(this, newLength) -public fun DoubleArray.copyOf(newLength: Int = this.size) : DoubleArray = Arrays.copyOf(this, newLength) -public fun CharArray.copyOf(newLength: Int = this.size) : CharArray = Arrays.copyOf(this, newLength) - -// TODO: resuling array may contain nulls even if T is non-nullable -public fun Array.copyOf(newLength: Int = this.size) : Array = Arrays.copyOf(this, newLength) as Array - -public fun BooleanArray.copyOfRange(from: Int, to: Int) : BooleanArray = Arrays.copyOfRange(this, from, to) -public fun ByteArray.copyOfRange(from: Int, to: Int) : ByteArray = Arrays.copyOfRange(this, from, to) -public fun ShortArray.copyOfRange(from: Int, to: Int) : ShortArray = Arrays.copyOfRange(this, from, to) -public fun IntArray.copyOfRange(from: Int, to: Int) : IntArray = Arrays.copyOfRange(this, from, to) -public fun LongArray.copyOfRange(from: Int, to: Int) : LongArray = Arrays.copyOfRange(this, from, to) -public fun FloatArray.copyOfRange(from: Int, to: Int) : FloatArray = Arrays.copyOfRange(this, from, to) -public fun DoubleArray.copyOfRange(from: Int, to: Int) : DoubleArray = Arrays.copyOfRange(this, from, to) -public fun CharArray.copyOfRange(from: Int, to: Int) : CharArray = Arrays.copyOfRange(this, from, to) - -// TODO: resuling array may contain nulls even if T is non-nullable -public fun Array.copyOfRange(from: Int, to: Int) : Array = Arrays.copyOfRange(this, from, to) as Array - -public val ByteArray.inputStream : ByteArrayInputStream - get() = ByteArrayInputStream(this) - -public fun ByteArray.inputStream(offset: Int, length: Int) : ByteArrayInputStream = ByteArrayInputStream(this, offset, length) - -public fun ByteArray.toString(encoding: String): String = String(this, encoding) -public fun ByteArray.toString(encoding: Charset): String = String(this, encoding) - -[Intrinsic("kotlin.collections.copyToArray")] public fun Collection.copyToArray(): Array = - throw UnsupportedOperationException() diff --git a/libraries/stdlib/src/kotlin/Deprecated.kt b/libraries/stdlib/src/kotlin/Deprecated.kt new file mode 100644 index 00000000000..6e7c6917ba4 --- /dev/null +++ b/libraries/stdlib/src/kotlin/Deprecated.kt @@ -0,0 +1,73 @@ +package kotlin + +import java.util.* +import java.util.concurrent.Callable + +deprecated("Use firstOrNull function instead.") +public inline fun Array.find(predicate: (T) -> Boolean): T? = firstOrNull(predicate) + +deprecated("Use firstOrNull function instead.") +public inline fun Iterable.find(predicate: (T) -> Boolean): T? = firstOrNull(predicate) + +deprecated("Use listOf(...) or arrayListOf(...) instead") +public fun arrayList(vararg values: T): ArrayList = arrayListOf(*values) + +deprecated("Use setOf(...) or hashSetOf(...) instead") +public fun hashSet(vararg values: T): HashSet = hashSetOf(*values) + +deprecated("Use mapOf(...) or hashMapOf(...) instead") +public fun hashMap(vararg values: Pair): HashMap = hashMapOf(*values) + +deprecated("Use listOf(...) or linkedListOf(...) instead") +public fun linkedList(vararg values: T): LinkedList = linkedListOf(*values) + +deprecated("Use sortedSetOf(...) instead") +public fun sortedSet(vararg values: T): TreeSet = sortedSetOf(*values) + +deprecated("Use sortedSetOf(...) instead") +public fun sortedSet(comparator: Comparator, vararg values: T): TreeSet = sortedSetOf(comparator, *values) + +deprecated("Use sortedMapOf(...) instead") +public fun sortedMap(vararg values: Pair): SortedMap = sortedMapOf(*values) + +deprecated("Use linkedMapOf(...) instead") +public fun linkedMap(vararg values: Pair): LinkedHashMap = linkedMapOf(*values) + +/** + * A helper method for creating a [[Callable]] from a function + */ +deprecated("Use SAM constructor: Callable(...)") +public /*inline*/ fun callable(action: () -> T): Callable { + return object: Callable { + public override fun call() = action() + } +} + +/** + * A helper method for creating a [[Runnable]] from a function + */ +deprecated("Use SAM constructor: Runnable(...)") +public /*inline*/ fun runnable(action: () -> Unit): Runnable { + return object: Runnable { + public override fun run() { + action() + } + } +} + +deprecated("Use withIndices() followed by forEach {}") +public inline fun List.forEachWithIndex(operation : (Int, T) -> Unit): Unit = withIndices().forEach { + operation(it.first, it.second) +} + +deprecated("Function with undefined semantic") +public fun countTo(n: Int): (T) -> Boolean { + var count = 0 + return { ++count; count <= n } +} + +deprecated("Use contains() function instead") +public fun Iterable.containsItem(item : T) : Boolean = contains(item) + +deprecated("Use sortBy() instead") +public fun Iterable.sort(comparator: java.util.Comparator) : List = sortBy(comparator) diff --git a/libraries/stdlib/src/kotlin/Functions.kt b/libraries/stdlib/src/kotlin/Functions.kt new file mode 100644 index 00000000000..84dd0e299b7 --- /dev/null +++ b/libraries/stdlib/src/kotlin/Functions.kt @@ -0,0 +1,12 @@ +package kotlin + +public fun Function1.toGenerator(initialValue: T): Function0 { + var nextValue: T? = initialValue + return { + nextValue?.let { result -> + nextValue = this@toGenerator(result) + result + } + } +} + diff --git a/libraries/stdlib/src/kotlin/IterablesSpecial.kt b/libraries/stdlib/src/kotlin/IterablesSpecial.kt deleted file mode 100644 index eb5a8a13c92..00000000000 --- a/libraries/stdlib/src/kotlin/IterablesSpecial.kt +++ /dev/null @@ -1,77 +0,0 @@ -package kotlin -// Number of extension function for java.lang.Iterable that shouldn't participate in auto generation - -import java.util.AbstractList -import java.util.Comparator -import java.util.ArrayList - -/** - * Count the number of elements in collection. - * - * If base collection implements [[Collection]] interface method [[Collection.size()]] will be used. - * Otherwise, this method determines the count by iterating through the all items. - */ -public fun Iterable.count() : Int { - if (this is Collection) { - return this.size() - } - - var number : Int = 0 - for (elem in this) { - ++number - } - return number -} - -public fun countTo(n: Int): (T) -> Boolean { - var count = 0 - return { ++count; count <= n } -} - - -/** - * Get the first element in the collection. - * - * Will throw an exception if there are no elements - */ -public fun Iterable.first() : T { - if (this is List) { - return this.first() - } - - return this.iterator().next() -} - -/** - * Checks if collection contains given item. - * - * Method checks equality of the objects with T.equals method. - * If collection implements [[java.util.AbstractCollection]] an overridden implementation of the contains - * method will be used. - */ -public fun Iterable.containsItem(item : T) : Boolean { - if (this is java.util.AbstractCollection) { - return this.contains(item); - } - - for (elem in this) { - if (elem == item) { - return true - } - } - - return false -} - - -public fun > Iterable.sort() : List { - val list = toCollection(ArrayList()) - java.util.Collections.sort(list) - return list -} - -public fun Iterable.sort(comparator: java.util.Comparator) : List { - val list = toCollection(ArrayList()) - java.util.Collections.sort(list, comparator) - return list -} diff --git a/libraries/stdlib/src/kotlin/JUtil.kt b/libraries/stdlib/src/kotlin/JUtil.kt deleted file mode 100644 index 6052211b6c3..00000000000 --- a/libraries/stdlib/src/kotlin/JUtil.kt +++ /dev/null @@ -1,103 +0,0 @@ -package kotlin - -import java.util.* - -/** Returns the size of the collection */ -public val Collection<*>.size : Int - get() = size() - -/** Returns true if this collection is empty */ -public val Collection<*>.empty : Boolean - get() = isEmpty() - -public val Collection<*>.indices : IntRange - get() = 0..size-1 - -public val Int.indices: IntRange - get() = 0..this-1 - -/** Returns true if the collection is not empty */ -public fun Collection.isNotEmpty() : Boolean = !this.isEmpty() - -/** Returns true if this collection is not empty */ -val Collection<*>.notEmpty : Boolean - get() = isNotEmpty() - -/** Returns the Collection if its not null otherwise it returns the empty list */ -public fun Collection?.orEmpty() : Collection = this ?: Collections.emptyList() - - -/** TODO these functions don't work when they generate the Array versions when they are in JLIterables */ -public fun > Iterable.toSortedList() : List = toCollection(ArrayList()).sort() - -public fun > Iterable.toSortedList(comparator: java.util.Comparator) : List = toList().sort(comparator) - - -// List APIs - -/** Returns the List if its not null otherwise returns the empty list */ -public fun List?.orEmpty() : List = this ?: Collections.emptyList() - -/** - TODO figure out necessary variance/generics ninja stuff... :) -public inline fun List.sort(transform: fun(T) : java.lang.Comparable<*>) : List { - val comparator = java.util.Comparator() { - public fun compare(o1: T, o2: T): Int { - val v1 = transform(o1) - val v2 = transform(o2) - if (v1 == v2) { - return 0 - } else { - return v1.compareTo(v2) - } - } - } - answer.sort(comparator) -} -*/ - -/** - * Returns the first item in the list or null if the list is empty - * - * @includeFunctionBody ../../test/ListTest.kt first - */ -val List.first : T? - get() = this.head - - -/** - * Returns the last item in the list or null if the list is empty - * - * @includeFunctionBody ../../test/ListTest.kt last - */ -val List.last : T? - get() { - val s = this.size - return if (s > 0) this.get(s - 1) else null - } - -/** - * Returns the index of the last item in the list or -1 if the list is empty - * - * @includeFunctionBody ../../test/ListTest.kt lastIndex - */ -val List.lastIndex : Int - get() = this.size - 1 - -/** - * Returns the first item in the list or null if the list is empty - * - * @includeFunctionBody ../../test/ListTest.kt head - */ -val List.head : T? - get() = if (this.isNotEmpty()) this.get(0) else null - -/** - * Returns all elements in this collection apart from the first one - * - * @includeFunctionBody ../../test/ListTest.kt tail - */ -val List.tail : List - get() { - return this.drop(1) - } diff --git a/libraries/stdlib/src/kotlin/JUtilJVM.kt b/libraries/stdlib/src/kotlin/JUtilJVM.kt deleted file mode 100644 index 9e198ed18da..00000000000 --- a/libraries/stdlib/src/kotlin/JUtilJVM.kt +++ /dev/null @@ -1,114 +0,0 @@ -package kotlin - -import java.util.* - -/** Returns a new read-only list of given elements */ -public fun listOf(vararg values: T): List = arrayListOf(*values) - -/** Returns a new read-only set of given elements */ -public fun setOf(vararg values: T): Set = values.toCollection(LinkedHashSet()) - -/** Returns a new read-only map of given pairs, where the first value is the key, and the second is value */ -public fun mapOf(vararg values: Pair): Map = hashMapOf(*values) - -/** Returns a new ArrayList with a variable number of initial elements */ -public fun arrayListOf(vararg values: T) : ArrayList = values.toCollection(ArrayList(values.size)) - -deprecated("Use listOf(...) or arrayListOf(...) instead") -public fun arrayList(vararg values: T) : ArrayList = arrayListOf(*values) - -/** Returns a new LinkedList with a variable number of initial elements */ -public fun linkedListOf(vararg values: T) : LinkedList = values.toCollection(LinkedList()) - -deprecated("Use listOf(...) or linkedListOf(...) instead") -public fun linkedList(vararg values: T) : LinkedList = linkedListOf(*values) - -/** Returns a new HashSet with a variable number of initial elements */ -public fun hashSetOf(vararg values: T) : HashSet = values.toCollection(HashSet(values.size)) - -deprecated("Use setOf(...) or hashSetOf(...) instead") -public fun hashSet(vararg values: T) : HashSet = hashSetOf(*values) - -/** - * Returns a new [[SortedSet]] with the initial elements - */ -public fun sortedSetOf(vararg values: T) : TreeSet = values.toCollection(TreeSet()) - -deprecated("Use sortedSetOf(...) instead") -public fun sortedSet(vararg values: T) : TreeSet = sortedSetOf(*values) - -/** - * Returns a new [[SortedSet]] with the given *comparator* and the initial elements - */ -public fun sortedSetOf(comparator: Comparator, vararg values: T) : TreeSet = values.toCollection(TreeSet(comparator)) - -deprecated("Use sortedSetOf(...) instead") -public fun sortedSet(comparator: Comparator, vararg values: T) : TreeSet = sortedSetOf(comparator, *values) - -/** - * Returns a new [[HashMap]] populated with the given pairs where the first value in each pair - * is the key and the second value is the value - * - * @includeFunctionBody ../../test/MapTest.kt createUsingPairs - */ -public fun hashMapOf(vararg values: Pair): HashMap { - val answer = HashMap(values.size) - /** - TODO replace by this simpler call when we can pass vararg values into other methods - answer.putAll(values) - */ - for (v in values) { - answer.put(v.first, v.second) - } - return answer -} - -deprecated("Use mapOf(...) or hashMapOf(...) instead") -public fun hashMap(vararg values: Pair): HashMap = hashMapOf(*values) - -/** - * Returns a new [[SortedMap]] populated with the given pairs where the first value in each pair - * is the key and the second value is the value - * - * @includeFunctionBody ../../test/MapTest.kt createSortedMap - */ -public fun sortedMapOf(vararg values: Pair): SortedMap { - val answer = TreeMap() - /** - TODO replace by this simpler call when we can pass vararg values into other methods - answer.putAll(values) - */ - for (v in values) { - answer.put(v.first, v.second) - } - return answer -} - -deprecated("Use sortedMapOf(...) instead") -public fun sortedMap(vararg values: Pair): SortedMap = sortedMapOf(*values) - -/** - * Returns a new [[LinkedHashMap]] populated with the given pairs where the first value in each pair - * is the key and the second value is the value. This map preserves insertion order so iterating through - * the map's entries will be in the same order - * - * @includeFunctionBody ../../test/MapTest.kt createLinkedMap - */ -public fun linkedMapOf(vararg values: Pair): LinkedHashMap { - val answer = LinkedHashMap(values.size) - /** - TODO replace by this simpler call when we can pass vararg values into other methods - answer.putAll(values) - */ - for (v in values) { - answer.put(v.first, v.second) - } - return answer -} - -deprecated("Use linkedMapOf(...) instead") -public fun linkedMap(vararg values: Pair): LinkedHashMap = linkedMapOf(*values) - -/** Returns the Set if its not null otherwise returns the empty set */ -public fun Set?.orEmpty() : Set - = if (this != null) this else Collections.EMPTY_SET as Set diff --git a/libraries/stdlib/src/kotlin/Lists.kt b/libraries/stdlib/src/kotlin/Lists.kt deleted file mode 100644 index f5c65acbb14..00000000000 --- a/libraries/stdlib/src/kotlin/Lists.kt +++ /dev/null @@ -1,82 +0,0 @@ -package kotlin - -/** - * Get the first element in the list or throws [[EmptyIterableException]] if list is empty. - */ -public fun List.first() : T { - return if (size() > 0) get(0) else throw EmptyIterableException(this) -} - -/** - * Get the first element in the list or *null* if list is empty. - */ -public fun List.firstOrNull() : T? { - return if (size() > 0) get(0) else null -} - -/** - * Get the last element in the list or throws [[EmptyIterableException]] if list is empty. - */ -public fun List.last() : T { - val s = size() - return if (s > 0) get(s - 1) else throw EmptyIterableException(this) -} - -/** - * Get the last element in the list or *null* if list is empty. - */ -public fun List.lastOrNull() : T? { - val s = size() - return if (s > 0) get(s - 1) else null -} - -public inline fun List.forEachWithIndex(operation : (Int, T) -> Unit) { - for (index in indices) { - operation(index, get(index)) - } -} - -/** - * Folds all elements from right to left with the *initial* value to perform the operation on sequential pairs of elements - */ -public inline fun List.foldRight(initial: R, operation: (T, R) -> R) : R { - var r = initial - var index = size - 1 - - while (index >= 0) { - r = operation(get(index--), r) - } - - return r -} - -/** - * Applies binary operation to all elements of iterable, going from right to left. - * Similar to foldRight function, but uses the last element as initial value - */ -public inline fun List.reduceRight(operation: (T, T) -> T) : T { - var index = size - 1 - if (index < 0) { - throw UnsupportedOperationException("Empty iterable can't be reduced") - } - - var r = get(index--) - while (index >= 0) { - r = operation(get(index--), r) - } - - return r -} - -/** - * Returns a original Iterable containing all the non-*null* elements, throwing an [[IllegalArgumentException]] if there are any null elements - */ -public fun List.requireNoNulls() : List { - for (element in this) { - if (element == null) { - throw IllegalArgumentException("null element found in $this") - } - } - return this as List -} - diff --git a/libraries/stdlib/src/kotlin/MutableCollections.kt b/libraries/stdlib/src/kotlin/MutableCollections.kt deleted file mode 100644 index fccea3c9d21..00000000000 --- a/libraries/stdlib/src/kotlin/MutableCollections.kt +++ /dev/null @@ -1,15 +0,0 @@ -package kotlin - -/** - * Adds all elements of the given *iterator* to this [[MutableCollection]] - */ -public fun MutableCollection.addAll(iterator: Iterator): Unit { - for (e in iterator) add(e) -} - -/** - * Adds all elements of the given *iterable* to this [[MutableCollection]] - */ -public fun MutableCollection.addAll(iterable: Iterable): Unit { - for (e in iterable) add(e) -} diff --git a/libraries/stdlib/src/kotlin/Standard.kt b/libraries/stdlib/src/kotlin/Standard.kt index 70cdcc0d480..975dc425c30 100644 --- a/libraries/stdlib/src/kotlin/Standard.kt +++ b/libraries/stdlib/src/kotlin/Standard.kt @@ -1,63 +1,24 @@ package kotlin -import java.util.ArrayList -import java.util.HashSet -import java.util.LinkedList - -/** -Helper to make java.util.Enumeration usable in for -*/ -public fun java.util.Enumeration.iterator(): Iterator = object: Iterator { - override fun hasNext(): Boolean = hasMoreElements() - - public override fun next() : T = nextElement() -} - -/* - * Extension functions on the standard Kotlin types to behave like the java.lang.* and java.util.* collections - */ - -/** -Add iterated elements to given container -*/ -/* -public fun > Iterator.toCollection(container: U) : U { - while(hasNext()) - container.add(next()) - return container -} -*/ - -/** -Add iterated elements to java.util.ArrayList -*/ -public fun Iterator.toArrayList() : ArrayList = toCollection(ArrayList()) - -/** -Add iterated elements to java.util.HashSet -*/ -public fun Iterator.toHashSet() : HashSet = toCollection(HashSet()) - - /** * Creates a tuple of type [[Pair]] from this and *that* which can be useful for creating [[Map]] literals * with less noise, for example - * @includeFunctionBody ../../test/MapTest.kt createUsingTo + * @includeFunctionBody ../../test/collections/MapTest.kt createUsingTo */ -public fun A.to(that: B): Pair = Pair(this, that) +public fun A.to(that: B): Pair = Pair(this, that) /** Run function f -*/ -public inline fun run(f: () -> T) : T = f() + */ +public inline fun run(f: () -> T): T = f() /** * Execute f with given receiver */ -public inline fun with(receiver: T, f: T.() -> R) : R = receiver.f() +public inline fun with(receiver: T, f: T.() -> R): R = receiver.f() /** * Converts receiver to body parameter -*/ -public inline fun T.let(f: (T) -> R): R = f(this) + */ +public inline fun T.let(f: (T) -> R): R = f(this) diff --git a/libraries/stdlib/src/kotlin/StandardJVM.kt b/libraries/stdlib/src/kotlin/StandardJVM.kt index 7381c7a8f3c..b43ef508e83 100644 --- a/libraries/stdlib/src/kotlin/StandardJVM.kt +++ b/libraries/stdlib/src/kotlin/StandardJVM.kt @@ -1,26 +1,7 @@ package kotlin -import java.util.ArrayList -import java.util.LinkedList -import java.util.HashSet -import java.util.LinkedHashSet -import java.util.TreeSet -import java.util.SortedSet -import java.util.Comparator import java.io.PrintWriter import java.io.PrintStream -import java.util.concurrent.Callable - -/** - * Add iterated elements to a [[LinkedHashSet]] to preserve insertion order - */ -public fun Iterator.toLinkedSet() : LinkedHashSet = toCollection(LinkedHashSet()) - -/** - * Add iterated elements to [[SortedSet]] with the given *comparator* to ensure iteration is in the order of the given comparator - */ -public fun Iterator.toSortedSet(comparator: Comparator) : SortedSet = toCollection(TreeSet(comparator)) - /** * Allows a stack trace to be printed from Kotlin's [[Throwable]] @@ -42,29 +23,8 @@ public fun Throwable.printStackTrace(stream: PrintStream): Unit { * Returns the stack trace */ -public fun Throwable.getStackTrace() : Array { +public fun Throwable.getStackTrace(): Array { val jlt = this as java.lang.Throwable return jlt.getStackTrace()!! } -/** - * A helper method for creating a [[Callable]] from a function - */ -deprecated("Use SAM constructor: Callable(...)") -public /*inline*/ fun callable(action: ()-> T): Callable { - return object: Callable { - public override fun call() = action() - } -} - -/** - * A helper method for creating a [[Runnable]] from a function - */ -deprecated("Use SAM constructor: Runnable(...)") -public /*inline*/ fun runnable(action: ()-> Unit): Runnable { - return object: Runnable { - public override fun run() { - action() - } - } -} diff --git a/libraries/stdlib/src/kotlin/Arrays.kt b/libraries/stdlib/src/kotlin/collections/Arrays.kt similarity index 75% rename from libraries/stdlib/src/kotlin/Arrays.kt rename to libraries/stdlib/src/kotlin/collections/Arrays.kt index 814648726d4..49e096dc4f9 100644 --- a/libraries/stdlib/src/kotlin/Arrays.kt +++ b/libraries/stdlib/src/kotlin/collections/Arrays.kt @@ -1,11 +1,5 @@ package kotlin -/** Returns true if the array is not empty */ -public fun Array.isNotEmpty() : Boolean = !this.isEmpty() - -/** Returns true if the array is empty */ -public fun Array.isEmpty() : Boolean = this.size == 0 - public val BooleanArray.lastIndex : Int get() = this.size - 1 diff --git a/libraries/stdlib/src/kotlin/collections/ArraysJVM.kt b/libraries/stdlib/src/kotlin/collections/ArraysJVM.kt new file mode 100644 index 00000000000..873c52a273f --- /dev/null +++ b/libraries/stdlib/src/kotlin/collections/ArraysJVM.kt @@ -0,0 +1,37 @@ +package kotlin + +import java.io.ByteArrayInputStream +import java.nio.charset.Charset +import java.util.Arrays +import kotlin.jvm.internal.Intrinsic + +// Array "constructor" +[Intrinsic("kotlin.arrays.array")] public fun array(vararg t : T) : Array = t + +// "constructors" for primitive types array +[Intrinsic("kotlin.arrays.array")] public fun doubleArray(vararg content : Double) : DoubleArray = content + +[Intrinsic("kotlin.arrays.array")] public fun floatArray(vararg content : Float) : FloatArray = content + +[Intrinsic("kotlin.arrays.array")] public fun longArray(vararg content : Long) : LongArray = content + +[Intrinsic("kotlin.arrays.array")] public fun intArray(vararg content : Int) : IntArray = content + +[Intrinsic("kotlin.arrays.array")] public fun charArray(vararg content : Char) : CharArray = content + +[Intrinsic("kotlin.arrays.array")] public fun shortArray(vararg content : Short) : ShortArray = content + +[Intrinsic("kotlin.arrays.array")] public fun byteArray(vararg content : Byte) : ByteArray = content + +[Intrinsic("kotlin.arrays.array")] public fun booleanArray(vararg content : Boolean) : BooleanArray = content + +public val ByteArray.inputStream : ByteArrayInputStream + get() = ByteArrayInputStream(this) + +public fun ByteArray.inputStream(offset: Int, length: Int) : ByteArrayInputStream = ByteArrayInputStream(this, offset, length) + +public fun ByteArray.toString(encoding: String): String = String(this, encoding) +public fun ByteArray.toString(encoding: Charset): String = String(this, encoding) + +[Intrinsic("kotlin.collections.copyToArray")] public fun Collection.copyToArray(): Array = + throw UnsupportedOperationException() diff --git a/libraries/stdlib/src/kotlin/Exceptions.kt b/libraries/stdlib/src/kotlin/collections/Exceptions.kt similarity index 100% rename from libraries/stdlib/src/kotlin/Exceptions.kt rename to libraries/stdlib/src/kotlin/collections/Exceptions.kt diff --git a/libraries/stdlib/src/kotlin/ImmutableArrayList.kt b/libraries/stdlib/src/kotlin/collections/ImmutableArrayList.kt similarity index 100% rename from libraries/stdlib/src/kotlin/ImmutableArrayList.kt rename to libraries/stdlib/src/kotlin/collections/ImmutableArrayList.kt diff --git a/libraries/stdlib/src/kotlin/collections/Iterators.kt b/libraries/stdlib/src/kotlin/collections/Iterators.kt new file mode 100644 index 00000000000..710dfaa8f5d --- /dev/null +++ b/libraries/stdlib/src/kotlin/collections/Iterators.kt @@ -0,0 +1,15 @@ +package kotlin + +/** +Helper to make java.util.Enumeration usable in for + */ +public fun java.util.Enumeration.iterator(): Iterator = object: Iterator { + override fun hasNext(): Boolean = hasMoreElements() + + public override fun next() : T = nextElement() +} + +/** + * Returns the given iterator itself. This allows to use an instance of iterator in a ranged for-loop + */ +public fun Iterator.iterator(): Iterator = this diff --git a/libraries/stdlib/src/kotlin/collections/JUtil.kt b/libraries/stdlib/src/kotlin/collections/JUtil.kt new file mode 100644 index 00000000000..ccf15acf398 --- /dev/null +++ b/libraries/stdlib/src/kotlin/collections/JUtil.kt @@ -0,0 +1,120 @@ +package kotlin + +import java.util.* + +/** Returns a new read-only list of given elements */ +public fun listOf(vararg values: T): List = arrayListOf(*values) + +/** Returns a new read-only map of given pairs, where the first value is the key, and the second is value */ +public fun mapOf(vararg values: Pair): Map = hashMapOf(*values) + +/** Returns a new ArrayList with a variable number of initial elements */ +public fun arrayListOf(vararg values: T): ArrayList = values.toCollection(ArrayList(values.size)) + +/** Returns a new HashSet with a variable number of initial elements */ +public fun hashSetOf(vararg values: T): HashSet = values.toCollection(HashSet(values.size)) + +/** + * Returns a new [[HashMap]] populated with the given pairs where the first value in each pair + * is the key and the second value is the value + * + * @includeFunctionBody ../../test/collections/MapTest.kt createUsingPairs + */ +public fun hashMapOf(vararg values: Pair): HashMap { + val answer = HashMap(values.size) + answer.putAll(*values) + return answer +} + +/** Returns the size of the collection */ +public val Collection<*>.size: Int + get() = size() + +/** Returns true if this collection is empty */ +public val Collection<*>.empty: Boolean + get() = isEmpty() + +public val Collection<*>.indices: IntRange + get() = 0..size - 1 + +public val Int.indices: IntRange + get() = 0..this - 1 + +/** Returns true if the collection is not empty */ +public fun Collection.isNotEmpty(): Boolean = !this.isEmpty() + +/** Returns true if this collection is not empty */ +val Collection<*>.notEmpty: Boolean + get() = isNotEmpty() + +/** Returns the Collection if its not null otherwise it returns the empty list */ +public fun Collection?.orEmpty(): Collection = this ?: Collections.emptyList() + +// List APIs + +/** Returns the List if its not null otherwise returns the empty list */ +public fun List?.orEmpty(): List = this ?: Collections.emptyList() + +/** +TODO figure out necessary variance/generics ninja stuff... :) +public inline fun List.sort(transform: fun(T) : java.lang.Comparable<*>) : List { +val comparator = java.util.Comparator() { +public fun compare(o1: T, o2: T): Int { +val v1 = transform(o1) +val v2 = transform(o2) +if (v1 == v2) { +return 0 +} else { +return v1.compareTo(v2) +} +} +} +answer.sort(comparator) +} + */ + +/** + * Returns the first item in the list or null if the list is empty + * + * @includeFunctionBody ../../test/collections/ListSpecificTest.kt first + */ +val List.first: T? + get() = this.head + + +/** + * Returns the last item in the list or null if the list is empty + * + * @includeFunctionBody ../../test/collections/ListSpecificTest.kt last + */ +val List.last: T? + get() { + val s = this.size + return if (s > 0) this.get(s - 1) else null + } + +/** + * Returns the index of the last item in the list or -1 if the list is empty + * + * @includeFunctionBody ../../test/collections/ListSpecificTest.kt lastIndex + */ +val List.lastIndex: Int + get() = this.size - 1 + +/** + * Returns the first item in the list or null if the list is empty + * + * @includeFunctionBody ../../test/collections/ListSpecificTest.kt head + */ +val List.head: T? + get() = if (this.isNotEmpty()) this.get(0) else null + +/** + * Returns all elements in this collection apart from the first one + * + * @includeFunctionBody ../../test/collections/ListSpecificTest.kt tail + */ +val List.tail: List + get() { + return this.drop(1) + } diff --git a/libraries/stdlib/src/kotlin/collections/JUtilJVM.kt b/libraries/stdlib/src/kotlin/collections/JUtilJVM.kt new file mode 100644 index 00000000000..18a0ea23086 --- /dev/null +++ b/libraries/stdlib/src/kotlin/collections/JUtilJVM.kt @@ -0,0 +1,60 @@ +package kotlin + +import java.util.* + +/** Returns a new read-only set of given elements */ +public fun setOf(vararg values: T): Set = values.toCollection(LinkedHashSet()) + +/** Returns a new LinkedList with a variable number of initial elements */ +public fun linkedListOf(vararg values: T): LinkedList = values.toCollection(LinkedList()) + +/** + * Returns a new [[SortedSet]] with the initial elements + */ +public fun sortedSetOf(vararg values: T): TreeSet = values.toCollection(TreeSet()) + +/** + * Returns a new [[SortedSet]] with the given *comparator* and the initial elements + */ +public fun sortedSetOf(comparator: Comparator, vararg values: T): TreeSet = values.toCollection(TreeSet(comparator)) + +/** + * Returns a new [[SortedMap]] populated with the given pairs where the first value in each pair + * is the key and the second value is the value + * + * @includeFunctionBody ../../test/collections/MapTest.kt createSortedMap + */ +public fun sortedMapOf(vararg values: Pair): SortedMap { + val answer = TreeMap() + /** + TODO replace by this simpler call when we can pass vararg values into other methods + answer.putAll(values) + */ + for (v in values) { + answer.put(v.first, v.second) + } + return answer +} + +/** + * Returns a new [[LinkedHashMap]] populated with the given pairs where the first value in each pair + * is the key and the second value is the value. This map preserves insertion order so iterating through + * the map's entries will be in the same order + * + * @includeFunctionBody ../../test/collections/MapTest.kt createLinkedMap + */ +public fun linkedMapOf(vararg values: Pair): LinkedHashMap { + val answer = LinkedHashMap(values.size) + /** + TODO replace by this simpler call when we can pass vararg values into other methods + answer.putAll(values) + */ + for (v in values) { + answer.put(v.first, v.second) + } + return answer +} + +/** Returns the Set if its not null otherwise returns the empty set */ +public fun Set?.orEmpty(): Set + = if (this != null) this else Collections.EMPTY_SET as Set diff --git a/libraries/stdlib/src/kotlin/Maps.kt b/libraries/stdlib/src/kotlin/collections/Maps.kt similarity index 76% rename from libraries/stdlib/src/kotlin/Maps.kt rename to libraries/stdlib/src/kotlin/collections/Maps.kt index cb100563b63..2ae2d769c74 100644 --- a/libraries/stdlib/src/kotlin/Maps.kt +++ b/libraries/stdlib/src/kotlin/collections/Maps.kt @@ -42,7 +42,7 @@ fun Map.Entry.component2() : V { /** * Returns the value for the given key or returns the result of the defaultValue function if there was no entry for the given key * - * @includeFunctionBody ../../test/MapTest.kt getOrElse + * @includeFunctionBody ../../test/collections/MapTest.kt getOrElse */ public inline fun Map.getOrElse(key: K, defaultValue: ()-> V) : V { if (this.containsKey(key)) { @@ -55,7 +55,7 @@ public inline fun Map.getOrElse(key: K, defaultValue: ()-> V) : V { /** * Returns the value for the given key or the result of the defaultValue function is put into the map for the given value and returned * - * @includeFunctionBody ../../test/MapTest.kt getOrElse + * @includeFunctionBody ../../test/collections/MapTest.kt getOrPut */ public inline fun MutableMap.getOrPut(key: K, defaultValue: ()-> V) : V { if (this.containsKey(key)) { @@ -71,23 +71,13 @@ public inline fun MutableMap.getOrPut(key: K, defaultValue: ()-> V) : /** * Returns an [[Iterator]] over the entries in the [[Map]] * - * @includeFunctionBody ../../test/MapTest.kt iterateWithProperties + * @includeFunctionBody ../../test/collections/MapTest.kt iterateWithProperties */ public fun Map.iterator(): Iterator> { val entrySet = this.entrySet() return entrySet.iterator() } -/** - * Transforms each [[Map.Entry]] in this [[Map]] with the given *transform* function and - * adds each return value to the given *results* collection - */ -public inline fun > Map.mapTo(result: C, transform: (Map.Entry) -> R) : C { - for (item in this) - result.add(transform(item)) - return result -} - /** * Populates the given *result* [[Map]] with the value returned by applying the *transform* function on each [[Map.Entry]] in this [[Map]] */ @@ -116,19 +106,10 @@ public fun Map.toMap(map: MutableMap): Map { return map } -/** - * Returns a new List containing the results of applying the given *transform* function to each [[Map.Entry]] in this [[Map]] - * - * @includeFunctionBody ../../test/CollectionTest.kt map - */ -public inline fun Map.map(transform: (Map.Entry) -> R) : List { - return mapTo(java.util.ArrayList(this.size), transform) -} - /** * Returns a new Map containing the results of applying the given *transform* function to each [[Map.Entry]] in this [[Map]] * - * @includeFunctionBody ../../test/MapTest.kt mapValues + * @includeFunctionBody ../../test/collections/MapTest.kt mapValues */ public inline fun Map.mapValues(transform : (Map.Entry) -> R): Map { return mapValuesTo(java.util.HashMap(this.size), transform) diff --git a/libraries/stdlib/src/kotlin/MapsJVM.kt b/libraries/stdlib/src/kotlin/collections/MapsJVM.kt similarity index 83% rename from libraries/stdlib/src/kotlin/MapsJVM.kt rename to libraries/stdlib/src/kotlin/collections/MapsJVM.kt index aaa347132b3..9638f9124f2 100644 --- a/libraries/stdlib/src/kotlin/MapsJVM.kt +++ b/libraries/stdlib/src/kotlin/collections/MapsJVM.kt @@ -16,7 +16,7 @@ public fun Map.toLinkedMap(): LinkedHashMap = toMap(LinkedH /** * Converts this [[Map]] to a [[SortedMap]] so iteration order will be in key order * - * @includeFunctionBody ../../test/MapTest.kt toSortedMap + * @includeFunctionBody ../../test/collections/MapTest.kt toSortedMap */ public fun Map.toSortedMap(): SortedMap = toMap(TreeMap()) as SortedMap @@ -24,7 +24,7 @@ public fun Map.toSortedMap(): SortedMap = toMap(TreeMap()) * Converts this [[Map]] to a [[SortedMap]] using the given *comparator* so that iteration order will be in the order * defined by the comparator * - * @includeFunctionBody ../../test/MapTest.kt toSortedMapWithComparator + * @includeFunctionBody ../../test/collections/MapTest.kt toSortedMapWithComparator */ public fun Map.toSortedMap(comparator: Comparator): SortedMap = toMap(TreeMap(comparator)) as SortedMap @@ -32,7 +32,7 @@ public fun Map.toSortedMap(comparator: Comparator): SortedMap /** * Converts this [[Map]] to a [[Properties]] object * - * @includeFunctionBody ../../test/MapTest.kt toProperties + * @includeFunctionBody ../../test/collections/MapTest.kt toProperties */ public fun Map.toProperties(): Properties { val answer = Properties() diff --git a/libraries/stdlib/src/kotlin/collections/MutableCollections.kt b/libraries/stdlib/src/kotlin/collections/MutableCollections.kt new file mode 100644 index 00000000000..1a99bebe612 --- /dev/null +++ b/libraries/stdlib/src/kotlin/collections/MutableCollections.kt @@ -0,0 +1,16 @@ +package kotlin + +/** + * Adds all elements of the given *iterable* to this [[MutableCollection]] + */ +public fun MutableCollection.addAll(iterable: Iterable): Unit { + for (e in iterable) add(e) +} + +public fun MutableCollection.addAll(stream: Stream): Unit { + for (e in stream) add(e) +} + +public fun MutableCollection.addAll(array: Array): Unit { + for (e in array) add(e) +} diff --git a/libraries/stdlib/src/kotlin/collections/Stream.kt b/libraries/stdlib/src/kotlin/collections/Stream.kt new file mode 100644 index 00000000000..5c92ee5a07b --- /dev/null +++ b/libraries/stdlib/src/kotlin/collections/Stream.kt @@ -0,0 +1,132 @@ +package kotlin + +import kotlin.support.AbstractIterator + +public trait Stream { + public fun iterator(): Iterator +} + +public fun Iterable.stream(): Stream = object : Stream { + override fun iterator(): Iterator { + return this@stream.iterator() + } +} + +public class FilteringStream(val stream: Stream, val sendWhen: Boolean = true, val predicate: (T) -> Boolean) : Stream { + override fun iterator(): Iterator = object : AbstractIterator() { + val iterator = stream.iterator() + override fun computeNext() { + while (iterator.hasNext()) { + val item = iterator.next() + if (predicate(item) == sendWhen) { + setNext(item) + return + } + } + done() + } + } +} + +public class TransformingStream(val stream: Stream, val transformer: (T) -> R) : Stream { + override fun iterator(): Iterator = object : AbstractIterator() { + val iterator = stream.iterator() + override fun computeNext() { + if (iterator.hasNext()) { + setNext(transformer(iterator.next())) + } else { + done() + } + } + } +} + +class ZippingStream(val stream1: Stream, val stream2: Stream) : Stream> { + override fun iterator(): Iterator> = object : AbstractIterator>() { + val iterator1 = stream1.iterator() + val iterator2 = stream2.iterator() + override fun computeNext() { + if (iterator1.hasNext() && iterator2.hasNext()) { + setNext(iterator1.next() to iterator2.next()) + } else { + done() + } + } + } +} + +public class FlatteningStream(val stream: Stream, val transformer: (T) -> Stream) : Stream { + override fun iterator(): Iterator = object : AbstractIterator() { + val iterator = stream.iterator() + var itemIterator: Iterator? = null + override fun computeNext() { + while (itemIterator == null) { + if (!iterator.hasNext()) { + done() + break; + } else { + val element = iterator.next() + val nextItemIterator = transformer(element).iterator() + if (nextItemIterator.hasNext()) + itemIterator = nextItemIterator + } + } + + val currentItemIterator = itemIterator + if (currentItemIterator == null) { + done() + } else { + setNext(currentItemIterator.next()) + if (!currentItemIterator.hasNext()) + itemIterator = null + } + } + } +} + +public class LimitedStream(val stream: Stream, val stopWhen: Boolean = true, val predicate: (T) -> Boolean) : Stream { + override fun iterator(): Iterator = object : AbstractIterator() { + val iterator = stream.iterator() + override fun computeNext() { + if (!iterator.hasNext()) { + done() + } else { + val item = iterator.next() + if (predicate(item) == stopWhen) { + done() + } else { + setNext(item) + } + } + } + } +} + +public class FunctionStream(val producer: () -> T?) : Stream { + override fun iterator(): Iterator = object : AbstractIterator() { + + override fun computeNext() { + val item = producer() + if (item == null) { + done() + } else { + setNext(item) + } + } + } +} + +/** + * Returns a stream which invokes the function to calculate the next value on each iteration until the function returns *null* + */ +public fun stream(nextFunction: () -> T?): Stream { + return FunctionStream(nextFunction) +} + +/** + * Returns a stream which invokes the function to calculate the next value based on the previous one on each iteration + * until the function returns *null* + */ +public /*inline*/ fun stream(initialValue: T, nextFunction: (T) -> T?): Stream = + stream(nextFunction.toGenerator(initialValue)) + diff --git a/libraries/stdlib/src/kotlin/Iterators.kt b/libraries/stdlib/src/kotlin/collections/iterators/Iterators.kt similarity index 86% rename from libraries/stdlib/src/kotlin/Iterators.kt rename to libraries/stdlib/src/kotlin/collections/iterators/Iterators.kt index e032bdc31e5..f5e48357b57 100644 --- a/libraries/stdlib/src/kotlin/Iterators.kt +++ b/libraries/stdlib/src/kotlin/collections/iterators/Iterators.kt @@ -4,14 +4,10 @@ import kotlin.support.* import java.util.Collections import kotlin.test.assertTrue -/** - * Returns the given iterator itself. This allows to use an instance of iterator in a ranged for-loop - */ -public fun Iterator.iterator(): Iterator = this - /** * Returns an iterator which invokes the function to calculate the next value on each iteration until the function returns *null* */ +deprecated("Use streams for lazy collection operations.") public fun iterate(nextFunction: () -> T?) : Iterator { return FunctionIterator(nextFunction) } @@ -20,19 +16,23 @@ public fun iterate(nextFunction: () -> T?) : Iterator { * Returns an iterator which invokes the function to calculate the next value based on the previous one on each iteration * until the function returns *null* */ +deprecated("Use streams for lazy collection operations.") public /*inline*/ fun iterate(initialValue: T, nextFunction: (T) -> T?): Iterator = iterate(nextFunction.toGenerator(initialValue)) /** * Returns an iterator whose values are pairs composed of values produced by given pair of iterators */ +deprecated("Use streams for lazy collection operations.") public fun Iterator.zip(iterator: Iterator): Iterator> = PairIterator(this, iterator) /** * Returns an iterator shifted to right by the given number of elements */ +deprecated("Use streams for lazy collection operations.") public fun Iterator.skip(n: Int): Iterator = SkippingIterator(this, n) +deprecated("Use streams for lazy collection operations.") class FilterIterator(val iterator : Iterator, val predicate: (T)-> Boolean) : AbstractIterator() { override protected fun computeNext(): Unit { while (iterator.hasNext()) { @@ -46,6 +46,7 @@ class FilterIterator(val iterator : Iterator, val predicate: (T)-> Boolean } } +deprecated("Use streams for lazy collection operations.") class FilterNotNullIterator(val iterator : Iterator?) : AbstractIterator() { override protected fun computeNext(): Unit { if (iterator != null) { @@ -61,6 +62,7 @@ class FilterNotNullIterator(val iterator : Iterator?) : AbstractItera } } +deprecated("Use streams for lazy collection operations.") class MapIterator(val iterator : Iterator, val transform: (T) -> R) : AbstractIterator() { override protected fun computeNext() : Unit { if (iterator.hasNext()) { @@ -71,6 +73,7 @@ class MapIterator(val iterator : Iterator, val transform: (T) -> R) : A } } +deprecated("Use streams for lazy collection operations.") class FlatMapIterator(val iterator : Iterator, val transform: (T) -> Iterator) : AbstractIterator() { var transformed: Iterator = iterate { null } @@ -90,6 +93,7 @@ class FlatMapIterator(val iterator : Iterator, val transform: (T) -> It } } +deprecated("Use streams for lazy collection operations.") class TakeWhileIterator(val iterator: Iterator, val predicate: (T) -> Boolean) : AbstractIterator() { override protected fun computeNext() : Unit { if (iterator.hasNext()) { @@ -104,6 +108,7 @@ class TakeWhileIterator(val iterator: Iterator, val predicate: (T) -> Bool } /** An [[Iterator]] which invokes a function to calculate the next value in the iteration until the function returns *null* */ +deprecated("Use streams for lazy collection operations.") class FunctionIterator(val nextFunction: () -> T?): AbstractIterator() { override protected fun computeNext(): Unit { @@ -117,8 +122,10 @@ class FunctionIterator(val nextFunction: () -> T?): AbstractIterator() } /** An [[Iterator]] which iterates over a number of iterators in sequence */ +deprecated("Use streams for lazy collection operations.") fun CompositeIterator(vararg iterators: Iterator): CompositeIterator = CompositeIterator(iterators.iterator()) +deprecated("Use streams for lazy collection operations.") class CompositeIterator(val iterators: Iterator>): AbstractIterator() { var currentIter: Iterator? = null @@ -147,6 +154,7 @@ class CompositeIterator(val iterators: Iterator>): AbstractIterat } /** A singleton [[Iterator]] which invokes once over a value */ +deprecated("Use streams for lazy collection operations.") class SingleIterator(val value: T): AbstractIterator() { var first = true @@ -160,6 +168,7 @@ class SingleIterator(val value: T): AbstractIterator() { } } +deprecated("Use streams for lazy collection operations.") class IndexIterator(val iterator : Iterator): Iterator> { private var index : Int = 0 @@ -172,6 +181,7 @@ class IndexIterator(val iterator : Iterator): Iterator> { } } +deprecated("Use streams for lazy collection operations.") public class PairIterator( val iterator1 : Iterator, val iterator2 : Iterator ): AbstractIterator>() { @@ -185,6 +195,7 @@ public class PairIterator( } } +deprecated("Use streams for lazy collection operations.") class SkippingIterator(val iterator: Iterator, val n: Int): Iterator { private var firstTime: Boolean = true @@ -208,13 +219,3 @@ class SkippingIterator(val iterator: Iterator, val n: Int): Iterator { return iterator.hasNext() } } - -public fun Function1.toGenerator(initialValue: T): Function0 { - var nextValue: T? = initialValue - return { - nextValue?.let { result -> - nextValue = this@toGenerator(result) - result - } - } -} \ No newline at end of file diff --git a/libraries/stdlib/src/kotlin/IteratorsJVM.kt b/libraries/stdlib/src/kotlin/collections/iterators/IteratorsJVM.kt similarity index 84% rename from libraries/stdlib/src/kotlin/IteratorsJVM.kt rename to libraries/stdlib/src/kotlin/collections/iterators/IteratorsJVM.kt index 14d5e671e2d..7340ec784d6 100644 --- a/libraries/stdlib/src/kotlin/IteratorsJVM.kt +++ b/libraries/stdlib/src/kotlin/collections/iterators/IteratorsJVM.kt @@ -3,8 +3,10 @@ package kotlin import kotlin.support.* /** Returns an iterator over elements that are instances of a given type *R* which is a subclass of *T* */ +deprecated("Use streams for lazy collection operations.") public fun Iterator.filterIsInstance(klass: Class): Iterator = FilterIsIterator(this, klass) +deprecated("Use streams for lazy collection operations.") private class FilterIsIterator(val iterator : Iterator, val klass: Class) : AbstractIterator() { override protected fun computeNext(): Unit { while (iterator.hasNext()) { diff --git a/libraries/stdlib/src/generated/_Iterators.kt b/libraries/stdlib/src/kotlin/collections/iterators/_Iterators.kt similarity index 81% rename from libraries/stdlib/src/generated/_Iterators.kt rename to libraries/stdlib/src/kotlin/collections/iterators/_Iterators.kt index f23b5f75f53..bda28d89fc5 100644 --- a/libraries/stdlib/src/generated/_Iterators.kt +++ b/libraries/stdlib/src/kotlin/collections/iterators/_Iterators.kt @@ -10,6 +10,7 @@ import java.util.* /** * Returns *true* if all elements match the given *predicate* */ +deprecated("Use streams for lazy collection operations.") public inline fun Iterator.all(predicate: (T) -> Boolean) : Boolean { for (element in this) if (!predicate(element)) return false return true @@ -18,6 +19,7 @@ public inline fun Iterator.all(predicate: (T) -> Boolean) : Boolean { /** * Returns *true* if any elements match the given *predicate* */ +deprecated("Use streams for lazy collection operations.") public inline fun Iterator.any(predicate: (T) -> Boolean) : Boolean { for (element in this) if (predicate(element)) return true return false @@ -28,6 +30,7 @@ public inline fun Iterator.any(predicate: (T) -> Boolean) : Boolean { * If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will * a special *truncated* separator (which defaults to "..." */ +deprecated("Use streams for lazy collection operations.") public fun Iterator.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit { buffer.append(prefix) var count = 0 @@ -45,6 +48,7 @@ public fun Iterator.appendString(buffer: Appendable, separator: String = /** * Returns the number of elements which match the given *predicate* */ +deprecated("Use streams for lazy collection operations.") public inline fun Iterator.count(predicate: (T) -> Boolean) : Int { var count = 0 for (element in this) if (predicate(element)) count++ @@ -54,6 +58,7 @@ public inline fun Iterator.count(predicate: (T) -> Boolean) : Int { /** * Returns a list containing everything but the first *n* elements */ +deprecated("Use streams for lazy collection operations.") public fun Iterator.drop(n: Int) : List { return dropWhile(countTo(n)) } @@ -61,6 +66,7 @@ public fun Iterator.drop(n: Int) : List { /** * Returns a list containing the everything but the first elements that satisfy the given *predicate* */ +deprecated("Use streams for lazy collection operations.") public inline fun Iterator.dropWhile(predicate: (T) -> Boolean) : List { return dropWhileTo(ArrayList(), predicate) } @@ -68,6 +74,7 @@ public inline fun Iterator.dropWhile(predicate: (T) -> Boolean) : List /** * Returns a list containing the everything but the first elements that satisfy the given *predicate* */ +deprecated("Use streams for lazy collection operations.") public inline fun > Iterator.dropWhileTo(result: L, predicate: (T) -> Boolean) : L { var start = true for (element in this) { @@ -84,6 +91,7 @@ public inline fun > Iterator.dropWhileTo(result: L, p /** * Returns an iterator over elements which match the given *predicate* */ +deprecated("Use streams for lazy collection operations.") public fun Iterator.filter(predicate: (T) -> Boolean) : Iterator { return FilterIterator(this, predicate) } @@ -91,6 +99,7 @@ public fun Iterator.filter(predicate: (T) -> Boolean) : Iterator { /** * Returns an iterator over elements which don't match the given *predicate* */ +deprecated("Use streams for lazy collection operations.") public inline fun Iterator.filterNot(predicate: (T) -> Boolean) : Iterator { return filter {!predicate(it)} } @@ -98,6 +107,7 @@ public inline fun Iterator.filterNot(predicate: (T) -> Boolean) : Iterato /** * Returns an iterator over non-*null* elements */ +deprecated("Use streams for lazy collection operations.") public fun Iterator.filterNotNull() : Iterator { return FilterNotNullIterator(this) } @@ -105,6 +115,7 @@ public fun Iterator.filterNotNull() : Iterator { /** * Filters all non-*null* elements into the given list */ +deprecated("Use streams for lazy collection operations.") public fun > Iterator.filterNotNullTo(result: C) : C { for (element in this) if (element != null) result.add(element) return result @@ -113,6 +124,7 @@ public fun > Iterator.filterNotNullTo(resu /** * Returns a list containing all elements which do not match the given *predicate* */ +deprecated("Use streams for lazy collection operations.") public inline fun > Iterator.filterNotTo(result: C, predicate: (T) -> Boolean) : C { for (element in this) if (!predicate(element)) result.add(element) return result @@ -121,6 +133,7 @@ public inline fun > Iterator.filterNotTo(result /** * Filters all elements which match the given predicate into the given list */ +deprecated("Use streams for lazy collection operations.") public inline fun > Iterator.filterTo(result: C, predicate: (T) -> Boolean) : C { for (element in this) if (predicate(element)) result.add(element) return result @@ -129,6 +142,7 @@ public inline fun > Iterator.filterTo(result: C /** * Returns the first element which matches the given *predicate* or *null* if none matched */ +deprecated("Use streams for lazy collection operations.") public inline fun Iterator.find(predicate: (T) -> Boolean) : T? { for (element in this) if (predicate(element)) return element return null @@ -137,6 +151,7 @@ public inline fun Iterator.find(predicate: (T) -> Boolean) : T? { /** * Returns an iterator over the concatenated results of transforming each element to one or more values */ +deprecated("Use streams for lazy collection operations.") public fun Iterator.flatMap(transform: (T) -> Iterator) : Iterator { return FlatMapIterator(this, transform) } @@ -144,6 +159,7 @@ public fun Iterator.flatMap(transform: (T) -> Iterator) : Iterator< /** * Returns the result of transforming each element to one or more values which are concatenated together into a single collection */ +deprecated("Use streams for lazy collection operations.") public inline fun > Iterator.flatMapTo(result: C, transform: (T) -> Iterable) : C { for (element in this) { val list = transform(element) @@ -155,6 +171,7 @@ public inline fun > Iterator.flatMapTo(resul /** * Folds all elements from from left to right with the *initial* value to perform the operation on sequential pairs of elements */ +deprecated("Use streams for lazy collection operations.") public inline fun Iterator.fold(initial: R, operation: (R, T) -> R) : R { var answer = initial for (element in this) answer = operation(answer, element) @@ -164,6 +181,7 @@ public inline fun Iterator.fold(initial: R, operation: (R, T) -> R) : /** * Performs the given *operation* on each element */ +deprecated("Use streams for lazy collection operations.") public inline fun Iterator.forEach(operation: (T) -> Unit) : Unit { for (element in this) operation(element) } @@ -171,10 +189,12 @@ public inline fun Iterator.forEach(operation: (T) -> Unit) : Unit { /** * Groups the elements in the collection into a new [[Map]] using the supplied *toKey* function to calculate the key to group the elements by */ +deprecated("Use streams for lazy collection operations.") public inline fun Iterator.groupBy(toKey: (T) -> K) : Map> { return groupByTo(HashMap>(), toKey) } +deprecated("Use streams for lazy collection operations.") public inline fun Iterator.groupByTo(result: MutableMap>, toKey: (T) -> K) : Map> { for (element in this) { val key = toKey(element) @@ -189,15 +209,19 @@ public inline fun Iterator.groupByTo(result: MutableMap Iterator.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String { val buffer = StringBuilder() appendString(buffer, separator, prefix, postfix, limit, truncated) return buffer.toString() } +// ------------------------- + /** * Returns an iterator obtained by applying *transform*, a function transforming an object of type *T* into an object of type *R* */ +deprecated("Use streams for lazy collection operations.") public fun Iterator.map(transform : (T) -> R) : Iterator { return MapIterator(this, transform) } @@ -206,6 +230,7 @@ public fun Iterator.map(transform : (T) -> R) : Iterator { * Transforms each element of this collection with the given *transform* function and * adds each return value to the given *results* collection */ +deprecated("Use streams for lazy collection operations.") public inline fun > Iterator.mapTo(result: C, transform : (T) -> R) : C { for (item in this) result.add(transform(item)) @@ -215,9 +240,10 @@ public inline fun > Iterator.mapTo(result: C /** * Returns the largest element or null if there are no elements */ +deprecated("Use streams for lazy collection operations.") public fun > Iterator.max() : T? { if (!hasNext()) return null - + var max = next() while (hasNext()) { val e = next() @@ -229,9 +255,10 @@ public fun > Iterator.max() : T? { /** * Returns the first element yielding the largest value of the given function or null if there are no elements */ +deprecated("Use streams for lazy collection operations.") public inline fun , T: Any> Iterator.maxBy(f: (T) -> R) : T? { if (!hasNext()) return null - + var maxElem = next() var maxValue = f(maxElem) while (hasNext()) { @@ -248,9 +275,10 @@ public inline fun , T: Any> Iterator.maxBy(f: (T) -> R) : T? /** * Returns the smallest element or null if there are no elements */ +deprecated("Use streams for lazy collection operations.") public fun > Iterator.min() : T? { if (!hasNext()) return null - + var min = next() while (hasNext()) { val e = next() @@ -262,9 +290,10 @@ public fun > Iterator.min() : T? { /** * Returns the first element yielding the smallest value of the given function or null if there are no elements */ +deprecated("Use streams for lazy collection operations.") public inline fun , T: Any> Iterator.minBy(f: (T) -> R) : T? { if (!hasNext()) return null - + var minElem = next() var minValue = f(minElem) while (hasNext()) { @@ -281,6 +310,7 @@ public inline fun , T: Any> Iterator.minBy(f: (T) -> R) : T? /** * Partitions this collection into a pair of collections */ +deprecated("Use streams for lazy collection operations.") public inline fun Iterator.partition(predicate: (T) -> Boolean) : Pair, List> { val first = ArrayList() val second = ArrayList() @@ -297,6 +327,7 @@ public inline fun Iterator.partition(predicate: (T) -> Boolean) : Pair
  • Iterator.plus(collection: Iterable) : Iterator { return plus(collection.iterator()) } @@ -304,6 +335,7 @@ public fun Iterator.plus(collection: Iterable) : Iterator { /** * Creates an [[Iterator]] which iterates over this iterator then the given element at the end */ +deprecated("Use streams for lazy collection operations.") public fun Iterator.plus(element: T) : Iterator { return CompositeIterator(this, SingleIterator(element)) } @@ -311,6 +343,7 @@ public fun Iterator.plus(element: T) : Iterator { /** * Creates an [[Iterator]] which iterates over this iterator then the following iterator */ +deprecated("Use streams for lazy collection operations.") public fun Iterator.plus(iterator: Iterator) : Iterator { return CompositeIterator(this, iterator) } @@ -319,23 +352,25 @@ public fun Iterator.plus(iterator: Iterator) : Iterator { * Applies binary operation to all elements of iterable, going from left to right. * Similar to fold function, but uses the first element as initial value */ +deprecated("Use streams for lazy collection operations.") public inline fun Iterator.reduce(operation: (T, T) -> T) : T { val iterator = this.iterator() if (!iterator.hasNext()) { throw UnsupportedOperationException("Empty iterable can't be reduced") } - + var result: T = iterator.next() //compiler doesn't understand that result will initialized anyway while (iterator.hasNext()) { result = operation(result, iterator.next()) } - + return result } /** * Returns a original Iterable containing all the non-*null* elements, throwing an [[IllegalArgumentException]] if there are any null elements */ +deprecated("Use streams for lazy collection operations.") public fun Iterator.requireNoNulls() : Iterator { return map{ if (it == null) throw IllegalArgumentException("null element in iterator $this") else it @@ -345,6 +380,7 @@ public fun Iterator.requireNoNulls() : Iterator { /** * Reverses the order the elements into a list */ +deprecated("Use streams for lazy collection operations.") public fun Iterator.reverse() : List { val list = toCollection(ArrayList()) Collections.reverse(list) @@ -355,6 +391,7 @@ public fun Iterator.reverse() : List { * Copies all elements into a [[List]] and sorts it by value of compare_function(element) * E.g. arrayList("two" to 2, "one" to 1).sortBy({it.second}) returns list sorted by second element of pair */ +deprecated("Use streams for lazy collection operations.") public inline fun > Iterator.sortBy(f: (T) -> R) : List { val sortedList = toCollection(ArrayList()) val sortBy: Comparator = comparator {(x: T, y: T) -> @@ -369,6 +406,7 @@ public inline fun > Iterator.sortBy(f: (T) -> R) : List Iterator.take(n: Int) : Iterator { var count = n return takeWhile{ --count >= 0 } @@ -377,6 +415,7 @@ public fun Iterator.take(n: Int) : Iterator { /** * Returns an iterator restricted to the first elements that match the given *predicate* */ +deprecated("Use streams for lazy collection operations.") public fun Iterator.takeWhile(predicate: (T) -> Boolean) : Iterator { return TakeWhileIterator(this, predicate) } @@ -384,6 +423,7 @@ public fun Iterator.takeWhile(predicate: (T) -> Boolean) : Iterator { /** * Returns a list containing the first elements that satisfy the given *predicate* */ +deprecated("Use streams for lazy collection operations.") public inline fun > Iterator.takeWhileTo(result: C, predicate: (T) -> Boolean) : C { for (element in this) if (predicate(element)) result.add(element) else break return result @@ -392,6 +432,7 @@ public inline fun > Iterator.takeWhileTo(result /** * Copies all elements into the given collection */ +deprecated("Use streams for lazy collection operations.") public fun > Iterator.toCollection(result: C) : C { for (element in this) result.add(element) return result @@ -400,6 +441,7 @@ public fun > Iterator.toCollection(result: C) : /** * Copies all elements into a [[LinkedList]] */ +deprecated("Use streams for lazy collection operations.") public fun Iterator.toLinkedList() : LinkedList { return toCollection(LinkedList()) } @@ -407,20 +449,39 @@ public fun Iterator.toLinkedList() : LinkedList { /** * Copies all elements into a [[List]] */ +deprecated("Use streams for lazy collection operations.") public fun Iterator.toList() : List { return toCollection(ArrayList()) } +/** + * Copies all elements into a [[ArrayList]] + */ +deprecated("Use streams for lazy collection operations.") +public fun Iterator.toArrayList() : ArrayList { + return toCollection(ArrayList()) +} + /** * Copies all elements into a [[Set]] */ +deprecated("Use streams for lazy collection operations.") public fun Iterator.toSet() : Set { return toCollection(LinkedHashSet()) } +/** + * Copies all elements into a [[HashSet]] + */ +deprecated("Use streams for lazy collection operations.") +public fun Iterator.toHashSet() : HashSet { + return toCollection(HashSet()) +} + /** * Copies all elements into a [[SortedSet]] */ +deprecated("Use streams for lazy collection operations.") public fun Iterator.toSortedSet() : SortedSet { return toCollection(TreeSet()) } @@ -428,6 +489,7 @@ public fun Iterator.toSortedSet() : SortedSet { /** * Returns an iterator of Pairs(index, data) */ +deprecated("Use streams for lazy collection operations.") public fun Iterator.withIndices() : Iterator> { return IndexIterator(iterator()) } diff --git a/libraries/stdlib/src/kotlin/dom/Dom.kt b/libraries/stdlib/src/kotlin/dom/Dom.kt index 5f9c202d1e1..3a840a601c5 100644 --- a/libraries/stdlib/src/kotlin/dom/Dom.kt +++ b/libraries/stdlib/src/kotlin/dom/Dom.kt @@ -153,7 +153,7 @@ fun Document?.get(selector: String): List { val id = selector.substring(1) val element = this?.getElementById(id) return if (element != null) - arrayList(element) + arrayListOf(element) else emptyElementList() } else { @@ -174,7 +174,7 @@ fun Element.get(selector: String): List { } else if (selector.startsWith("#")) { val element = this.ownerDocument?.getElementById(selector.substring(1)) return if (element != null) - arrayList(element) + arrayListOf(element) else emptyElementList() } else { @@ -259,33 +259,35 @@ fun Node.clear(): Unit { } /** Returns an [[Iterator]] over the next siblings of this node */ -fun Node.nextSiblings() : Iterator = NextSiblingIterator(this) +fun Node.nextSiblings() : Iterable = NextSiblings(this) -class NextSiblingIterator(var node: Node) : AbstractIterator() { - - override fun computeNext(): Unit { - val nextValue = node.nextSibling - if (nextValue != null) { - setNext(nextValue) - node = nextValue - } else { - done() +class NextSiblings(var node: Node) : Iterable { + override fun iterator(): Iterator = object : AbstractIterator() { + override fun computeNext(): Unit { + val nextValue = node.nextSibling + if (nextValue != null) { + setNext(nextValue) + node = nextValue + } else { + done() + } } } } /** Returns an [[Iterator]] over the next siblings of this node */ -fun Node.previousSiblings() : Iterator = PreviousSiblingIterator(this) +fun Node.previousSiblings() : Iterable = PreviousSiblings(this) -class PreviousSiblingIterator(var node: Node) : AbstractIterator() { - - override fun computeNext(): Unit { - val nextValue = node.previousSibling - if (nextValue != null) { - setNext(nextValue) - node = nextValue - } else { - done() +class PreviousSiblings(var node: Node) : Iterable { + override fun iterator(): Iterator = object : AbstractIterator() { + override fun computeNext(): Unit { + val nextValue = node.previousSibling + if (nextValue != null) { + setNext(nextValue) + node = nextValue + } else { + done() + } } } } diff --git a/libraries/stdlib/src/kotlin/dom/DomJVM.kt b/libraries/stdlib/src/kotlin/dom/DomJVM.kt index e7cf03ecdd7..faf84c86f21 100644 --- a/libraries/stdlib/src/kotlin/dom/DomJVM.kt +++ b/libraries/stdlib/src/kotlin/dom/DomJVM.kt @@ -112,10 +112,10 @@ public val NodeList.outerHTML: String get() = toList().map { it.innerHTML }.makeString("") /** Returns an [[Iterator]] of all the next [[Element]] siblings */ -fun Node.nextElements(): Iterator = nextSiblings().filterIsInstance(javaClass()) +fun Node.nextElements(): List = nextSiblings().filterIsInstance(javaClass()) /** Returns an [[Iterator]] of all the previous [[Element]] siblings */ -fun Node.previousElements(): Iterator = previousSiblings().filterIsInstance(javaClass()) +fun Node.previousElements(): List = previousSiblings().filterIsInstance(javaClass()) var Element.classSet : MutableSet diff --git a/libraries/stdlib/src/kotlin/io/Closable.kt b/libraries/stdlib/src/kotlin/io/Closable.kt new file mode 100644 index 00000000000..eab1f333822 --- /dev/null +++ b/libraries/stdlib/src/kotlin/io/Closable.kt @@ -0,0 +1,31 @@ +package kotlin + +import java.io.Closeable + +/** Uses the given resource then closes it down correctly whether an exception is thrown or not */ +public inline fun T.use(block: (T) -> R): R { + var closed = false + try { + return block(this) + } catch (e: Exception) { + closed = true + try { + this.close() + } catch (closeException: Exception) { + // eat the closeException as we are already throwing the original cause + // and we don't want to mask the real exception + + // TODO on Java 7 we should call + // e.addSuppressed(closeException) + // to work like try-with-resources + // http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html#suppressed-exceptions + } + throw e + } finally { + if (!closed) { + this.close() + } + } +} + + diff --git a/libraries/stdlib/src/kotlin/io/Files.kt b/libraries/stdlib/src/kotlin/io/Files.kt index 3ecc0cce932..9b872f267b5 100644 --- a/libraries/stdlib/src/kotlin/io/Files.kt +++ b/libraries/stdlib/src/kotlin/io/Files.kt @@ -92,21 +92,21 @@ public fun File.reader(): FileReader = FileReader(this) * This method is not recommended on huge files. */ public fun File.readBytes(): ByteArray { - return FileInputStream(this).use{ it.readBytes(this.length().toInt()) } + return FileInputStream(this).use { it.readBytes(this.length().toInt()) } } /** * Writes the bytes as the contents of the file */ public fun File.writeBytes(data: ByteArray): Unit { - return FileOutputStream(this).use{ it.write(data) } + return FileOutputStream(this).use { it.write(data) } } /** * Appends bytes to the contents of the file. */ public fun File.appendBytes(data: ByteArray): Unit { - return FileOutputStream(this, true).use{ it.write(data) } + return FileOutputStream(this, true).use { it.write(data) } } /** diff --git a/libraries/stdlib/src/kotlin/io/JIO.kt b/libraries/stdlib/src/kotlin/io/JIO.kt index 3ff6bd969b9..2136380db87 100644 --- a/libraries/stdlib/src/kotlin/io/JIO.kt +++ b/libraries/stdlib/src/kotlin/io/JIO.kt @@ -17,84 +17,84 @@ public val defaultCharset: Charset = Charset.forName("UTF-8")!! /** Prints the given message to [[System.out]] */ -public fun print(message : Any?) { +public fun print(message: Any?) { System.out.print(message) } /** Prints the given message to [[System.out]] */ -public fun print(message : Int) { +public fun print(message: Int) { System.out.print(message) } /** Prints the given message to [[System.out]] */ -public fun print(message : Long) { +public fun print(message: Long) { System.out.print(message) } /** Prints the given message to [[System.out]] */ -public fun print(message : Byte) { +public fun print(message: Byte) { System.out.print(message) } /** Prints the given message to [[System.out]] */ -public fun print(message : Short) { +public fun print(message: Short) { System.out.print(message) } /** Prints the given message to [[System.out]] */ -public fun print(message : Char) { +public fun print(message: Char) { System.out.print(message) } /** Prints the given message to [[System.out]] */ -public fun print(message : Boolean) { +public fun print(message: Boolean) { System.out.print(message) } /** Prints the given message to [[System.out]] */ -public fun print(message : Float) { +public fun print(message: Float) { System.out.print(message) } /** Prints the given message to [[System.out]] */ -public fun print(message : Double) { +public fun print(message: Double) { System.out.print(message) } /** Prints the given message to [[System.out]] */ -public fun print(message : CharArray) { +public fun print(message: CharArray) { System.out.print(message) } /** Prints the given message and newline to [[System.out]] */ -public fun println(message : Any?) { +public fun println(message: Any?) { System.out.println(message) } /** Prints the given message and newline to [[System.out]] */ -public fun println(message : Int) { +public fun println(message: Int) { System.out.println(message) } /** Prints the given message and newline to [[System.out]] */ -public fun println(message : Long) { +public fun println(message: Long) { System.out.println(message) } /** Prints the given message and newline to [[System.out]] */ -public fun println(message : Byte) { +public fun println(message: Byte) { System.out.println(message) } /** Prints the given message and newline to [[System.out]] */ -public fun println(message : Short) { +public fun println(message: Short) { System.out.println(message) } /** Prints the given message and newline to [[System.out]] */ -public fun println(message : Char) { +public fun println(message: Char) { System.out.println(message) } /** Prints the given message and newline to [[System.out]] */ -public fun println(message : Boolean) { +public fun println(message: Boolean) { System.out.println(message) } /** Prints the given message and newline to [[System.out]] */ -public fun println(message : Float) { +public fun println(message: Float) { System.out.println(message) } /** Prints the given message and newline to [[System.out]] */ -public fun println(message : Double) { +public fun println(message: Double) { System.out.println(message) } /** Prints the given message and newline to [[System.out]] */ -public fun println(message : CharArray) { +public fun println(message: CharArray) { System.out.println(message) } /** Prints a newline t[[System.out]] */ @@ -102,8 +102,11 @@ public fun println() { System.out.println() } -private val stdin : BufferedReader = BufferedReader(InputStreamReader(object : InputStream() { - public override fun read() : Int { +// Since System.in can change its value on the course of program running, +// we should always delegate to current value and cannot just pass it to InputStreamReader constructor. +// We could use "by" implementation, but we can only use "by" with traits and InputStream is abstract class. +private val stdin: BufferedReader = BufferedReader(InputStreamReader(object : InputStream() { + public override fun read(): Int { return System.`in`.read() } @@ -141,80 +144,62 @@ private val stdin : BufferedReader = BufferedReader(InputStreamReader(object : I })) /** Reads a line of input from [[System.in]] */ -public fun readLine() : String? = stdin.readLine() - -/** Uses the given resource then closes it down correctly whether an exception is thrown or not */ -public inline fun T.use(block: (T)-> R) : R { - var closed = false - try { - return block(this) - } catch (e: Exception) { - closed = true - try { - this.close() - } catch (closeException: Exception) { - // eat the closeException as we are already throwing the original cause - // and we don't want to mask the real exception - - // TODO on Java 7 we should call - // e.addSuppressed(closeException) - // to work like try-with-resources - // http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html#suppressed-exceptions - } - throw e - } finally { - if (!closed) { - this.close() - } - } -} +public fun readLine(): String? = stdin.readLine() /** Returns an [Iterator] of bytes over an input stream */ -public fun InputStream.iterator() : ByteIterator = -object: ByteIterator() { - override fun hasNext() : Boolean = available() > 0 +public fun InputStream.iterator(): ByteIterator = + object: ByteIterator() { + override fun hasNext(): Boolean = available() > 0 - public override fun nextByte() : Byte = read().toByte() -} + public override fun nextByte(): Byte = read().toByte() + } /** Creates a buffered input stream */ -public fun InputStream.buffered(bufferSize: Int = defaultBufferSize) : InputStream -= if (this is BufferedInputStream) +public fun InputStream.buffered(bufferSize: Int = defaultBufferSize): InputStream + = if (this is BufferedInputStream) this else BufferedInputStream(this, bufferSize) -public fun InputStream.reader(encoding: Charset = defaultCharset) : InputStreamReader = InputStreamReader(this, encoding) +/** Creates a reader on an input stream with specified *encoding* */ +public fun InputStream.reader(encoding: Charset = defaultCharset): InputStreamReader = InputStreamReader(this, encoding) -public fun InputStream.reader(encoding: String) : InputStreamReader = InputStreamReader(this, encoding) +/** Creates a reader on an input stream with specified *encoding* */ +public fun InputStream.reader(encoding: String): InputStreamReader = InputStreamReader(this, encoding) -public fun InputStream.reader(encoding: CharsetDecoder) : InputStreamReader = InputStreamReader(this, encoding) +/** Creates a reader on an input stream with specified *encoding* */ +public fun InputStream.reader(encoding: CharsetDecoder): InputStreamReader = InputStreamReader(this, encoding) -public fun OutputStream.buffered(bufferSize: Int = defaultBufferSize) : BufferedOutputStream -= if (this is BufferedOutputStream) this else BufferedOutputStream(this, bufferSize) +/** Creates a buffered output stream */ +public fun OutputStream.buffered(bufferSize: Int = defaultBufferSize): BufferedOutputStream + = if (this is BufferedOutputStream) this else BufferedOutputStream(this, bufferSize) -public fun OutputStream.writer(encoding: Charset = defaultCharset) : OutputStreamWriter = OutputStreamWriter(this, encoding) +/** Creates a writer on an output stream with specified *encoding* */ +public fun OutputStream.writer(encoding: Charset = defaultCharset): OutputStreamWriter = OutputStreamWriter(this, encoding) -public fun OutputStream.writer(encoding: String) : OutputStreamWriter = OutputStreamWriter(this, encoding) +/** Creates a writer on an output stream with specified *encoding* */ +public fun OutputStream.writer(encoding: String): OutputStreamWriter = OutputStreamWriter(this, encoding) -public fun OutputStream.writer(encoding: CharsetEncoder) : OutputStreamWriter = OutputStreamWriter(this, encoding) +/** Creates a writer on an output stream with specified *encoding* */ +public fun OutputStream.writer(encoding: CharsetEncoder): OutputStreamWriter = OutputStreamWriter(this, encoding) +/** Creates a buffered reader, or returns self if Reader is already buffered */ public fun Reader.buffered(bufferSize: Int = defaultBufferSize): BufferedReader -= if(this is BufferedReader) this else BufferedReader(this, bufferSize) + = if (this is BufferedReader) this else BufferedReader(this, bufferSize) +/** Creates a buffered writer, or returns self if Writer is already buffered */ public fun Writer.buffered(bufferSize: Int = defaultBufferSize): BufferedWriter -= if(this is BufferedWriter) this else BufferedWriter(this, bufferSize) - + = if (this is BufferedWriter) this else BufferedWriter(this, bufferSize) /** * Iterates through each line of this reader then closing the [[Reader]] when its completed */ -public inline fun Reader.forEachLine(block: (String) -> Unit): Unit = useLines { lines -> lines.forEach(block) } +public fun Reader.forEachLine(block: (String) -> Unit): Unit = useLines { lines -> lines.forEach(block) } -public inline fun Reader.useLines(block: (Iterator) -> T): T = - this.buffered().use{ block(it.lineIterator()) } +public inline fun Reader.useLines(block: (Stream) -> T): T = + this.buffered().use { block(it.lines()) } /** * Returns an iterator over each line. @@ -224,33 +209,38 @@ public inline fun Reader.useLines(block: (Iterator) -> T): T = *
    * We suggest you try the method useLines() instead which closes the stream when the processing is complete. */ -public fun BufferedReader.lineIterator() : Iterator = LineIterator(this) +public fun BufferedReader.lines(): Stream = LinesStream(this) -class LineIterator(val reader: BufferedReader) : Iterator { - private var nextValue: String? = null - private var done = false +deprecated("Use lines() function which returns Stream") +public fun BufferedReader.lineIterator(): Iterator = lines().iterator() - override fun hasNext(): Boolean { - if (nextValue == null && !done) { - nextValue = reader.readLine() - if (nextValue == null) done = true +class LinesStream(val reader: BufferedReader) : Stream { + override fun iterator(): Iterator { + return object : Iterator { + private var nextValue: String? = null + private var done = false + + override fun hasNext(): Boolean { + if (nextValue == null && !done) { + nextValue = reader.readLine() + if (nextValue == null) done = true + } + return nextValue != null + } + + public override fun next(): String { + if (!hasNext()) { + throw NoSuchElementException() + } + val answer = nextValue + nextValue = null + return answer!! + } } - return nextValue != null - } - - public override fun next(): String { - if (!hasNext()) { - throw NoSuchElementException() - } - val answer = nextValue - nextValue = null - return answer!! } } - - /** * Reads this stream completely into a byte array * @@ -326,5 +316,5 @@ public fun URL.readText(encoding: Charset): String = readBytes().toString(encodi * * This method is not recommended on huge files. */ -public fun URL.readBytes(): ByteArray = this.openStream()!!.use{ it.readBytes() } +public fun URL.readBytes(): ByteArray = this.openStream()!!.use{ it.readBytes() } diff --git a/libraries/stdlib/src/kotlin/test/TestJVM.kt b/libraries/stdlib/src/kotlin/test/TestJVM.kt index ccf28e2d9f9..5547c8dd8ec 100644 --- a/libraries/stdlib/src/kotlin/test/TestJVM.kt +++ b/libraries/stdlib/src/kotlin/test/TestJVM.kt @@ -31,7 +31,7 @@ public var asserter: Asserter if (_asserter == null) { val klass = javaClass() val loader = ServiceLoader.load(klass) - for (a in loader.iterator()) { + for (a in loader) { if (a != null) { _asserter = a break diff --git a/libraries/stdlib/src/kotlin/Char.kt b/libraries/stdlib/src/kotlin/text/Char.kt similarity index 95% rename from libraries/stdlib/src/kotlin/Char.kt rename to libraries/stdlib/src/kotlin/text/Char.kt index 6de4b87ead6..8f6e20e5a21 100644 --- a/libraries/stdlib/src/kotlin/Char.kt +++ b/libraries/stdlib/src/kotlin/text/Char.kt @@ -21,7 +21,7 @@ public fun Char.isJavaLetterOrDigit(): Boolean = Character.isJavaLetterOrDigit(t /** * Returns true if the character is whitespace * - * @includeFunctionBody ../../test/StringTest.kt count + * @includeFunctionBody ../../test/text/StringTest.kt count */ public fun Char.isWhitespace(): Boolean = Character.isWhitespace(this) diff --git a/libraries/stdlib/src/kotlin/Strings.kt b/libraries/stdlib/src/kotlin/text/Strings.kt similarity index 89% rename from libraries/stdlib/src/kotlin/Strings.kt rename to libraries/stdlib/src/kotlin/text/Strings.kt index 31250f69b2f..f0e8513495e 100644 --- a/libraries/stdlib/src/kotlin/Strings.kt +++ b/libraries/stdlib/src/kotlin/text/Strings.kt @@ -8,6 +8,12 @@ import java.util.LinkedList /** Returns the string with leading and trailing text matching the given string removed */ public fun String.trim(text: String) : String = trimLeading(text).trimTrailing(text) +/** Returns the first character */ +public fun String.first() : Char = this[0] + +/** Returns the last character */ +public fun String.last() : Char = this[length - 1] + /** Returns the string with the prefix and postfix text trimmed */ public fun String.trim(prefix: String, postfix: String) : String = trimLeading(prefix).trimTrailing(postfix) @@ -55,7 +61,7 @@ get() = this.length /** * Counts the number of characters which match the given predicate * - * @includeFunctionBody ../../test/StringTest.kt count + * @includeFunctionBody ../../test/text/StringTest.kt count */ public inline fun String.count(predicate: (Char) -> Boolean): Int { var answer = 0 diff --git a/libraries/stdlib/src/kotlin/StringsJVM.kt b/libraries/stdlib/src/kotlin/text/StringsJVM.kt similarity index 91% rename from libraries/stdlib/src/kotlin/StringsJVM.kt rename to libraries/stdlib/src/kotlin/text/StringsJVM.kt index 288b59b21d9..8b86c35c7a3 100644 --- a/libraries/stdlib/src/kotlin/StringsJVM.kt +++ b/libraries/stdlib/src/kotlin/text/StringsJVM.kt @@ -176,7 +176,7 @@ get() = length() /** * Returns a copy of this string capitalised if it is not empty or already starting with an uppper case letter, otherwise returns this * - * @includeFunctionBody ../../test/StringTest.kt capitalize + * @includeFunctionBody ../../test/text/StringTest.kt capitalize */ public fun String.capitalize(): String { return if (isNotEmpty() && charAt(0).isLowerCase()) substring(0, 1).toUpperCase() + substring(1) else this @@ -185,7 +185,7 @@ public fun String.capitalize(): String { /** * Returns a copy of this string with the first letter lower case if it is not empty or already starting with a lower case letter, otherwise returns this * - * @includeFunctionBody ../../test/StringTest.kt decapitalize + * @includeFunctionBody ../../test/text/StringTest.kt decapitalize */ public fun String.decapitalize(): String { return if (isNotEmpty() && charAt(0).isUpperCase()) substring(0, 1).toLowerCase() + substring(1) else this @@ -194,7 +194,7 @@ public fun String.decapitalize(): String { /** * Repeats a given string n times. * When n < 0, IllegalArgumentException is thrown. - * @includeFunctionBody ../../test/StringTest.kt repeat + * @includeFunctionBody ../../test/text/StringTest.kt repeat */ public fun String.repeat(n: Int): String { require(n >= 0, { "Cannot repeat string $n times" }) @@ -209,14 +209,14 @@ public fun String.repeat(n: Int): String { /** * Filters characters which match the given predicate into new String object * - * @includeFunctionBody ../../test/StringTest.kt filter + * @includeFunctionBody ../../test/text/StringTest.kt filter */ public inline fun String.filter(predicate: (Char) -> Boolean): String = filterTo(StringBuilder(), predicate).toString() /** * Returns an Appendable containing all characters which match the given *predicate* * - * @includeFunctionBody ../../test/StringTest.kt filter + * @includeFunctionBody ../../test/text/StringTest.kt filter */ public inline fun String.filterTo(result: T, predicate: (Char) -> Boolean): T { @@ -227,14 +227,14 @@ public inline fun String.filterTo(result: T, predicate: (Char) - /** * Filters characters which match the given predicate into new String object * - * @includeFunctionBody ../../test/StringTest.kt filterNot + * @includeFunctionBody ../../test/text/StringTest.kt filterNot */ public inline fun String.filterNot(predicate: (Char) -> Boolean): String = filterNotTo(StringBuilder(), predicate).toString() /** * Returns an Appendable containing all characters which do not match the given *predicate* * - * @includeFunctionBody ../../test/StringTest.kt filterNot + * @includeFunctionBody ../../test/text/StringTest.kt filterNot */ public inline fun String.filterNotTo(result: T, predicate: (Char) -> Boolean): T { for (element in this) if (!predicate(element)) result.append(element) @@ -244,21 +244,21 @@ public inline fun String.filterNotTo(result: T, predicate: (Char /** * Reverses order of characters in a string * - * @includeFunctionBody ../../test/StringTest.kt reverse + * @includeFunctionBody ../../test/text/StringTest.kt reverse */ public fun String.reverse(): String = StringBuilder(this).reverse().toString() /** * Performs the given *operation* on each character * - * @includeFunctionBody ../../test/StringTest.kt forEach + * @includeFunctionBody ../../test/text/StringTest.kt forEach */ public inline fun String.forEach(operation: (Char) -> Unit) { for(c in this) operation(c) } /** * Returns *true* if all characters match the given *predicate* * - * @includeFunctionBody ../../test/StringTest.kt all + * @includeFunctionBody ../../test/text/StringTest.kt all */ public inline fun String.all(predicate: (Char) -> Boolean): Boolean { for(c in this) if(!predicate(c)) return false @@ -268,7 +268,7 @@ public inline fun String.all(predicate: (Char) -> Boolean): Boolean { /** * Returns *true* if any character matches the given *predicate* * - * @includeFunctionBody ../../test/StringTest.kt any + * @includeFunctionBody ../../test/text/StringTest.kt any */ public inline fun String.any(predicate: (Char) -> Boolean): Boolean { for (c in this) if (predicate(c)) return true @@ -281,7 +281,7 @@ public inline fun String.any(predicate: (Char) -> Boolean): Boolean { * If a string could be huge you can specify a non-negative value of *limit* which will only show substring then it will * a special *truncated* separator (which defaults to "..." * - * @includeFunctionBody ../../test/StringTest.kt appendString + * @includeFunctionBody ../../test/text/StringTest.kt appendString */ public fun String.appendString(buffer: Appendable, separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): Unit { buffer.append(prefix) @@ -297,7 +297,7 @@ public fun String.appendString(buffer: Appendable, separator: String = ", ", pre /** * Returns the first character which matches the given *predicate* or *null* if none matched * - * @includeFunctionBody ../../test/StringTest.kt find + * @includeFunctionBody ../../test/text/StringTest.kt find */ public inline fun String.find(predicate: (Char) -> Boolean): Char? { for (c in this) if (predicate(c)) return c @@ -307,7 +307,7 @@ public inline fun String.find(predicate: (Char) -> Boolean): Char? { /** * Returns the first character which does not match the given *predicate* or *null* if none matched * - * @includeFunctionBody ../../test/StringTest.kt findNot + * @includeFunctionBody ../../test/text/StringTest.kt findNot */ public inline fun String.findNot(predicate: (Char) -> Boolean): Char? { for (c in this) if (!predicate(c)) return c @@ -317,7 +317,7 @@ public inline fun String.findNot(predicate: (Char) -> Boolean): Char? { /** * Partitions this string into a pair of string * -* @includeFunctionBody ../../test/StringTest.kt partition +* @includeFunctionBody ../../test/text/StringTest.kt partition */ public inline fun String.partition(predicate: (Char) -> Boolean): Pair { val first = StringBuilder() @@ -351,14 +351,14 @@ public inline fun > String.mapTo(result: C, transf /** * Returns the result of transforming each character to one or more values which are concatenated together into a single list * - * @includeFunctionBody ../../test/StringTest.kt flatMap + * @includeFunctionBody ../../test/text/StringTest.kt flatMap */ public inline fun String.flatMap(transform: (Char) -> Collection): Collection = flatMapTo(ArrayList(), transform) /** * Returns the result of transforming each character to one or more values which are concatenated together into a passed list * - * @includeFunctionBody ../../test/StringTest.kt flatMap + * @includeFunctionBody ../../test/text/StringTest.kt flatMap */ public inline fun String.flatMapTo(result: MutableCollection, transform: (Char) -> Collection): Collection { for (c in this) result.addAll(transform(c)) @@ -368,7 +368,7 @@ public inline fun String.flatMapTo(result: MutableCollection, transform: /** * Folds all characters from left to right with the *initial* value to perform the operation on sequential pairs of characters * - * @includeFunctionBody ../../test/StringTest.kt fold + * @includeFunctionBody ../../test/text/StringTest.kt fold */ public inline fun String.fold(initial: R, operation: (R, Char) -> R): R { var answer = initial @@ -379,7 +379,7 @@ public inline fun String.fold(initial: R, operation: (R, Char) -> R): R { /** * Folds all characters from right to left with the *initial* value to perform the operation on sequential pairs of characters * - * @includeFunctionBody ../../test/StringTest.kt foldRight + * @includeFunctionBody ../../test/text/StringTest.kt foldRight */ public inline fun String.foldRight(initial: R, operation: (Char, R) -> R): R = reverse().fold(initial, { x, y -> operation(y, x) }) @@ -387,7 +387,7 @@ public inline fun String.foldRight(initial: R, operation: (Char, R) -> R): R * Applies binary operation to all characters in a string, going from left to right. * Similar to fold function, but uses the first character as initial value * - * @includeFunctionBody ../../test/StringTest.kt reduce + * @includeFunctionBody ../../test/text/StringTest.kt reduce */ public inline fun String.reduce(operation: (Char, Char) -> Char): Char { val iterator = this.iterator() @@ -407,7 +407,7 @@ public inline fun String.reduce(operation: (Char, Char) -> Char): Char { * Applies binary operation to all characters in a string, going from right to left. * Similar to foldRight function, but uses the last character as initial value * - * @includeFunctionBody ../../test/StringTest.kt reduceRight + * @includeFunctionBody ../../test/text/StringTest.kt reduceRight */ public inline fun String.reduceRight(operation: (Char, Char) -> Char): Char = reverse().reduce { x, y -> operation(y, x) } @@ -415,14 +415,14 @@ public inline fun String.reduceRight(operation: (Char, Char) -> Char): Char = re /** * Groups the characters in the string into a new [[Map]] using the supplied *toKey* function to calculate the key to group the characters by * - * @includeFunctionBody ../../test/StringTest.kt groupBy + * @includeFunctionBody ../../test/text/StringTest.kt groupBy */ public inline fun String.groupBy(toKey: (Char) -> K): Map = groupByTo(HashMap(), toKey) /** * Groups the characters in the string into the given [[Map]] using the supplied *toKey* function to calculate the key to group the characters by * - * @includeFunctionBody ../../test/StringTest.kt groupBy + * @includeFunctionBody ../../test/text/StringTest.kt groupBy */ public inline fun String.groupByTo(result: MutableMap, toKey: (Char) -> K): Map { for (c in this) { @@ -439,7 +439,7 @@ public inline fun String.groupByTo(result: MutableMap, toKey: (Ch * If a string could be huge you can specify a non-negative value of *limit* which will only show a substring then it will * a special *truncated* separator (which defaults to "..." * - * @includeFunctionBody ../../test/StringTest.kt makeString + * @includeFunctionBody ../../test/text/StringTest.kt makeString */ public fun String.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): String { val buffer = StringBuilder() @@ -450,7 +450,7 @@ public fun String.makeString(separator: String = ", ", prefix: String = "", post /** * Returns an Appendable containing the everything but the first characters that satisfy the given *predicate* * - * @includeFunctionBody ../../test/StringTest.kt dropWhile + * @includeFunctionBody ../../test/text/StringTest.kt dropWhile */ public inline fun String.dropWhileTo(result: T, predicate: (Char) -> Boolean): T { var start = true @@ -468,21 +468,21 @@ public inline fun String.dropWhileTo(result: T, predicate: (Char /** * Returns a new String containing the everything but the first characters that satisfy the given *predicate* * - * @includeFunctionBody ../../test/StringTest.kt dropWhile + * @includeFunctionBody ../../test/text/StringTest.kt dropWhile */ public inline fun String.dropWhile(predicate: (Char) -> Boolean): String = dropWhileTo(StringBuilder(), predicate).toString() /** * Returns a string containing everything but the first *n* characters * - * @includeFunctionBody ../../test/StringTest.kt drop + * @includeFunctionBody ../../test/text/StringTest.kt drop */ -public fun String.drop(n: Int): String = dropWhile(countTo(n)) +public fun String.drop(n: Int): String = substring(Math.min(length, n)) /** * Returns an Appendable containing the first characters that satisfy the given *predicate* * - * @includeFunctionBody ../../test/StringTest.kt takeWhile + * @includeFunctionBody ../../test/text/StringTest.kt takeWhile */ public inline fun String.takeWhileTo(result: T, predicate: (Char) -> Boolean): T { for (c in this) if (predicate(c)) result.append(c) else break @@ -492,16 +492,16 @@ public inline fun String.takeWhileTo(result: T, predicate: (Char /** * Returns a new String containing the first characters that satisfy the given *predicate* * - * @includeFunctionBody ../../test/StringTest.kt takeWhile + * @includeFunctionBody ../../test/text/StringTest.kt takeWhile */ public inline fun String.takeWhile(predicate: (Char) -> Boolean): String = takeWhileTo(StringBuilder(), predicate).toString() /** * Returns a string containing the first *n* characters * - * @includeFunctionBody ../../test/StringTest.kt take + * @includeFunctionBody ../../test/text/StringTest.kt take */ -public fun String.take(n: Int): String = takeWhile(countTo(n)) +public fun String.take(n: Int): String = substring(0, Math.min(length, n)) /** Copies all characters into the given collection */ public fun > String.toCollection(result: C): C { diff --git a/libraries/stdlib/test/CollectionApiCheck.kt b/libraries/stdlib/test/CollectionApiCheck.kt deleted file mode 100644 index 615ec8ee36e..00000000000 --- a/libraries/stdlib/test/CollectionApiCheck.kt +++ /dev/null @@ -1,35 +0,0 @@ -package test.apicheck - -import kotlin.util.* -import java.util.* - -trait Traversable { - - /** Returns true if any elements in the collection match the given predicate */ - fun any(predicate: (T)-> Boolean) : Boolean - - /** Returns true if all elements in the collection match the given predicate */ - fun all(predicate: (T)-> Boolean) : Boolean - - /** Returns the first item in the collection which matches the given predicate or null if none matched */ - fun find(predicate: (T)-> Boolean) : T? - - /** Returns a new collection containing all elements in this collection which match the given predicate */ - // TODO using: Collection for the return type - I wonder if this exact type could be - // deduced somewhat from the This.Type; e.g. returning Set on a Set, Array on Array etc - fun filter(predicate: (T)-> Boolean) : Collection - - /** Performs the given operation on each element inside the collection */ - fun forEach(operation: (element: T)-> Unit) - - /** Returns a new collection containing the results of applying the given function to each element in this collection */ - fun Iterable.map(transform : (T)-> R) : Collection -} - -/** -TODO try use delegation here to make sure we implement all the methods in the Traversable API - -class ListImpl(coll: ArrayList) : Traversable by coll { -} - -*/ diff --git a/libraries/stdlib/test/CollectionJVMTest.kt b/libraries/stdlib/test/CollectionJVMTest.kt deleted file mode 100644 index b62b23fd264..00000000000 --- a/libraries/stdlib/test/CollectionJVMTest.kt +++ /dev/null @@ -1,124 +0,0 @@ -package test.collections - -import kotlin.test.* - -import java.util.* - -import org.junit.Test as test - -class CollectionJVMTest { - - test fun flatMap() { - val data = arrayList("", "foo", "bar", "x", "") - val characters = data.flatMap{ it.toCharList() } - println("Got list of characters ${characters}") - assertEquals(7, characters.size()) - val text = characters.makeString("") - assertEquals("foobarx", text) - } - - - // TODO would be nice to avoid the - test fun filterIntoLinkedList() { - val data = arrayList("foo", "bar") - val foo = data.filterTo(linkedList()){it.startsWith("f")} - - assertTrue { - foo.all{it.startsWith("f")} - } - assertEquals(1, foo.size) - assertEquals(linkedList("foo"), foo) - - assertTrue { - foo is LinkedList - } - } - - // TODO would be nice to avoid the - test fun filterNotIntoLinkedList() { - val data = arrayList("foo", "bar") - val foo = data.filterNotTo(linkedList()){it.startsWith("f")} - - assertTrue { - foo.all{!it.startsWith("f")} - } - assertEquals(1, foo.size) - assertEquals(linkedList("bar"), foo) - - assertTrue { - foo is LinkedList - } - } - - // TODO would be nice to avoid the - test fun filterNotNullIntoLinkedList() { - val data = arrayList(null, "foo", null, "bar") - val foo = data.filterNotNullTo(linkedList()) - - assertEquals(2, foo.size) - assertEquals(linkedList("foo", "bar"), foo) - - assertTrue { - foo is LinkedList - } - } - - - // TODO would be nice to avoid the - test fun filterIntoSortedSet() { - val data = arrayList("foo", "bar") - val sorted = data.filterTo(sortedSet()){it.length == 3} - assertEquals(2, sorted.size) - assertEquals(sortedSet("bar", "foo"), sorted) - assertTrue { - sorted is TreeSet - } - } - - //todo after KT-1873 the name might be returned to 'last' - test fun lastElement() { - val data = arrayList("foo", "bar") - assertEquals("bar", data.last()) - assertEquals(25, arrayList(15, 19, 20, 25).last()) - assertEquals('a', linkedList('a').last()) - } - - test fun lastException() { - fails { linkedList().last() } - } - - test fun contains() { - assertTrue(linkedList(15, 19, 20).contains(15)) - } - - test fun sortBy() { - expect(arrayList("two" to 2, "three" to 3)) { - arrayList("three" to 3, "two" to 2).sortBy { it.second } - } - expect(arrayList("three" to 3, "two" to 2)) { - arrayList("three" to 3, "two" to 2).sortBy { it.first } - } - expect(arrayList("two" to 2, "three" to 3)) { - arrayList("three" to 3, "two" to 2).sortBy { it.first.length } - } - } - - - test fun sortFunctionShouldReturnSortedCopyForList() { - // TODO fixme Some sort of in/out variance thing - or an issue with Java interop? - todo { -// val list : List = arrayList(2, 3, 1) -// expect(arrayList(1, 2, 3)) { list.sort() } -// expect(arrayList(2, 3, 1)) { list } - } - } - - test fun sortFunctionShouldReturnSortedCopyForIterable() { - // TODO fixme Some sort of in/out variance thing - or an issue with Java interop? - todo { -// val list : Iterable = arrayList(2, 3, 1) -// expect(arrayList(1, 2, 3)) { list.sort() } -// expect(arrayList(2, 3, 1)) { list } - } - } -} diff --git a/libraries/stdlib/test/CollectionTest.kt b/libraries/stdlib/test/CollectionTest.kt deleted file mode 100644 index a09ac9a6b3f..00000000000 --- a/libraries/stdlib/test/CollectionTest.kt +++ /dev/null @@ -1,492 +0,0 @@ -package test.collections - -import kotlin.test.* - -import java.util.* - -import org.junit.Test as test - -class CollectionTest { - - test fun all() { - val data = arrayList("foo", "bar") - assertTrue { - data.all{it.length == 3} - } - assertNot { - data.all{s -> s.startsWith("b")} - } - } - - test fun any() { - val data = arrayList("foo", "bar") - assertTrue { - data.any{it.startsWith("f")} - } - assertNot { - data.any{it.startsWith("x")} - } - } - - - test fun appendString() { - val data = arrayList("foo", "bar") - val buffer = StringBuilder() - val text = data.appendString(buffer, "-", "{", "}") - assertEquals("{foo-bar}", buffer.toString()) - } - - test fun count() { - val data = arrayList("foo", "bar") - assertEquals(1, data.count{it.startsWith("b")}) - assertEquals(2, data.count{it.size == 3}) - } - - test fun filter() { - val data = arrayList("foo", "bar") - val foo = data.filter{it.startsWith("f")} - assertTrue { - foo.all{it.startsWith("f")} - } - assertEquals(1, foo.size) - assertEquals(arrayList("foo"), foo) - } - - test fun filterReturnsList() { - val data = arrayList("foo", "bar") - val foo = data.filter{it.startsWith("f")} - assertTrue { - foo is List - } - } - - test fun filterNot() { - val data = arrayList("foo", "bar") - val foo = data.filterNot{it.startsWith("b")} - - assertTrue { - foo.all{it.startsWith("f")} - } - assertEquals(1, foo.size) - assertEquals(arrayList("foo"), foo) - } - - test fun filterNotNull() { - val data = arrayList(null, "foo", null, "bar") - val foo = data.filterNotNull() - - assertEquals(2, foo.size) - assertEquals(arrayList("foo", "bar"), foo) - - assertTrue { - foo is List - } - } - - // TODO would be nice to avoid the - test fun filterIntoSet() { - val data = arrayList("foo", "bar") - val foo = data.filterTo(hashSet()){it.startsWith("f")} - - assertTrue { - foo.all{it.startsWith("f")} - } - assertEquals(1, foo.size) - assertEquals(hashSet("foo"), foo) - - assertTrue { - foo is HashSet - } - } - - test fun find() { - val data = arrayList("foo", "bar") - val x = data.find{it.startsWith("x")} - assertNull(x) - - val f = data.find{it.startsWith("f")} - f!! - assertEquals("foo", f) - } - - test fun forEach() { - val data = arrayList("foo", "bar") - var count = 0 - data.forEach{ count += it.length } - assertEquals(6, count) - } - - test fun fold() { - // lets calculate the sum of some numbers - expect(10) { - val numbers = arrayList(1, 2, 3, 4) - numbers.fold(0){ a, b -> a + b} - } - - expect(0) { - val numbers = arrayList() - numbers.fold(0){ a, b -> a + b} - } - - // lets concatenate some strings - expect("1234") { - val numbers = arrayList(1, 2, 3, 4) - numbers.map{it.toString()}.fold(""){ a, b -> a + b} - } - } - - test fun foldWithDifferentTypes() { - expect(7) { - val numbers = arrayList("a", "ab", "abc") - numbers.fold(1){ a, b -> a + b.size} - } - - expect("1234") { - val numbers = arrayList(1, 2, 3, 4) - numbers.fold(""){ a, b -> a + b} - } - } - - test fun foldWithNonCommutativeOperation() { - expect(1) { - val numbers = arrayList(1, 2, 3) - numbers.fold(7) {a, b -> a - b} - } - } - - test fun foldRight() { - expect("1234") { - val numbers = arrayList(1, 2, 3, 4) - numbers.map{it.toString()}.foldRight(""){ a, b -> a + b} - } - } - - test fun foldRightWithDifferentTypes() { - expect("1234") { - val numbers = arrayList(1, 2, 3, 4) - numbers.foldRight(""){ a, b -> "" + a + b} - } - } - - test fun foldRightWithNonCommutativeOperation() { - expect(-5) { - val numbers = arrayList(1, 2, 3) - numbers.foldRight(7) {a, b -> a - b} - } - } - - test fun partition() { - val data = arrayList("foo", "bar", "something", "xyz") - val pair = data.partition{it.size == 3} - - assertEquals(arrayList("foo", "bar", "xyz"), pair.first, "pair.first") - assertEquals(arrayList("something"), pair.second, "pair.second") - } - - test fun reduce() { - expect("1234") { - val list = arrayList("1", "2", "3", "4") - list.reduce { a, b -> a + b } - } - - failsWith(javaClass()) { - arrayList().reduce { a, b -> a + b} - } - } - - test fun reduceRight() { - expect("1234") { - val list = arrayList("1", "2", "3", "4") - list.reduceRight { a, b -> a + b } - } - - failsWith(javaClass()) { - arrayList().reduceRight { a, b -> a + b} - } - } - - test fun groupBy() { - val words = arrayList("a", "ab", "abc", "def", "abcd") - val byLength = words.groupBy{ it.length } - assertEquals(4, byLength.size()) - - val l3 = byLength.getOrElse(3, {ArrayList()}) - assertEquals(2, l3.size) - } - - test fun makeString() { - val data = arrayList("foo", "bar") - val text = data.makeString("-", "<", ">") - assertEquals("", text) - - val big = arrayList("a", "b", "c", "d" , "e", "f") - val text2 = big.makeString(limit = 3, truncated = "*") - assertEquals("a, b, c, *", text2) - } - - test fun map() { - val data = arrayList("foo", "bar") - val lengths = data.map{ it.length } - assertTrue { - lengths.all{it == 3} - } - assertEquals(2, lengths.size) - assertEquals(arrayList(3, 3), lengths) - } - - test fun plus() { - val list = arrayList("foo", "bar") - val list2 = list + "cheese" - assertEquals(arrayList("foo", "bar"), list) - assertEquals(arrayList("foo", "bar", "cheese"), list2) - - // lets use a mutable variable - var list3 = arrayList("a", "b") - list3 += "c" - assertEquals(arrayList("a", "b", "c"), list3) - } - - test fun plusCollectionBug() { - val list = arrayList("foo", "bar") + arrayList("cheese", "wine") - assertEquals(arrayList("foo", "bar", "cheese", "wine"), list) - } - - test fun plusCollection() { - val a = arrayList("foo", "bar") - val b = arrayList("cheese", "wine") - val list = a + b - assertEquals(arrayList("foo", "bar", "cheese", "wine"), list) - - // lets use a mutable variable - var ml = a - ml += "beer" - ml += b - ml += "z" - assertEquals(arrayList("foo", "bar", "beer", "cheese", "wine", "z"), ml) - } - - test fun requireNoNulls() { - val data = arrayList("foo", "bar") - val notNull = data.requireNoNulls() - assertEquals(arrayList("foo", "bar"), notNull) - - val hasNulls = arrayList("foo", null, "bar") - failsWith(javaClass()) { - // should throw an exception as we have a null - hasNulls.requireNoNulls() - } - } - - test fun reverse() { - val data = arrayList("foo", "bar") - val rev = data.reverse() - assertEquals(arrayList("bar", "foo"), rev) - } - - test fun reverseFunctionShouldReturnReversedCopyForList() { - val list : List = arrayList(2, 3, 1) - expect(arrayList(1, 3, 2)) { list.reverse() } - expect(arrayList(2, 3, 1)) { list } - } - - test fun reverseFunctionShouldReturnReversedCopyForIterable() { - val iterable : Iterable = arrayList(2, 3, 1) - expect(arrayList(1, 3, 2)) { iterable.reverse() } - expect(arrayList(2, 3, 1)) { iterable } - } - - - test fun drop() { - val coll = arrayList("foo", "bar", "abc") - assertEquals(arrayList("bar", "abc"), coll.drop(1)) - assertEquals(arrayList("abc"), coll.drop(2)) - } - - test fun dropWhile() { - val coll = arrayList("foo", "bar", "abc") - assertEquals(arrayList("bar", "abc"), coll.dropWhile{ it.startsWith("f") }) - } - - test fun take() { - val coll = arrayList("foo", "bar", "abc") - assertEquals(arrayList("foo"), coll.take(1)) - assertEquals(arrayList("foo", "bar"), coll.take(2)) - } - - test fun takeWhile() { - val coll = arrayList("foo", "bar", "abc") - assertEquals(arrayList("foo"), coll.takeWhile{ it.startsWith("f") }) - assertEquals(arrayList("foo", "bar", "abc"), coll.takeWhile{ it.size == 3 }) - } - - test fun toArray() { - val data = arrayList("foo", "bar") - val arr = data.toArray() - println("Got array ${arr}") - assertEquals(2, arr.size) - todo { - assertTrue { - arr is Array - } - } - } - - test fun simpleCount() { - val data = arrayList("foo", "bar") - assertEquals(2, data.count()) - assertEquals(3, hashSet(12, 14, 15).count()) - assertEquals(0, ArrayList().count()) - } - - //todo after KT-1873 the name might be returned to 'last' - test fun lastElement() { - val data = arrayList("foo", "bar") - assertEquals("bar", data.last()) - assertEquals(25, arrayList(15, 19, 20, 25).last()) - assertEquals('a', arrayList('a').last()) - } - // TODO - // assertEquals(19, TreeSet(arrayList(90, 47, 19)).first()) - - - test fun lastException() { - fails { arrayList().last() } - } - - test fun subscript() { - val list = arrayList("foo", "bar") - assertEquals("foo", list[0]) - assertEquals("bar", list[1]) - - // lists throw an exception if out of range - fails { - assertEquals(null, list[2]) - } - - // lets try update the list - list[0] = "new" - list[1] = "thing" - - // lists don't allow you to set past the end of the list - fails { - list[2] = "works" - } - - list.add("works") - assertEquals(arrayList("new", "thing", "works"), list) - } - - test fun indices() { - val data = arrayList("foo", "bar") - val indices = data.indices - assertEquals(0, indices.start) - assertEquals(1, indices.end) - - assertEquals(indices, data.size. indices) - } - - test fun contains() { - val data = arrayList("foo", "bar") - assertTrue(data.contains("foo")) - assertTrue(data.contains("bar")) - assertFalse(data.contains("some")) - - // TODO: Problems with generation - // assertTrue(IterableWrapper(data).contains("bar")) - // assertFalse(IterableWrapper(data).contains("some")) - - assertFalse(hashSet().contains(12)) - assertTrue(arrayList(15, 19, 20).contains(15)) - - // assertTrue(IterableWrapper(hashSet(45, 14, 13)).contains(14)) - // assertFalse(IterableWrapper(linkedList()).contains(15)) - } - - test fun sortForMutableIterable() { - val list : MutableIterable = arrayList(2, 3, 1) - expect(arrayList(1, 2, 3)) { list.sort() } - expect(arrayList(2, 3, 1)) { list } - } - - test fun sortForIterable() { - val list : Iterable = listOf(2, 3, 1) - expect(arrayList(1, 2, 3)) { list.sort() } - expect(arrayList(2, 3, 1)) { list } - } - - test fun min() { - expect(null, { listOf().min() }) - expect(1, { listOf(1).min() }) - expect(2, { listOf(2, 3).min() }) - expect(2000000000000, { listOf(3000000000000, 2000000000000).min() }) - expect('a', { listOf('a', 'b').min() }) - expect("a", { listOf("a", "b").min() }) - expect(null, { listOf().iterator().min() }) - expect(2, { listOf(2, 3).iterator().min() }) - } - - test fun max() { - expect(null, { listOf().max() }) - expect(1, { listOf(1).max() }) - expect(3, { listOf(2, 3).max() }) - expect(3000000000000, { listOf(3000000000000, 2000000000000).max() }) - expect('b', { listOf('a', 'b').max() }) - expect("b", { listOf("a", "b").max() }) - expect(null, { listOf().iterator().max() }) - expect(3, { listOf(2, 3).iterator().max() }) - } - - test fun minBy() { - expect(null, { listOf().minBy { it } }) - expect(1, { listOf(1).minBy { it } }) - expect(3, { listOf(2, 3).minBy { -it } }) - expect('a', { listOf('a', 'b').minBy { "x$it" } }) - expect("b", { listOf("b", "abc").minBy { it.length } }) - expect(null, { listOf().iterator().minBy { it } }) - expect(3, { listOf(2, 3).iterator().minBy { -it } }) - } - - test fun maxBy() { - expect(null, { listOf().maxBy { it } }) - expect(1, { listOf(1).maxBy { it } }) - expect(2, { listOf(2, 3).maxBy { -it } }) - expect('b', { listOf('a', 'b').maxBy { "x$it" } }) - expect("abc", { listOf("b", "abc").maxBy { it.length } }) - expect(null, { listOf().iterator().maxBy { it } }) - expect(2, { listOf(2, 3).iterator().maxBy { -it } }) - } - - test fun minByEvaluateOnce() { - var c = 0 - expect(1, { listOf(5, 4, 3, 2, 1).minBy { c++; it * it } }) - assertEquals(5, c) - c = 0 - expect(1, { listOf(5, 4, 3, 2, 1).iterator().minBy { c++; it * it } }) - assertEquals(5, c) - } - - test fun maxByEvaluateOnce() { - var c = 0 - expect(5, { listOf(5, 4, 3, 2, 1).maxBy { c++; it * it } }) - assertEquals(5, c) - c = 0 - expect(5, { listOf(5, 4, 3, 2, 1).iterator().maxBy { c++; it * it } }) - assertEquals(5, c) - } - - test fun sum() { - expect(0) { ArrayList().sum() } - expect(14) { arrayListOf(2, 3, 9).sum() } - expect(3.0) { arrayListOf(1.0, 2.0).sum() } - expect(3000000000000) { arrayListOf(1000000000000, 2000000000000).sum() } - expect(3.0.toFloat()) { arrayListOf(1.0.toFloat(), 2.0.toFloat()).sum() } - } - - class IterableWrapper(collection : Iterable) : Iterable { - private val collection = collection - - override fun iterator(): Iterator { - return collection.iterator() - } - } -} diff --git a/libraries/stdlib/test/CompareTest.kt b/libraries/stdlib/test/CompareTest.kt index 9d9b4949507..713e7d062f3 100644 --- a/libraries/stdlib/test/CompareTest.kt +++ b/libraries/stdlib/test/CompareTest.kt @@ -42,8 +42,8 @@ class CompareTest { val diff = c.compare(v1, v2) assertTrue(diff < 0) - val items = arrayList(v1, v2) - items.sort(c) + val items = arrayListOf(v1, v2) + items.sortBy(c) println("Sorted list in rating order $items") } @@ -60,8 +60,8 @@ class CompareTest { val diff = c.compare(v1, v2) assertTrue(diff > 0) - val items = arrayList(v1, v2) - items.sort(c) + val items = arrayListOf(v1, v2) + items.sortBy(c) println("Sorted list in rating order $items") } diff --git a/libraries/stdlib/test/EnumerationIteratorTest.kt b/libraries/stdlib/test/EnumerationIteratorTest.kt deleted file mode 100644 index f4a714224ad..00000000000 --- a/libraries/stdlib/test/EnumerationIteratorTest.kt +++ /dev/null @@ -1,18 +0,0 @@ - -import java.util.Vector -import junit.framework.TestCase -import kotlin.test.assertEquals - -class EnumerationIteratorTest() : TestCase() { - fun testIteration () { - val v = Vector() - for(i in 1..5) - v.add(i) - - var sum = 0 - for(k in v.elements()) - sum += k - - assertEquals(15, sum) - } -} \ No newline at end of file diff --git a/libraries/stdlib/test/ListTest.kt b/libraries/stdlib/test/ListTest.kt deleted file mode 100644 index d3af926b534..00000000000 --- a/libraries/stdlib/test/ListTest.kt +++ /dev/null @@ -1,79 +0,0 @@ -package test.collections - -import java.util.ArrayList -import kotlin.test.* -import org.junit.Test as test - -class ListTest { - - test fun _toString() { - val data = arrayList("foo", "bar") - assertEquals("[foo, bar]", data.toString()) - } - - test fun emptyHead() { - val data = ArrayList() - assertNull(data.head) - } - - test fun head() { - val data = arrayList("foo", "bar") - assertEquals("foo", data.head) - } - - test fun tail() { - val data = arrayList("foo", "bar", "whatnot") - val actual = data.tail - val expected = arrayList("bar", "whatnot") - assertEquals(expected, actual) - } - - test fun emptyFirst() { - val data = ArrayList() - assertNull(data.first) - } - - test fun first() { - val data = arrayList("foo", "bar") - assertEquals("foo", data.first) - } - - test fun last() { - val data = arrayList("foo", "bar") - assertEquals("bar", data.last) - } - - test fun forEachWithIndex() { - val data = arrayList("foo", "bar") - var index = 0 - - data.forEachWithIndex { (i, d) -> - assertEquals(i, index) - assertEquals(d, data[index]) - index++ - } - - assertEquals(data.size(), index) - } - - test fun withIndices() { - val data = arrayList("foo", "bar") - var index = 0 - - for ((i, d) in data.withIndices()) { - assertEquals(i, index) - assertEquals(d, data[index]) - index++ - } - - assertEquals(data.size(), index) - } - - test fun lastIndex() { - val emptyData = ArrayList() - val data = arrayList("foo", "bar") - - assertEquals(-1, emptyData.lastIndex) - assertEquals(1, data.lastIndex) - } -} diff --git a/libraries/stdlib/test/SetTest.kt b/libraries/stdlib/test/SetTest.kt deleted file mode 100644 index 723a0cf6e59..00000000000 --- a/libraries/stdlib/test/SetTest.kt +++ /dev/null @@ -1,65 +0,0 @@ -package test.collections - -import kotlin.test.* -import java.util.* -import org.junit.Test - -class SetTest { - val data = hashSet("foo", "bar") - - Test fun any() { - assertTrue { - data.any{it.startsWith("f")} - } - assertNot { - data.any{it.startsWith("x")} - } - } - - Test fun all() { - assertTrue { - data.all{it.length == 3} - } - assertNot { - data.all{(s: String) -> s.startsWith("b")} - } - } - - Test fun filter() { - val foo = data.filter{it.startsWith("f")}.toSet() - - assertTrue { - foo.all{it.startsWith("f")} - } - assertEquals(1, foo.size) - - assertEquals(hashSet("foo"), foo) - - assertTrue("Filter on a Set should return a Set") { - foo is Set - } - } - - Test fun find() { - val x = data.find{it.startsWith("x")} - assertNull(x) - - val f = data.find{it.startsWith("f")} - assertEquals("foo", f) - } - - Test fun map() { - /** - TODO compiler bug - we should be able to remove the explicit type on the function - http://youtrack.jetbrains.net/issue/KT-849 - */ - val lengths = data.map{s -> s.length} - assertTrue { - lengths.all{it == 3} - } - assertEquals(2, lengths.size) - assertEquals(arrayList(3, 3), lengths) - } - -} diff --git a/libraries/stdlib/test/StandardCollectionTest.kt b/libraries/stdlib/test/StandardCollectionTest.kt deleted file mode 100644 index bb351f1f239..00000000000 --- a/libraries/stdlib/test/StandardCollectionTest.kt +++ /dev/null @@ -1,22 +0,0 @@ -package test.collections - -import kotlin.* -import kotlin.test.* -import junit.framework.TestCase - -class StandardCollectionTest() : TestCase() { - - fun testDisabled() { - } - - fun testAny() { - val data: Iterable = listOf("foo", "bar") - - assertTrue { - data.any{it.startsWith("f")} - } - assertNot { - data.any{it.startsWith("x")} - } - } -} diff --git a/libraries/stdlib/test/ArraysJVMTest.kt b/libraries/stdlib/test/collections/ArraysJVMTest.kt similarity index 99% rename from libraries/stdlib/test/ArraysJVMTest.kt rename to libraries/stdlib/test/collections/ArraysJVMTest.kt index 7690350df6c..77c3f802466 100644 --- a/libraries/stdlib/test/ArraysJVMTest.kt +++ b/libraries/stdlib/test/collections/ArraysJVMTest.kt @@ -1,4 +1,4 @@ -package test.arrays +package test.collections import kotlin.test.* import org.junit.Test as test diff --git a/libraries/stdlib/test/ArraysTest.kt b/libraries/stdlib/test/collections/ArraysTest.kt similarity index 90% rename from libraries/stdlib/test/ArraysTest.kt rename to libraries/stdlib/test/collections/ArraysTest.kt index 264d5f5b1f0..a4888c0d826 100644 --- a/libraries/stdlib/test/ArraysTest.kt +++ b/libraries/stdlib/test/collections/ArraysTest.kt @@ -1,4 +1,4 @@ -package test.arrays +package test.collections import kotlin.test.* import org.junit.Test as test @@ -153,8 +153,7 @@ class ArraysTest { expect(3.0) { array(1.0, 2.0).sum() } expect(200) { array(100, 100).sum() } expect(50000) { array(20000, 30000).sum() } - //TODO: uncomment when toLong() will be supported - //expect(3000000000000) { array(1000000000000, 2000000000000).sum() } + expect(3000000000000) { array(1000000000000, 2000000000000).sum() } expect(3.0.toFloat()) { array(1.0.toFloat(), 2.0.toFloat()).sum() } } @@ -165,6 +164,28 @@ class ArraysTest { expect(2) { array("cat", "dog", "bird").indexOf("bird") } expect(0) { array(null, "dog", null).indexOf(null)} } + + test fun plus() { + assertEquals(listOf("1","2","3","4"), array("1", "2") + array("3", "4")) + assertEquals(listOf("1","2","3","4"), listOf("1", "2") + array("3", "4")) + } + + test fun first() { + expect(1) { array(1,2,3).first() } + expect(2) { array(1,2,3).first { it % 2 == 0 } } + } + + test fun last() { + expect(3) { array(1,2,3).last() } + expect(2) { array(1,2,3).last { it % 2 == 0 } } + } + + test fun contains() { + assertTrue(array("1","2","3","4").contains("2")) + assertTrue("3" in array("1","2","3","4")) + assertTrue("0" !in array("1","2","3","4")) + } + /* TODO FIXME ASAP: These currently fail on JS due to missing upto() method on numbers diff --git a/libraries/stdlib/test/collections/CollectionJVMTest.kt b/libraries/stdlib/test/collections/CollectionJVMTest.kt new file mode 100644 index 00000000000..5049402a09a --- /dev/null +++ b/libraries/stdlib/test/collections/CollectionJVMTest.kt @@ -0,0 +1,115 @@ +package test.collections + +import kotlin.test.* + +import java.util.* + +import org.junit.Test as test + +class CollectionJVMTest { + + test fun flatMap() { + val data = arrayListOf("", "foo", "bar", "x", "") + val characters = data.flatMap { it.toCharList() } + println("Got list of characters ${characters}") + assertEquals(7, characters.size()) + val text = characters.makeString("") + assertEquals("foobarx", text) + } + + + test fun filterIntolinkedListOf() { + val data = arrayListOf("foo", "bar") + val foo = data.filterTo(linkedListOf()) { it.startsWith("f") } + + assertTrue { + foo.all { it.startsWith("f") } + } + assertEquals(1, foo.size) + assertEquals(linkedListOf("foo"), foo) + + assertTrue { + foo is LinkedList + } + } + + test fun filterNotIntolinkedListOf() { + val data = arrayListOf("foo", "bar") + val foo = data.filterNotTo(linkedListOf()) { it.startsWith("f") } + + assertTrue { + foo.all { !it.startsWith("f") } + } + assertEquals(1, foo.size) + assertEquals(linkedListOf("bar"), foo) + + assertTrue { + foo is LinkedList + } + } + + // TODO would be nice to avoid the + test fun filterNotNullIntolinkedListOf() { + val data = arrayListOf(null, "foo", null, "bar") + val foo = data.filterNotNullTo(linkedListOf()) + + assertEquals(2, foo.size) + assertEquals(linkedListOf("foo", "bar"), foo) + + assertTrue { + foo is LinkedList + } + } + + + // TODO would be nice to avoid the + test fun filterIntoSortedSet() { + val data = arrayListOf("foo", "bar") + val sorted = data.filterTo(sortedSetOf()) { it.length == 3 } + assertEquals(2, sorted.size) + assertEquals(sortedSetOf("bar", "foo"), sorted) + assertTrue { + sorted is TreeSet + } + } + + test fun last() { + val data = arrayListOf("foo", "bar") + assertEquals("bar", data.last()) + assertEquals(25, arrayListOf(15, 19, 20, 25).last()) + assertEquals('a', linkedListOf('a').last()) + } + + test fun lastException() { + fails { linkedListOf().last() } + } + + test fun contains() { + assertTrue(linkedListOf(15, 19, 20).contains(15)) + } + + test fun sortBy() { + expect(arrayListOf("two" to 2, "three" to 3)) { + arrayListOf("three" to 3, "two" to 2).sortBy { it.second } + } + expect(arrayListOf("three" to 3, "two" to 2)) { + arrayListOf("three" to 3, "two" to 2).sortBy { it.first } + } + expect(arrayListOf("two" to 2, "three" to 3)) { + arrayListOf("three" to 3, "two" to 2).sortBy { it.first.length } + } + } + + + test fun sortFunctionShouldReturnSortedCopyForList() { + val list: List = arrayListOf(2, 3, 1) + expect(arrayListOf(1, 2, 3)) { list.sort() } + expect(arrayListOf(2, 3, 1)) { list } + } + + test fun sortFunctionShouldReturnSortedCopyForIterable() { + val list: Iterable = arrayListOf(2, 3, 1) + expect(arrayListOf(1, 2, 3)) { list.sort() } + expect(arrayListOf(2, 3, 1)) { list } + } +} diff --git a/libraries/stdlib/test/collections/CollectionTest.kt b/libraries/stdlib/test/collections/CollectionTest.kt new file mode 100644 index 00000000000..4938627e1aa --- /dev/null +++ b/libraries/stdlib/test/collections/CollectionTest.kt @@ -0,0 +1,432 @@ +package test.collections + +import kotlin.test.* + +import java.util.* + +import org.junit.Test as test + +class CollectionTest { + + test fun appendString() { + val data = arrayListOf("foo", "bar") + val buffer = StringBuilder() + val text = data.appendString(buffer, "-", "{", "}") + assertEquals("{foo-bar}", buffer.toString()) + } + + test fun makeString() { + val data = arrayListOf("foo", "bar") + val text = data.makeString("-", "<", ">") + assertEquals("", text) + + val big = arrayListOf("a", "b", "c", "d", "e", "f") + val text2 = big.makeString(limit = 3, truncated = "*") + assertEquals("a, b, c, *", text2) + } + + test fun filterNotNull() { + val data = arrayListOf(null, "foo", null, "bar") + val foo = data.filterNotNull() + + assertEquals(2, foo.size) + assertEquals(arrayListOf("foo", "bar"), foo) + + assertTrue { + foo is List + } + } + + test fun mapNotNull() { + val data = arrayListOf(null, "foo", null, "bar") + val foo = data.mapNotNull { it.length } + assertEquals(2, foo.size) + assertEquals(arrayListOf(3, 3), foo) + + assertTrue { + foo is List + } + } + + // TODO would be nice to avoid the + test fun filterIntoSet() { + val data = arrayListOf("foo", "bar") + val foo = data.filterTo(hashSetOf()) { it.startsWith("f") } + + assertTrue { + foo.all { it.startsWith("f") } + } + assertEquals(1, foo.size) + assertEquals(hashSetOf("foo"), foo) + + assertTrue { + foo is HashSet + } + } + + test fun fold() { + // lets calculate the sum of some numbers + expect(10) { + val numbers = arrayListOf(1, 2, 3, 4) + numbers.fold(0) { a, b -> a + b } + } + + expect(0) { + val numbers = arrayListOf() + numbers.fold(0) { a, b -> a + b } + } + + // lets concatenate some strings + expect("1234") { + val numbers = arrayListOf(1, 2, 3, 4) + numbers.map { it.toString() }.fold("") { a, b -> a + b } + } + } + + test fun foldWithDifferentTypes() { + expect(7) { + val numbers = arrayListOf("a", "ab", "abc") + numbers.fold(1) { a, b -> a + b.size } + } + + expect("1234") { + val numbers = arrayListOf(1, 2, 3, 4) + numbers.fold("") { a, b -> a + b } + } + } + + test fun foldWithNonCommutativeOperation() { + expect(1) { + val numbers = arrayListOf(1, 2, 3) + numbers.fold(7) { a, b -> a - b } + } + } + + test fun foldRight() { + expect("1234") { + val numbers = arrayListOf(1, 2, 3, 4) + numbers.map { it.toString() }.foldRight("") { a, b -> a + b } + } + } + + test fun foldRightWithDifferentTypes() { + expect("1234") { + val numbers = arrayListOf(1, 2, 3, 4) + numbers.foldRight("") { a, b -> "" + a + b } + } + } + + test fun foldRightWithNonCommutativeOperation() { + expect(-5) { + val numbers = arrayListOf(1, 2, 3) + numbers.foldRight(7) { a, b -> a - b } + } + } + + test fun partition() { + val data = arrayListOf("foo", "bar", "something", "xyz") + val pair = data.partition { it.size == 3 } + + assertEquals(arrayListOf("foo", "bar", "xyz"), pair.first, "pair.first") + assertEquals(arrayListOf("something"), pair.second, "pair.second") + } + + test fun reduce() { + expect("1234") { + val list = arrayListOf("1", "2", "3", "4") + list.reduce { a, b -> a + b } + } + + failsWith(javaClass()) { + arrayListOf().reduce { a, b -> a + b } + } + } + + test fun reduceRight() { + expect("1234") { + val list = arrayListOf("1", "2", "3", "4") + list.reduceRight { a, b -> a + b } + } + + failsWith(javaClass()) { + arrayListOf().reduceRight { a, b -> a + b } + } + } + + test fun groupBy() { + val words = arrayListOf("a", "ab", "abc", "def", "abcd") + val byLength = words.groupBy { it.length } + assertEquals(4, byLength.size()) + + val l3 = byLength.getOrElse(3, { ArrayList() }) + assertEquals(2, l3.size) + } + + test fun plusRanges() { + val range1 = 1..3 + val range2 = 4..7 + val combined = range1 + range2 + assertEquals((1..7).toList(), combined) + } + + test fun mapRanges() { + val range = 1..3 map { it * 2} + assertEquals(listOf(2,4,6), range) + } + + test fun plus() { + val list = arrayListOf("foo", "bar") + val list2 = list + "cheese" + assertEquals(arrayListOf("foo", "bar"), list) + assertEquals(arrayListOf("foo", "bar", "cheese"), list2) + + // lets use a mutable variable + var list3 = arrayListOf("a", "b") + list3 += "c" + assertEquals(arrayListOf("a", "b", "c"), list3) + } + + test fun plusCollectionBug() { + val list = arrayListOf("foo", "bar") + arrayListOf("cheese", "wine") + assertEquals(arrayListOf("foo", "bar", "cheese", "wine"), list) + } + + test fun plusCollection() { + val a = arrayListOf("foo", "bar") + val b = arrayListOf("cheese", "wine") + val list = a + b + assertEquals(arrayListOf("foo", "bar", "cheese", "wine"), list) + + // lets use a mutable variable + var ml = a + ml += "beer" + ml += b + ml += "z" + assertEquals(arrayListOf("foo", "bar", "beer", "cheese", "wine", "z"), ml) + } + + test fun requireNoNulls() { + val data = arrayListOf("foo", "bar") + val notNull = data.requireNoNulls() + assertEquals(arrayListOf("foo", "bar"), notNull) + + val hasNulls = arrayListOf("foo", null, "bar") + failsWith(javaClass()) { + // should throw an exception as we have a null + hasNulls.requireNoNulls() + } + } + + test fun reverse() { + val data = arrayListOf("foo", "bar") + val rev = data.reverse() + assertEquals(arrayListOf("bar", "foo"), rev) + } + + test fun reverseFunctionShouldReturnReversedCopyForList() { + val list: List = arrayListOf(2, 3, 1) + expect(arrayListOf(1, 3, 2)) { list.reverse() } + expect(arrayListOf(2, 3, 1)) { list } + } + + test fun reverseFunctionShouldReturnReversedCopyForIterable() { + val iterable: Iterable = arrayListOf(2, 3, 1) + expect(arrayListOf(1, 3, 2)) { iterable.reverse() } + expect(arrayListOf(2, 3, 1)) { iterable } + } + + + test fun drop() { + val coll = arrayListOf("foo", "bar", "abc") + assertEquals(arrayListOf("bar", "abc"), coll.drop(1)) + assertEquals(arrayListOf("abc"), coll.drop(2)) + } + + test fun dropWhile() { + val coll = arrayListOf("foo", "bar", "abc") + assertEquals(arrayListOf("bar", "abc"), coll.dropWhile { it.startsWith("f") }) + } + + test fun take() { + val coll = arrayListOf("foo", "bar", "abc") + assertEquals(arrayListOf("foo"), coll.take(1)) + assertEquals(arrayListOf("foo", "bar"), coll.take(2)) + } + + test fun takeWhile() { + val coll = arrayListOf("foo", "bar", "abc") + assertEquals(arrayListOf("foo"), coll.takeWhile { it.startsWith("f") }) + assertEquals(arrayListOf("foo", "bar", "abc"), coll.takeWhile { it.size == 3 }) + } + + test fun toArray() { + val data = arrayListOf("foo", "bar") + val arr = data.toArray() + println("Got array ${arr}") + assertEquals(2, arr.size) + todo { + assertTrue { + arr is Array + } + } + } + + test fun simpleCount() { + val data = arrayListOf("foo", "bar") + assertEquals(2, data.count()) + assertEquals(3, hashSetOf(12, 14, 15).count()) + assertEquals(0, ArrayList().count()) + } + + //todo after KT-1873 the name might be returned to 'last' + test fun lastElement() { + val data = arrayListOf("foo", "bar") + assertEquals("bar", data.last()) + assertEquals(25, arrayListOf(15, 19, 20, 25).last()) + assertEquals('a', arrayListOf('a').last()) + } + // TODO + // assertEquals(19, TreeSet(arrayListOf(90, 47, 19)).first()) + + + test fun lastException() { + fails { arrayListOf().last() } + } + + test fun subscript() { + val list = arrayListOf("foo", "bar") + assertEquals("foo", list[0]) + assertEquals("bar", list[1]) + + // lists throw an exception if out of range + fails { + assertEquals(null, list[2]) + } + + // lets try update the list + list[0] = "new" + list[1] = "thing" + + // lists don't allow you to set past the end of the list + fails { + list[2] = "works" + } + + list.add("works") + assertEquals(arrayListOf("new", "thing", "works"), list) + } + + test fun indices() { + val data = arrayListOf("foo", "bar") + val indices = data.indices + assertEquals(0, indices.start) + assertEquals(1, indices.end) + + assertEquals(indices, data.size. indices) + } + + test fun contains() { + val data = arrayListOf("foo", "bar") + assertTrue(data.contains("foo")) + assertTrue(data.contains("bar")) + assertFalse(data.contains("some")) + + // TODO: Problems with generation + // assertTrue(IterableWrapper(data).contains("bar")) + // assertFalse(IterableWrapper(data).contains("some")) + + assertFalse(hashSetOf().contains(12)) + assertTrue(arrayListOf(15, 19, 20).contains(15)) + + // assertTrue(IterableWrapper(hashSet(45, 14, 13)).contains(14)) + // assertFalse(IterableWrapper(linkedList()).contains(15)) + } + + test fun sortForMutableIterable() { + val list: MutableIterable = arrayListOf(2, 3, 1) + expect(arrayListOf(1, 2, 3)) { list.sort() } + expect(arrayListOf(2, 3, 1)) { list } + } + + test fun sortForIterable() { + val list: Iterable = listOf(2, 3, 1) + expect(arrayListOf(1, 2, 3)) { list.sort() } + expect(arrayListOf(2, 3, 1)) { list } + } + + test fun min() { + expect(null, { listOf().min() }) + expect(1, { listOf(1).min() }) + expect(2, { listOf(2, 3).min() }) + expect(2000000000000, { listOf(3000000000000, 2000000000000).min() }) + expect('a', { listOf('a', 'b').min() }) + expect("a", { listOf("a", "b").min() }) + expect(null, { listOf().stream().min() }) + expect(2, { listOf(2, 3).stream().min() }) + } + + test fun max() { + expect(null, { listOf().max() }) + expect(1, { listOf(1).max() }) + expect(3, { listOf(2, 3).max() }) + expect(3000000000000, { listOf(3000000000000, 2000000000000).max() }) + expect('b', { listOf('a', 'b').max() }) + expect("b", { listOf("a", "b").max() }) + expect(null, { listOf().stream().max() }) + expect(3, { listOf(2, 3).stream().max() }) + } + + test fun minBy() { + expect(null, { listOf().minBy { it } }) + expect(1, { listOf(1).minBy { it } }) + expect(3, { listOf(2, 3).minBy { -it } }) + expect('a', { listOf('a', 'b').minBy { "x$it" } }) + expect("b", { listOf("b", "abc").minBy { it.length } }) + expect(null, { listOf().stream().minBy { it } }) + expect(3, { listOf(2, 3).stream().minBy { -it } }) + } + + test fun maxBy() { + expect(null, { listOf().maxBy { it } }) + expect(1, { listOf(1).maxBy { it } }) + expect(2, { listOf(2, 3).maxBy { -it } }) + expect('b', { listOf('a', 'b').maxBy { "x$it" } }) + expect("abc", { listOf("b", "abc").maxBy { it.length } }) + expect(null, { listOf().stream().maxBy { it } }) + expect(2, { listOf(2, 3).stream().maxBy { -it } }) + } + + test fun minByEvaluateOnce() { + var c = 0 + expect(1, { listOf(5, 4, 3, 2, 1).minBy { c++; it * it } }) + assertEquals(5, c) + c = 0 + expect(1, { listOf(5, 4, 3, 2, 1).stream().minBy { c++; it * it } }) + assertEquals(5, c) + } + + test fun maxByEvaluateOnce() { + var c = 0 + expect(5, { listOf(5, 4, 3, 2, 1).maxBy { c++; it * it } }) + assertEquals(5, c) + c = 0 + expect(5, { listOf(5, 4, 3, 2, 1).stream().maxBy { c++; it * it } }) + assertEquals(5, c) + } + + test fun sum() { + expect(0) { arrayListOf().sum() } + expect(14) { arrayListOf(2, 3, 9).sum() } + expect(3.0) { arrayListOf(1.0, 2.0).sum() } + expect(3000000000000) { arrayListOf(1000000000000, 2000000000000).sum() } + expect(3.0.toFloat()) { arrayListOf(1.0.toFloat(), 2.0.toFloat()).sum() } + } + + class IterableWrapper(collection: Iterable) : Iterable { + private val collection = collection + + override fun iterator(): Iterator { + return collection.iterator() + } + } +} diff --git a/libraries/stdlib/test/ImmutableArrayListTest.kt b/libraries/stdlib/test/collections/ImmutableArrayListTest.kt similarity index 98% rename from libraries/stdlib/test/ImmutableArrayListTest.kt rename to libraries/stdlib/test/collections/ImmutableArrayListTest.kt index 0ff92c2bb63..ea29324dc35 100644 --- a/libraries/stdlib/test/ImmutableArrayListTest.kt +++ b/libraries/stdlib/test/collections/ImmutableArrayListTest.kt @@ -1,4 +1,4 @@ -package test.collection +package test.collections import kotlin.test.* diff --git a/libraries/stdlib/test/collections/IterableJVMTests.kt b/libraries/stdlib/test/collections/IterableJVMTests.kt new file mode 100644 index 00000000000..abd4a6d23c1 --- /dev/null +++ b/libraries/stdlib/test/collections/IterableJVMTests.kt @@ -0,0 +1,9 @@ +package test.collections + +import org.junit.Test +import kotlin.test.* +import java.util.* + +class LinkedSetTest : OrderedIterableTests>(setOf("foo", "bar"), setOf()) +class LinkedListTest : OrderedIterableTests>(linkedListOf("foo", "bar"), linkedListOf()) + diff --git a/libraries/stdlib/test/collections/IterableTests.kt b/libraries/stdlib/test/collections/IterableTests.kt new file mode 100644 index 00000000000..15d5b9deb2f --- /dev/null +++ b/libraries/stdlib/test/collections/IterableTests.kt @@ -0,0 +1,203 @@ +package test.collections + +import org.junit.Test +import kotlin.test.* +import java.util.* + +class SetTest : IterableTests>(hashSetOf("foo", "bar"), hashSetOf()) +class ListTest : OrderedIterableTests>(listOf("foo", "bar"), listOf()) +class ArrayListTest : OrderedIterableTests>(arrayListOf("foo", "bar"), arrayListOf()) + +abstract class OrderedIterableTests>(data: T, empty: T) : IterableTests(data, empty) { + Test fun indexOf() { + expect(0) { data.indexOf("foo") } + expect(-1) { empty.indexOf("foo") } + expect(1) { data.indexOf("bar") } + expect(-1) { data.indexOf("zap") } + } + + Test fun lastIndexOf() { + expect(0) { data.lastIndexOf("foo") } + expect(-1) { empty.lastIndexOf("foo") } + expect(1) { data.lastIndexOf("bar") } + expect(-1) { data.lastIndexOf("zap") } + } + + Test fun elementAt() { + expect("foo") { data.elementAt(0) } + expect("bar") { data.elementAt(1) } + fails { data.elementAt(2) } + fails { data.elementAt(-1) } + fails { empty.elementAt(0) } + } + + Test fun first() { + expect("foo") { data.first() } + fails { + data.first { it.startsWith("x") } + } + fails { + empty.first() + } + expect("foo") { data.first { it.startsWith("f") } } + } + + Test fun firstOrNull() { + expect(null) { data.firstOrNull { it.startsWith("x") } } + expect(null) { empty.firstOrNull() } + + val f = data.firstOrNull { it.startsWith("f") } + assertEquals("foo", f) + } + + Test fun last() { + assertEquals("bar", data.last()) + fails { + data.last { it.startsWith("x") } + } + fails { + empty.last() + } + expect("foo") { data.last { it.startsWith("f") } } + } + + Test fun lastOrNull() { + expect(null) { data.lastOrNull { it.startsWith("x") } } + expect(null) { empty.lastOrNull() } + expect("foo") { data.lastOrNull { it.startsWith("f") } } + } +} + +abstract class IterableTests>(val data: T, val empty: T) { + Test fun any() { + expect(true) { data.any() } + expect(false) { empty.any() } + expect(true) { data.any { it.startsWith("f") } } + expect(false) { data.any { it.startsWith("x") } } + expect(false) { empty.any { it.startsWith("x") } } + } + + Test fun all() { + expect(true) { data.all { it.length == 3 } } + expect(false) { data.all { it.startsWith("b") } } + expect(true) { empty.all { it.startsWith("b") } } + } + + Test fun none() { + expect(false) { data.none() } + expect(true) { empty.none() } + expect(false) { data.none { it.length == 3 } } + expect(false) { data.none { it.startsWith("b") } } + expect(true) { data.none { it.startsWith("x") } } + expect(true) { empty.none { it.startsWith("b") } } + } + + Test fun filter() { + val foo = data.filter { it.startsWith("f") } + // TODO uncomment this when KT-4651 will be fixed + //expect(true) { foo is List } + expect(true) { foo.all { it.startsWith("f") } } + expect(1) { foo.size } + assertEquals(listOf("foo"), foo) + } + + Test fun filterNot() { + val notFoo = data.filterNot { it.startsWith("f") } + // TODO uncomment this when KT-4651 will be fixed + //expect(true) { notFoo is List } + expect(true) { notFoo.none { it.startsWith("f") } } + expect(1) { notFoo.size } + assertEquals(listOf("bar"), notFoo) + } + + Test fun forEach() { + var count = 0 + data.forEach { count += it.length } + assertEquals(6, count) + } + + Test fun contains() { + assertTrue(data.contains("foo")) + assertTrue("bar" in data) + assertTrue("baz" !in data) + assertFalse("baz" in empty) + } + + Test fun single() { + fails { data.single() } + fails { empty.single() } + expect("foo") { data.single { it.startsWith("f") } } + expect("bar") { data.single { it.startsWith("b") } } + fails { + data.single { it.length == 3 } + } + } + + Test + fun singleOrNull() { + fails { data.singleOrNull() } + fails { empty.singleOrNull() } + expect("foo") { data.singleOrNull { it.startsWith("f") } } + expect("bar") { data.singleOrNull { it.startsWith("b") } } + fails { + data.singleOrNull { it.length == 3 } + } + } + + Test + fun map() { + val lengths = data.map { it.length } + assertTrue { + lengths.all { it == 3 } + } + assertEquals(2, lengths.size) + assertEquals(arrayListOf(3, 3), lengths) + } + + Test + fun max() { + expect("foo") { data.max() } + expect("bar") { data.maxBy { it.last() } } + } + + Test + fun min() { + expect("bar") { data.min() } + expect("foo") { data.minBy { it.last() } } + } + + Test + fun count() { + expect(2) { data.count() } + expect(0) { empty.count() } + + expect(1) { data.count { it.startsWith("f") } } + expect(0) { empty.count { it.startsWith("f") } } + + expect(0) { data.count { it.startsWith("x") } } + expect(0) { empty.count { it.startsWith("x") } } + } + + Test + fun withIndices() { + var index = 0 + for ((i, d) in data.withIndices()) { + assertEquals(i, index) + assertEquals(d, data.elementAt(index)) + index++ + } + assertEquals(data.count(), index) + } + + Test + fun fold() { + + } + + Test + fun reduce() { + + } + + +} diff --git a/libraries/stdlib/test/collections/IteratorsJVMTest.kt b/libraries/stdlib/test/collections/IteratorsJVMTest.kt new file mode 100644 index 00000000000..3afbde1d23b --- /dev/null +++ b/libraries/stdlib/test/collections/IteratorsJVMTest.kt @@ -0,0 +1,44 @@ +package test.collections + +import org.junit.Test as test +import kotlin.test.* +import java.util.* + +class IteratorsJVMTest { + + test fun testEnumeration() { + val v = Vector() + for(i in 1..5) + v.add(i) + + var sum = 0 + for(k in v.elements()) + sum += k + + assertEquals(15, sum) + } + + test fun flatMapAndTakeExtractTheTransformedElements() { + fun intToBinaryDigits() = { (i: Int) -> + val binary = Integer.toBinaryString(i)!! + var index = 0 + stream { if (index < binary.length()) binary.get(index++) else null } + } + + val expected = arrayListOf( + '0', // fibonacci(0) = 0 + '1', // fibonacci(1) = 1 + '1', // fibonacci(2) = 1 + '1', '0', // fibonacci(3) = 2 + '1', '1', // fibonacci(4) = 3 + '1', '0', '1' // fibonacci(5) = 5 + ) + + assertEquals(expected, fibonacci().flatMap(intToBinaryDigits()).take(10).toList()) + } + + test fun flatMapOnStream() { + val result = listOf(1, 2).stream().flatMap { (0..it).stream() } + assertEquals(listOf(0, 1, 0, 1, 2), result.toList()) + } +} diff --git a/libraries/stdlib/test/collections/IteratorsTest.kt b/libraries/stdlib/test/collections/IteratorsTest.kt new file mode 100644 index 00000000000..5155fbaf103 --- /dev/null +++ b/libraries/stdlib/test/collections/IteratorsTest.kt @@ -0,0 +1,15 @@ +package test.collections + +import kotlin.test.* +import org.junit.Test as test + +class IteratorsTest { + test fun iterationOverIterator() { + val c = arrayListOf(0, 1, 2, 3, 4, 5) + var s = "" + for (i in c.iterator()) { + s = s + i.toString() + } + assertEquals("012345", s) + } +} diff --git a/libraries/stdlib/test/collections/ListSpecificTest.kt b/libraries/stdlib/test/collections/ListSpecificTest.kt new file mode 100644 index 00000000000..1f9d67f3ce4 --- /dev/null +++ b/libraries/stdlib/test/collections/ListSpecificTest.kt @@ -0,0 +1,33 @@ +package test.collections + +import java.util.ArrayList +import kotlin.test.* +import org.junit.Test + +class ListSpecificTest { + val data = listOf("foo", "bar") + val empty = listOf() + + Test fun _toString() { + assertEquals("[foo, bar]", data.toString()) + } + + Test fun tail() { + val data = arrayListOf("foo", "bar", "whatnot") + val actual = data.tail + val expected = arrayListOf("bar", "whatnot") + assertEquals(expected, actual) + } + + Test fun utils() { + assertNull(empty.head) + assertNull(empty.first) + assertNull(empty.last) + assertEquals(-1, empty.lastIndex) + + assertEquals("foo", data.head) + assertEquals("foo", data.first) + assertEquals("bar", data.last) + assertEquals(1, data.lastIndex) + } +} diff --git a/libraries/stdlib/test/MapTest.kt b/libraries/stdlib/test/collections/MapTest.kt similarity index 100% rename from libraries/stdlib/test/MapTest.kt rename to libraries/stdlib/test/collections/MapTest.kt diff --git a/libraries/stdlib/test/MutableCollectionsTest.kt b/libraries/stdlib/test/collections/MutableCollectionsTest.kt similarity index 86% rename from libraries/stdlib/test/MutableCollectionsTest.kt rename to libraries/stdlib/test/collections/MutableCollectionsTest.kt index 86b33d126db..2aa7ee6d491 100644 --- a/libraries/stdlib/test/MutableCollectionsTest.kt +++ b/libraries/stdlib/test/collections/MutableCollectionsTest.kt @@ -17,11 +17,11 @@ class MutableCollectionTest { assertEquals(data, collection) } - test fun fromIterator() { + test fun fromStream() { val list = arrayListOf("foo", "bar") val collection = ArrayList() - collection.addAll(list.iterator()) + collection.addAll(list.stream()) assertEquals(list, collection) } diff --git a/libraries/stdlib/test/collections/StreamTest.kt b/libraries/stdlib/test/collections/StreamTest.kt new file mode 100644 index 00000000000..e1d5798b8f1 --- /dev/null +++ b/libraries/stdlib/test/collections/StreamTest.kt @@ -0,0 +1,148 @@ +package test.collections + +import org.junit.Test +import kotlin.test.* +import java.util.* + +fun fibonacci(): Stream { + // fibonacci terms + var index = 0; + var a = 0; + var b = 1 + return stream { + when (index++) { 0 -> a; 1 -> b; else -> { + val result = a + b; a = b; b = result; result + } } + } +} + +public class StreamTest { + + Test fun requireNoNulls() { + val stream = arrayListOf("foo", "bar").stream() + val notNull = stream.requireNoNulls() + assertEquals(arrayListOf("foo", "bar"), notNull.toList()) + + val streamWithNulls = arrayListOf("foo", null, "bar").stream() + val notNull2 = streamWithNulls.requireNoNulls() // shouldn't fail yet + fails { + // should throw an exception as we have a null + notNull2.toList() + } + } + + test fun mapNotNull() { + val data = arrayListOf(null, "foo", null, "bar").stream() + val foo = data.mapNotNull { it.length } + assertEquals(arrayListOf(3, 3), foo.toList()) + + assertTrue { + foo is Stream + } + } + + Test fun filterAndTakeWhileExtractTheElementsWithinRange() { + assertEquals(arrayListOf(144, 233, 377, 610, 987), fibonacci().filter { it > 100 }.takeWhile { it < 1000 }.toList()) + } + + Test fun foldReducesTheFirstNElements() { + val sum = {(a: Int, b: Int) -> a + b } + assertEquals(arrayListOf(13, 21, 34, 55, 89).fold(0, sum), fibonacci().filter { it > 10 }.take(5).fold(0, sum)) + } + + Test fun takeExtractsTheFirstNElements() { + assertEquals(arrayListOf(0, 1, 1, 2, 3, 5, 8, 13, 21, 34), fibonacci().take(10).toList()) + } + + Test fun mapAndTakeWhileExtractTheTransformedElements() { + assertEquals(arrayListOf(0, 3, 3, 6, 9, 15), fibonacci().map { it * 3 }.takeWhile {(i: Int) -> i < 20 }.toList()) + } + + Test fun joinConcatenatesTheFirstNElementsAboveAThreshold() { + assertEquals("13, 21, 34, 55, 89, ...", fibonacci().filter { it > 10 }.makeString(separator = ", ", limit = 5)) + } + + Test fun skippingIterator() { + assertEquals("13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...", fibonacci().drop(7).makeString(limit = 10)) + assertEquals("13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...", fibonacci().drop(3).drop(4).makeString(limit = 10)) + } + + Test fun toStringJoinsNoMoreThanTheFirstTenElements() { + assertEquals("0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...", fibonacci().makeString(limit = 10)) + assertEquals("13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...", fibonacci().filter { it > 10 }.makeString(limit = 10)) + assertEquals("144, 233, 377, 610, 987", fibonacci().filter { it > 100 }.takeWhile { it < 1000 }.makeString()) + } + + Test fun plus() { + val stream = listOf("foo", "bar").stream() + val streamChease = stream + "cheese" + assertEquals(listOf("foo", "bar", "cheese"), streamChease.toList()) + + // lets use a mutable variable + var mi = listOf("a", "b").stream() + mi += "c" + assertEquals(listOf("a", "b", "c"), mi.toList()) + } + + Test fun plusCollection() { + val a = listOf("foo", "bar") + val b = listOf("cheese", "wine") + val stream = a.stream() + b + assertEquals(listOf("foo", "bar", "cheese", "wine"), stream.toList()) + + // lets use a mutable variable + var ml = listOf("a").stream() + ml += a + ml += "beer" + ml += b + ml += "z" + assertEquals(listOf("a", "foo", "bar", "beer", "cheese", "wine", "z"), ml.toList()) + } + + + Test fun iterationOverStream() { + val c = arrayListOf(0, 1, 2, 3, 4, 5) + var s = "" + for (i in c.stream()) { + s = s + i.toString() + } + assertEquals("012345", s) + } + + Test fun streamFromFunction() { + var count = 3 + + val stream = stream { + count-- + if (count >= 0) count else null + } + + val list = stream.toList() + assertEquals(listOf(2, 1, 0), list) + } + + Test fun streamFromFunctionWithInitialValue() { + val values = stream(3) { n -> if (n > 0) n - 1 else null } + assertEquals(arrayListOf(3, 2, 1, 0), values.toList()) + } + + private fun > Stream.takeWhileTo(result: C, predicate: (T) -> Boolean): C { + for (element in this) if (predicate(element)) result.add(element) else break + return result + } + + Test fun streamExtensions() { + val c = arrayListOf(0, 1, 2, 3, 4, 5) + val d = ArrayList() + c.stream().takeWhileTo(d, { i -> i < 4 }) + assertEquals(4, d.size()) + } + + /* + Test fun pairIterator() { + val pairStr = (fibonacci() zip fibonacci().map { i -> i*2 }).makeString(limit = 10) + assertEquals("(0, 0), (1, 2), (1, 2), (2, 4), (3, 6), (5, 10), (8, 16), (13, 26), (21, 42), (34, 68), ...", pairStr) + } +*/ + +} \ No newline at end of file diff --git a/libraries/stdlib/test/concurrent/SerialFunAndTupleTest.kt b/libraries/stdlib/test/concurrent/SerialFunAndTupleTest.kt index 2daecf4c883..53a7f2351d2 100644 --- a/libraries/stdlib/test/concurrent/SerialFunAndTupleTest.kt +++ b/libraries/stdlib/test/concurrent/SerialFunAndTupleTest.kt @@ -1,4 +1,4 @@ -package serial +package test.concurrent import java.io.ObjectOutputStream import java.io.ByteArrayOutputStream diff --git a/libraries/stdlib/test/concurrent/ThreadTest.kt b/libraries/stdlib/test/concurrent/ThreadTest.kt index 20fa607f72a..e779cd3f93d 100644 --- a/libraries/stdlib/test/concurrent/ThreadTest.kt +++ b/libraries/stdlib/test/concurrent/ThreadTest.kt @@ -1,4 +1,4 @@ -package concurrent +package test.concurrent import kotlin.concurrent.* import kotlin.test.* diff --git a/libraries/stdlib/test/concurrent/TimerTest.kt b/libraries/stdlib/test/concurrent/TimerTest.kt index b2ee976c901..e3830608af3 100644 --- a/libraries/stdlib/test/concurrent/TimerTest.kt +++ b/libraries/stdlib/test/concurrent/TimerTest.kt @@ -1,4 +1,4 @@ -package concurrent +package test.concurrent import kotlin.concurrent.* import kotlin.test.* diff --git a/libraries/stdlib/test/dom/NextSiblingTest.kt b/libraries/stdlib/test/dom/NextSiblingTest.kt index b4ad9a166b0..3034d1a00a2 100644 --- a/libraries/stdlib/test/dom/NextSiblingTest.kt +++ b/libraries/stdlib/test/dom/NextSiblingTest.kt @@ -39,7 +39,7 @@ class NextSiblingTest { val elems = doc["#id3"] val element = elems.first() - val elements = element.nextElements().toList() + val elements = element.nextElements() val nodes = element.nextSiblings().toList() assertEquals(1, elements.size()) diff --git a/libraries/stdlib/test/IoTest.kt b/libraries/stdlib/test/io/IoTest.kt similarity index 98% rename from libraries/stdlib/test/IoTest.kt rename to libraries/stdlib/test/io/IoTest.kt index b13f483286f..ab275c9d1ef 100644 --- a/libraries/stdlib/test/IoTest.kt +++ b/libraries/stdlib/test/io/IoTest.kt @@ -1,4 +1,4 @@ -package test.collections +package test.io import kotlin.test.* @@ -12,7 +12,7 @@ class IoTest(){ test fun testLineIteratorWithManualClose() { val reader = sample().buffered() try { - val list = reader.lineIterator().toArrayList() + val list = reader.lines().toArrayList() assertEquals(arrayListOf("Hello", "World"), list) } finally { reader.close() diff --git a/libraries/stdlib/test/js/MapJsTest.kt b/libraries/stdlib/test/js/MapJsTest.kt index 4b71c730be3..2d45023e3e9 100644 --- a/libraries/stdlib/test/js/MapJsTest.kt +++ b/libraries/stdlib/test/js/MapJsTest.kt @@ -175,14 +175,14 @@ class MapJsTest { */ test fun createUsingPairs() { - val map = hashMap(Pair("a", 1), Pair("b", 2)) + val map = mapOf(Pair("a", 1), Pair("b", 2)) assertEquals(2, map.size) assertEquals(1, map.get("a")) assertEquals(2, map.get("b")) } test fun createUsingTo() { - val map = hashMap("a" to 1, "b" to 2) + val map = mapOf("a" to 1, "b" to 2) assertEquals(2, map.size) assertEquals(1, map.get("a")) assertEquals(2, map.get("b")) diff --git a/libraries/stdlib/test/js/SetJsTest.kt b/libraries/stdlib/test/js/SetJsTest.kt index 96920552aaf..bf156cb8abb 100644 --- a/libraries/stdlib/test/js/SetJsTest.kt +++ b/libraries/stdlib/test/js/SetJsTest.kt @@ -6,7 +6,7 @@ import org.junit.Test class SetJsTest { val data: Set = createTestMutableSet() - val empty: Set = hashSet() + val empty: Set = hashSetOf() Test fun size() { assertEquals(2, data.size()) @@ -39,10 +39,10 @@ class SetJsTest { } Test fun containsAll() { - assertTrue(data.containsAll(arrayList("foo", "bar"))) - assertTrue(data.containsAll(arrayList())) - assertFalse(data.containsAll(arrayList("foo", "bar", "baz"))) - assertFalse(data.containsAll(arrayList("baz"))) + assertTrue(data.containsAll(arrayListOf("foo", "bar"))) + assertTrue(data.containsAll(arrayListOf())) + assertFalse(data.containsAll(arrayListOf("foo", "bar", "baz"))) + assertFalse(data.containsAll(arrayListOf("baz"))) } Test fun add() { @@ -51,7 +51,7 @@ class SetJsTest { assertEquals(3, data.size()) assertFalse(data.add("baz")) assertEquals(3, data.size()) - assertTrue(data.containsAll(arrayList("foo", "bar", "baz"))) + assertTrue(data.containsAll(arrayListOf("foo", "bar", "baz"))) } Test fun remove() { @@ -65,36 +65,36 @@ class SetJsTest { Test fun addAll() { val data = createTestMutableSet() - assertTrue(data.addAll(arrayList("foo", "bar", "baz", "boo"))) + assertTrue(data.addAll(arrayListOf("foo", "bar", "baz", "boo"))) assertEquals(4, data.size()) - assertFalse(data.addAll(arrayList("foo", "bar", "baz", "boo"))) + assertFalse(data.addAll(arrayListOf("foo", "bar", "baz", "boo"))) assertEquals(4, data.size()) - assertTrue(data.containsAll(arrayList("foo", "bar", "baz", "boo"))) + assertTrue(data.containsAll(arrayListOf("foo", "bar", "baz", "boo"))) } Test fun removeAll() { val data = createTestMutableSet() - assertFalse(data.removeAll(arrayList("baz"))) - assertTrue(data.containsAll(arrayList("foo", "bar"))) + assertFalse(data.removeAll(arrayListOf("baz"))) + assertTrue(data.containsAll(arrayListOf("foo", "bar"))) assertEquals(2, data.size()) - assertTrue(data.removeAll(arrayList("foo"))) + assertTrue(data.removeAll(arrayListOf("foo"))) assertTrue(data.contains("bar")) assertEquals(1, data.size()) - assertTrue(data.removeAll(arrayList("foo", "bar"))) + assertTrue(data.removeAll(arrayListOf("foo", "bar"))) assertEquals(0, data.size()) val data2 = createTestMutableSet() - assertFalse(data.removeAll(arrayList("foo", "bar", "baz"))) + assertFalse(data.removeAll(arrayListOf("foo", "bar", "baz"))) assertTrue(data.isEmpty()) } Test fun retainAll() { val data1 = createTestMutableSet() - assertTrue(data1.retainAll(arrayList("baz"))) + assertTrue(data1.retainAll(arrayListOf("baz"))) assertTrue(data1.isEmpty()) val data2 = createTestMutableSet() - assertTrue(data2.retainAll(arrayList("foo"))) + assertTrue(data2.retainAll(arrayListOf("foo"))) assertTrue(data2.contains("foo")) assertEquals(1, data2.size()) } @@ -109,5 +109,5 @@ class SetJsTest { } //Helpers - fun createTestMutableSet(): MutableSet = hashSet("foo", "bar") + fun createTestMutableSet(): MutableSet = hashSetOf("foo", "bar") } diff --git a/libraries/stdlib/test/StringJVMTest.kt b/libraries/stdlib/test/text/StringJVMTest.kt similarity index 98% rename from libraries/stdlib/test/StringJVMTest.kt rename to libraries/stdlib/test/text/StringJVMTest.kt index 621c982c048..c43cabe190b 100644 --- a/libraries/stdlib/test/StringJVMTest.kt +++ b/libraries/stdlib/test/text/StringJVMTest.kt @@ -1,4 +1,4 @@ -package test.string +package test.text import kotlin.test.* @@ -252,7 +252,9 @@ class StringJVMTest { test fun drop() { val data = "abcd1234" assertEquals("d1234", data.drop(3)) - assertEquals(data, data.drop(-2)) + fails { + data.drop(-2) + } assertEquals("", data.drop(data.length + 5)) } @@ -265,7 +267,9 @@ class StringJVMTest { test fun take() { val data = "abcd1234" assertEquals("abc", data.take(3)) - assertEquals("", data.take(-7)) + fails { + data.take(-7) + } assertEquals(data, data.take(data.length + 42)) } diff --git a/libraries/stdlib/test/StringTest.kt b/libraries/stdlib/test/text/StringTest.kt similarity index 98% rename from libraries/stdlib/test/StringTest.kt rename to libraries/stdlib/test/text/StringTest.kt index 30280466d11..4c87bbbbc5a 100644 --- a/libraries/stdlib/test/StringTest.kt +++ b/libraries/stdlib/test/text/StringTest.kt @@ -1,4 +1,4 @@ -package test +package test.text import kotlin.test.* import org.junit.Test as test diff --git a/libraries/stdlib/test/StringUtilTest.kt b/libraries/stdlib/test/text/StringUtilTest.kt similarity index 93% rename from libraries/stdlib/test/StringUtilTest.kt rename to libraries/stdlib/test/text/StringUtilTest.kt index 8e997b3645e..3998aaeedd7 100644 --- a/libraries/stdlib/test/StringUtilTest.kt +++ b/libraries/stdlib/test/text/StringUtilTest.kt @@ -1,4 +1,4 @@ -package test.string +package test.text import kotlin.* import kotlin.test.* diff --git a/libraries/tools/kotlin-stdlib-gen/src/generators/GenerateCollections.kt b/libraries/tools/kotlin-stdlib-gen/src/generators/GenerateCollections.kt new file mode 100644 index 00000000000..7422d52ca01 --- /dev/null +++ b/libraries/tools/kotlin-stdlib-gen/src/generators/GenerateCollections.kt @@ -0,0 +1,35 @@ +package generators + +import java.io.* +import templates.Family.* +import templates.* +import templates.PrimitiveType.* + +fun generateCollectionsAPI(outDir : File) { + elements().writeTo(File(outDir, "_Elements.kt")) { build() } + filtering().writeTo(File(outDir, "_Filtering.kt")) { build() } + ordering().writeTo(File(outDir, "_Ordering.kt")) { build() } + arrays().writeTo(File(outDir, "_Arrays.kt")) { build() } + snapshots().writeTo(File(outDir, "_Snapshots.kt")) { build() } + mapping().writeTo(File(outDir, "_Mapping.kt")) { build() } + aggregates().writeTo(File(outDir, "_Aggregates.kt")) { build() } + guards().writeTo(File(outDir, "_Guards.kt")) { build() } + generators().writeTo(File(outDir, "_Generators.kt")) { build() } + strings().writeTo(File(outDir, "_Strings.kt")) { build() } + specialJVM().writeTo(File(outDir, "_SpecialJVM.kt")) { build() } + + numeric().writeTo(File(outDir, "_Numeric.kt")) { + val builder = StringBuilder() + // TODO: decide if sum for byte and short is needed and how to make it work + for(numeric in listOf(Int, Long, /*Byte, Short, */ Double, Float)) { + build(builder, Iterables, numeric) + } + + for(numeric in listOf(Int, Long, Byte, Short, Double, Float)) { + build(builder, ArraysOfObjects, numeric) + build(builder, ArraysOfPrimitives, numeric) + } + builder.toString() + } + +} diff --git a/libraries/tools/kotlin-stdlib-gen/src/generators/GenerateStandardLib.kt b/libraries/tools/kotlin-stdlib-gen/src/generators/GenerateStandardLib.kt index 438cc701ee5..8460b63870a 100644 --- a/libraries/tools/kotlin-stdlib-gen/src/generators/GenerateStandardLib.kt +++ b/libraries/tools/kotlin-stdlib-gen/src/generators/GenerateStandardLib.kt @@ -28,29 +28,7 @@ fun main(args: Array) { generateDomAPI(File(jsCoreDir, "dom.kt")) generateDomEventsAPI(File(jsCoreDir, "domEvents.kt")) - iterators().writeTo(File(outDir, "_Iterators.kt")) { - buildFor(Iterators, null) - } - - val arrays = arrays() - val sumFunctions = PrimitiveType.values().map(::sumFunction).filterNotNull() - (arrays + sumFunctions).writeTo(File(outDir, "_Arrays.kt")) { - buildFor(Arrays, null) - } - - for (primitive in PrimitiveType.values()) { - (arrays + sumFunction(primitive)).filterNotNull().writeTo(File(outDir, "_${primitive.name}Arrays.kt")) { - buildFor(PrimitiveArrays, primitive) - } - } - - (iterables().sort() + sumFunctions).writeTo(File(outDir, "_Iterables.kt")) { - buildFor(Iterables, null) - } - - collections().writeTo(File(outDir, "_Collections.kt")) { - buildFor(Collections, null) - } + generateCollectionsAPI(outDir) generateDownTos(File(outDir, "_DownTo.kt"), "package kotlin") } @@ -65,20 +43,8 @@ fun List.writeTo(file: File, builder: GenericFunction.() -> Str its.append("package kotlin\n\n") its.append("$COMMON_AUTOGENERATED_WARNING\n\n") its.append("import java.util.*\n\n") - for (t in this) { + for (t in this.sort()) { its.append(t.builder()) } } } - -// Pretty hacky way to code generate; ideally we'd be using the AST and just changing the function prototypes -fun replaceGenerics(arrayName: String, it: String): String { - return it.replaceAll(" ", " ").replaceAll(" ", " "). - replaceAll("", "<${arrayName}>").replaceAll("", "<${arrayName}>"). - replaceAll("\\(T\\)", "(${arrayName})").replaceAll("T\\?", "${arrayName}?"). - replaceAll("T,", "${arrayName},"). - replaceAll("T\\)", "${arrayName})"). - replaceAll(" T ", " ${arrayName} ") -} - diff --git a/libraries/tools/kotlin-stdlib-gen/src/templates/Aggregates.kt b/libraries/tools/kotlin-stdlib-gen/src/templates/Aggregates.kt new file mode 100644 index 00000000000..f0a527cfa42 --- /dev/null +++ b/libraries/tools/kotlin-stdlib-gen/src/templates/Aggregates.kt @@ -0,0 +1,399 @@ +package templates + +import templates.Family.* + +fun aggregates(): List { + val templates = arrayListOf() + + templates add f("all(predicate: (T) -> Boolean)") { + inline(true) + doc { "Returns *true* if all elements match the given *predicate*" } + returns("Boolean") + body { + """ + for (element in this) if (!predicate(element)) return false + return true + """ + } + include(Maps) + } + + templates add f("none(predicate: (T) -> Boolean)") { + inline(true) + + doc { "Returns *true* if no elements match the given *predicate*" } + returns("Boolean") + body { + """ + for (element in this) if (predicate(element)) return false + return true + """ + } + include(Maps) + } + + templates add f("none()") { + doc { "Returns *true* if collection has no elements" } + returns("Boolean") + body { + """ + for (element in this) return false + return true + """ + } + include(Maps) + } + + templates add f("any(predicate: (T) -> Boolean)") { + inline(true) + + doc { "Returns *true* if any element matches the given *predicate*" } + returns("Boolean") + body { + """ + for (element in this) if (predicate(element)) return true + return false + """ + } + include(Maps) + } + + templates add f("any()") { + doc { "Returns *true* if collection has at least one element" } + returns("Boolean") + body { + """ + for (element in this) return true + return false + """ + } + include(Maps) + } + + templates add f("count(predicate: (T) -> Boolean)") { + inline(true) + + doc { "Returns the number of elements matching the given *predicate*" } + returns("Int") + body { + """ + var count = 0 + for (element in this) if (predicate(element)) count++ + return count + """ + } + include(Maps) + } + + templates add f("count()") { + doc { "Returns the number of elements" } + returns("Int") + body { + """ + var count = 0 + for (element in this) count++ + return count + """ + } + body(Maps, Collections, ArraysOfObjects, ArraysOfPrimitives) { + "return size" + } + } + + templates add f("min()") { + doc { "Returns the smallest element or null if there are no elements" } + returns("T?") + exclude(PrimitiveType.Boolean) + typeParam("T: Comparable") + body { + """ + val iterator = iterator() + if (!iterator.hasNext()) return null + + var min = iterator.next() + while (iterator.hasNext()) { + val e = iterator.next() + if (min > e) min = e + } + return min + """ + } + body(ArraysOfObjects, ArraysOfPrimitives) { + """ + if (isEmpty()) return null + var min = this[0] + for (i in 1..lastIndex) { + val e = this[i] + if (min > e) min = e + } + return min + """ + } + } + + templates add f("minBy(f: (T) -> R)") { + inline(true) + + doc { "Returns the first element yielding the smallest value of the given function or null if there are no elements" } + typeParam("R: Comparable") + typeParam("T: Any") + returns("T?") + body { + """ + val iterator = iterator() + if (!iterator.hasNext()) return null + + var minElem = iterator.next() + var minValue = f(minElem) + while (iterator.hasNext()) { + val e = iterator.next() + val v = f(e) + if (minValue > v) { + minElem = e + minValue = v + } + } + return minElem + """ + } + body(ArraysOfObjects, ArraysOfPrimitives) { + """ + if (size == 0) return null + + var minElem = this[0] + var minValue = f(minElem) + for (i in 1..lastIndex) { + val e = this[i] + val v = f(e) + if (minValue > v) { + minElem = e + minValue = v + } + } + return minElem + """ + } + } + + templates add f("minBy(f: (T) -> R)") { + inline(true) + + only(Maps) + doc { "Returns the first element yielding the smallest value of the given function or null if there are no elements" } + typeParam("R: Comparable") + returns("T?") + body { + """ + val iterator = iterator() + if (!iterator.hasNext()) return null + + var minElem = iterator.next() + var minValue = f(minElem) + while (iterator.hasNext()) { + val e = iterator.next() + val v = f(e) + if (minValue > v) { + minElem = e + minValue = v + } + } + return minElem + """ + } + } + + templates add f("max()") { + doc { "Returns the largest element or null if there are no elements" } + returns("T?") + exclude(PrimitiveType.Boolean) + typeParam("T: Comparable") + body { + """ + val iterator = iterator() + if (!iterator.hasNext()) return null + + var max = iterator.next() + while (iterator.hasNext()) { + val e = iterator.next() + if (max < e) max = e + } + return max + """ + } + + body(ArraysOfObjects, ArraysOfPrimitives) { + """ + if (isEmpty()) return null + + var max = this[0] + for (i in 1..lastIndex) { + val e = this[i] + if (max < e) max = e + } + return max + """ + } + } + + templates add f("maxBy(f: (T) -> R)") { + inline(true) + + doc { "Returns the first element yielding the largest value of the given function or null if there are no elements" } + typeParam("R: Comparable") + typeParam("T: Any") + returns("T?") + body { + """ + val iterator = iterator() + if (!iterator.hasNext()) return null + + var maxElem = iterator.next() + var maxValue = f(maxElem) + while (iterator.hasNext()) { + val e = iterator.next() + val v = f(e) + if (maxValue < v) { + maxElem = e + maxValue = v + } + } + return maxElem + """ + } + body(ArraysOfObjects, ArraysOfPrimitives) { + """ + if (isEmpty()) return null + + var maxElem = this[0] + var maxValue = f(maxElem) + for (i in 1..lastIndex) { + val e = this[i] + val v = f(e) + if (maxValue < v) { + maxElem = e + maxValue = v + } + } + return maxElem + """ + } + } + + templates add f("maxBy(f: (T) -> R)") { + inline(true) + + only(Maps) + doc { "Returns the first element yielding the largest value of the given function or null if there are no elements" } + typeParam("R: Comparable") + returns("T?") + body { + """ + val iterator = iterator() + if (!iterator.hasNext()) return null + + var maxElem = iterator.next() + var maxValue = f(maxElem) + while (iterator.hasNext()) { + val e = iterator.next() + val v = f(e) + if (maxValue < v) { + maxElem = e + maxValue = v + } + } + return maxElem + """ + } + } + + templates add f("fold(initial: R, operation: (R, T) -> R)") { + inline(true) + + doc { "Accumulates value starting with *initial* value and applying *operation* from left to right to current accumulator value and each element" } + typeParam("R") + returns("R") + body { + """ + var accumulator = initial + for (element in this) accumulator = operation(accumulator, element) + return accumulator + """ + } + } + + templates add f("foldRight(initial: R, operation: (T, R) -> R)") { + inline(true) + + only(Lists, ArraysOfObjects, ArraysOfPrimitives) + doc { "Accumulates value starting with *initial* value and applying *operation* from right to left to each element and current accumulator value" } + typeParam("R") + returns("R") + body { + """ + var index = size - 1 + var accumulator = initial + while (index >= 0) { + accumulator = operation(get(index--), accumulator) + } + return accumulator + """ + } + } + + + templates add f("reduce(operation: (T, T) -> T)") { + inline(true) + + doc { "Accumulates value starting with the first element and applying *operation* from left to right to current accumulator value and each element" } + returns("T") + body { + """ + val iterator = this.iterator() + if (!iterator.hasNext()) throw UnsupportedOperationException("Empty iterable can't be reduced") + + var accumulator = iterator.next() + while (iterator.hasNext()) { + accumulator = operation(accumulator, iterator.next()) + } + return accumulator + """ + } + } + + templates add f("reduceRight(operation: (T, T) -> T)") { + inline(true) + + only(Lists, ArraysOfObjects, ArraysOfPrimitives) + doc { "Accumulates value starting with last element and applying *operation* from right to left to each element and current accumulator value" } + returns("T") + body { + """ + var index = size - 1 + if (index < 0) throw UnsupportedOperationException("Empty iterable can't be reduced") + + var accumulator = get(index--) + while (index >= 0) { + accumulator = operation(get(index--), accumulator) + } + + return accumulator + """ + } + } + + + templates add f("forEach(operation: (T) -> Unit)") { + inline(true) + + doc { "Performs the given *operation* on each element" } + returns("Unit") + body { + """ + for (element in this) operation(element) + """ + } + include(Maps) + } + + return templates +} \ No newline at end of file diff --git a/libraries/tools/kotlin-stdlib-gen/src/templates/Arrays.kt b/libraries/tools/kotlin-stdlib-gen/src/templates/Arrays.kt index aa8b7841136..3e0a1435742 100644 --- a/libraries/tools/kotlin-stdlib-gen/src/templates/Arrays.kt +++ b/libraries/tools/kotlin-stdlib-gen/src/templates/Arrays.kt @@ -3,12 +3,11 @@ package templates import templates.Family.* fun arrays(): List { - val templates = iterables() + val templates = arrayListOf() templates add f("isEmpty()") { - absentFor(Arrays) - isInline = false - doc = "Returns true if the array is empty" + only(ArraysOfObjects, ArraysOfPrimitives) + doc { "Returns true if the array is empty" } returns("Boolean") body { "return size == 0" @@ -16,57 +15,13 @@ fun arrays(): List { } templates add f("isNotEmpty()") { - absentFor(Arrays) - isInline = false - doc = "Returns true if the array is empty" + only(ArraysOfObjects, ArraysOfPrimitives) + doc { "Returns true if the array is not empty" } returns("Boolean") body { "return !isEmpty()" } } - templates add f("indexOf(item: T)") { - absentFor(PrimitiveArrays) - isInline = false - doc = "Returns first index of item, or -1 if the array does not contain item" - returns("Int") - body { - """ - if (item == null) { - for (i in indices) { - if (this[i] == null) { - return i - } - } - } else { - for (i in indices) { - if (item == this[i]) { - return i - } - } - } - return -1 - """ - } - } - - // implementation for PrimitiveArrays is separate from Arrays, because they cannot hold null elements - templates add f("indexOf(item: T)") { - absentFor(Arrays) - isInline = false - doc = "Returns first index of item, or -1 if the array does not contain item" - returns("Int") - body { - """ - for (i in indices) { - if (item == this[i]) { - return i - } - } - return -1 - """ - } - } - - return templates.sort() + return templates } \ No newline at end of file diff --git a/libraries/tools/kotlin-stdlib-gen/src/templates/Collections.kt b/libraries/tools/kotlin-stdlib-gen/src/templates/Collections.kt deleted file mode 100644 index 84a024c2763..00000000000 --- a/libraries/tools/kotlin-stdlib-gen/src/templates/Collections.kt +++ /dev/null @@ -1,33 +0,0 @@ -package templates - -import java.util.ArrayList -import templates.Family.* - -fun collections(): List { - - val templates = ArrayList() - - templates add f("requireNoNulls()") { - isInline = false - absentFor(PrimitiveArrays) // Those are inherently non-nulls - doc = "Returns a original Iterable containing all the non-*null* elements, throwing an [[IllegalArgumentException]] if there are any null elements" - typeParam("T:Any") - toNullableT = true - returns("SELF") - - body { - val THIS = "\$this" - """ - for (element in this) { - if (element == null) { - throw IllegalArgumentException("null element found in $THIS") - } - } - return this as SELF - """ - } - - } - - return templates.sort() -} \ No newline at end of file diff --git a/libraries/tools/kotlin-stdlib-gen/src/templates/Commons.kt b/libraries/tools/kotlin-stdlib-gen/src/templates/Commons.kt deleted file mode 100644 index 476c4e1a28e..00000000000 --- a/libraries/tools/kotlin-stdlib-gen/src/templates/Commons.kt +++ /dev/null @@ -1,467 +0,0 @@ -package templates - -import java.util.ArrayList -import templates.Family.* - -fun commons(): ArrayList { - - val templates = ArrayList() - - templates add f("all(predicate: (T) -> Boolean)") { - doc = "Returns *true* if all elements match the given *predicate*" - returns("Boolean") - - body { - """ - for (element in this) if (!predicate(element)) return false - return true - """ - } - } - - templates add f("any(predicate: (T) -> Boolean)") { - doc = "Returns *true* if any elements match the given *predicate*" - returns("Boolean") - - body { - """ - for (element in this) if (predicate(element)) return true - return false - """ - } - } - - templates add f("count(predicate: (T) -> Boolean)") { - doc = "Returns the number of elements which match the given *predicate*" - returns("Int") - body { - """ - var count = 0 - for (element in this) if (predicate(element)) count++ - return count - """ - } - } - - - templates add f("find(predicate: (T) -> Boolean)") { - doc = "Returns the first element which matches the given *predicate* or *null* if none matched" - typeParam("T:Any") - returns("T?") - - body { - """ - for (element in this) if (predicate(element)) return element - return null - """ - } - } - - templates add f("filterTo(result: C, predicate: (T) -> Boolean)") { - doc = "Filters all elements which match the given predicate into the given list" - typeParam("C: MutableCollection") - returns("C") - - body { - """ - for (element in this) if (predicate(element)) result.add(element) - return result - """ - } - } - - templates add f("filterNotTo(result: C, predicate: (T) -> Boolean)") { - doc = "Returns a list containing all elements which do not match the given *predicate*" - typeParam("C: MutableCollection") - returns("C") - - body { - """ - for (element in this) if (!predicate(element)) result.add(element) - return result - """ - } - } - - templates add f("filterNotNullTo(result: C)") { - isInline = false - absentFor(PrimitiveArrays) // Those are inherently non-nulls - doc = "Filters all non-*null* elements into the given list" - typeParam("T:Any") - toNullableT = true - typeParam("C: MutableCollection") - returns("C") - - body { - """ - for (element in this) if (element != null) result.add(element) - return result - """ - } - } - - templates add f("partition(predicate: (T) -> Boolean)") { - doc = "Partitions this collection into a pair of collections" - returns("Pair, List>") - - body { - """ - val first = ArrayList() - val second = ArrayList() - for (element in this) { - if (predicate(element)) { - first.add(element) - } else { - second.add(element) - } - } - return Pair(first, second) - """ - } - } - - templates add f("mapTo(result: C, transform : (T) -> R)") { - doc = """ - Transforms each element of this collection with the given *transform* function and - adds each return value to the given *results* collection - """ - - typeParam("R") - typeParam("C: MutableCollection") - returns("C") - - body { - """ - for (item in this) - result.add(transform(item)) - return result - """ - } - } - - templates add f("flatMapTo(result: C, transform: (T) -> Iterable)") { - doc = "Returns the result of transforming each element to one or more values which are concatenated together into a single collection" - typeParam("R") - typeParam("C: MutableCollection") - returns("C") - - body { - """ - for (element in this) { - val list = transform(element) - for (r in list) result.add(r) - } - return result - """ - } - } - - templates add f("forEach(operation: (T) -> Unit)") { - doc = "Performs the given *operation* on each element" - returns("Unit") - body { - """ - for (element in this) operation(element) - """ - } - } - - templates add f("fold(initial: R, operation: (R, T) -> R)") { - doc = "Folds all elements from from left to right with the *initial* value to perform the operation on sequential pairs of elements" - typeParam("R") - returns("R") - - body { - """ - var answer = initial - for (element in this) answer = operation(answer, element) - return answer - """ - } - } - - templates add f("foldRight(initial: R, operation: (T, R) -> R)") { - doc = "Folds all elements from right to left with the *initial* value to perform the operation on sequential pairs of elements" - typeParam("R") - returns("R") - - absentFor(Iterators, Iterables, Collections) - - body { - """ - var r = initial - var index = size - 1 - - while (index >= 0) { - r = operation(get(index--), r) - } - - return r - """ - } - } - - templates add f("reduce(operation: (T, T) -> T)") { - doc = """ - Applies binary operation to all elements of iterable, going from left to right. - Similar to fold function, but uses the first element as initial value - """ - returns("T") - - body { - """ - val iterator = this.iterator() - if (!iterator.hasNext()) { - throw UnsupportedOperationException("Empty iterable can't be reduced") - } - - var result: T = iterator.next() //compiler doesn't understand that result will initialized anyway - while (iterator.hasNext()) { - result = operation(result, iterator.next()) - } - - return result - """ - } - } - - templates add f("reduceRight(operation: (T, T) -> T)") { - doc = """ - Applies binary operation to all elements of iterable, going from right to left. - Similar to foldRight function, but uses the last element as initial value - """ - returns("T") - absentFor(Iterators, Iterables, Collections) - - body { - """ - var index = size - 1 - if (index < 0) { - throw UnsupportedOperationException("Empty iterable can't be reduced") - } - - var r = get(index--) - while (index >= 0) { - r = operation(get(index--), r) - } - - return r - """ - } - } - - templates add f("groupBy(toKey: (T) -> K)") { - doc = "Groups the elements in the collection into a new [[Map]] using the supplied *toKey* function to calculate the key to group the elements by" - typeParam("K") - returns("Map>") - - body { "return groupByTo(HashMap>(), toKey)" } - } - - templates add f("groupByTo(result: MutableMap>, toKey: (T) -> K)") { - typeParam("K") - returns("Map>") - body { - """ - for (element in this) { - val key = toKey(element) - val list = result.getOrPut(key) { ArrayList() } - list.add(element) - } - return result - """ - } - } - - templates add f("drop(n: Int)") { - isInline = false - doc = "Returns a list containing everything but the first *n* elements" - returns("List") - body { - "return dropWhile(countTo(n))" - } - } - - templates add f("dropWhile(predicate: (T) -> Boolean)") { - doc = "Returns a list containing the everything but the first elements that satisfy the given *predicate*" - returns("List") - body { - "return dropWhileTo(ArrayList(), predicate)" - } - } - - - templates add f("dropWhileTo(result: L, predicate: (T) -> Boolean)") { - doc = "Returns a list containing the everything but the first elements that satisfy the given *predicate*" - typeParam("L: MutableList") - returns("L") - - body { - """ - var start = true - for (element in this) { - if (start && predicate(element)) { - // ignore - } else { - start = false - result.add(element) - } - } - return result - """ - } - } - - templates add f("takeWhileTo(result: C, predicate: (T) -> Boolean)") { - doc = "Returns a list containing the first elements that satisfy the given *predicate*" - typeParam("C: MutableCollection") - returns("C") - - body { - """ - for (element in this) if (predicate(element)) result.add(element) else break - return result - """ - } - } - - templates add f("toCollection(result: C)") { - isInline = false - doc = "Copies all elements into the given collection" - typeParam("C: MutableCollection") - returns("C") - - body { - """ - for (element in this) result.add(element) - return result - """ - } - } - - templates add f("reverse()") { - isInline = false - doc = "Reverses the order the elements into a list" - returns("List") - body { - """ - val list = toCollection(ArrayList()) - Collections.reverse(list) - return list - """ - } - } - - templates add f("toLinkedList()") { - isInline = false - doc = "Copies all elements into a [[LinkedList]]" - returns("LinkedList") - - body { "return toCollection(LinkedList())" } - } - - templates add f("toList()") { - isInline = false - doc = "Copies all elements into a [[List]]" - returns("List") - - body { "return toCollection(ArrayList())" } - } - - templates add f("toSet()") { - isInline = false - doc = "Copies all elements into a [[Set]]" - returns("Set") - - body { "return toCollection(LinkedHashSet())" } - } - - templates add f("toSortedSet()") { - isInline = false - doc = "Copies all elements into a [[SortedSet]]" - returns("SortedSet") - - body { "return toCollection(TreeSet())" } - } - - templates add f("withIndices()") { - isInline = false - doc = "Returns an iterator of Pairs(index, data)" - returns("Iterator>") - - body { - "return IndexIterator(iterator())" - } - } - - templates add f("sortBy(f: (T) -> R)") { - doc = """ - Copies all elements into a [[List]] and sorts it by value of compare_function(element) - E.g. arrayList("two" to 2, "one" to 1).sortBy({it.second}) returns list sorted by second element of pair - """ - returns("List") - typeParam("R: Comparable") - - body { - """ - val sortedList = toCollection(ArrayList()) - val sortBy: Comparator = comparator {(x: T, y: T) -> - val xr = f(x) - val yr = f(y) - xr.compareTo(yr) - } - java.util.Collections.sort(sortedList, sortBy) - return sortedList - """ - } - } - - templates add f("appendString(buffer: Appendable, separator: String = \", \", prefix: String =\"\", postfix: String = \"\", limit: Int = -1, truncated: String = \"...\")") { - isInline = false - doc = - """ - Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied - - If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will - a special *truncated* separator (which defaults to "..." - """ - returns("Unit") - - body { - """ - buffer.append(prefix) - var count = 0 - for (element in this) { - if (++count > 1) buffer.append(separator) - if (limit < 0 || count <= limit) { - val text = if (element == null) "null" else element.toString() - buffer.append(text) - } else break - } - if (limit >= 0 && count > limit) buffer.append(truncated) - buffer.append(postfix) - """ - } - } - - templates add f("makeString(separator: String = \", \", prefix: String = \"\", postfix: String = \"\", limit: Int = -1, truncated: String = \"...\")") { - isInline = false - doc = """ - Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied. - - If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will - a special *truncated* separator (which defaults to "..." - """ - - returns("String") - body { - """ - val buffer = StringBuilder() - appendString(buffer, separator, prefix, postfix, limit, truncated) - return buffer.toString() - """ - } - } - - return templates -} diff --git a/libraries/tools/kotlin-stdlib-gen/src/templates/Elements.kt b/libraries/tools/kotlin-stdlib-gen/src/templates/Elements.kt new file mode 100644 index 00000000000..ed23bb5e31e --- /dev/null +++ b/libraries/tools/kotlin-stdlib-gen/src/templates/Elements.kt @@ -0,0 +1,408 @@ +package templates + +import templates.Family.* + +fun elements(): List { + val templates = arrayListOf() + + templates add f("contains(element: T)") { + doc { "Returns true if *element* is found in the collection" } + returns("Boolean") + body { + "return indexOf(element) >= 0" + } + } + + templates add f("indexOf(element: T)") { + doc { "Returns first index of *element*, or -1 if the collection does not contain element" } + returns("Int") + body { + """ + var index = 0 + for (item in this) { + if (element == item) + return index + index++ + } + return -1 + """ + } + + body(ArraysOfObjects) { + """ + if (element == null) { + for (index in indices) { + if (this[index] == null) { + return index + } + } + } else { + for (index in indices) { + if (element == this[index]) { + return index + } + } + } + return -1 + """ + } + body(ArraysOfPrimitives) { + """ + for (index in indices) { + if (element == this[index]) { + return index + } + } + return -1 + """ + } + } + + templates add f("lastIndexOf(element: T)") { + doc { "Returns last index of *element*, or -1 if the collection does not contain element" } + returns("Int") + body { + """ + var lastIndex = -1 + var index = 0 + for (item in this) { + if (element == item) + lastIndex = index + index++ + } + return lastIndex + """ + } + + include(Lists) + body(Lists, ArraysOfObjects) { + """ + if (element == null) { + for (index in indices.reverse()) { + if (this[index] == null) { + return index + } + } + } else { + for (index in indices.reverse()) { + if (element == this[index]) { + return index + } + } + } + return -1 + """ + } + body(ArraysOfPrimitives) { + """ + for (index in indices.reverse()) { + if (element == this[index]) { + return index + } + } + return -1 + """ + } + } + + templates add f("elementAt(index : Int)") { + doc { "Returns element at given *index*" } + returns("T") + body { + """ + if (this is List<*>) + return get(index) as T + val iterator = iterator() + var count = 0 + while (iterator.hasNext()) { + val element = iterator.next() + if (index == count++) + return element + } + throw IndexOutOfBoundsException("Collection doesn't contain element at index") + """ + } + body(Streams) { + """ + val iterator = iterator() + var count = 0 + while (iterator.hasNext()) { + val element = iterator.next() + if (index == count++) + return element + } + throw IndexOutOfBoundsException("Collection doesn't contain element at index") + """ + } + body(Lists, ArraysOfObjects, ArraysOfPrimitives) { + """ + return get(index) + """ + } + } + + templates add f("first()") { + doc { "Returns first element" } + returns("T") + body { + """ + val iterator = iterator() + if (!iterator.hasNext()) + throw IllegalArgumentException("Collection is empty") + return iterator.next() + """ + } + body(Lists, ArraysOfObjects, ArraysOfPrimitives) { + """ + return this[0] + """ + } + } + templates add f("firstOrNull()") { + doc { "Returns first elementm, or null if collection is empty" } + returns("T?") + body { + """ + val iterator = iterator() + if (!iterator.hasNext()) + return null + return iterator.next() + """ + } + body(Lists, ArraysOfObjects, ArraysOfPrimitives) { + """ + return if (size > 0) this[0] else null + """ + } + } + + templates add f("first(predicate: (T) -> Boolean)") { + inline(true) + + doc { "Returns first element matching the given *predicate*" } + returns("T") + body { + """ + for (element in this) if (predicate(element)) return element + throw IllegalArgumentException("No element matching predicate was found") + """ + } + } + + templates add f("firstOrNull(predicate: (T) -> Boolean)") { + inline(true) + + doc { "Returns first element matching the given *predicate*, or *null* if element was not found" } + returns("T?") + body { + """ + for (element in this) if (predicate(element)) return element + return null + """ + } + } + + templates add f("last()") { + doc { "Returns last element" } + returns("T") + body { + """ + when (this) { + is List<*> -> return this[size - 1] as T + else -> { + val iterator = iterator() + if (!iterator.hasNext()) + throw IllegalArgumentException("Collection is empty") + var last = iterator.next() + while (iterator.hasNext()) + last = iterator.next() + return last + } + } + """ + } + body(Lists, ArraysOfObjects, ArraysOfPrimitives) { + """ + if (size == 0) + throw IllegalArgumentException("Collection is empty") + return this[size - 1] + """ + } + } + + templates add f("lastOrNull()") { + doc { "Returns last element, or null if collection is empty" } + returns("T?") + body { + """ + when (this) { + is List<*> -> return if (size > 0) this[size - 1] as T else null + else -> { + val iterator = iterator() + if (!iterator.hasNext()) + return null + var last = iterator.next() + while (iterator.hasNext()) + last = iterator.next() + return last + } + } + """ + } + include(Lists) + body(Lists, ArraysOfObjects, ArraysOfPrimitives) { + """ + return if (size > 0) this[size - 1] else null + """ + } + } + + templates add f("last(predicate: (T) -> Boolean)") { + doc { "Returns last element matching the given *predicate*" } + returns("T") + body { + """ + fun first(it : Iterator) : T { + for (element in it) if (predicate(element)) return element + throw IllegalArgumentException("Collection doesn't contain any element matching predicate") + } + val iterator = iterator() + var last = first(iterator) + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + last = element + } + return last + """ + } + } + + templates add f("lastOrNull(predicate: (T) -> Boolean)") { + doc { "Returns last element matching the given *predicate*, or null if element was not found" } + returns("T?") + body { + """ + fun first(it : Iterator) : T? { + for (element in it) if (predicate(element)) return element + return null + } + val iterator = iterator() + var last = first(iterator) + if (last == null) + return null + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + last = element + } + return last + """ + } + } + + val bucks = '$' + templates add f("single()") { + doc { "Returns single element, or throws exception if there is no or more than one element" } + returns("T") + body { + """ + when (this) { + is List<*> -> return if (size == 1) this[0] as T else throw IllegalArgumentException("Collection has ${bucks}size elements") + else -> { + val iterator = iterator() + if (!iterator.hasNext()) + throw IllegalArgumentException("Collection is empty") + var single = iterator.next() + if (iterator.hasNext()) + throw IllegalArgumentException("Collection has more than one element") + return single + } + } + """ + } + body(ArraysOfObjects, ArraysOfPrimitives) { + """ + if (size != 1) + throw IllegalArgumentException("Collection has ${bucks}size elements") + return this[0] + """ + } + } + + templates add f("singleOrNull()") { + doc { "Returns single element, or null if collection is empty, or throws exception if there is more than one element" } + returns("T?") + body { + """ + when (this) { + is List<*> -> return if (size == 1) this[0] as T else if (size == 0) null else throw IllegalArgumentException("Collection has ${bucks}size elements") + else -> { + val iterator = iterator() + if (!iterator.hasNext()) + return null + var single = iterator.next() + if (iterator.hasNext()) + throw IllegalArgumentException("Collection has more than one element") + return single + } + } + """ + } + body(ArraysOfObjects, ArraysOfPrimitives) { + """ + if (size == 0) + return null + if (size != 1) + throw IllegalArgumentException("Collection has ${bucks}size elements") + return this[0] + """ + } + } + + templates add f("single(predicate: (T) -> Boolean)") { + doc { "Returns single element matching the given *predicate*, or throws exception if there is no or more than one element" } + returns("T") + body { + """ + fun first(it : Iterator) : T { + for (element in it) if (predicate(element)) return element + throw IllegalArgumentException("Collection doesn't have matching element") + } + val iterator = iterator() + var single = first(iterator) + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + throw IllegalArgumentException("Collection has more than one matching element") + } + return single + """ + } + } + + templates add f("singleOrNull(predicate: (T) -> Boolean)") { + doc { "Returns single element matching the given *predicate*, or null if element was not found or more than one elements were found" } + returns("T?") + body { + """ + fun first(it : Iterator) : T? { + for (element in it) if (predicate(element)) return element + return null + } + val iterator = iterator() + var single = first(iterator) + if (single == null) + return null + while (iterator.hasNext()) { + val element = iterator.next() + if (predicate(element)) + throw IllegalArgumentException("Collection has more than one matching element") + } + return single + """ + } + } + + return templates +} \ No newline at end of file diff --git a/libraries/tools/kotlin-stdlib-gen/src/templates/Engine.kt b/libraries/tools/kotlin-stdlib-gen/src/templates/Engine.kt index 88be3c3f0ea..42500ccd8b5 100644 --- a/libraries/tools/kotlin-stdlib-gen/src/templates/Engine.kt +++ b/libraries/tools/kotlin-stdlib-gen/src/templates/Engine.kt @@ -8,110 +8,206 @@ import java.io.StringReader import java.util.StringTokenizer enum class Family { - Iterators + Streams Iterables Collections - Arrays - PrimitiveArrays + Lists + Maps + ArraysOfObjects + ArraysOfPrimitives } -class GenericFunction(val signature : String): Comparable { - var doc : String = "" - var toNullableT : Boolean = false - var isInline : Boolean = true; - private val customReceivers = HashMap() - val blockedFor = HashSet() - private val blockedForPrimitive = HashSet() +enum class PrimitiveType(val name: String) { + Boolean: PrimitiveType("Boolean") + Byte: PrimitiveType("Byte") + Char: PrimitiveType("Char") + Short: PrimitiveType("Short") + Int: PrimitiveType("Int") + Long: PrimitiveType("Long") + Float: PrimitiveType("Float") + Double: PrimitiveType("Double") +} + + +class GenericFunction(val signature: String) : Comparable { + val defaultFamilies = array(Iterables, Streams, ArraysOfObjects, ArraysOfPrimitives) + + var toNullableT: Boolean = false + + var defaultInline = false + val inlineFamilies = HashMap() + + val buildFamilies = HashSet(defaultFamilies.toList()) + private val buildPrimitives = HashSet(PrimitiveType.values().toList()) + + var doc: String = "" + val docs = HashMap() + + var defaultBody: String = "" val bodies = HashMap() + + var defaultReturnType = "" val returnTypes = HashMap() + val typeParams = ArrayList() - fun body(b : () -> String) { - for (f in Family.values()) { - if (bodies[f] == null) f.body(b) + fun body(vararg families: Family, b: () -> String) { + if (families.isEmpty()) + defaultBody = b() + else { + for (f in families) { + include(f) + bodies[f] = b() + } } } - fun Family.body(b : () -> String) { - bodies[this] = b() - } - - fun returns(r : String) { - for (f in Family.values()) { - if (returnTypes[f] == null) f.returns(r) + fun doc(vararg families: Family, b: () -> String) { + if (families.isEmpty()) + doc = b() + else { + for (f in families) { + docs[f] = b() + } } } - fun Family.returns(r:String) { - returnTypes[this] = r + fun returns(vararg families: Family, b: () -> String) { + if (families.isEmpty()) + defaultReturnType = b() + else { + for (f in families) { + returnTypes[f] = b() + } + } } - fun Family.customReceiver(r: String) { - customReceivers[this] = r + fun returns(r: String) { + defaultReturnType = r } - fun typeParam(t:String) { + fun typeParam(t: String) { typeParams.add(t) } - fun absentFor(vararg f : Family) { - blockedFor.addAll(f.toList()) + fun inline(value : Boolean, vararg families: Family) { + if (families.isEmpty()) + defaultInline = value + else + for (f in families) + inlineFamilies.put(f, value) } - fun absentFor(vararg p: PrimitiveType) { - blockedForPrimitive.addAll(p.toList()) + fun exclude(vararg families: Family) { + buildFamilies.removeAll(families.toList()) } - private fun effectiveTypeParams(f : Family) : List { - val types = ArrayList(typeParams) - if (typeParams.find { it.startsWith("T") } == null && !customReceivers.containsKey(f)) { - types.add(0, "T") + fun only(vararg families: Family) { + buildFamilies.clear() + buildFamilies.addAll(families.toList()) + } + + fun include(vararg families: Family) { + buildFamilies.addAll(families.toList()) + } + + fun exclude(vararg p: PrimitiveType) { + buildPrimitives.removeAll(p.toList()) + } + + fun include(vararg p: PrimitiveType) { + buildPrimitives.addAll(p.toList()) + } + + + fun build(vararg families: Family = Family.values()): String { + val builder = StringBuilder() + for (family in families.sortBy { it.name() }) { + if (buildFamilies.contains(family)) + build(builder, family) } - - if (f == PrimitiveArrays) { - types.remove(types.find { it.startsWith("T") }) - } - - return types + return builder.toString() } + fun build(builder: StringBuilder, f: Family) { + if (f == ArraysOfPrimitives) { + for (primitive in buildPrimitives.sortBy { it.name() }) + build(builder, f, primitive) + } else { + build(builder, f, null) + } + } + fun build(builder: StringBuilder, f: Family, primitive: PrimitiveType?) { + val returnType = returnTypes[f] ?: defaultReturnType + if (returnType.isEmpty()) + throw RuntimeException("No return type specified for $signature") - fun buildFor(f: Family, primitiveType: PrimitiveType?) : String { - if (blockedFor.contains(f)) return "" - if (primitiveType != null && blockedForPrimitive.contains(primitiveType)) return "" - - if (returnTypes[f] == null) throw RuntimeException("No return type specified for $signature") - val retType = returnTypes[f]!! - - val selftype = when (f) { + val receiver = when (f) { Iterables -> "Iterable" Collections -> "Collection" - Iterators -> "Iterator" - Arrays -> "Array" - PrimitiveArrays -> "${primitiveType!!.name}Array" + Lists -> "List" + Maps -> "Map" + Streams -> "Stream" + ArraysOfObjects -> "Array" + ArraysOfPrimitives -> primitive?.let { it.name() + "Array" } ?: throw IllegalArgumentException("Primitive array should specify primitive type") + else -> throw IllegalStateException("Invalid family") } - fun String.renderType() : String { + fun String.renderType(): String { val t = StringTokenizer(this, " \t\n,:()<>?.", true) val answer = StringBuilder() while (t.hasMoreTokens()) { val token = t.nextToken() answer.append(when (token) { - "SELF" -> selftype - "T" -> if (f == Family.PrimitiveArrays) primitiveType!!.name else token - else -> token - }) + "SELF" -> receiver + "PRIMITIVE" -> primitive?.name() ?: token + "SUM" -> { + when (primitive) { + PrimitiveType.Byte, PrimitiveType.Short -> "Int" + else -> primitive + } + } + "ZERO" -> when (primitive) { + PrimitiveType.Double -> "0.0" + PrimitiveType.Float -> "0.0f" + else -> "0" + } + "T" -> { + if (f == Maps) + "Map.Entry" + else + primitive?.name() ?: token + } + else -> token + }) } return answer.toString() } - val builder = StringBuilder() - if (doc != "") { + fun effectiveTypeParams(): List { + val types = ArrayList(typeParams) + if (primitive == null) { + val implicitTypeParameters = receiver.dropWhile { it != '<' }.drop(1).takeWhile { it != '>' }.split(",") + for (implicit in implicitTypeParameters.reverse()) { + if (!types.any { it.startsWith(implicit) }) { + types.add(0, implicit) + } + } + + return types + } else { + // primitive type arrays should drop constraints + return typeParams.filter { !it.startsWith("T") } + } + } + + val methodDoc = docs[f] ?: doc + if (methodDoc != "") { builder.append("/**\n") - StringReader(doc).forEachLine { + StringReader(methodDoc).forEachLine { val line = it.trim() if (!line.isEmpty()) { builder.append(" * ").append(line).append("\n") @@ -121,56 +217,53 @@ class GenericFunction(val signature : String): Comparable { } builder.append("public ") - if (isInline) builder.append("inline ") + if (inlineFamilies[f] ?: defaultInline) + builder.append("inline ") builder.append("fun ") - val types = effectiveTypeParams(f) - + val types = effectiveTypeParams() if (!types.isEmpty()) { builder.append(types.makeString(separator = ", ", prefix = "<", postfix = "> ").renderType()) } - builder.append((customReceivers[f] ?: + val receiverType = ( if (toNullableT) { - selftype.replace("T>", "T?>") - } - else { - selftype - }).renderType()) + receiver.replace("T>", "T?>") + } else { + if (receiver == "Array") + "Array" + else + receiver + }).renderType() - builder.append(".${signature.renderType()} : ${retType.renderType()} {") - val body = bodies[f]!!.trim("\n") - val prefix : Int = body.takeWhile { it == ' ' }.length + builder.append(receiverType) + builder.append(".${signature.renderType()} : ${returnType.renderType()} {") + + val body = (bodies[f] ?: defaultBody).trim("\n") + val prefix: Int = body.takeWhile { it == ' ' }.length StringReader(body).forEachLine { builder.append('\n') var count = prefix - builder.append(" ").append(it.dropWhile {count-- > 0 && it == ' '} .renderType()) + builder.append(" ").append(it.dropWhile { count-- > 0 && it == ' ' } .renderType()) } - return builder.toString().trimTrailingSpaces() + "\n}\n\n" + builder.append("\n}\n\n") } - public override fun compareTo(other : GenericFunction) : Int = this.signature.compareTo(other.signature) + public override fun compareTo(other: GenericFunction): Int = this.signature.compareTo(other.signature) } -fun String.trimTrailingSpaces() : String { +fun String.trimTrailingSpaces(): String { var answer = this; while (answer.endsWith(' ') || answer.endsWith('\n')) answer = answer.substring(0, answer.length() - 1) return answer } -fun f(signature : String, init : GenericFunction.() -> Unit): GenericFunction { +fun f(signature: String, init: GenericFunction.() -> Unit): GenericFunction { val gf = GenericFunction(signature) gf.init() return gf } - -fun main(args : Array) { - val templates = collections() - for (t in templates) { - print(t.buildFor(PrimitiveArrays, PrimitiveType.Byte)) - } -} diff --git a/libraries/tools/kotlin-stdlib-gen/src/templates/Filtering.kt b/libraries/tools/kotlin-stdlib-gen/src/templates/Filtering.kt new file mode 100644 index 00000000000..32f9f897703 --- /dev/null +++ b/libraries/tools/kotlin-stdlib-gen/src/templates/Filtering.kt @@ -0,0 +1,266 @@ +package templates + +import templates.Family.* + +fun filtering(): List { + val templates = arrayListOf() + + templates add f("drop(n: Int)") { + doc { "Returns a list containing all elements except first *n* elements" } + returns("List") + body { + """ + var count = 0 + val list = ArrayList() + for (item in this) { + if (count++ >= n) list.add(item) + } + return list + """ + } + + doc(Streams) { "Returns a stream containing all elements except first *n* elements" } + returns(Streams) { "Stream" } + body(Streams) { + """ + var count = 0; + return FilteringStream(this) { count++ >= n } + """ + } + + include(Collections) + body(Collections, ArraysOfObjects, ArraysOfPrimitives) { + """ + if (n >= size) + return ArrayList() + + var count = 0 + val list = ArrayList(size - n) + for (item in this) { + if (count++ >= n) list.add(item) + } + return list + """ + } + } + + templates add f("take(n: Int)") { + doc { "Returns a list containing first *n* elements" } + returns("List") + body { + """ + var count = 0 + val list = ArrayList(n) + for (item in this) + if (count++ >= n) + list.add(item) + return list + """ + } + + doc(Streams) { "Returns a stream containing first *n* elements" } + returns(Streams) { "Stream" } + body(Streams) { + """ + var count = 0 + return LimitedStream(this) { count++ == n } + """ + } + + include(Collections) + body(Collections, ArraysOfObjects, ArraysOfPrimitives) { + """ + var count = 0 + val realN = if (n > size) size else n + val list = ArrayList(realN) + for (item in this) { + if (count++ == realN) + break; + list.add(item) + } + return list + """ + } + } + + templates add f("dropWhile(predicate: (T)->Boolean)") { + inline(true) + + doc { "Returns a list containing all elements except first elements that satisfy the given *predicate*" } + returns("List") + body { + """ + var yielding = false + val list = ArrayList() + for (item in this) + if (yielding) + list.add(item) + else if(!predicate(item)) { + list.add(item) + yielding = true + } + return list + """ + } + + inline(false, Streams) + doc(Streams) { "Returns a stream containing all elements except first elements that satisfy the given *predicate*" } + returns(Streams) { "Stream" } + body(Streams) { + """ + var yielding = false + return FilteringStream(this) { + if (yielding) + true + else if (!predicate(it)) { + yielding = true + true + } else + false + } + """ + } + + } + + templates add f("takeWhile(predicate: (T)->Boolean)") { + inline(true) + + doc { "Returns a list containing first elements satisfying the given *predicate*" } + returns("List") + body { + """ + val list = ArrayList() + for (item in this) { + if(!predicate(item)) + break; + list.add(item) + } + return list + """ + } + + inline(false, Streams) + doc(Streams) { "Returns a stream containing first elements satisfying the given *predicate*" } + returns(Streams) { "Stream" } + body(Streams) { + """ + return LimitedStream(this, false, predicate) + """ + } + } + + templates add f("filter(predicate: (T)->Boolean)") { + inline(true) + + doc { "Returns a list containing all elements matching the given *predicate*" } + returns("List") + body { + """ + return filterTo(ArrayList(), predicate) + """ + } + + inline(false, Streams) + doc(Streams) { "Returns a stream containing all elements matching the given *predicate*" } + returns(Streams) { "Stream" } + body(Streams) { + """ + return FilteringStream(this, true, predicate) + """ + } + include(Maps) + } + + templates add f("filterTo(collection: C, predicate: (T) -> Boolean)") { + inline(true) + + doc { "Appends all elements matching the given *predicate* into the given *collection*" } + typeParam("C: MutableCollection") + returns("C") + + body { + """ + for (element in this) if (predicate(element)) collection.add(element) + return collection + """ + } + include(Maps) + } + + templates add f("filterNot(predicate: (T)->Boolean)") { + inline(true) + + doc { "Returns a list containing all elements not matching the given *predicate*" } + returns("List") + body { + """ + return filterNotTo(ArrayList(), predicate) + """ + } + + inline(false, Streams) + doc(Streams) { "Returns a stream containing all elements not matching the given *predicate*" } + returns(Streams) { "Stream" } + body(Streams) { + """ + return FilteringStream(this, false, predicate) + """ + } + include(Maps) + } + + templates add f("filterNotTo(collection: C, predicate: (T) -> Boolean)") { + inline(true) + + doc { "Appends all elements not matching the given *predicate* to the given *collection*" } + typeParam("C: MutableCollection") + returns("C") + + body { + """ + for (element in this) if (!predicate(element)) collection.add(element) + return collection + """ + } + include(Maps) + } + + templates add f("filterNotNull()") { + exclude(ArraysOfPrimitives) + doc { "Returns a list containing all elements that are not null" } + typeParam("T: Any") + returns("List") + toNullableT = true + body { + """ + return filterNotNullTo(ArrayList()) + """ + } + + doc(Streams) { "Returns a stream containing all elements that are not null" } + returns(Streams) { "Stream" } + body(Streams) { + """ + return FilteringStream(this, false, { it != null }) as Stream + """ + } + } + + templates add f("filterNotNullTo(collection: C)") { + exclude(ArraysOfPrimitives) + doc { "Appends all elements that are not null to the given *collection*" } + typeParam("C: MutableCollection") + typeParam("T: Any") + returns("C") + toNullableT = true + body { + """ + for (element in this) if (element != null) collection.add(element) + return collection + """ + } + } + + return templates +} \ No newline at end of file diff --git a/libraries/tools/kotlin-stdlib-gen/src/templates/Generators.kt b/libraries/tools/kotlin-stdlib-gen/src/templates/Generators.kt new file mode 100644 index 00000000000..d317e31034e --- /dev/null +++ b/libraries/tools/kotlin-stdlib-gen/src/templates/Generators.kt @@ -0,0 +1,177 @@ +package templates + +import templates.Family.* + +fun generators(): List { + val templates = arrayListOf() + + templates add f("plus(element: T)") { + doc { "Returns a list containing all elements of original collection and then the given element" } + returns("List") + body { + """ + val answer = toArrayList() + answer.add(element) + return answer + """ + } + + doc(Streams) { "Returns a stream containing all elements of original stream and then the given element" } + returns(Streams) { "Stream" } + // TODO: Implement lazy behavior + body(Streams) { + """ + val answer = toArrayList() + answer.add(element) + return answer.stream() + """ + } + } + + templates add f("plus(collection: Iterable)") { + exclude(Streams) + doc { "Returns a list containing all elements of original collection and then all elements of the given *collection*" } + returns("List") + + body { + """ + val answer = toArrayList() + answer.addAll(collection) + return answer + """ + } + } + + templates add f("plus(array: Array)") { + exclude(Streams) + doc { "Returns a list containing all elements of original collection and then all elements of the given *collection*" } + returns("List") + + body { + """ + val answer = toArrayList() + answer.addAll(array) + return answer + """ + } + } + + templates add f("plus(collection: Iterable)") { + only(Streams) + doc { "Returns a stream containing all elements of original stream and then all elements of the given *collection*" } + returns("Stream") + + // TODO: Implement lazy behavior + body { + """ + val answer = toArrayList() + answer.addAll(collection) + return answer.stream() + """ + } + } + + templates add f("plus(stream: Stream)") { + only(Streams) + doc { "Returns a stream containing all elements of original stream and then all elements of the given *stream*" } + returns("Stream") + body { + // TODO: Implement lazy behavior + """ + val answer = toArrayList() + answer.addAll(stream) + return answer.stream() + """ + } + } + + templates add f("partition(predicate: (T) -> Boolean)") { + inline(true) + + doc { + """ + Splits original collection into pair of collections, + where *first* collection contains elements for which predicate yielded *true*, + while *second* collection contains elements for which predicate yielded *false* + """ + } + // TODO: Stream variant + returns("Pair, List>") + body { + """ + val first = ArrayList() + val second = ArrayList() + for (element in this) { + if (predicate(element)) { + first.add(element) + } else { + second.add(element) + } + } + return Pair(first, second) + """ + } + } + + templates add f("zip(collection: Iterable)") { + exclude(Streams) + doc { + """ + Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection. + """ + } + typeParam("R") + returns("List>") + body { + """ + val first = iterator() + val second = collection.iterator() + val list = ArrayList>() + while (first.hasNext() && second.hasNext()) { + list.add(first.next() to second.next()) + } + return list + """ + } + } + + templates add f("zip(array: Array)") { + exclude(Streams) + doc { + """ + Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection. + """ + } + typeParam("R") + returns("List>") + body { + """ + val first = iterator() + val second = array.iterator() + val list = ArrayList>() + while (first.hasNext() && second.hasNext()) { + list.add(first.next() to second.next()) + } + return list + """ + } + } + + templates add f("zip(stream: Stream)") { + only(Streams) + doc { + """ + Returns a stream of pairs built from elements of both collections with same indexes. List has length of shortest collection. + """ + } + typeParam("R") + returns("Stream>") + body { + """ + return ZippingStream(this, stream) + """ + } + } + + return templates +} \ No newline at end of file diff --git a/libraries/tools/kotlin-stdlib-gen/src/templates/Guards.kt b/libraries/tools/kotlin-stdlib-gen/src/templates/Guards.kt new file mode 100644 index 00000000000..12e811578e9 --- /dev/null +++ b/libraries/tools/kotlin-stdlib-gen/src/templates/Guards.kt @@ -0,0 +1,41 @@ +package templates + +import java.util.ArrayList +import templates.Family.* + +fun guards(): List { + val THIS = "\$this" + + val templates = ArrayList() + + templates add f("requireNoNulls()") { + include(Lists) + exclude(ArraysOfPrimitives) + doc { "Returns an original collection containing all the non-*null* elements, throwing an [[IllegalArgumentException]] if there are any null elements" } + typeParam("T:Any") + toNullableT = true + returns("SELF") + body { + """ + for (element in this) { + if (element == null) { + throw IllegalArgumentException("null element found in $THIS") + } + } + return this as SELF + """ + } + body(Streams) { + """ + return FilteringStream(this) { + if (it == null) { + throw IllegalArgumentException("null element found in $THIS") + } + true + } as Stream + """ + } + } + + return templates +} \ No newline at end of file diff --git a/libraries/tools/kotlin-stdlib-gen/src/templates/Iterables.kt b/libraries/tools/kotlin-stdlib-gen/src/templates/Iterables.kt deleted file mode 100644 index 0d966ce060e..00000000000 --- a/libraries/tools/kotlin-stdlib-gen/src/templates/Iterables.kt +++ /dev/null @@ -1,308 +0,0 @@ -package templates - -import java.util.ArrayList -import templates.Family.* - -fun iterables(): ArrayList { - - val templates = commons() - - templates add f("filter(predicate: (T) -> Boolean)") { - doc = "Returns a list containing all elements which match the given *predicate*" - returns("List") - - body { - "return filterTo(ArrayList(), predicate)" - } - - Iterators.returns("Iterator(this, predicate)" - } - } - - templates add f("filterNot(predicate: (T) -> Boolean)") { - doc = "Returns a list containing all elements which do not match the given *predicate*" - returns("List") - - body { - "return filterNotTo(ArrayList(), predicate)" - } - } - - templates add f("filterNotNull()") { - isInline = false - absentFor(PrimitiveArrays) // Those are inherently non-nulls - doc = "Returns a list containing all the non-*null* elements" - typeParam("T:Any") - toNullableT = true - returns("List") - - body { - "return filterNotNullTo>(ArrayList())" - } - } - - templates add f("map(transform : (T) -> R)") { - doc = "Returns a new List containing the results of applying the given *transform* function to each element in this collection" - typeParam("R") - returns("List") - - body { - "return mapTo(ArrayList(), transform)" - } - } - - templates add f("flatMap(transform: (T)-> Iterable)") { - doc = "Returns the result of transforming each element to one or more values which are concatenated together into a single list" - typeParam("R") - returns("List") - - body { - "return flatMapTo(ArrayList(), transform)" - } - } - - templates add f("take(n: Int)") { - isInline = false - doc = "Returns a list containing the first *n* elements" - returns("List") - body { - "return takeWhile(countTo(n))" - } - } - - templates add f("takeWhile(predicate: (T) -> Boolean)") { - doc = "Returns a list containing the first elements that satisfy the given *predicate*" - returns("List") - - body { - "return takeWhileTo(ArrayList(), predicate)" - } - } - - templates add f("requireNoNulls()") { - isInline = false - absentFor(PrimitiveArrays) // Those are inherently non-nulls - doc = "Returns a original Iterable containing all the non-*null* elements, throwing an [[IllegalArgumentException]] if there are any null elements" - typeParam("T:Any") - toNullableT = true - returns("SELF") - - body { - val THIS = "\$this" - """ - for (element in this) { - if (element == null) { - throw IllegalArgumentException("null element found in $THIS") - } - } - return this as SELF - """ - } - - } - - templates add f("plus(element: T)") { - isInline = false - doc = "Creates an [[Iterator]] which iterates over this iterator then the given element at the end" - returns("List") - - body { - """ - val answer = ArrayList() - toCollection(answer) - answer.add(element) - return answer - """ - } - - } - - templates add f("plus(iterator: Iterator)") { - isInline = false - doc = "Creates an [[Iterator]] which iterates over this iterator then the following iterator" - returns("List") - - body { - """ - val answer = ArrayList() - toCollection(answer) - for (element in iterator) { - answer.add(element) - } - return answer - """ - } - } - - templates add f("plus(collection: Iterable)") { - isInline = false - doc = "Creates an [[Iterator]] which iterates over this iterator then the following collection" - returns("List") - - body { - "return plus(collection.iterator())" - } - } - - templates add f("min()") { - doc = "Returns the smallest element or null if there are no elements" - returns("T?") - absentFor(PrimitiveType.Boolean) - typeParam("T: Comparable") - isInline = false - Iterables.body { - """ - val iterator = iterator() - if (!iterator.hasNext()) return null - - var min = iterator.next() - while (iterator.hasNext()) { - val e = iterator.next() - if (min > e) min = e - } - return min - """ - } - listOf(Arrays, PrimitiveArrays).forEach { - it.body { - """ - if (isEmpty()) return null - - var min = this[0] - for (i in 1..lastIndex) { - val e = this[i] - if (min > e) min = e - } - return min - """ - } - } - } - - templates add f("max()") { - doc = "Returns the largest element or null if there are no elements" - returns("T?") - absentFor(PrimitiveType.Boolean) - typeParam("T: Comparable") - isInline = false - Iterables.body { - """ - val iterator = iterator() - if (!iterator.hasNext()) return null - - var max = iterator.next() - while (iterator.hasNext()) { - val e = iterator.next() - if (max < e) max = e - } - return max - """ - } - listOf(Arrays, PrimitiveArrays).forEach { - it.body { - """ - if (isEmpty()) return null - - var max = this[0] - for (i in 1..lastIndex) { - val e = this[i] - if (max < e) max = e - } - return max - """ - } - } - } - - templates add f("minBy(f: (T) -> R)") { - doc = "Returns the first element yielding the smallest value of the given function or null if there are no elements" - typeParam("R: Comparable") - typeParam("T: Any") - returns("T?") - Iterables.body { - """ - val iterator = iterator() - if (!iterator.hasNext()) return null - - var minElem = iterator.next() - var minValue = f(minElem) - while (iterator.hasNext()) { - val e = iterator.next() - val v = f(e) - if (minValue > v) { - minElem = e - minValue = v - } - } - return minElem - """ - } - listOf(Arrays, PrimitiveArrays).forEach { - it.body { - """ - if (size == 0) return null - - var minElem = this[0] - var minValue = f(minElem) - for (i in 1..lastIndex) { - val e = this[i] - val v = f(e) - if (minValue > v) { - minElem = e - minValue = v - } - } - return minElem - """ - } - } - } - - templates add f("maxBy(f: (T) -> R)") { - doc = "Returns the first element yielding the largest value of the given function or null if there are no elements" - typeParam("R: Comparable") - typeParam("T: Any") - returns("T?") - Iterables.body { - """ - val iterator = iterator() - if (!iterator.hasNext()) return null - - var maxElem = iterator.next() - var maxValue = f(maxElem) - while (iterator.hasNext()) { - val e = iterator.next() - val v = f(e) - if (maxValue < v) { - maxElem = e - maxValue = v - } - } - return maxElem - """ - } - listOf(Arrays, PrimitiveArrays).forEach { - it.body { - """ - if (isEmpty()) return null - - var maxElem = this[0] - var maxValue = f(maxElem) - for (i in 1..lastIndex) { - val e = this[i] - val v = f(e) - if (maxValue < v) { - maxElem = e - maxValue = v - } - } - return maxElem - """ - } - } - } - - return templates -} diff --git a/libraries/tools/kotlin-stdlib-gen/src/templates/Iterators.kt b/libraries/tools/kotlin-stdlib-gen/src/templates/Iterators.kt deleted file mode 100644 index 0f0895d1797..00000000000 --- a/libraries/tools/kotlin-stdlib-gen/src/templates/Iterators.kt +++ /dev/null @@ -1,222 +0,0 @@ -package templates - -import java.util.ArrayList - -fun iterators(): List { - - val templates = commons() - - templates add f("filter(predicate: (T) -> Boolean)") { - isInline = false - doc = "Returns an iterator over elements which match the given *predicate*" - - returns("Iterator") - body { - "return FilterIterator(this, predicate)" - } - } - - templates add f("filterNot(predicate: (T) -> Boolean)") { - doc = "Returns an iterator over elements which don't match the given *predicate*" - returns("Iterator") - - body { - "return filter {!predicate(it)}" - } - } - - templates add f("filterNotNull()") { - isInline = false - doc = "Returns an iterator over non-*null* elements" - typeParam("T:Any") - toNullableT = true - returns("Iterator") - - body { - "return FilterNotNullIterator(this)" - } - } - - templates add f("map(transform : (T) -> R)") { - isInline = false - doc = "Returns an iterator obtained by applying *transform*, a function transforming an object of type *T* into an object of type *R*" - typeParam("R") - returns("Iterator") - - body { - "return MapIterator(this, transform)" - } - } - - templates add f("flatMap(transform: (T) -> Iterator)") { - isInline = false - doc = "Returns an iterator over the concatenated results of transforming each element to one or more values" - typeParam("R") - returns("Iterator") - - body { - "return FlatMapIterator(this, transform)" - } - } - - templates add f("requireNoNulls()") { - isInline = false - doc = "Returns a original Iterable containing all the non-*null* elements, throwing an [[IllegalArgumentException]] if there are any null elements" - typeParam("T:Any") - toNullableT = true - returns("Iterator") - - body { - val THIS = "\$this" - """ - return map{ - if (it == null) throw IllegalArgumentException("null element in iterator $THIS") else it - } - """ - } - } - - - templates add f("take(n: Int)") { - isInline = false - doc = "Returns an iterator restricted to the first *n* elements" - returns("Iterator") - body { - """ - var count = n - return takeWhile{ --count >= 0 } - """ - } - } - - templates add f("takeWhile(predicate: (T) -> Boolean)") { - isInline = false - doc = "Returns an iterator restricted to the first elements that match the given *predicate*" - returns("Iterator") - - body { - "return TakeWhileIterator(this, predicate)" - } - } - - // TODO: drop(n), dropWhile - - templates add f("plus(element: T)") { - isInline = false - doc = "Creates an [[Iterator]] which iterates over this iterator then the given element at the end" - returns("Iterator") - - body { - "return CompositeIterator(this, SingleIterator(element))" - } - - } - - templates add f("plus(iterator: Iterator)") { - isInline = false - doc = "Creates an [[Iterator]] which iterates over this iterator then the following iterator" - returns("Iterator") - - body { - "return CompositeIterator(this, iterator)" - } - } - - templates add f("plus(collection: Iterable)") { - isInline = false - doc = "Creates an [[Iterator]] which iterates over this iterator then the following collection" - returns("Iterator") - - body { - "return plus(collection.iterator())" - } - } - - templates add f("min()") { - doc = "Returns the smallest element or null if there are no elements" - returns("T?") - typeParam("T: Comparable") - isInline = false - body { - """ - if (!hasNext()) return null - - var min = next() - while (hasNext()) { - val e = next() - if (min > e) min = e - } - return min - """ - } - } - - templates add f("max()") { - doc = "Returns the largest element or null if there are no elements" - returns("T?") - typeParam("T: Comparable") - isInline = false - body { - """ - if (!hasNext()) return null - - var max = next() - while (hasNext()) { - val e = next() - if (max < e) max = e - } - return max - """ - } - } - - templates add f("minBy(f: (T) -> R)") { - doc = "Returns the first element yielding the smallest value of the given function or null if there are no elements" - typeParam("R: Comparable") - typeParam("T: Any") - returns("T?") - body { - """ - if (!hasNext()) return null - - var minElem = next() - var minValue = f(minElem) - while (hasNext()) { - val e = next() - val v = f(e) - if (minValue > v) { - minElem = e - minValue = v - } - } - return minElem - """ - } - } - - templates add f("maxBy(f: (T) -> R)") { - doc = "Returns the first element yielding the largest value of the given function or null if there are no elements" - typeParam("R: Comparable") - typeParam("T: Any") - returns("T?") - body { - """ - if (!hasNext()) return null - - var maxElem = next() - var maxValue = f(maxElem) - while (hasNext()) { - val e = next() - val v = f(e) - if (maxValue < v) { - maxElem = e - maxValue = v - } - } - return maxElem - """ - } - } - - return templates.sort() -} \ No newline at end of file diff --git a/libraries/tools/kotlin-stdlib-gen/src/templates/Mapping.kt b/libraries/tools/kotlin-stdlib-gen/src/templates/Mapping.kt new file mode 100644 index 00000000000..206e667edd0 --- /dev/null +++ b/libraries/tools/kotlin-stdlib-gen/src/templates/Mapping.kt @@ -0,0 +1,208 @@ +package templates + +import templates.Family.* + +fun mapping(): List { + val templates = arrayListOf() + + templates add f("withIndices()") { + doc { "Returns a list containing pairs of each element of the original collection and their index" } + returns("List>") + body { + """ + var index = 0 + return mapTo(ArrayList>(), { index++ to it }) + """ + } + + returns(Streams) { "Stream>" } + doc(Streams) { "Returns a stream containing pairs of each element of the original collection and their index" } + body(Streams) { + """ + var index = 0 + return TransformingStream(this, { index++ to it }) + """ + } + } + + templates add f("map(transform : (T) -> R)") { + inline(true) + + doc { "Returns a list containing the results of applying the given *transform* function to each element of the original collection" } + typeParam("R") + returns("List") + body { + "return mapTo(ArrayList(), transform)" + } + + inline(false, Streams) + returns(Streams) { "Stream" } + doc(Streams) { "Returns a stream containing the results of applying the given *transform* function to each element of the original stream" } + body(Streams) { + "return TransformingStream(this, transform) " + } + include(Maps) + } + + templates add f("mapNotNull(transform : (T) -> R)") { + exclude(ArraysOfPrimitives) + doc { "Returns a list containing the results of applying the given *transform* function to each non-null element of the original collection" } + typeParam("T: Any") + typeParam("R") + returns("List") + toNullableT = true + body { + """ + return mapNotNullTo(ArrayList(), transform) + """ + } + + doc(Streams) { "Returns a stream containing the results of applying the given *transform* function to each non-null element of the original stream" } + returns(Streams) { "Stream" } + body(Streams) { + """ + return TransformingStream(FilteringStream(this, false, { it != null }) as Stream, transform) + """ + } + } + + templates add f("mapTo(collection: C, transform : (T) -> R)") { + inline(true) + + doc { + """ + Appends transformed elements of original collection using the given *transform* function + to the given *collection* + """ + } + typeParam("R") + typeParam("C: MutableCollection") + returns("C") + + body { + """ + for (item in this) + collection.add(transform(item)) + return collection + """ + } + include(Maps) + } + + templates add f("mapNotNullTo(collection: C, transform : (T) -> R)") { + inline(true) + exclude(ArraysOfPrimitives) + doc { + """ + Appends transformed non-null elements of original collection using the given *transform* function + to the given *collection* + """ + } + typeParam("T: Any") + typeParam("R") + typeParam("C: MutableCollection") + returns("C") + toNullableT = true + body { + """ + for (element in this) { + if (element != null) { + collection.add(transform(element)) + } + } + return collection + """ + } + } + + templates add f("flatMap(transform: (T)-> Iterable)") { + inline(true) + + exclude(Streams) + doc { "Returns a single list of all elements yielded from results of *transform* function being invoked on each element of original collection" } + typeParam("R") + returns("List") + body { + "return flatMapTo(ArrayList(), transform)" + } + include(Maps) + } + + templates add f("flatMap(transform: (T)-> Stream)") { + only(Streams) + doc { "Returns a single stream of all elements streamed from results of *transform* function being invoked on each element of original stream" } + typeParam("R") + returns("Stream") + body { + "return FlatteningStream(this, transform)" + } + } + + templates add f("flatMapTo(collection: C, transform: (T) -> Iterable)") { + inline(true) + exclude(Streams) + doc { "Appends all elements yielded from results of *transform* function being invoked on each element of original collection, to the given *collection*" } + typeParam("R") + typeParam("C: MutableCollection") + returns("C") + body { + """ + for (element in this) { + val list = transform(element) + collection.addAll(list) + } + return collection + """ + } + include(Maps) + } + + templates add f("flatMapTo(collection: C, transform: (T) -> Stream)") { + inline(true) + + only(Streams) + doc { "Appends all elements yielded from results of *transform* function being invoked on each element of original stream, to the given *collection*" } + typeParam("R") + typeParam("C: MutableCollection") + returns("C") + body { + """ + for (element in this) { + val list = transform(element) + collection.addAll(list) + } + return collection + """ + } + } + + templates add f("groupBy(toKey: (T) -> K)") { + inline(true) + + doc { "Returns a map of the elements in original collection grouped by the result of given *toKey* function" } + typeParam("K") + returns("Map>") + body { "return groupByTo(HashMap>(), toKey)" } + include(Maps) + } + + templates add f("groupByTo(map: MutableMap>, toKey: (T) -> K)") { + inline(true) + + typeParam("K") + doc { "Appends elements from original collection grouped by the result of given *toKey* function to the given *map*" } + returns("Map>") + body { + """ + for (element in this) { + val key = toKey(element) + val list = map.getOrPut(key) { ArrayList() } + list.add(element) + } + return map + """ + } + include(Maps) + } + return templates +} \ No newline at end of file diff --git a/libraries/tools/kotlin-stdlib-gen/src/templates/Numeric.kt b/libraries/tools/kotlin-stdlib-gen/src/templates/Numeric.kt new file mode 100644 index 00000000000..affce76a241 --- /dev/null +++ b/libraries/tools/kotlin-stdlib-gen/src/templates/Numeric.kt @@ -0,0 +1,24 @@ +package templates + +import templates.Family.* + +fun numeric(): List { + val templates = arrayListOf() + + templates add f("sum()") { + doc { "Returns the sum of all elements in the collection" } + returns("SUM") + body { + """ + val iterator = iterator() + var sum : SUM = ZERO + while (iterator.hasNext()) { + sum += iterator.next() + } + return sum + """ + } + } + + return templates +} diff --git a/libraries/tools/kotlin-stdlib-gen/src/templates/Ordering.kt b/libraries/tools/kotlin-stdlib-gen/src/templates/Ordering.kt new file mode 100644 index 00000000000..4889bf7f05e --- /dev/null +++ b/libraries/tools/kotlin-stdlib-gen/src/templates/Ordering.kt @@ -0,0 +1,131 @@ +package templates + +import templates.Family.* + +fun ordering(): List { + val templates = arrayListOf() + + templates add f("reverse()") { + doc { "Returns a list with elements in reversed order" } + returns { "List" } + body { + """ + val list = toArrayList() + Collections.reverse(list) + return list + """ + } + + exclude(Streams) + } + + templates add f("sort()") { + doc { + """ + Returns a sorted list of all elements + """ + } + returns("List") + typeParam("T: Comparable") + body { + """ + val sortedList = toArrayList() + java.util.Collections.sort(sortedList) + return sortedList + """ + } + + exclude(Streams) + exclude(ArraysOfPrimitives) // TODO: resolve collision between inplace sort and this function + exclude(ArraysOfObjects) + } + + templates add f("sortDescending()") { + doc { + """ + Returns a sorted list of all elements + """ + } + returns("List") + typeParam("T: Comparable") + body { + """ + val sortedList = toArrayList() + val sortBy: Comparator = comparator {(x: T, y: T) -> -x.compareTo(y)} + java.util.Collections.sort(sortedList, sortBy) + return sortedList + """ + } + + exclude(Streams) + exclude(ArraysOfPrimitives) // TODO: resolve collision between inplace sort and this function + exclude(ArraysOfObjects) + } + + templates add f("sortBy(order: (T) -> R)") { + inline(true) + + doc { + """ + Returns a list of all elements, sorted by results of specified *order* function. + """ + } + returns("List") + typeParam("R: Comparable") + body { + """ + val sortedList = toArrayList() + val sortBy: Comparator = comparator {(x: T, y: T) -> order(x).compareTo(order(y))} + java.util.Collections.sort(sortedList, sortBy) + return sortedList + """ + } + + exclude(Streams) + exclude(ArraysOfPrimitives) + } + + templates add f("sortDescendingBy(order: (T) -> R)") { + inline(true) + + doc { + """ + Returns a list of all elements, sorted by results of specified *order* function. + """ + } + returns("List") + typeParam("R: Comparable") + body { + """ + val sortedList = toArrayList() + val sortBy: Comparator = comparator {(x: T, y: T) -> -order(x).compareTo(order(y))} + java.util.Collections.sort(sortedList, sortBy) + return sortedList + """ + } + + exclude(Streams) + exclude(ArraysOfPrimitives) + } + + templates add f("sortBy(comparator : Comparator)") { + doc { + """ + Returns a list of all elements, sorted by the specified *comparator* + """ + } + returns("List") + body { + """ + val sortedList = toArrayList() + java.util.Collections.sort(sortedList, comparator) + return sortedList + """ + } + + exclude(Streams) + exclude(ArraysOfPrimitives) + } + + return templates +} \ No newline at end of file diff --git a/libraries/tools/kotlin-stdlib-gen/src/templates/Primitives.kt b/libraries/tools/kotlin-stdlib-gen/src/templates/Primitives.kt deleted file mode 100644 index 81ceab28862..00000000000 --- a/libraries/tools/kotlin-stdlib-gen/src/templates/Primitives.kt +++ /dev/null @@ -1,47 +0,0 @@ -package templates - -import templates.Family.* - -enum class PrimitiveType(val name: String) { - Boolean: PrimitiveType("Boolean") - Byte: PrimitiveType("Byte") - Char: PrimitiveType("Char") - Short: PrimitiveType("Short") - Int: PrimitiveType("Int") - Long: PrimitiveType("Long") - Float: PrimitiveType("Float") - Double: PrimitiveType("Double") -} - -private fun PrimitiveType.zero() = when (this) { - PrimitiveType.Int -> "0" - PrimitiveType.Byte -> "0" - PrimitiveType.Short -> "0" - PrimitiveType.Long -> "0.toLong()" - PrimitiveType.Double -> "0.0" - PrimitiveType.Float -> "0.toFloat()" - else -> null -} - -private fun returnTypeForSum(primitive: PrimitiveType) = when (primitive) { - PrimitiveType.Byte -> PrimitiveType.Int - PrimitiveType.Short -> PrimitiveType.Int - else -> primitive -} - -fun sumFunction(primitive: PrimitiveType) = primitive.zero()?.let { zero -> - f("sum()") { - doc = "Sums up the elements" - isInline = false - if (returnTypeForSum(primitive) != primitive) { - //this is required to avoid clash of erasured method signatures (Iterables.sum(): Int) - absentFor(Iterables) - } - Iterables.customReceiver("Iterable<${primitive.name}>") - Arrays.customReceiver("Array<${primitive.name}>") - returns(returnTypeForSum(primitive).name) - body { - "return fold($zero, {a,b -> a+b})" - } - } -} \ No newline at end of file diff --git a/libraries/tools/kotlin-stdlib-gen/src/templates/Snapshots.kt b/libraries/tools/kotlin-stdlib-gen/src/templates/Snapshots.kt new file mode 100644 index 00000000000..d000bb45d32 --- /dev/null +++ b/libraries/tools/kotlin-stdlib-gen/src/templates/Snapshots.kt @@ -0,0 +1,104 @@ +package templates + +import templates.Family.* + +fun snapshots(): List { + val templates = arrayListOf() + + templates add f("toCollection(collection : C)") { + doc { "Appends all elements to the given *collection*" } + returns("C") + typeParam("C : MutableCollection") + body { + """ + for (item in this) { + collection.add(item) + } + return collection + """ + } + } + + templates add f("toSet()") { + doc { "Returns a Set of all elements" } + returns("Set") + body { "return toCollection(LinkedHashSet())" } + } + + templates add f("toHashSet()") { + doc { "Returns a HashSet of all elements" } + returns("HashSet") + body { "return toCollection(HashSet())" } + } + + templates add f("toSortedSet()") { + doc { "Returns a SortedSet of all elements" } + returns("SortedSet") + body { "return toCollection(TreeSet())" } + } + + templates add f("toArrayList()") { + doc { "Returns an ArrayList of all elements" } + returns("ArrayList") + body { "return toCollection(ArrayList())" } + + // ISSUE: JavaScript can't perform this operation +/* + body(Collections) { + """ + return ArrayList(this) + """ + } +*/ + body(ArraysOfObjects, ArraysOfPrimitives) { + """ + val list = ArrayList(size) + for (item in this) list.add(item) + return list + """ + } + } + + templates add f("toList()") { + doc { "Returns a List containing all elements" } + returns("List") + body { "return toCollection(ArrayList())" } + + // ISSUE: JavaScript can't perform this operations +/* + body(Collections) { + """ + return ArrayList(this) + """ + } + body(ArraysOfObjects) { + """ + return ArrayList(Arrays.asList(*this)) + """ + } +*/ + body(ArraysOfPrimitives) { + """ + val list = ArrayList(size) + for (item in this) list.add(item) + return list + """ + } + } + + templates add f("toLinkedList()") { + doc { "Returns a LinkedList containing all elements" } + returns("LinkedList") + body { "return toCollection(LinkedList())" } + } + + templates add f("toSortedList()") { + doc { "Returns a sorted list of all elements" } + typeParam("T: Comparable") + returns("List") + body { "return toArrayList().sort()" } + body(Iterables) { "return sort()" } + } + + return templates +} \ No newline at end of file diff --git a/libraries/tools/kotlin-stdlib-gen/src/templates/SpecialJVM.kt b/libraries/tools/kotlin-stdlib-gen/src/templates/SpecialJVM.kt new file mode 100644 index 00000000000..abef658b432 --- /dev/null +++ b/libraries/tools/kotlin-stdlib-gen/src/templates/SpecialJVM.kt @@ -0,0 +1,94 @@ +package templates + +import templates.Family.* + +fun specialJVM(): List { + val templates = arrayListOf() + + templates add f("copyOfRange(from: Int, to: Int)") { + only(ArraysOfObjects, ArraysOfPrimitives) + doc { "Returns new array which is a copy of range of original array" } + returns("SELF") + body { + "return Arrays.copyOfRange(this, from, to)" + } + } + + // TODO: when newLength is larger than size, we can get null items + templates add f("copyOf(newSize: Int = size)") { + only(ArraysOfObjects, ArraysOfPrimitives) + doc { "Returns new array which is a copy of the riginal array" } + returns("SELF") + body { + "return Arrays.copyOf(this, newSize)" + } + body(ArraysOfObjects) { + "return Arrays.copyOf(this, newSize) as Array" + } + } + + templates add f("fill(element: T)") { + only(ArraysOfObjects, ArraysOfPrimitives) + doc { "Fills original array with the provided value" } + returns("Unit") + body { + "Arrays.fill(this, element)" + } + } + + templates add f("binarySearch(element: T, fromIndex: Int = 0, toIndex: Int = size - 1)") { + only(ArraysOfObjects, ArraysOfPrimitives) + exclude(PrimitiveType.Boolean) + doc { "Searches array or range of array for provided element index using binary search algorithm. Array is expected to be sorted." } + returns("Int") + body { + "return Arrays.binarySearch(this, fromIndex, toIndex, element)" + } + } + + templates add f("sort(fromIndex : Int = 0, toIndex : Int = size - 1)") { + only(ArraysOfObjects, ArraysOfPrimitives) + exclude(PrimitiveType.Boolean) + doc { "Sorts array or range in array inplace" } + returns("Unit") + body { + "Arrays.sort(this, fromIndex, toIndex)" + } + } + + templates add f("filterIsInstanceTo(collection: C, klass: Class)") { + doc { "Appends all elements that are instances of specified class into the given *collection*" } + typeParam("C: MutableCollection") + typeParam("R: T") + returns("C") + exclude(ArraysOfPrimitives) + body { + """ + for (element in this) if (klass.isInstance(element)) collection.add(element as R) + return collection + """ + } + } + + templates add f("filterIsInstance(klass: Class)") { + doc { "Returns a list containing all elements that are instances of specified class" } + typeParam("R: T") + returns("List") + body { + """ + return filterIsInstanceTo(ArrayList(), klass) + """ + } + exclude(ArraysOfPrimitives) + + doc(Streams) { "Returns a stream containing all elements that are instances of specified class" } + returns(Streams) { "Stream" } + body(Streams) { + """ + return FilteringStream(this, true, { klass.isInstance(it) }) + """ + } + } + + return templates +} \ No newline at end of file diff --git a/libraries/tools/kotlin-stdlib-gen/src/templates/Strings.kt b/libraries/tools/kotlin-stdlib-gen/src/templates/Strings.kt new file mode 100644 index 00000000000..dbc699aa8a5 --- /dev/null +++ b/libraries/tools/kotlin-stdlib-gen/src/templates/Strings.kt @@ -0,0 +1,56 @@ +package templates + +import templates.Family.* + +fun strings(): List { + val templates = arrayListOf() + + templates add f("appendString(buffer: Appendable, separator: String = \", \", prefix: String =\"\", postfix: String = \"\", limit: Int = -1, truncated: String = \"...\")") { + doc { + """ + Appends the string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied + + If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will + a special *truncated* separator (which defaults to "..." + """ + } + returns { "Unit" } + body { + """ + buffer.append(prefix) + var count = 0 + for (element in this) { + if (++count > 1) buffer.append(separator) + if (limit < 0 || count <= limit) { + val text = if (element == null) "null" else element.toString() + buffer.append(text) + } else break + } + if (limit >= 0 && count > limit) buffer.append(truncated) + buffer.append(postfix) + """ + } + } + + templates add f("makeString(separator: String = \", \", prefix: String = \"\", postfix: String = \"\", limit: Int = -1, truncated: String = \"...\")") { + doc { + """ + Creates a string from all the elements separated using the *separator* and using the given *prefix* and *postfix* if supplied. + + If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will + a special *truncated* separator (which defaults to "..." + """ + } + + returns("String") + body { + """ + val buffer = StringBuilder() + appendString(buffer, separator, prefix, postfix, limit, truncated) + return buffer.toString() + """ + } + } + + return templates +} \ No newline at end of file