Created
June 3, 2017 15:53
-
-
Save williamwebb/8a72750ef1dbe3acfd40d8424d1bae88 to your computer and use it in GitHub Desktop.
kotlin implementation to read Hearthstone Deck Strings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
typealias Cards = Map<Int, Int> | |
data class Deck(val version: Int, val format: Int, val cards: Cards, val heros: List<Int>) | |
fun ByteArrayInputStream.readVarInt() = getVarInt(this) | |
fun decodeDeckString(deckString: String): Deck { | |
val bytes = Base64.decodeBase64(deckString) | |
val byteStream = ByteArrayInputStream(bytes) | |
//Zero byte | |
byteStream.read() | |
//Version - currently unused, always 1 | |
val version = byteStream.readVarInt() | |
//Format - determined dynamically | |
val format = byteStream.readVarInt() | |
//Num Heroes - always 1 | |
val numHeros = byteStream.readVarInt() | |
val heros = IntRange(0, numHeros - 1).map { byteStream.readVarInt() } | |
val cards = HashMap<Int, Int>() | |
// Read Single Cards | |
val singleCardCount = byteStream.readVarInt() | |
repeat(singleCardCount) { | |
val id = byteStream.readVarInt() | |
// add card with quantity of 1 | |
cards.put(id, 1) | |
} | |
// Read Double Cards | |
val doubleCardCount = byteStream.readVarInt() | |
repeat(doubleCardCount) { | |
val id = byteStream.readVarInt() | |
// add card with quantity of 2 | |
cards.put(id, 2) | |
} | |
// Read Multi Cards | |
val multiCardCount = byteStream.readVarInt() | |
repeat(multiCardCount) { | |
val id = byteStream.readVarInt() | |
val count = byteStream.readVarInt() | |
// add card with quantity of count | |
cards.put(id, count) | |
} | |
return Deck(version, format, cards, heros) | |
} | |
@Throws(IOException::class) | |
private fun getVarInt(inputStream: InputStream): Int { | |
var result = 0 | |
var shift = 0 | |
var b: Int | |
do { | |
if (shift >= 32) { | |
// Out of range | |
throw IndexOutOfBoundsException("varint too long") | |
} | |
// Get 7 bits from next byte | |
b = inputStream.read() | |
result = result or (b and 0x7F shl shift) | |
shift += 7 | |
} while (b and 0x80 != 0) | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment