From 6749400a4d33cf926e3cb310880866fa8d26e8a6 Mon Sep 17 00:00:00 2001 From: lukellmann <47486203+lukellmann@users.noreply.github.com> Date: Sat, 2 Sep 2023 03:34:15 +0200 Subject: [PATCH] Fix usage of BigInteger in DiscordBitSet.value (#864) DiscordBitSet can only represent positive numbers, so the BigInteger used for getting a decimal representation can be constructed using the sign-magnitude representation instead of the two's-complement binary representation. This fixes two bugs: * DiscordBitSets with an empty data array couldn't be converted to a BigInteger because the constructor taking the two's-complement binary representation throws a NumberFormatException if the given array is empty. This bug was reported by @Tmpod: https://discord.com/channels/556525343595298817/1147254164469063773 * DiscordBitSets with a negative Long at the last position in their data array would be misinterpreted as negative numbers in the conversion to BigIntegers because the two's-complement binary representation was used. Example where this bug could be observed: // printed -9223372036854775808, should be 9223372036854775808 println(DiscordBitSet(1L shl 63).value) --- common/src/commonTest/kotlin/BitSetTests.kt | 27 +++++++++++++++++++ common/src/jvmMain/kotlin/DiscordBitSetJvm.kt | 2 +- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/common/src/commonTest/kotlin/BitSetTests.kt b/common/src/commonTest/kotlin/BitSetTests.kt index 0360bdfdf60..2ff2c4f401c 100644 --- a/common/src/commonTest/kotlin/BitSetTests.kt +++ b/common/src/commonTest/kotlin/BitSetTests.kt @@ -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 { @@ -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..