package ru.dbotthepony.kstarbound.util

import java.util.Spliterator
import java.util.concurrent.RecursiveAction

class ParallelPerform<E>(val spliterator: Spliterator<E>, val action: (E) -> Unit, val targetSize: Long = 32L) : RecursiveAction() {
	override fun compute() {
		if (spliterator.estimateSize() <= targetSize) {
			spliterator.forEachRemaining(action)
		} else {
			val split = spliterator.trySplit() ?: return spliterator.forEachRemaining(action)

			val task0 = ParallelPerform(spliterator, action, targetSize)
			val task1 = ParallelPerform(split, action, targetSize)
			task0.fork()
			task1.fork()
			task0.join()
			task1.join()
		}
	}
}
