package ru.dbotthepony.kstarbound.util import java.util.Spliterator import java.util.function.Consumer class ArraySpliterator(private val source: Array, private val offset: Int = 0, private val size: Int = source.size) : Spliterator { 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): Boolean { if (index < size) { action.accept(source[offset + index++]) return true } return false } override fun trySplit(): Spliterator? { 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 } }