Add support for overriding the charset in readString/writeString

Signed-off-by: Graham <gpe@openrs2.org>
Graham 4 years ago
parent f26e6ef0b9
commit 29fecec34e
  1. 8
      buffer/src/main/kotlin/org/openrs2/buffer/ByteBufExtensions.kt
  2. 57
      buffer/src/test/kotlin/org/openrs2/buffer/ByteBufExtensionsTest.kt

@ -95,7 +95,7 @@ public fun ByteBuf.writeUnsignedIntSmart(v: Int): ByteBuf {
return this
}
public fun ByteBuf.readString(): String {
public fun ByteBuf.readString(charset: Charset = Cp1252Charset): String {
val start = readerIndex()
val end = forEachByte(ByteProcessor.FIND_NUL)
@ -103,13 +103,13 @@ public fun ByteBuf.readString(): String {
"Unterminated string"
}
val s = toString(start, end - start, Cp1252Charset)
val s = toString(start, end - start, charset)
readerIndex(end + 1)
return s
}
public fun ByteBuf.writeString(s: CharSequence): ByteBuf {
writeCharSequence(s, Cp1252Charset)
public fun ByteBuf.writeString(s: CharSequence, charset: Charset = Cp1252Charset): ByteBuf {
writeCharSequence(s, charset)
writeByte(0)
return this
}

@ -2,6 +2,7 @@ package org.openrs2.buffer
import io.netty.buffer.ByteBufAllocator
import io.netty.buffer.Unpooled
import org.openrs2.util.charset.ModifiedUtf8Charset
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
@ -433,6 +434,33 @@ class ByteBufExtensionsTest {
}
}
@Test
fun testReadStringCharset() {
wrappedBuffer(0).use { buf ->
assertEquals("", buf.readString(ModifiedUtf8Charset))
assertFalse(buf.isReadable)
}
wrappedBuffer(
0xC3.toByte(),
0x96.toByte(),
'p'.code.toByte(),
'e'.code.toByte(),
'n'.code.toByte(),
'R'.code.toByte(),
'S'.code.toByte(),
'2'.code.toByte(),
0
).use { buf ->
assertEquals("ÖpenRS2", buf.readString(ModifiedUtf8Charset))
assertFalse(buf.isReadable)
}
assertFailsWith<IllegalArgumentException> {
Unpooled.EMPTY_BUFFER.readString(ModifiedUtf8Charset)
}
}
@Test
fun testWriteString() {
ByteBufAllocator.DEFAULT.buffer().use { actual ->
@ -461,6 +489,35 @@ class ByteBufExtensionsTest {
}
}
@Test
fun testWriteStringCharset() {
ByteBufAllocator.DEFAULT.buffer().use { actual ->
actual.writeString("", ModifiedUtf8Charset)
wrappedBuffer(0).use { expected ->
assertEquals(expected, actual)
}
}
ByteBufAllocator.DEFAULT.buffer().use { actual ->
actual.writeString("ÖpenRS2", ModifiedUtf8Charset)
wrappedBuffer(
0xC3.toByte(),
0x96.toByte(),
'p'.code.toByte(),
'e'.code.toByte(),
'n'.code.toByte(),
'R'.code.toByte(),
'S'.code.toByte(),
'2'.code.toByte(),
0
).use { expected ->
assertEquals(expected, actual)
}
}
}
@Test
fun testReadVersionedString() {
wrappedBuffer(0, 0).use { buf ->

Loading…
Cancel
Save