refactored int codecs to DRY and easy support signed/unsigned values

This commit is contained in:
sergeych committed 2023-03-11 14:35:37 +01:00
1 parent 0f9702b1dc
commit 8fb052c4f9
9 files changed
+148 -108

No files matched your search

+16 -5
View File
@@ -1,16 +1,18 @@
package bintools
import com.icodici.ubdata.Smartint
import com.icodici.ubdata.Varint
import net.sergeych.bintools.decode
import net.sergeych.bintools.encode
import net.sergeych.bintools.encodeToHex
import kotlin.test.Test
import kotlin.test.assertEquals
class SmartintTest {
fun testValue(x: Long) {
assertEquals(x.toULong(), Smartint.decode(Smartint.encode(x.toULong())))
assertEquals(x, Smartint.decodeSigned(Smartint.encodeSigned(x)))
println("+ ${x}: ${Smartint.encode(x.toULong()).encodeToHex()}")
inline fun <reified T:Number>testValue(x: T) {
assertEquals(x, Smartint.decode(Smartint.encode(x)))
println("+ ${x}: ${Smartint.encode(x).encodeToHex()}")
}
fun testAround(bits: Int) {
@@ -19,10 +21,12 @@ class SmartintTest {
var median: Long = (1.toULong() shl bits).toLong()
for( x in (median-2)..(median+2)) {
testValue(x)
testValue(-x)
}
median = median * 3 / 2
for( x in (median-5)..(median+5)) {
testValue(x)
testValue(-x)
}
}
@@ -39,6 +43,13 @@ class SmartintTest {
}
@Test
fun decode() {
fun compareTest() {
for( x in listOf<ULong>(0uL, 1uL, 66uL, 129uL, 219uL, 0x1122uL, 0xFFEEuL, 0xAAbbCCdduL,
0x1111222233334444uL, (1UL shl 63))) {
// 1--12--23--34--4
println("--- $x / 0x${x.encodeToHex(8)}")
println("V: ${Varint.encode(x).encodeToHex()}")
println("S: ${Smartint.encode(x).encodeToHex()}")
}
}
}