Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix usage of BigInteger in DiscordBitSet.value #864

Merged
merged 1 commit into from
Sep 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions common/src/commonTest/kotlin/BitSetTests.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package dev.kord.common

import kotlin.js.JsName
import kotlin.random.Random
import kotlin.random.nextLong
import kotlin.test.*

class BitSetTests {
Expand Down Expand Up @@ -99,4 +101,29 @@ class BitSetTests {
DiscordBitSet(0b1011, 0b111001, 0b110).binary,
)
}

@Test
fun value_works_for_DiscordBitSet_with_empty_data_array() {
val bits = DiscordBitSet(data = LongArray(size = 0))
assertEquals("0", bits.value)
}

@Test
fun value_works_for_all_single_bit_Longs() {
for (shift in 0..<Long.SIZE_BITS) {
val value = 1L shl shift
val bits = DiscordBitSet(value)
assertEquals(value.toULong().toString(), bits.value)
}
}

@Test
fun value_is_never_negative() {
for (size in 1..10) {
val data = LongArray(size)
data[size - 1] = Random.nextLong(Long.MIN_VALUE..-1)
val bits = DiscordBitSet(data)
assertTrue(bits.value.all { it in '0'..'9' })
}
}
}
2 changes: 1 addition & 1 deletion common/src/jvmMain/kotlin/DiscordBitSetJvm.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ internal actual fun formatIntegerFromLittleEndianLongArray(data: LongArray): Str
// need to convert from little-endian data to big-endian expected by BigInteger
val buffer = ByteBuffer.allocate(data.size * Long.SIZE_BYTES)
buffer.asLongBuffer().put(data.reversedArray())
return BigInteger(buffer.array()).toString()
return BigInteger(/* signum = */ 1, /* magnitude = */ buffer.array()).toString()
}

internal actual fun parseIntegerToBigEndianByteArray(value: String): ByteArray = BigInteger(value).toByteArray()