KStarbound/src/main/kotlin/ru/dbotthepony/kstarbound/util/ArraySpliterator.kt
2022-09-11 17:55:47 +07:00

46 lines
1.0 KiB
Kotlin

package ru.dbotthepony.kstarbound.util
import java.util.Spliterator
import java.util.function.Consumer
class ArraySpliterator<T>(private val source: Array<T>, private val offset: Int = 0, private val size: Int = source.size) : Spliterator<T> {
init {
require(offset + size <= source.size) { "Invalid dimensions for spliterator: offset = $offset, size = $size, source has size of ${source.size}" }
}
private var index = 0
override fun tryAdvance(action: Consumer<in T>): Boolean {
if (index < size) {
action.accept(source[offset + index++])
return true
}
return false
}
override fun trySplit(): Spliterator<T>? {
if (index + 1 >= size) {
return null
}
val splitSize = size / 2
if (splitSize == 0) {
return null
}
val pointer = index + offset
index += splitSize
return ArraySpliterator(source, pointer, splitSize)
}
override fun estimateSize(): Long {
return (size - index).toLong()
}
override fun characteristics(): Int {
return Spliterator.ORDERED or Spliterator.SIZED
}
}