Skip to content

Instantly share code, notes, and snippets.

@kxbmap
Last active December 11, 2015 23:18
Show Gist options
  • Save kxbmap/4675315 to your computer and use it in GitHub Desktop.
Save kxbmap/4675315 to your computer and use it in GitHub Desktop.
import io.netty.buffer.{Unpooled, ByteBuf}
import java.nio.charset.Charset
object NettyUtil {
implicit class ByteBufOps(val buf: ByteBuf) extends AnyVal {
def getUTF(index: Int): String = {
val length = buf.getUnsignedShort(index)
sliceToString(index + 2, length)
}
def readUTF(): String = {
val length = buf.getUnsignedShort(buf.readerIndex())
val s = sliceToString(buf.readerIndex() + 2, length)
buf.skipBytes(length + 2)
s
}
private def sliceToString(index: Int, length: Int): String =
buf.slice(index, length).toString(Charset.forName("UTF8"))
def setUTF(index: Int, s: String): ByteBuf = {
set(index, s)
buf
}
def writeUTF(s: String): ByteBuf = {
val length = set(buf.writerIndex(), s)
buf.writerIndex(buf.writerIndex() + length + 2)
}
private def set(index: Int, s: String): Int = {
val sb = Unpooled.copiedBuffer(s, Charset.forName("UTF8"))
val length = sb.readableBytes()
buf.setBytes(index + 2, sb)
buf.setShort(index, length)
length
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment