All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.ch.softappeal.yass2.serialize.VarInt.kt Maven / Gradle / Ivy

There is a newer version: 5.0.0
Show newest version
package ch.softappeal.yass2.serialize

private const val IntInv7F: Int = 0x7F.inv()

fun Writer.writeVarInt(v: Int) {
    var value = v
    while (true) {
        if (value and IntInv7F == 0) {
            writeByte(value.toByte())
            return
        }
        writeByte((value and 0x7F or 0x80).toByte())
        value = value ushr 7
    }
}

fun Reader.readVarInt(): Int {
    var shift = 0
    var value = 0
    while (true) {
        val b = readByte().toInt()
        value = value or (b and 0x7F shl shift)
        if (b and 0x80 == 0) return value
        shift += 7
    }
}

private const val LongInv7F: Long = 0x7FL.inv()

fun Writer.writeVarLong(v: Long) {
    var value = v
    while (true) {
        if (value and LongInv7F == 0L) {
            writeByte(value.toByte())
            return
        }
        writeByte((value and 0x7F or 0x80).toByte())
        value = value ushr 7
    }
}

fun Reader.readVarLong(): Long {
    var shift = 0
    var value = 0L
    while (true) {
        val b = readByte().toLong()
        value = value or (b and 0x7F shl shift)
        if (b and 0x80 == 0L) return value
        shift += 7
    }
}

fun Int.toZigZag(): Int = (this shl 1) xor (this shr 31)

fun Int.fromZigZag(): Int = (this ushr 1) xor -(this and 1)

fun Long.toZigZag(): Long = (this shl 1) xor (this shr 63)

fun Long.fromZigZag(): Long = (this ushr 1) xor -(this and 1)




© 2015 - 2025 Weber Informatics LLC | Privacy Policy