Binary input/output
The desert
library uses the BinaryInput
and BinaryOutput
interfaces to read and write data.
The default implementation is JavaStreamBinaryInput
and JavaStreamBinaryOutput
. These are simple
wrappers on top of Java IO streams, capturing failures and adding some extra functionality.
Variable length integer encoding
One extra feature is the variable length integer encoding which was borrowed from the Kryo library.
It encodes 32 bit integers in 1-5 bytes. It is used for all “integer id like” data within the library.
import java.io.ByteArrayOutputStream
import io.github.vigoo.desert._
import io.github.vigoo.desert.internal._
val stream = new ByteArrayOutputStream()
// stream: ByteArrayOutputStream = ����
val output = new JavaStreamBinaryOutput(stream)
// output: JavaStreamBinaryOutput = io.github.vigoo.desert.internal.JavaStreamBinaryOutput@6effc769
output.writeVarInt(1, optimizeForPositive = true)
val r1 = stream.toByteArray
// r1: Array[Byte] = Array(1)
stream.reset()
output.writeVarInt(4096, optimizeForPositive = true)
val r2 = stream.toByteArray
// r2: Array[Byte] = Array(-128, 32)
stream.reset()
output.writeVarInt(-1, optimizeForPositive = true)
val r3 = stream.toByteArray
// r3: Array[Byte] = Array(-1, -1, -1, -1, 15)