Skip to content

Commit 80b01e0

Browse files
committed
Changed varint to use only 7 bits
1 parent b2ad25d commit 80b01e0

File tree

2 files changed

+16
-17
lines changed

2 files changed

+16
-17
lines changed

common/src/main/kotlin/com/lambda/util/VarIntIterator.kt

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,6 @@ package com.lambda.util
1919

2020
class VarIntIterator(
2121
private val bytes: ByteArray,
22-
private val bitsPerEntry: Int = 7,
23-
private val maxGroups: Int = 5,
2422
) : Iterator<Int> {
2523
private var index: Int = 0
2624

@@ -31,23 +29,23 @@ class VarIntIterator(
3129
throw NoSuchElementException("No more elements to read")
3230

3331
var value = 0
34-
var bitsRead = 0
32+
var size = 0
3533

36-
val groupMask = (1 shl bitsPerEntry) - 1
37-
val continuationBit = 1 shl bitsPerEntry
38-
39-
var b: Byte
4034
do {
41-
if (index >= bytes.size)
42-
throw NoSuchElementException("Unexpected end of byte array while reading VarInt")
43-
44-
b = bytes[index++]
45-
value = value or ((b.toInt() and groupMask) shl bitsRead)
46-
bitsRead += bitsPerEntry
35+
val b = bytes[index++].toInt()
36+
value = value or ((b and SEGMENT_BIT) shl (size++ * 7))
4737

48-
require(bitsRead <= bitsPerEntry * maxGroups) { "VarInt size cannot exceed $maxGroups bytes" }
49-
} while ((b.toInt() and continuationBit) != 0)
38+
if (size > 5) throw IllegalArgumentException("VarInt size cannot exceed 5 bytes")
39+
} while ((b and CONTINUE_BIT) != 0)
5040

5141
return value
5242
}
43+
44+
companion object {
45+
const val SEGMENT_BIT = 127
46+
const val CONTINUE_BIT = 128
47+
}
5348
}
49+
50+
inline fun ByteArray.varIterator(block: (Int) -> Unit) =
51+
VarIntIterator(this).forEach(block)

common/src/main/kotlin/com/lambda/util/extension/Structures.kt

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ package com.lambda.util.extension
2020
import com.lambda.Lambda.mc
2121
import com.lambda.util.VarIntIterator
2222
import com.lambda.util.math.MathUtils.logCap
23+
import com.lambda.util.varIterator
2324
import com.lambda.util.world.FastVector
2425
import com.lambda.util.world.fastVectorOf
2526
import com.lambda.util.world.x
@@ -117,8 +118,8 @@ private fun StructureTemplate.readSpongeV1OrException(
117118

118119
val newBlocks = NbtList()
119120
var blockIndex = 0
120-
VarIntIterator(nbt.getByteArray("BlockData"))
121-
.forEach { blockId ->
121+
nbt.getByteArray("BlockData")
122+
.varIterator { blockId ->
122123
val blockpos = positionFromIndex(width, length, blockIndex++)
123124

124125
newBlocks.add(NbtCompound().apply {

0 commit comments

Comments
 (0)