Last active
August 22, 2026 15:04
-
-
Save mrenouf/7cd7ac6cb4875ea18f33090e3f54cca4 to your computer and use it in GitHub Desktop.
Varint Encoding
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
| fun writeVarint(long: Long) { | |
| require(long >= 0) { "Varint must be non-negative" } | |
| var v = long | |
| while (v and 0x7fL.inv() != 0L) { | |
| writeByte(((v and 0x7fL) or 0x80L).toByte()) | |
| v = v ushr 7 | |
| } | |
| writeByte((v and 0x7fL).toByte()) | |
| } | |
| fun readVarint(): Long { | |
| var result = 0L | |
| var shift = 0 | |
| while(true) { | |
| val byte = readByte().toLong() | |
| result = result or ((byte and 0x7fL) shl shift) | |
| if (byte and 0x80L == 0L) break | |
| shift += 7 | |
| if (shift > 63) { | |
| throw IllegalArgumentException("Invalid varint value: overflow while decoding") | |
| } | |
| } | |
| return result | |
| } | |
| fun writeByte(value: Byte) | |
| fun readByte(): Byte |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment