Optimize Container.balance

This commit is contained in:
DBotThePony 2023-06-23 23:42:30 +07:00
parent dbf28efe89
commit 7cddbdea31
Signed by: DBot
GPG Key ID: DCC23B5715498507

View File

@ -119,8 +119,8 @@ inline fun Container.forEachNonEmpty(lambda: (ItemStack) -> Unit) {
}
}
fun Container.balance(slots: IntSet) {
if (slots.isEmpty() || !slots.any { getItem(it).isNotEmpty }) return
fun Container.balance(slots: IntSet, checkForEmpty: Boolean = true) {
if (slots.isEmpty() || checkForEmpty && !slots.any { getItem(it).isNotEmpty }) return
val empty = IntArrayList()
val itemTypes = Object2ObjectOpenCustomHashMap<ItemStack, IntAVLTreeSet>(ItemStackHashStrategy)
@ -250,5 +250,15 @@ fun Container.balance(slots: IntRange) {
fun Container.balance(startSlot: Int = 0, endSlot: Int = containerSize - 1) {
require(startSlot <= endSlot) { "Invalid slot range: $startSlot .. $endSlot" }
balance(IntArrayList(endSlot - startSlot + 1).also { for (i in startSlot .. endSlot) it.add(i) })
var any = false
for (i in startSlot .. endSlot) {
if (getItem(i).isNotEmpty) {
any = true
break
}
}
if (!any) return
balance(IntArraySet(endSlot - startSlot + 1).also { for (i in startSlot .. endSlot) it.add(i) }, false)
}