Skip to content

Commit

Permalink
Removed unsigned numbers from RawNumberReader + added test
Browse files Browse the repository at this point in the history
  • Loading branch information
vooft committed May 18, 2024
1 parent 604d241 commit 2685d9a
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -1,28 +1,29 @@
package io.github.vooft.kotlinsmile.decoder.raw

import io.github.vooft.kotlinsmile.common.ByteArrayIterator
import kotlin.experimental.and
import kotlin.experimental.xor

fun ByteArrayIterator.nextRawInt(): Int {
var result = 0
var byte = next()
while (byte.toUInt() and FIRST_BIT_MASK == 0u) {
while (byte and FIRST_BIT_MASK == 0.toByte()) {
result = (result shl 7) or byte.toInt()
byte = next()
}

return (result shl 6) or (byte xor FIRST_BIT_MASK.toByte()).toInt()
return (result shl 6) or (byte xor FIRST_BIT_MASK).toInt()
}

fun ByteArrayIterator.nextRawLong(): Long {
var result = 0L
var byte = next()
while (byte.toUInt() and FIRST_BIT_MASK == 0u) {
while (byte and FIRST_BIT_MASK == 0.toByte()) {
result = (result shl 7) or byte.toLong()
byte = next()
}

return (result shl 6) or (byte xor FIRST_BIT_MASK.toByte()).toLong()
return (result shl 6) or (byte xor FIRST_BIT_MASK).toLong()
}

private const val FIRST_BIT_MASK = 0b1000_0000u
private const val FIRST_BIT_MASK: Byte = 0b1000_0000.toByte()
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package io.github.vooft.kotlinsmile.decoder.raw

import io.github.vooft.kotlinsmile.common.ByteArrayIteratorImpl
import io.kotest.matchers.shouldBe
import kotlin.test.Test

class RawNumberReaderTest {
@Test
fun should_read_raw_int() {
val expected = 12345
val iterator = ByteArrayIteratorImpl(byteArrayOf(0x01, 0x40, 0xB9.toByte()))

iterator.nextRawInt() shouldBe expected
}

@Test
fun should_read_raw_max_int() {
val expected = Int.MAX_VALUE
val iterator = ByteArrayIteratorImpl(byteArrayOf(0x0F, 0x7F, 0x7F, 0x7F, 0xBF.toByte()))

iterator.nextRawInt() shouldBe expected
}

@Test
fun should_read_raw_min_int() {
val expected = Int.MIN_VALUE
val iterator = ByteArrayIteratorImpl(byteArrayOf(0x10, 0x00, 0x00, 0x00, 0x80.toByte()))

iterator.nextRawInt() shouldBe expected
}

@Test
fun should_read_raw_long() {
val expected = 123456789L
val iterator = ByteArrayIteratorImpl(byteArrayOf(0x75, 0x5E, 0x34, 0x95.toByte()))

iterator.nextRawLong() shouldBe expected
}

@Test
fun should_read_raw_max_long() {
val expected = Long.MAX_VALUE
val iterator = ByteArrayIteratorImpl(byteArrayOf(0x01, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0xBF.toByte()))

iterator.nextRawLong() shouldBe expected
}

@Test
fun should_read_raw_min_long() {
val expected = Long.MIN_VALUE
val iterator = ByteArrayIteratorImpl(byteArrayOf(0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80.toByte()))

iterator.nextRawLong() shouldBe expected
}
}

0 comments on commit 2685d9a

Please sign in to comment.