From 78f8069177a4f0386d6159ffccefa7c8c4b96ffc Mon Sep 17 00:00:00 2001 From: Graham Date: Wed, 2 Sep 2020 22:57:17 +0100 Subject: [PATCH] Add method for stripping the version trailer from a ByteBuf Signed-off-by: Graham --- .../java/dev/openrs2/cache/VersionTrailer.kt | 16 +++++++++ .../dev/openrs2/cache/VersionTrailerTest.kt | 35 +++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 cache/src/main/java/dev/openrs2/cache/VersionTrailer.kt create mode 100644 cache/src/test/java/dev/openrs2/cache/VersionTrailerTest.kt diff --git a/cache/src/main/java/dev/openrs2/cache/VersionTrailer.kt b/cache/src/main/java/dev/openrs2/cache/VersionTrailer.kt new file mode 100644 index 00000000..25f562f3 --- /dev/null +++ b/cache/src/main/java/dev/openrs2/cache/VersionTrailer.kt @@ -0,0 +1,16 @@ +package dev.openrs2.cache + +import io.netty.buffer.ByteBuf + +public object VersionTrailer { + public fun strip(buf: ByteBuf): Int? { + return if (buf.readableBytes() >= 2) { + val index = buf.writerIndex() - 2 + val version = buf.getUnsignedShort(index) + buf.writerIndex(index) + version + } else { + null + } + } +} diff --git a/cache/src/test/java/dev/openrs2/cache/VersionTrailerTest.kt b/cache/src/test/java/dev/openrs2/cache/VersionTrailerTest.kt new file mode 100644 index 00000000..6cf8c849 --- /dev/null +++ b/cache/src/test/java/dev/openrs2/cache/VersionTrailerTest.kt @@ -0,0 +1,35 @@ +package dev.openrs2.cache + +import dev.openrs2.buffer.use +import io.netty.buffer.Unpooled +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +object VersionTrailerTest { + @Test + public fun testStrip() { + assertNull(VersionTrailer.strip(Unpooled.EMPTY_BUFFER)) + + Unpooled.wrappedBuffer(byteArrayOf(0)).use { buf -> + assertNull(VersionTrailer.strip(buf)) + + Unpooled.wrappedBuffer(byteArrayOf(0)).use { expected -> + assertEquals(expected, buf) + } + } + + Unpooled.wrappedBuffer(byteArrayOf(0x12, 0x34)).use { buf -> + assertEquals(0x1234, VersionTrailer.strip(buf)) + assertEquals(Unpooled.EMPTY_BUFFER, buf) + } + + Unpooled.wrappedBuffer(byteArrayOf(0x12, 0x34, 0x56)).use { buf -> + assertEquals(0x3456, VersionTrailer.strip(buf)) + + Unpooled.wrappedBuffer(byteArrayOf(0x012)).use { expected -> + assertEquals(expected, buf) + } + } + } +}