Refactor: extract JVM API into separate files

Increase visibility to internal for:
- copyToArrayOfAny
- UNINITIALIZED_VALUE
- InitializedLazyImpl

Change file classes to multifile:
- LazyKt
- GroupingKt
- IntrinsicsKt (coroutines)
This commit is contained in:
Ilya Gorbunov
2018-03-16 22:11:56 +03:00
parent 5dc4e31918
commit 5d13b1681f
26 changed files with 893 additions and 759 deletions
@@ -92,14 +92,6 @@ public fun <T> listOf(vararg elements: T): List<T> = if (elements.size > 0) elem
@kotlin.internal.InlineOnly
public inline fun <T> listOf(): List<T> = emptyList()
/**
* Returns an immutable list containing only the specified object [element].
* The returned list is serializable.
* @sample samples.collections.Collections.Lists.singletonReadOnlyList
*/
@JvmVersion
public fun <T> listOf(element: T): List<T> = java.util.Collections.singletonList(element)
/**
* Returns an empty new [MutableList].
* @sample samples.collections.Collections.Lists.emptyMutableList
@@ -200,15 +192,6 @@ public inline fun <T> Collection<T>?.orEmpty(): Collection<T> = this ?: emptyLis
@kotlin.internal.InlineOnly
public inline fun <T> List<T>?.orEmpty(): List<T> = this ?: emptyList()
/**
* Returns a list containing the elements returned by this enumeration
* in the order they are returned by the enumeration.
* @sample samples.collections.Collections.Lists.listFromEnumeration
*/
@JvmVersion
@kotlin.internal.InlineOnly
public inline fun <T> java.util.Enumeration<T>.toList(): List<T> = java.util.Collections.list(this)
/**
* Checks if all elements in the specified collection are contained in this collection.
*
@@ -225,25 +208,6 @@ internal fun <T> List<T>.optimizeReadOnlyList() = when (size) {
else -> this
}
@JvmVersion
@kotlin.internal.InlineOnly
internal inline fun copyToArrayImpl(collection: Collection<*>): Array<Any?> =
kotlin.jvm.internal.collectionToArray(collection)
@JvmVersion
@kotlin.internal.InlineOnly
internal inline fun <T> copyToArrayImpl(collection: Collection<*>, array: Array<T>): Array<T> =
kotlin.jvm.internal.collectionToArray(collection, array as Array<Any?>) as Array<T>
// copies typed varargs array to array of objects
@JvmVersion
private fun <T> Array<out T>.copyToArrayOfAny(isVarargs: Boolean): Array<Any?> =
if (isVarargs && this.javaClass == Array<Any?>::class.java)
// if the array came from varargs and already is array of Any, copying isn't required
@Suppress("UNCHECKED_CAST") (this as Array<Any?>)
else
java.util.Arrays.copyOf(this, this.size, Array<Any?>::class.java)
/**
* Searches this list or its range for the provided [element] using the binary search algorithm.
* The list is expected to be sorted into ascending order according to the Comparable natural ordering of its elements,
@@ -0,0 +1,49 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
@file:kotlin.jvm.JvmMultifileClass
@file:kotlin.jvm.JvmName("CollectionsKt")
package kotlin.collections
import kotlin.*
/**
* Returns an immutable list containing only the specified object [element].
* The returned list is serializable.
* @sample samples.collections.Collections.Lists.singletonReadOnlyList
*/
@JvmVersion
public fun <T> listOf(element: T): List<T> = java.util.Collections.singletonList(element)
/**
* Returns a list containing the elements returned by this enumeration
* in the order they are returned by the enumeration.
* @sample samples.collections.Collections.Lists.listFromEnumeration
*/
@JvmVersion
@kotlin.internal.InlineOnly
public inline fun <T> java.util.Enumeration<T>.toList(): List<T> = java.util.Collections.list(this)
@JvmVersion
@kotlin.internal.InlineOnly
internal inline fun copyToArrayImpl(collection: Collection<*>): Array<Any?> =
kotlin.jvm.internal.collectionToArray(collection)
@JvmVersion
@kotlin.internal.InlineOnly
internal inline fun <T> copyToArrayImpl(collection: Collection<*>, array: Array<T>): Array<T> =
kotlin.jvm.internal.collectionToArray(collection, array as Array<Any?>) as Array<T>
// copies typed varargs array to array of objects
@JvmVersion
internal fun <T> Array<out T>.copyToArrayOfAny(isVarargs: Boolean): Array<Any?> =
if (isVarargs && this.javaClass == Array<Any?>::class.java)
// if the array came from varargs and already is array of Any, copying isn't required
@Suppress("UNCHECKED_CAST") (this as Array<Any?>)
else
java.util.Arrays.copyOf(this, this.size, Array<Any?>::class.java)
@@ -1,3 +1,6 @@
@file:kotlin.jvm.JvmName("GroupingKt")
@file:kotlin.jvm.JvmMultifileClass
package kotlin.collections
/**
@@ -226,22 +229,6 @@ public inline fun <S, T : S, K, M : MutableMap<in K, S>> Grouping<T, K>.reduceTo
}
/**
* Groups elements from the [Grouping] source by key and counts elements in each group.
*
* @return a [Map] associating the key of each group with the count of elements in the group.
*
* @sample samples.collections.Collections.Transformations.groupingByEachCount
*/
@SinceKotlin("1.1")
@JvmVersion
public fun <T, K> Grouping<T, K>.eachCount(): Map<K, Int> =
// fold(0) { acc, e -> acc + 1 } optimized for boxing
foldTo( destination = mutableMapOf(),
initialValueSelector = { _, _ -> kotlin.jvm.internal.Ref.IntRef() },
operation = { _, acc, _ -> acc.apply { element += 1 } })
.mapValuesInPlace { it.value.element }
/**
* Groups elements from the [Grouping] source by key and counts elements in each group to the given [destination] map.
*
@@ -256,21 +243,7 @@ public fun <T, K> Grouping<T, K>.eachCount(): Map<K, Int> =
public fun <T, K, M : MutableMap<in K, Int>> Grouping<T, K>.eachCountTo(destination: M): M =
foldTo(destination, 0) { acc, _ -> acc + 1 }
/**
/**
* Groups elements from the [Grouping] source by key and sums values provided by the [valueSelector] function for elements in each group.
*
* @return a [Map] associating the key of each group with the sum of elements in the group.
*/
@SinceKotlin("1.1")
@JvmVersion
public inline fun <T, K> Grouping<T, K>.eachSumOf(valueSelector: (T) -> Int): Map<K, Int> =
// fold(0) { acc, e -> acc + valueSelector(e)} optimized for boxing
foldTo( destination = mutableMapOf(),
initialValueSelector = { _, _ -> kotlin.jvm.internal.Ref.IntRef() },
operation = { _, acc, e -> acc.apply { element += valueSelector(e) } })
.mapValuesInPlace { it.value.element }
/*
/**
* Groups elements from the [Grouping] source by key and sums values provided by the [valueSelector] function for elements in each group
* to the given [destination] map.
@@ -286,16 +259,6 @@ public inline fun <T, K, M : MutableMap<in K, Int>> Grouping<T, K>.eachSumOfTo(d
foldTo(destination, 0) { acc, e -> acc + valueSelector(e)}
*/
@JvmVersion
@PublishedApi
@kotlin.internal.InlineOnly
@Suppress("UNCHECKED_CAST") // tricks with erased generics go here, do not repeat at reified platforms
internal inline fun <K, V, R> MutableMap<K, V>.mapValuesInPlace(f: (Map.Entry<K, V>) -> R): MutableMap<K, R> {
entries.forEach {
(it as MutableMap.MutableEntry<K, R>).setValue(f(it))
}
return (this as MutableMap<K, R>)
}
/*
// TODO: sum by long and by double overloads
@@ -0,0 +1,55 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
@file:kotlin.jvm.JvmName("GroupingKt")
@file:kotlin.jvm.JvmMultifileClass
package kotlin.collections
/**
* Groups elements from the [Grouping] source by key and counts elements in each group.
*
* @return a [Map] associating the key of each group with the count of elements in the group.
*
* @sample samples.collections.Collections.Transformations.groupingByEachCount
*/
@SinceKotlin("1.1")
@JvmVersion
public fun <T, K> Grouping<T, K>.eachCount(): Map<K, Int> =
// fold(0) { acc, e -> acc + 1 } optimized for boxing
foldTo(destination = mutableMapOf(),
initialValueSelector = { _, _ -> kotlin.jvm.internal.Ref.IntRef() },
operation = { _, acc, _ -> acc.apply { element += 1 } })
.mapValuesInPlace { it.value.element }
/*
/**
* Groups elements from the [Grouping] source by key and sums values provided by the [valueSelector] function for elements in each group.
*
* @return a [Map] associating the key of each group with the sum of elements in the group.
*/
@SinceKotlin("1.X")
@JvmVersion
public inline fun <T, K> Grouping<T, K>.eachSumOf(valueSelector: (T) -> Int): Map<K, Int> =
// fold(0) { acc, e -> acc + valueSelector(e)} optimized for boxing
foldTo( destination = mutableMapOf(),
initialValueSelector = { _, _ -> kotlin.jvm.internal.Ref.IntRef() },
operation = { _, acc, e -> acc.apply { element += valueSelector(e) } })
.mapValuesInPlace { it.value.element }
*/
@JvmVersion
@PublishedApi
@kotlin.internal.InlineOnly
@Suppress("UNCHECKED_CAST") // tricks with erased generics go here, do not repeat on reified platforms
internal inline fun <K, V, R> MutableMap<K, V>.mapValuesInPlace(f: (Map.Entry<K, V>) -> R): MutableMap<K, R> {
entries.forEach {
(it as MutableMap.MutableEntry<K, R>).setValue(f(it))
}
return (this as MutableMap<K, R>)
}
@@ -3,16 +3,6 @@
package kotlin.collections
/**
* Creates an [Iterator] for an [java.util.Enumeration], allowing to use it in `for` loops.
* @sample samples.collections.Iterators.iteratorForEnumeration
*/
@kotlin.jvm.JvmVersion
public operator fun <T> java.util.Enumeration<T>.iterator(): Iterator<T> = object : Iterator<T> {
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 `for` loop.
@@ -0,0 +1,20 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
@file:kotlin.jvm.JvmMultifileClass
@file:kotlin.jvm.JvmName("CollectionsKt")
package kotlin.collections
/**
* Creates an [Iterator] for an [java.util.Enumeration], allowing to use it in `for` loops.
* @sample samples.collections.Iterators.iteratorForEnumeration
*/
@kotlin.jvm.JvmVersion
public operator fun <T> java.util.Enumeration<T>.iterator(): Iterator<T> = object : Iterator<T> {
override fun hasNext(): Boolean = hasMoreElements()
public override fun next(): T = nextElement()
}
@@ -54,17 +54,6 @@ public fun <K, V> mapOf(vararg pairs: Pair<K, V>): Map<K, V> = if (pairs.size >
@kotlin.internal.InlineOnly
public inline fun <K, V> mapOf(): Map<K, V> = emptyMap()
/**
* Returns an immutable map, mapping only the specified key to the
* specified value.
*
* The returned map is serializable.
*
* @sample samples.collections.Maps.Instantiation.mapFromPairs
*/
@JvmVersion
public fun <K, V> mapOf(pair: Pair<K, V>): Map<K, V> = java.util.Collections.singletonMap(pair.first, pair.second)
/**
* Returns an empty new [MutableMap].
*
@@ -705,13 +694,3 @@ internal fun <K, V> Map<K, V>.optimizeReadOnlyMap() = when (size) {
1 -> toSingletonMapOrSelf()
else -> this
}
// creates a singleton copy of map, if there is specialization available in target platform, otherwise returns itself
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
internal inline fun <K, V> Map<K, V>.toSingletonMapOrSelf(): Map<K, V> = toSingletonMap()
// creates a singleton copy of map
@kotlin.jvm.JvmVersion
internal fun <K, V> Map<out K, V>.toSingletonMap(): Map<K, V>
= with (entries.iterator().next()) { java.util.Collections.singletonMap(key, value) }
@@ -12,6 +12,17 @@ import java.util.TreeMap
import java.util.concurrent.ConcurrentMap
/**
* Returns an immutable map, mapping only the specified key to the
* specified value.
*
* The returned map is serializable.
*
* @sample samples.collections.Maps.Instantiation.mapFromPairs
*/
@JvmVersion
public fun <K, V> mapOf(pair: Pair<K, V>): Map<K, V> = java.util.Collections.singletonMap(pair.first, pair.second)
/**
* Concurrent getOrPut, that is safe for concurrent maps.
@@ -65,3 +76,14 @@ public fun <K : Comparable<K>, V> sortedMapOf(vararg pairs: Pair<K, V>): SortedM
public inline fun Map<String, String>.toProperties(): Properties
= Properties().apply { putAll(this@toProperties) }
// creates a singleton copy of map, if there is specialization available in target platform, otherwise returns itself
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
internal inline fun <K, V> Map<K, V>.toSingletonMapOrSelf(): Map<K, V> = toSingletonMap()
// creates a singleton copy of map
@kotlin.jvm.JvmVersion
internal fun <K, V> Map<out K, V>.toSingletonMap(): Map<K, V>
= with (entries.iterator().next()) { java.util.Collections.singletonMap(key, value) }
@@ -45,18 +45,6 @@ public inline fun <@kotlin.internal.OnlyInputTypes T> MutableCollection<out T>.r
@kotlin.internal.InlineOnly
public inline fun <T> MutableList<T>.remove(index: Int): T = removeAt(index)
@Deprecated("Use sortWith(comparator) instead.", ReplaceWith("this.sortWith(comparator)"), level = DeprecationLevel.ERROR)
@JvmVersion
@kotlin.internal.InlineOnly
@Suppress("UNUSED_PARAMETER")
public inline fun <T> MutableList<T>.sort(comparator: Comparator<in T>): Unit = throw NotImplementedError()
@Deprecated("Use sortWith(Comparator(comparison)) instead.", ReplaceWith("this.sortWith(Comparator(comparison))"), level = DeprecationLevel.ERROR)
@JvmVersion
@kotlin.internal.InlineOnly
@Suppress("UNUSED_PARAMETER")
public inline fun <T> MutableList<T>.sort(comparison: (T, T) -> Int): Unit = throw NotImplementedError()
/**
* Adds the specified [element] to this mutable collection.
*/
@@ -267,67 +255,3 @@ private fun MutableCollection<*>.retainNothing(): Boolean {
clear()
return result
}
/**
* Sorts elements in the list in-place according to their natural sort order.
*/
@kotlin.jvm.JvmVersion
public fun <T : Comparable<T>> MutableList<T>.sort(): Unit {
if (size > 1) java.util.Collections.sort(this)
}
/**
* Sorts elements in the list in-place according to the order specified with [comparator].
*/
@kotlin.jvm.JvmVersion
public fun <T> MutableList<T>.sortWith(comparator: Comparator<in T>): Unit {
if (size > 1) java.util.Collections.sort(this, comparator)
}
/**
* Fills the list with the provided [value].
*
* Each element in the list gets replaced with the [value].
*/
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
@SinceKotlin("1.2")
public inline fun <T> MutableList<T>.fill(value: T) {
java.util.Collections.fill(this, value)
}
/**
* Randomly shuffles elements in this mutable list.
*/
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
@SinceKotlin("1.2")
public inline fun <T> MutableList<T>.shuffle() {
java.util.Collections.shuffle(this)
}
/**
* Randomly shuffles elements in this mutable list using the specified [random] instance as the source of randomness.
*/
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
@SinceKotlin("1.2")
public inline fun <T> MutableList<T>.shuffle(random: java.util.Random) {
java.util.Collections.shuffle(this, random)
}
/**
* Returns a new list with the elements of this list randomly shuffled.
*/
@kotlin.jvm.JvmVersion
@SinceKotlin("1.2")
public fun <T> Iterable<T>.shuffled(): List<T> = toMutableList().apply { shuffle() }
/**
* Returns a new list with the elements of this list randomly shuffled
* using the specified [random] instance as the source of randomness.
*/
@kotlin.jvm.JvmVersion
@SinceKotlin("1.2")
public fun <T> Iterable<T>.shuffled(random: java.util.Random): List<T> = toMutableList().apply { shuffle(random) }
@@ -0,0 +1,87 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
@file:kotlin.jvm.JvmMultifileClass
@file:kotlin.jvm.JvmName("CollectionsKt")
package kotlin.collections
@Deprecated("Use sortWith(comparator) instead.", ReplaceWith("this.sortWith(comparator)"), level = DeprecationLevel.ERROR)
@JvmVersion
@kotlin.internal.InlineOnly
@Suppress("UNUSED_PARAMETER")
public inline fun <T> MutableList<T>.sort(comparator: Comparator<in T>): Unit = throw NotImplementedError()
@Deprecated("Use sortWith(Comparator(comparison)) instead.", ReplaceWith("this.sortWith(Comparator(comparison))"), level = DeprecationLevel.ERROR)
@JvmVersion
@kotlin.internal.InlineOnly
@Suppress("UNUSED_PARAMETER")
public inline fun <T> MutableList<T>.sort(comparison: (T, T) -> Int): Unit = throw NotImplementedError()
/**
* Sorts elements in the list in-place according to their natural sort order.
*/
@kotlin.jvm.JvmVersion
public fun <T : Comparable<T>> MutableList<T>.sort(): Unit {
if (size > 1) java.util.Collections.sort(this)
}
/**
* Sorts elements in the list in-place according to the order specified with [comparator].
*/
@kotlin.jvm.JvmVersion
public fun <T> MutableList<T>.sortWith(comparator: Comparator<in T>): Unit {
if (size > 1) java.util.Collections.sort(this, comparator)
}
/**
* Fills the list with the provided [value].
*
* Each element in the list gets replaced with the [value].
*/
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
@SinceKotlin("1.2")
public inline fun <T> MutableList<T>.fill(value: T) {
java.util.Collections.fill(this, value)
}
/**
* Randomly shuffles elements in this mutable list.
*/
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
@SinceKotlin("1.2")
public inline fun <T> MutableList<T>.shuffle() {
java.util.Collections.shuffle(this)
}
/**
* Randomly shuffles elements in this mutable list using the specified [random] instance as the source of randomness.
*/
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
@SinceKotlin("1.2")
public inline fun <T> MutableList<T>.shuffle(random: java.util.Random) {
java.util.Collections.shuffle(this, random)
}
/**
* Returns a new list with the elements of this list randomly shuffled.
*/
@kotlin.jvm.JvmVersion
@SinceKotlin("1.2")
public fun <T> Iterable<T>.shuffled(): List<T> = toMutableList().apply { shuffle() }
/**
* Returns a new list with the elements of this list randomly shuffled
* using the specified [random] instance as the source of randomness.
*/
@kotlin.jvm.JvmVersion
@SinceKotlin("1.2")
public fun <T> Iterable<T>.shuffled(random: java.util.Random): List<T> = toMutableList().apply { shuffle(random) }
@@ -22,14 +22,6 @@ public inline fun <T> Sequence(crossinline iterator: () -> Iterator<T>): Sequenc
*/
public fun <T> Iterator<T>.asSequence(): Sequence<T> = Sequence { this }.constrainOnce()
/**
* Creates a sequence that returns all values from this enumeration. The sequence is constrained to be iterated only once.
* @sample samples.collections.Sequences.Building.sequenceFromEnumeration
*/
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun<T> java.util.Enumeration<T>.asSequence(): Sequence<T> = this.iterator().asSequence()
/**
* Creates a sequence that returns the specified values.
*
@@ -553,16 +545,6 @@ public fun <T> Sequence<T>.constrainOnce(): Sequence<T> {
return if (this is ConstrainedOnceSequence<T>) this else ConstrainedOnceSequence(this)
}
@kotlin.jvm.JvmVersion
private class ConstrainedOnceSequence<T>(sequence: Sequence<T>) : Sequence<T> {
private val sequenceRef = java.util.concurrent.atomic.AtomicReference(sequence)
override fun iterator(): Iterator<T> {
val sequence = sequenceRef.getAndSet(null) ?: throw IllegalStateException("This sequence can be consumed only once.")
return sequence.iterator()
}
}
/**
@@ -0,0 +1,30 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
@file:kotlin.jvm.JvmMultifileClass
@file:kotlin.jvm.JvmName("SequencesKt")
package kotlin.sequences
import kotlin.*
/**
* Creates a sequence that returns all values from this enumeration. The sequence is constrained to be iterated only once.
* @sample samples.collections.Sequences.Building.sequenceFromEnumeration
*/
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun<T> java.util.Enumeration<T>.asSequence(): Sequence<T> = this.iterator().asSequence()
@kotlin.jvm.JvmVersion
internal class ConstrainedOnceSequence<T>(sequence: Sequence<T>) : Sequence<T> {
private val sequenceRef = java.util.concurrent.atomic.AtomicReference(sequence)
override fun iterator(): Iterator<T> {
val sequence = sequenceRef.getAndSet(null) ?: throw IllegalStateException("This sequence can be consumed only once.")
return sequence.iterator()
}
}
@@ -79,27 +79,6 @@ public fun <T> linkedSetOf(vararg elements: T): LinkedHashSet<T> = elements.toCo
@kotlin.internal.InlineOnly
public inline fun <T> Set<T>?.orEmpty(): Set<T> = this ?: emptySet()
/**
* Returns an immutable set containing only the specified object [element].
* The returned set is serializable.
*/
@JvmVersion
public fun <T> setOf(element: T): Set<T> = java.util.Collections.singleton(element)
/**
* Returns a new [java.util.SortedSet] with the given elements.
*/
@JvmVersion
public fun <T> sortedSetOf(vararg elements: T): java.util.TreeSet<T> = elements.toCollection(java.util.TreeSet<T>())
/**
* Returns a new [java.util.SortedSet] with the given [comparator] and elements.
*/
@JvmVersion
public fun <T> sortedSetOf(comparator: Comparator<in T>, vararg elements: T): java.util.TreeSet<T> = elements.toCollection(java.util.TreeSet<T>(comparator))
internal fun <T> Set<T>.optimizeReadOnlySet() = when (size) {
0 -> emptySet()
1 -> setOf(iterator().next())
@@ -0,0 +1,31 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
@file:kotlin.jvm.JvmMultifileClass
@file:kotlin.jvm.JvmName("SetsKt")
package kotlin.collections
/**
* Returns an immutable set containing only the specified object [element].
* The returned set is serializable.
*/
@JvmVersion
public fun <T> setOf(element: T): Set<T> = java.util.Collections.singleton(element)
/**
* Returns a new [java.util.SortedSet] with the given elements.
*/
@JvmVersion
public fun <T> sortedSetOf(vararg elements: T): java.util.TreeSet<T> = elements.toCollection(java.util.TreeSet<T>())
/**
* Returns a new [java.util.SortedSet] with the given [comparator] and elements.
*/
@JvmVersion
public fun <T> sortedSetOf(comparator: Comparator<in T>, vararg elements: T): java.util.TreeSet<T> = elements.toCollection(java.util.TreeSet<T>(comparator))
@@ -15,6 +15,7 @@
*/
@file:kotlin.jvm.JvmName("IntrinsicsKt")
@file:kotlin.jvm.JvmMultifileClass
package kotlin.coroutines.experimental.intrinsics
@@ -89,75 +90,3 @@ public suspend inline val coroutineContext: CoroutineContext
@SinceKotlin("1.1")
public val COROUTINE_SUSPENDED: Any = Any()
// JVM declarations
/**
* Creates a coroutine without receiver and with result type [T].
* This function creates a new, fresh instance of suspendable computation every time it is invoked.
*
* To start executing the created coroutine, invoke `resume(Unit)` on the returned [Continuation] instance.
* The [completion] continuation is invoked when coroutine completes with result or exception.
*
* This function is _unchecked_. Repeated invocation of any resume function on the resulting continuation corrupts the
* state machine of the coroutine and may result in arbitrary behaviour or exception.
*/
@SinceKotlin("1.1")
@kotlin.jvm.JvmVersion
public fun <T> (suspend () -> T).createCoroutineUnchecked(
completion: Continuation<T>
): Continuation<Unit> =
if (this !is kotlin.coroutines.experimental.jvm.internal.CoroutineImpl)
buildContinuationByInvokeCall(completion) {
@Suppress("UNCHECKED_CAST")
(this as Function1<Continuation<T>, Any?>).invoke(completion)
}
else
(this.create(completion) as kotlin.coroutines.experimental.jvm.internal.CoroutineImpl).facade
/**
* Creates a coroutine with receiver type [R] and result type [T].
* This function creates a new, fresh instance of suspendable computation every time it is invoked.
*
* To start executing the created coroutine, invoke `resume(Unit)` on the returned [Continuation] instance.
* The [completion] continuation is invoked when coroutine completes with result or exception.
*
* This function is _unchecked_. Repeated invocation of any resume function on the resulting continuation corrupts the
* state machine of the coroutine and may result in arbitrary behaviour or exception.
*/
@SinceKotlin("1.1")
@kotlin.jvm.JvmVersion
public fun <R, T> (suspend R.() -> T).createCoroutineUnchecked(
receiver: R,
completion: Continuation<T>
): Continuation<Unit> =
if (this !is kotlin.coroutines.experimental.jvm.internal.CoroutineImpl)
buildContinuationByInvokeCall(completion) {
@Suppress("UNCHECKED_CAST")
(this as Function2<R, Continuation<T>, Any?>).invoke(receiver, completion)
}
else
(this.create(receiver, completion) as kotlin.coroutines.experimental.jvm.internal.CoroutineImpl).facade
// INTERNAL DEFINITIONS
@kotlin.jvm.JvmVersion
private inline fun <T> buildContinuationByInvokeCall(
completion: Continuation<T>,
crossinline block: () -> Any?
): Continuation<Unit> {
val continuation =
object : Continuation<Unit> {
override val context: CoroutineContext
get() = completion.context
override fun resume(value: Unit) {
processBareContinuationResume(completion, block)
}
override fun resumeWithException(exception: Throwable) {
completion.resumeWithException(exception)
}
}
return kotlin.coroutines.experimental.jvm.internal.interceptContinuationIfNeeded(completion.context, continuation)
}
@@ -14,6 +14,8 @@
* limitations under the License.
*/
@file:kotlin.jvm.JvmName("IntrinsicsKt")
@file:kotlin.jvm.JvmMultifileClass
@file:kotlin.jvm.JvmVersion
package kotlin.coroutines.experimental.intrinsics
import kotlin.coroutines.experimental.*
@@ -46,3 +48,77 @@ public inline fun <R, T> (suspend R.() -> T).startCoroutineUninterceptedOrReturn
receiver: R,
completion: Continuation<T>
): Any? = (this as Function2<R, Continuation<T>, Any?>).invoke(receiver, completion)
// JVM declarations
/**
* Creates a coroutine without receiver and with result type [T].
* This function creates a new, fresh instance of suspendable computation every time it is invoked.
*
* To start executing the created coroutine, invoke `resume(Unit)` on the returned [Continuation] instance.
* The [completion] continuation is invoked when coroutine completes with result or exception.
*
* This function is _unchecked_. Repeated invocation of any resume function on the resulting continuation corrupts the
* state machine of the coroutine and may result in arbitrary behaviour or exception.
*/
@SinceKotlin("1.1")
@kotlin.jvm.JvmVersion
public fun <T> (suspend () -> T).createCoroutineUnchecked(
completion: Continuation<T>
): Continuation<Unit> =
if (this !is kotlin.coroutines.experimental.jvm.internal.CoroutineImpl)
buildContinuationByInvokeCall(completion) {
@Suppress("UNCHECKED_CAST")
(this as Function1<Continuation<T>, Any?>).invoke(completion)
}
else
(this.create(completion) as kotlin.coroutines.experimental.jvm.internal.CoroutineImpl).facade
/**
* Creates a coroutine with receiver type [R] and result type [T].
* This function creates a new, fresh instance of suspendable computation every time it is invoked.
*
* To start executing the created coroutine, invoke `resume(Unit)` on the returned [Continuation] instance.
* The [completion] continuation is invoked when coroutine completes with result or exception.
*
* This function is _unchecked_. Repeated invocation of any resume function on the resulting continuation corrupts the
* state machine of the coroutine and may result in arbitrary behaviour or exception.
*/
@SinceKotlin("1.1")
@kotlin.jvm.JvmVersion
public fun <R, T> (suspend R.() -> T).createCoroutineUnchecked(
receiver: R,
completion: Continuation<T>
): Continuation<Unit> =
if (this !is kotlin.coroutines.experimental.jvm.internal.CoroutineImpl)
buildContinuationByInvokeCall(completion) {
@Suppress("UNCHECKED_CAST")
(this as Function2<R, Continuation<T>, Any?>).invoke(receiver, completion)
}
else
(this.create(receiver, completion) as kotlin.coroutines.experimental.jvm.internal.CoroutineImpl).facade
// INTERNAL DEFINITIONS
@kotlin.jvm.JvmVersion
private inline fun <T> buildContinuationByInvokeCall(
completion: Continuation<T>,
crossinline block: () -> Any?
): Continuation<Unit> {
val continuation =
object : Continuation<Unit> {
override val context: CoroutineContext
get() = completion.context
override fun resume(value: Unit) {
processBareContinuationResume(completion, block)
}
override fun resumeWithException(exception: Throwable) {
completion.resumeWithException(exception)
}
}
return kotlin.coroutines.experimental.jvm.internal.interceptContinuationIfNeeded(completion.context, continuation)
}
@@ -70,36 +70,6 @@ private class ClosedDoubleRange (
override fun toString(): String = "$_start..$_endInclusive"
}
/**
* A closed range of values of type `Float`.
*
* Numbers are compared with the ends of this range according to IEEE-754.
*/
@JvmVersion
private class ClosedFloatRange (
start: Float,
endInclusive: Float
): ClosedFloatingPointRange<Float> {
private val _start = start
private val _endInclusive = endInclusive
override val start: Float get() = _start
override val endInclusive: Float get() = _endInclusive
override fun lessThanOrEquals(a: Float, b: Float): Boolean = a <= b
override fun contains(value: Float): Boolean = value >= _start && value <= _endInclusive
override fun isEmpty(): Boolean = !(_start <= _endInclusive)
override fun equals(other: Any?): Boolean {
return other is ClosedFloatRange && (isEmpty() && other.isEmpty() ||
_start == other._start && _endInclusive == other._endInclusive)
}
override fun hashCode(): Int {
return if (isEmpty()) -1 else 31 * _start.hashCode() + _endInclusive.hashCode()
}
override fun toString(): String = "$_start..$_endInclusive"
}
/**
* Creates a range from this [Comparable] value to the specified [that] value.
@@ -118,16 +88,6 @@ public operator fun <T: Comparable<T>> T.rangeTo(that: T): ClosedRange<T> = Comp
@SinceKotlin("1.1")
public operator fun Double.rangeTo(that: Double): ClosedFloatingPointRange<Double> = ClosedDoubleRange(this, that)
/**
* Creates a range from this [Float] value to the specified [that] value.
*
* Numbers are compared with the ends of this range according to IEEE-754.
* @sample samples.ranges.Ranges.rangeFromFloat
*/
@JvmVersion
@SinceKotlin("1.1")
public operator fun Float.rangeTo(that: Float): ClosedFloatingPointRange<Float> = ClosedFloatRange(this, that)
internal fun checkStepIsPositive(isPositive: Boolean, step: Number) {
if (!isPositive) throw IllegalArgumentException("Step must be positive, was: $step.")
@@ -0,0 +1,52 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
@file:kotlin.jvm.JvmMultifileClass
@file:kotlin.jvm.JvmName("RangesKt")
package kotlin.ranges
import kotlin.*
/**
* A closed range of values of type `Float`.
*
* Numbers are compared with the ends of this range according to IEEE-754.
*/
@JvmVersion
private class ClosedFloatRange (
start: Float,
endInclusive: Float
): ClosedFloatingPointRange<Float> {
private val _start = start
private val _endInclusive = endInclusive
override val start: Float get() = _start
override val endInclusive: Float get() = _endInclusive
override fun lessThanOrEquals(a: Float, b: Float): Boolean = a <= b
override fun contains(value: Float): Boolean = value >= _start && value <= _endInclusive
override fun isEmpty(): Boolean = !(_start <= _endInclusive)
override fun equals(other: Any?): Boolean {
return other is ClosedFloatRange && (isEmpty() && other.isEmpty() ||
_start == other._start && _endInclusive == other._endInclusive)
}
override fun hashCode(): Int {
return if (isEmpty()) -1 else 31 * _start.hashCode() + _endInclusive.hashCode()
}
override fun toString(): String = "$_start..$_endInclusive"
}
/**
* Creates a range from this [Float] value to the specified [that] value.
*
* Numbers are compared with the ends of this range according to IEEE-754.
* @sample samples.ranges.Ranges.rangeFromFloat
*/
@JvmVersion
@SinceKotlin("1.1")
public operator fun Float.rangeTo(that: Float): ClosedFloatingPointRange<Float> = ClosedFloatRange(this, that)
@@ -47,12 +47,6 @@ public fun StringBuilder.append(vararg value: Any?): StringBuilder {
return this
}
/**
* Sets the character at the specified [index] to the specified [value].
*/
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline operator fun StringBuilder.set(index: Int, value: Char): Unit = this.setCharAt(index, value)
internal fun <T> Appendable.appendElement(element: T, transform: ((T) -> CharSequence)?) {
@@ -4,6 +4,14 @@
package kotlin.text
/**
* Sets the character at the specified [index] to the specified [value].
*/
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline operator fun StringBuilder.set(index: Int, value: Char): Unit = this.setCharAt(index, value)
private object SystemProperties {
/** Line separator for current system. */
@JvmField
@@ -20,141 +20,7 @@
package kotlin.text
/**
* Returns a string representation of this [Byte] value in the specified [radix].
*
* @throws IllegalArgumentException when [radix] is not a valid radix for number to string conversion.
*/
@SinceKotlin("1.1")
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun Byte.toString(radix: Int): String = this.toInt().toString(checkRadix(radix))
/**
* Returns a string representation of this [Short] value in the specified [radix].
*
* @throws IllegalArgumentException when [radix] is not a valid radix for number to string conversion.
*/
@SinceKotlin("1.1")
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun Short.toString(radix: Int): String = this.toInt().toString(checkRadix(radix))
/**
* Returns a string representation of this [Int] value in the specified [radix].
*
* @throws IllegalArgumentException when [radix] is not a valid radix for number to string conversion.
*/
@SinceKotlin("1.1")
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun Int.toString(radix: Int): String = java.lang.Integer.toString(this, checkRadix(radix))
/**
* Returns a string representation of this [Long] value in the specified [radix].
*
* @throws IllegalArgumentException when [radix] is not a valid radix for number to string conversion.
*/
@SinceKotlin("1.1")
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun Long.toString(radix: Int): String = java.lang.Long.toString(this, checkRadix(radix))
/**
* Returns `true` if the contents of this string is equal to the word "true", ignoring case, and `false` otherwise.
*/
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun String.toBoolean(): Boolean = java.lang.Boolean.parseBoolean(this)
/**
* Parses the string as a signed [Byte] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
*/
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun String.toByte(): Byte = java.lang.Byte.parseByte(this)
/**
* Parses the string as a signed [Byte] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
* @throws IllegalArgumentException when [radix] is not a valid radix for string to number conversion.
*/
@SinceKotlin("1.1")
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun String.toByte(radix: Int): Byte = java.lang.Byte.parseByte(this, checkRadix(radix))
/**
* Parses the string as a [Short] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
*/
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun String.toShort(): Short = java.lang.Short.parseShort(this)
/**
* Parses the string as a [Short] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
* @throws IllegalArgumentException when [radix] is not a valid radix for string to number conversion.
*/
@SinceKotlin("1.1")
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun String.toShort(radix: Int): Short = java.lang.Short.parseShort(this, checkRadix(radix))
/**
* Parses the string as an [Int] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
*/
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun String.toInt(): Int = java.lang.Integer.parseInt(this)
/**
* Parses the string as an [Int] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
* @throws IllegalArgumentException when [radix] is not a valid radix for string to number conversion.
*/
@SinceKotlin("1.1")
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun String.toInt(radix: Int): Int = java.lang.Integer.parseInt(this, checkRadix(radix))
/**
* Parses the string as a [Long] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
*/
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun String.toLong(): Long = java.lang.Long.parseLong(this)
/**
* Parses the string as a [Long] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
* @throws IllegalArgumentException when [radix] is not a valid radix for string to number conversion.
*/
@SinceKotlin("1.1")
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun String.toLong(radix: Int): Long = java.lang.Long.parseLong(this, checkRadix(radix))
/**
* Parses the string as a [Float] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
*/
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun String.toFloat(): Float = java.lang.Float.parseFloat(this)
/**
* Parses the string as a [Double] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
*/
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun String.toDouble(): Double = java.lang.Double.parseDouble(this)
import kotlin.*
@@ -323,153 +189,3 @@ public fun String.toLongOrNull(radix: Int): Long? {
return if (isNegative) result else -result
}
/**
* Parses the string as a [Float] number and returns the result
* or `null` if the string is not a valid representation of a number.
*/
@SinceKotlin("1.1")
@kotlin.jvm.JvmVersion
public fun String.toFloatOrNull(): Float? = screenFloatValue(this, java.lang.Float::parseFloat)
/**
* Parses the string as a [Double] number and returns the result
* or `null` if the string is not a valid representation of a number.
*/
@SinceKotlin("1.1")
@kotlin.jvm.JvmVersion
public fun String.toDoubleOrNull(): Double? = screenFloatValue(this, java.lang.Double::parseDouble)
/**
* Parses the string as a [java.math.BigInteger] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
*/
@SinceKotlin("1.2")
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun String.toBigInteger(): java.math.BigInteger =
java.math.BigInteger(this)
/**
* Parses the string as a [java.math.BigInteger] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
* @throws IllegalArgumentException when [radix] is not a valid radix for string to number conversion.
*/
@SinceKotlin("1.2")
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun String.toBigInteger(radix: Int): java.math.BigInteger =
java.math.BigInteger(this, checkRadix(radix))
/**
* Parses the string as a [java.math.BigInteger] number and returns the result
* or `null` if the string is not a valid representation of a number.
*/
@SinceKotlin("1.2")
@kotlin.jvm.JvmVersion
public fun String.toBigIntegerOrNull(): java.math.BigInteger? = toBigIntegerOrNull(10)
/**
* Parses the string as a [java.math.BigInteger] number and returns the result
* or `null` if the string is not a valid representation of a number.
*
* @throws IllegalArgumentException when [radix] is not a valid radix for string to number conversion.
*/
@SinceKotlin("1.2")
@kotlin.jvm.JvmVersion
public fun String.toBigIntegerOrNull(radix: Int): java.math.BigInteger? {
checkRadix(radix)
val length = this.length
when (length) {
0 -> return null
1 -> if (digitOf(this[0], radix) < 0) return null
else -> {
val start = if (this[0] == '-') 1 else 0
for (index in start until length) {
if (digitOf(this[index], radix) < 0)
return null
}
}
}
return toBigInteger(radix)
}
/**
* Parses the string as a [java.math.BigDecimal] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
*/
@SinceKotlin("1.2")
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun String.toBigDecimal(): java.math.BigDecimal =
java.math.BigDecimal(this)
/**
* Parses the string as a [java.math.BigDecimal] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
*
* @param mathContext specifies the precision and the rounding mode.
* @throws ArithmeticException if the rounding is needed, but the rounding mode is [java.math.RoundingMode.UNNECESSARY].
*/
@SinceKotlin("1.2")
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun String.toBigDecimal(mathContext: java.math.MathContext): java.math.BigDecimal =
java.math.BigDecimal(this, mathContext)
/**
* Parses the string as a [java.math.BigDecimal] number and returns the result
* or `null` if the string is not a valid representation of a number.
*/
@SinceKotlin("1.2")
@kotlin.jvm.JvmVersion
public fun String.toBigDecimalOrNull(): java.math.BigDecimal? =
screenFloatValue(this) { it.toBigDecimal() }
/**
* Parses the string as a [java.math.BigDecimal] number and returns the result
* or `null` if the string is not a valid representation of a number.
*
* @param mathContext specifies the precision and the rounding mode.
* @throws ArithmeticException if the rounding is needed, but the rounding mode is [java.math.RoundingMode.UNNECESSARY].
*/
@SinceKotlin("1.2")
@kotlin.jvm.JvmVersion
public fun String.toBigDecimalOrNull(mathContext: java.math.MathContext): java.math.BigDecimal? =
screenFloatValue(this) { it.toBigDecimal(mathContext) }
/**
* Recommended floating point number validation RegEx from the javadoc of `java.lang.Double.valueOf(String)`
*/
@kotlin.jvm.JvmVersion
private object ScreenFloatValueRegEx {
@JvmField val value = run {
val Digits = "(\\p{Digit}+)"
val HexDigits = "(\\p{XDigit}+)"
val Exp = "[eE][+-]?$Digits"
val HexString = "(0[xX]$HexDigits(\\.)?)|" + // 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt
"(0[xX]$HexDigits?(\\.)$HexDigits)" // 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt
val Number = "($Digits(\\.)?($Digits?)($Exp)?)|" + // Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt
"(\\.($Digits)($Exp)?)|" + // . Digits ExponentPart_opt FloatTypeSuffix_opt
"(($HexString)[pP][+-]?$Digits)" // HexSignificand BinaryExponent
val fpRegex = "[\\x00-\\x20]*[+-]?(NaN|Infinity|(($Number)[fFdD]?))[\\x00-\\x20]*"
Regex(fpRegex)
}
}
@kotlin.jvm.JvmVersion
private inline fun <T> screenFloatValue(str: String, parse: (String) -> T): T? {
return try {
if (ScreenFloatValueRegEx.value.matches(str))
parse(str)
else
null
} catch(e: NumberFormatException) { // overflow
null
}
}
@@ -0,0 +1,300 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
@file:kotlin.jvm.JvmMultifileClass
@file:kotlin.jvm.JvmName("StringsKt")
@file:Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
package kotlin.text
import kotlin.*
/**
* Returns a string representation of this [Byte] value in the specified [radix].
*
* @throws IllegalArgumentException when [radix] is not a valid radix for number to string conversion.
*/
@SinceKotlin("1.1")
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun Byte.toString(radix: Int): String = this.toInt().toString(checkRadix(radix))
/**
* Returns a string representation of this [Short] value in the specified [radix].
*
* @throws IllegalArgumentException when [radix] is not a valid radix for number to string conversion.
*/
@SinceKotlin("1.1")
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun Short.toString(radix: Int): String = this.toInt().toString(checkRadix(radix))
/**
* Returns a string representation of this [Int] value in the specified [radix].
*
* @throws IllegalArgumentException when [radix] is not a valid radix for number to string conversion.
*/
@SinceKotlin("1.1")
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun Int.toString(radix: Int): String = java.lang.Integer.toString(this, checkRadix(radix))
/**
* Returns a string representation of this [Long] value in the specified [radix].
*
* @throws IllegalArgumentException when [radix] is not a valid radix for number to string conversion.
*/
@SinceKotlin("1.1")
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun Long.toString(radix: Int): String = java.lang.Long.toString(this, checkRadix(radix))
/**
* Returns `true` if the contents of this string is equal to the word "true", ignoring case, and `false` otherwise.
*/
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun String.toBoolean(): Boolean = java.lang.Boolean.parseBoolean(this)
/**
* Parses the string as a signed [Byte] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
*/
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun String.toByte(): Byte = java.lang.Byte.parseByte(this)
/**
* Parses the string as a signed [Byte] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
* @throws IllegalArgumentException when [radix] is not a valid radix for string to number conversion.
*/
@SinceKotlin("1.1")
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun String.toByte(radix: Int): Byte = java.lang.Byte.parseByte(this, checkRadix(radix))
/**
* Parses the string as a [Short] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
*/
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun String.toShort(): Short = java.lang.Short.parseShort(this)
/**
* Parses the string as a [Short] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
* @throws IllegalArgumentException when [radix] is not a valid radix for string to number conversion.
*/
@SinceKotlin("1.1")
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun String.toShort(radix: Int): Short = java.lang.Short.parseShort(this, checkRadix(radix))
/**
* Parses the string as an [Int] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
*/
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun String.toInt(): Int = java.lang.Integer.parseInt(this)
/**
* Parses the string as an [Int] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
* @throws IllegalArgumentException when [radix] is not a valid radix for string to number conversion.
*/
@SinceKotlin("1.1")
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun String.toInt(radix: Int): Int = java.lang.Integer.parseInt(this, checkRadix(radix))
/**
* Parses the string as a [Long] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
*/
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun String.toLong(): Long = java.lang.Long.parseLong(this)
/**
* Parses the string as a [Long] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
* @throws IllegalArgumentException when [radix] is not a valid radix for string to number conversion.
*/
@SinceKotlin("1.1")
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun String.toLong(radix: Int): Long = java.lang.Long.parseLong(this, checkRadix(radix))
/**
* Parses the string as a [Float] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
*/
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun String.toFloat(): Float = java.lang.Float.parseFloat(this)
/**
* Parses the string as a [Double] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
*/
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun String.toDouble(): Double = java.lang.Double.parseDouble(this)
/**
* Parses the string as a [Float] number and returns the result
* or `null` if the string is not a valid representation of a number.
*/
@SinceKotlin("1.1")
@kotlin.jvm.JvmVersion
public fun String.toFloatOrNull(): Float? = screenFloatValue(this, java.lang.Float::parseFloat)
/**
* Parses the string as a [Double] number and returns the result
* or `null` if the string is not a valid representation of a number.
*/
@SinceKotlin("1.1")
@kotlin.jvm.JvmVersion
public fun String.toDoubleOrNull(): Double? = screenFloatValue(this, java.lang.Double::parseDouble)
/**
* Parses the string as a [java.math.BigInteger] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
*/
@SinceKotlin("1.2")
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun String.toBigInteger(): java.math.BigInteger =
java.math.BigInteger(this)
/**
* Parses the string as a [java.math.BigInteger] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
* @throws IllegalArgumentException when [radix] is not a valid radix for string to number conversion.
*/
@SinceKotlin("1.2")
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun String.toBigInteger(radix: Int): java.math.BigInteger =
java.math.BigInteger(this, checkRadix(radix))
/**
* Parses the string as a [java.math.BigInteger] number and returns the result
* or `null` if the string is not a valid representation of a number.
*/
@SinceKotlin("1.2")
@kotlin.jvm.JvmVersion
public fun String.toBigIntegerOrNull(): java.math.BigInteger? = toBigIntegerOrNull(10)
/**
* Parses the string as a [java.math.BigInteger] number and returns the result
* or `null` if the string is not a valid representation of a number.
*
* @throws IllegalArgumentException when [radix] is not a valid radix for string to number conversion.
*/
@SinceKotlin("1.2")
@kotlin.jvm.JvmVersion
public fun String.toBigIntegerOrNull(radix: Int): java.math.BigInteger? {
checkRadix(radix)
val length = this.length
when (length) {
0 -> return null
1 -> if (digitOf(this[0], radix) < 0) return null
else -> {
val start = if (this[0] == '-') 1 else 0
for (index in start until length) {
if (digitOf(this[index], radix) < 0)
return null
}
}
}
return toBigInteger(radix)
}
/**
* Parses the string as a [java.math.BigDecimal] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
*/
@SinceKotlin("1.2")
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun String.toBigDecimal(): java.math.BigDecimal =
java.math.BigDecimal(this)
/**
* Parses the string as a [java.math.BigDecimal] number and returns the result.
* @throws NumberFormatException if the string is not a valid representation of a number.
*
* @param mathContext specifies the precision and the rounding mode.
* @throws ArithmeticException if the rounding is needed, but the rounding mode is [java.math.RoundingMode.UNNECESSARY].
*/
@SinceKotlin("1.2")
@kotlin.jvm.JvmVersion
@kotlin.internal.InlineOnly
public inline fun String.toBigDecimal(mathContext: java.math.MathContext): java.math.BigDecimal =
java.math.BigDecimal(this, mathContext)
/**
* Parses the string as a [java.math.BigDecimal] number and returns the result
* or `null` if the string is not a valid representation of a number.
*/
@SinceKotlin("1.2")
@kotlin.jvm.JvmVersion
public fun String.toBigDecimalOrNull(): java.math.BigDecimal? =
screenFloatValue(this) { it.toBigDecimal() }
/**
* Parses the string as a [java.math.BigDecimal] number and returns the result
* or `null` if the string is not a valid representation of a number.
*
* @param mathContext specifies the precision and the rounding mode.
* @throws ArithmeticException if the rounding is needed, but the rounding mode is [java.math.RoundingMode.UNNECESSARY].
*/
@SinceKotlin("1.2")
@kotlin.jvm.JvmVersion
public fun String.toBigDecimalOrNull(mathContext: java.math.MathContext): java.math.BigDecimal? =
screenFloatValue(this) { it.toBigDecimal(mathContext) }
/**
* Recommended floating point number validation RegEx from the javadoc of `java.lang.Double.valueOf(String)`
*/
@kotlin.jvm.JvmVersion
private object ScreenFloatValueRegEx {
@JvmField val value = run {
val Digits = "(\\p{Digit}+)"
val HexDigits = "(\\p{XDigit}+)"
val Exp = "[eE][+-]?$Digits"
val HexString = "(0[xX]$HexDigits(\\.)?)|" + // 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt
"(0[xX]$HexDigits?(\\.)$HexDigits)" // 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt
val Number = "($Digits(\\.)?($Digits?)($Exp)?)|" + // Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt
"(\\.($Digits)($Exp)?)|" + // . Digits ExponentPart_opt FloatTypeSuffix_opt
"(($HexString)[pP][+-]?$Digits)" // HexSignificand BinaryExponent
val fpRegex = "[\\x00-\\x20]*[+-]?(NaN|Infinity|(($Number)[fFdD]?))[\\x00-\\x20]*"
Regex(fpRegex)
}
}
@kotlin.jvm.JvmVersion
private inline fun <T> screenFloatValue(str: String, parse: (String) -> T): T? {
return try {
if (ScreenFloatValueRegEx.value.matches(str))
parse(str)
else
null
} catch(e: NumberFormatException) { // overflow
null
}
}
@@ -20,12 +20,3 @@ public inline fun String.toRegex(option: RegexOption): Regex = Regex(this, optio
*/
@kotlin.internal.InlineOnly
public inline fun String.toRegex(options: Set<RegexOption>): Regex = Regex(this, options)
/**
* Converts this [java.util.regex.Pattern] to an instance of [Regex].
*
* Provides the way to use Regex API on the instances of [java.util.regex.Pattern].
*/
@JvmVersion
@kotlin.internal.InlineOnly
public inline fun java.util.regex.Pattern.toRegex(): Regex = Regex(this)
@@ -0,0 +1,19 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
@file:kotlin.jvm.JvmMultifileClass
@file:kotlin.jvm.JvmName("StringsKt")
package kotlin.text
/**
* Converts this [java.util.regex.Pattern] to an instance of [Regex].
*
* Provides the way to use Regex API on the instances of [java.util.regex.Pattern].
*/
@JvmVersion
@kotlin.internal.InlineOnly
public inline fun java.util.regex.Pattern.toRegex(): Regex = Regex(this)
+3 -124
View File
@@ -1,4 +1,5 @@
@file:kotlin.jvm.JvmName("LazyKt")
@file:kotlin.jvm.JvmMultifileClass
package kotlin
@@ -27,50 +28,6 @@ public interface Lazy<out T> {
*/
public fun <T> lazyOf(value: T): Lazy<T> = InitializedLazyImpl(value)
/**
* Creates a new instance of the [Lazy] that uses the specified initialization function [initializer]
* and the default thread-safety mode [LazyThreadSafetyMode.SYNCHRONIZED].
*
* If the initialization of a value throws an exception, it will attempt to reinitialize the value at next access.
*
* Note that the returned instance uses itself to synchronize on. Do not synchronize from external code on
* the returned instance as it may cause accidental deadlock. Also this behavior can be changed in the future.
*/
@kotlin.jvm.JvmVersion
public fun <T> lazy(initializer: () -> T): Lazy<T> = SynchronizedLazyImpl(initializer)
/**
* Creates a new instance of the [Lazy] that uses the specified initialization function [initializer]
* and thread-safety [mode].
*
* If the initialization of a value throws an exception, it will attempt to reinitialize the value at next access.
*
* Note that when the [LazyThreadSafetyMode.SYNCHRONIZED] mode is specified the returned instance uses itself
* to synchronize on. Do not synchronize from external code on the returned instance as it may cause accidental deadlock.
* Also this behavior can be changed in the future.
*/
@kotlin.jvm.JvmVersion
public fun <T> lazy(mode: LazyThreadSafetyMode, initializer: () -> T): Lazy<T> =
when (mode) {
LazyThreadSafetyMode.SYNCHRONIZED -> SynchronizedLazyImpl(initializer)
LazyThreadSafetyMode.PUBLICATION -> SafePublicationLazyImpl(initializer)
LazyThreadSafetyMode.NONE -> UnsafeLazyImpl(initializer)
}
/**
* Creates a new instance of the [Lazy] that uses the specified initialization function [initializer]
* and the default thread-safety mode [LazyThreadSafetyMode.SYNCHRONIZED].
*
* If the initialization of a value throws an exception, it will attempt to reinitialize the value at next access.
*
* The returned instance uses the specified [lock] object to synchronize on.
* When the [lock] is not specified the instance uses itself to synchronize on,
* in this case do not synchronize from external code on the returned instance as it may cause accidental deadlock.
* Also this behavior can be changed in the future.
*/
@kotlin.jvm.JvmVersion
public fun <T> lazy(lock: Any?, initializer: () -> T): Lazy<T> = SynchronizedLazyImpl(initializer, lock)
/**
* An extension to delegate a read-only property of type [T] to an instance of [Lazy].
*
@@ -105,43 +62,7 @@ public enum class LazyThreadSafetyMode {
}
private object UNINITIALIZED_VALUE
@JvmVersion
private class SynchronizedLazyImpl<out T>(initializer: () -> T, lock: Any? = null) : Lazy<T>, Serializable {
private var initializer: (() -> T)? = initializer
@Volatile private var _value: Any? = UNINITIALIZED_VALUE
// final field is required to enable safe publication of constructed instance
private val lock = lock ?: this
override val value: T
get() {
val _v1 = _value
if (_v1 !== UNINITIALIZED_VALUE) {
@Suppress("UNCHECKED_CAST")
return _v1 as T
}
return synchronized(lock) {
val _v2 = _value
if (_v2 !== UNINITIALIZED_VALUE) {
@Suppress("UNCHECKED_CAST") (_v2 as T)
}
else {
val typedValue = initializer!!()
_value = typedValue
initializer = null
typedValue
}
}
}
override fun isInitialized(): Boolean = _value !== UNINITIALIZED_VALUE
override fun toString(): String = if (isInitialized()) value.toString() else "Lazy value not initialized yet."
private fun writeReplace(): Any = InitializedLazyImpl(value)
}
internal object UNINITIALIZED_VALUE
// internal to be called from lazy in JS
internal class UnsafeLazyImpl<out T>(initializer: () -> T) : Lazy<T>, Serializable {
@@ -165,52 +86,10 @@ internal class UnsafeLazyImpl<out T>(initializer: () -> T) : Lazy<T>, Serializab
private fun writeReplace(): Any = InitializedLazyImpl(value)
}
private class InitializedLazyImpl<out T>(override val value: T) : Lazy<T>, Serializable {
internal class InitializedLazyImpl<out T>(override val value: T) : Lazy<T>, Serializable {
override fun isInitialized(): Boolean = true
override fun toString(): String = value.toString()
}
@kotlin.jvm.JvmVersion
private class SafePublicationLazyImpl<out T>(initializer: () -> T) : Lazy<T>, Serializable {
@Volatile private var initializer: (() -> T)? = initializer
@Volatile private var _value: Any? = UNINITIALIZED_VALUE
// this final field is required to enable safe publication of constructed instance
private val final: Any = UNINITIALIZED_VALUE
override val value: T
get() {
val value = _value
if (value !== UNINITIALIZED_VALUE) {
@Suppress("UNCHECKED_CAST")
return value as T
}
val initializerValue = initializer
// if we see null in initializer here, it means that the value is already set by another thread
if (initializerValue != null) {
val newValue = initializerValue()
if (valueUpdater.compareAndSet(this, UNINITIALIZED_VALUE, newValue)) {
initializer = null
return newValue
}
}
@Suppress("UNCHECKED_CAST")
return _value as T
}
override fun isInitialized(): Boolean = _value !== UNINITIALIZED_VALUE
override fun toString(): String = if (isInitialized()) value.toString() else "Lazy value not initialized yet."
private fun writeReplace(): Any = InitializedLazyImpl(value)
companion object {
private val valueUpdater = java.util.concurrent.atomic.AtomicReferenceFieldUpdater.newUpdater(
SafePublicationLazyImpl::class.java,
Any::class.java,
"_value")
}
}
+135
View File
@@ -0,0 +1,135 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
@file:kotlin.jvm.JvmName("LazyKt")
@file:kotlin.jvm.JvmMultifileClass
package kotlin
/**
* Creates a new instance of the [Lazy] that uses the specified initialization function [initializer]
* and the default thread-safety mode [LazyThreadSafetyMode.SYNCHRONIZED].
*
* If the initialization of a value throws an exception, it will attempt to reinitialize the value at next access.
*
* Note that the returned instance uses itself to synchronize on. Do not synchronize from external code on
* the returned instance as it may cause accidental deadlock. Also this behavior can be changed in the future.
*/
@kotlin.jvm.JvmVersion
public fun <T> lazy(initializer: () -> T): Lazy<T> = SynchronizedLazyImpl(initializer)
/**
* Creates a new instance of the [Lazy] that uses the specified initialization function [initializer]
* and thread-safety [mode].
*
* If the initialization of a value throws an exception, it will attempt to reinitialize the value at next access.
*
* Note that when the [LazyThreadSafetyMode.SYNCHRONIZED] mode is specified the returned instance uses itself
* to synchronize on. Do not synchronize from external code on the returned instance as it may cause accidental deadlock.
* Also this behavior can be changed in the future.
*/
@kotlin.jvm.JvmVersion
public fun <T> lazy(mode: LazyThreadSafetyMode, initializer: () -> T): Lazy<T> =
when (mode) {
LazyThreadSafetyMode.SYNCHRONIZED -> SynchronizedLazyImpl(initializer)
LazyThreadSafetyMode.PUBLICATION -> SafePublicationLazyImpl(initializer)
LazyThreadSafetyMode.NONE -> UnsafeLazyImpl(initializer)
}
/**
* Creates a new instance of the [Lazy] that uses the specified initialization function [initializer]
* and the default thread-safety mode [LazyThreadSafetyMode.SYNCHRONIZED].
*
* If the initialization of a value throws an exception, it will attempt to reinitialize the value at next access.
*
* The returned instance uses the specified [lock] object to synchronize on.
* When the [lock] is not specified the instance uses itself to synchronize on,
* in this case do not synchronize from external code on the returned instance as it may cause accidental deadlock.
* Also this behavior can be changed in the future.
*/
@kotlin.jvm.JvmVersion
public fun <T> lazy(lock: Any?, initializer: () -> T): Lazy<T> = SynchronizedLazyImpl(initializer, lock)
@JvmVersion
private class SynchronizedLazyImpl<out T>(initializer: () -> T, lock: Any? = null) : Lazy<T>, Serializable {
private var initializer: (() -> T)? = initializer
@Volatile private var _value: Any? = UNINITIALIZED_VALUE
// final field is required to enable safe publication of constructed instance
private val lock = lock ?: this
override val value: T
get() {
val _v1 = _value
if (_v1 !== UNINITIALIZED_VALUE) {
@Suppress("UNCHECKED_CAST")
return _v1 as T
}
return synchronized(lock) {
val _v2 = _value
if (_v2 !== UNINITIALIZED_VALUE) {
@Suppress("UNCHECKED_CAST") (_v2 as T)
}
else {
val typedValue = initializer!!()
_value = typedValue
initializer = null
typedValue
}
}
}
override fun isInitialized(): Boolean = _value !== UNINITIALIZED_VALUE
override fun toString(): String = if (isInitialized()) value.toString() else "Lazy value not initialized yet."
private fun writeReplace(): Any = InitializedLazyImpl(value)
}
@kotlin.jvm.JvmVersion
private class SafePublicationLazyImpl<out T>(initializer: () -> T) : Lazy<T>, Serializable {
@Volatile private var initializer: (() -> T)? = initializer
@Volatile private var _value: Any? = UNINITIALIZED_VALUE
// this final field is required to enable safe publication of constructed instance
private val final: Any = UNINITIALIZED_VALUE
override val value: T
get() {
val value = _value
if (value !== UNINITIALIZED_VALUE) {
@Suppress("UNCHECKED_CAST")
return value as T
}
val initializerValue = initializer
// if we see null in initializer here, it means that the value is already set by another thread
if (initializerValue != null) {
val newValue = initializerValue()
if (valueUpdater.compareAndSet(this, UNINITIALIZED_VALUE, newValue)) {
initializer = null
return newValue
}
}
@Suppress("UNCHECKED_CAST")
return _value as T
}
override fun isInitialized(): Boolean = _value !== UNINITIALIZED_VALUE
override fun toString(): String = if (isInitialized()) value.toString() else "Lazy value not initialized yet."
private fun writeReplace(): Any = InitializedLazyImpl(value)
companion object {
private val valueUpdater = java.util.concurrent.atomic.AtomicReferenceFieldUpdater.newUpdater(
SafePublicationLazyImpl::class.java,
Any::class.java,
"_value")
}
}