34 lines
1 KiB
Kotlin
34 lines
1 KiB
Kotlin
package space.blokk.net
|
|
|
|
import io.netty.buffer.ByteBuf
|
|
import io.netty.channel.ChannelHandlerContext
|
|
import io.netty.handler.codec.ByteToMessageCodec
|
|
import space.blokk.net.MinecraftDataTypes.readVarInt
|
|
import space.blokk.net.MinecraftDataTypes.varIntReadable
|
|
import space.blokk.net.MinecraftDataTypes.writeVarInt
|
|
|
|
class FramingCodec : ByteToMessageCodec<ByteBuf>() {
|
|
private var currentLength: Int? = null
|
|
|
|
override fun encode(ctx: ChannelHandlerContext, msg: ByteBuf, out: ByteBuf) {
|
|
out.writeVarInt(msg.readableBytes())
|
|
msg.readerIndex(0)
|
|
out.writeBytes(msg)
|
|
}
|
|
|
|
override fun decode(ctx: ChannelHandlerContext, msg: ByteBuf, out: MutableList<Any>) {
|
|
var length = currentLength
|
|
|
|
if (length == null) {
|
|
if (msg.varIntReadable()) {
|
|
length = msg.readVarInt()
|
|
currentLength = length
|
|
} else return
|
|
}
|
|
|
|
if (msg.readableBytes() >= length) {
|
|
out.add(msg.readBytes(length))
|
|
currentLength = null
|
|
}
|
|
}
|
|
}
|