From 1376c9fe9fb2bb83e241b2443f27ff885f4482d3 Mon Sep 17 00:00:00 2001 From: 0xf4b1 <10889432+0xf4b1@users.noreply.github.com> Date: Fri, 10 May 2024 23:17:06 +0200 Subject: [PATCH] Fix track id encoding with leading zeros into long --- src/main/kotlin/beatport/api/Utils.kt | 15 ++++++++++++++- src/test/kotlin/Test.kt | 12 ++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/main/kotlin/beatport/api/Utils.kt b/src/main/kotlin/beatport/api/Utils.kt index 06554aa..7714dae 100644 --- a/src/main/kotlin/beatport/api/Utils.kt +++ b/src/main/kotlin/beatport/api/Utils.kt @@ -5,7 +5,15 @@ import java.lang.Exception object Utils { fun encode(code: String): Long { var res: Long = 0 + var zeros = 0 + var countZero = true for (i in code.indices) { + if (countZero) { + if (code[i] == '0') + zeros = zeros.inc() + else + countZero = false + } res = res shl 6 res = if (code[i] in '0'..'9') { res or (code[i] - '0').toLong() @@ -21,12 +29,17 @@ object Utils { throw Exception("Unmatched character: ${code[i]}") } } + res = res or (zeros.toLong() shl 60) return res } fun decode(code: Long): String { var code = code var res = "" + val zeros = (code shr 60).toInt() + if (zeros > 0) { + code = code and (15L shl 60).inv() + } while (code > 0) { val cur = code and 63 if (cur < 10) { @@ -42,6 +55,6 @@ object Utils { } code = code shr 6 } - return res + return res.padStart(res.length + zeros, '0') } } \ No newline at end of file diff --git a/src/test/kotlin/Test.kt b/src/test/kotlin/Test.kt index 0e0e21f..1ae9921 100644 --- a/src/test/kotlin/Test.kt +++ b/src/test/kotlin/Test.kt @@ -11,5 +11,17 @@ class Test { val test = "xEmR-uU_Gg" assertEquals(decode(encode(test)), test) } + + @Test + fun testEncodeDecodeLeadingZeros() { + var test = "0foobarbaz" + assertEquals(decode(encode(test)), test) + test = "00foobarba" + assertEquals(decode(encode(test)), test) + test = "0000foobar" + assertEquals(decode(encode(test)), test) + test = "0000000foo" + assertEquals(decode(encode(test)), test) + } }