package ru.dbotthepony.kstarbound.util

import kotlinx.coroutines.delay

class ExecutionTimePacer(val budget: Long, val pause: Long) {
	var elapsed = 0L

	suspend inline fun <T> measureAndSuspend(block: () -> T): T {
		if (budget <= 0L || pause <= 0L) {
			return block()
		}

		val origin = System.nanoTime()
		val result = block()
		elapsed += System.nanoTime() - origin

		if (elapsed >= budget) {
			elapsed = 0
			delay(pause)
		}

		return result
	}

	companion object {
		val UNLIMITED = ExecutionTimePacer(0L, 0L)
	}
}
