Created
June 27, 2016 14:21
-
-
Save basp1/6a4701a75934a2166752da3158710313 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
import java.nio.ByteBuffer | |
object LEB128 { | |
def write(buffer: ByteBuffer, offset: Int, longValue: Long): Int = { | |
var writtenBytes: Int = 0 | |
var value = longValue | |
if (value.abs <= 63) { | |
if (value < 0) { | |
value = value.abs | |
buffer.put(offset, (64 | value).toByte) | |
} else { | |
buffer.put(offset, value.toByte) | |
} | |
writtenBytes = 1 | |
} else { | |
if (value < 0) { | |
value = value.abs | |
buffer.put(offset + writtenBytes, (192 | (value & 63)).toByte) | |
} else { | |
buffer.put(offset + writtenBytes, (128 | (value & 63)).toByte) | |
} | |
writtenBytes = 1 | |
value >>= 6 | |
while (0 != value) { | |
if (value > 127) { | |
buffer.put(offset + writtenBytes, (128 | value & 127).toByte) | |
} else { | |
buffer.put(offset + writtenBytes, (value & 127).toByte) | |
} | |
writtenBytes += 1 | |
value >>= 7 | |
} | |
} | |
writtenBytes | |
} | |
def read(buffer: ByteBuffer, offset: Int): (Long, Int) = { | |
var readBytes: Int = 0 | |
var value = 0L | |
var negative = false | |
if ((64 & buffer.get(offset)) > 0) { | |
negative = true | |
} | |
value += (buffer.get(offset) & 63) | |
readBytes = 1 | |
if (128.toByte == (buffer.get(offset) & 128.toByte)) { | |
var j = 6 | |
while (128.toByte == (buffer.get(offset + readBytes) & 128.toByte)) { | |
value += ((buffer.get(offset + readBytes) & 127L) << j) | |
readBytes += 1 | |
j += 7 | |
} | |
value += (buffer.get(offset + readBytes).toLong << j) | |
readBytes += 1 | |
} | |
if (negative) { | |
value = -value | |
} | |
(value, readBytes) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment