Created
February 1, 2025 00:08
-
-
Save Edouard127/732c78cf78e3fe9acb79b2de72351dba to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class VarIntIterator( | |
private val bytes: ByteArray, | |
private val bitsPerEntry: Int = 7, | |
private val maxGroups: Int = 5, | |
) : Iterator<Int> { | |
private var index: Int = 0 | |
override fun hasNext(): Boolean = index < bytes.size | |
override fun next(): Int { | |
if (!hasNext()) | |
throw NoSuchElementException("No more elements to read") | |
var value = 0 | |
var bitsRead = 0 | |
val groupMask = (1 shl bitsPerEntry) - 1 | |
val continuationBit = 1 shl bitsPerEntry | |
var b: Byte | |
do { | |
if (index >= bytes.size) | |
throw NoSuchElementException("Unexpected end of byte array while reading VarInt") | |
b = bytes[index++] | |
value = value or ((b.toInt() and groupMask) shl bitsRead) | |
bitsRead += bitsPerEntry | |
require(bitsRead <= bitsPerEntry * maxGroups) { "VarInt size cannot exceed $maxGroups bytes" } | |
} while ((b.toInt() and continuationBit) != 0) | |
return value | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment