Skip to content

Commit

Permalink
Fix track id encoding with leading zeros into long
Browse files Browse the repository at this point in the history
  • Loading branch information
0xf4b1 committed May 10, 2024
1 parent f68c419 commit 1376c9f
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/main/kotlin/beatport/api/Utils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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) {
Expand All @@ -42,6 +55,6 @@ object Utils {
}
code = code shr 6
}
return res
return res.padStart(res.length + zeros, '0')
}
}
12 changes: 12 additions & 0 deletions src/test/kotlin/Test.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

0 comments on commit 1376c9f

Please sign in to comment.