[utils] Move atMostOne to core/util.runtime

There is nothing backend-specific about this helper function.
This commit is contained in:
Sergej Jaskiewicz
2023-08-22 21:07:15 +02:00
committed by teamcity
parent fa600a58ac
commit 56cb0bf071
15 changed files with 44 additions and 29 deletions
@@ -47,3 +47,31 @@ inline fun <reified T, reified R, C : MutableCollection<in R>> Iterable<*>.filte
}
return destination
}
/**
* Returns the single element of the collection if it contains at most one element.
*
* If the collection is empty, returns `null`.
*
* If the collection contains exactly one element, returns that element.
*
* If the collection contains more than one element, throws an exception.
*/
fun <T> Collection<T>.atMostOne(): T? {
return when (size) {
0 -> null
1 -> this.iterator().next()
else -> throw IllegalArgumentException("Collection has more than one element.")
}
}
/**
* Returns at most one element from the iterable that satisfies the given predicate.
*
* If there are no elements that satisfy [predicate], returns `null`.
*
* If there is exactly one element that satisfies [predicate], returns that element.
*
* If there are more such elements, throws an exception.
*/
inline fun <T> Iterable<T>.atMostOne(predicate: (T) -> Boolean): T? = this.filter(predicate).atMostOne()
@@ -104,12 +104,13 @@ infix fun <T, R> Collection<T>.memoryOptimizedZip(other: Collection<R>): List<Pa
}
/**
* [Sequence] variant of [org.jetbrains.kotlin.backend.common.atMostOne]
* [Sequence] variant of [org.jetbrains.kotlin.utils.atMostOne]
*
* So, when:
* - there is no element then `null` will be returned
* - there is a single element then the element will be returned
* - there is more than one element then the error will be thrown
* @see org.jetbrains.kotlin.backend.common.atMostOne
* @see org.jetbrains.kotlin.utils.atMostOne
*/
fun <T> Sequence<T>.atMostOne(): T? {
val iterator = iterator()
@@ -143,4 +144,4 @@ inline fun <reified T> Iterable<*>.findIsInstanceAnd(predicate: (T) -> Boolean):
* The same as [Collection.toMutableList] extension function, but it returns a SmartList which is better with in sense of memory consumption
* @see Collection.toMutableList
*/
fun <T> Collection<T>.toSmartList(): List<T> = SmartList<T>(this)
fun <T> Collection<T>.toSmartList(): List<T> = SmartList<T>(this)