Decoder.kt 2.42 KB
Newer Older
Kevin Cianfarini's avatar
Kevin Cianfarini committed
1 2 3 4
package com.corbit.bencoding

import com.corbit.binary.BinaryString
import com.corbit.binary.slice
5 6
import com.ionspin.kotlin.bignum.integer.BigInteger
import com.ionspin.kotlin.bignum.integer.toBigInteger
Kevin Cianfarini's avatar
Kevin Cianfarini committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38

internal class Decoder(private val source: BinaryString) {

    private var index: Int = 0
    private val nextByte: Byte get() = source[index]

    fun decode(): BencodedData = when (BencoderToken.fromToken(nextByte)) {
        BencoderToken.INTEGER -> decodeInteger()
        BencoderToken.STRING -> decodeString()
        BencoderToken.LIST -> decodeList()
        BencoderToken.DICT -> decodeDictionary()
        else -> error("Tried to parse from $nextByte")
    }

    private fun read(numBytes: Int): BinaryString = if (numBytes > 0) {
        source.slice(index, index + numBytes - 1).also { index += numBytes }
    } else {
        BinaryString.EMPTY
    }

    private fun readToNextToken(token: BencoderToken): BinaryString {
        val slice = source.slice(startIndex = index)

        return source.slice(
            startIndex = index,
            endIndex = index + slice.indexOf(token.token.first())
        ).also {
            index += it.size
        }
    }

    private fun decodeInteger(): BencodedInt {
39 40
        val value: BigInteger = readToNextToken(BencoderToken.END).run {
            slice(1, size - 2).utf8.toBigInteger()
Kevin Cianfarini's avatar
Kevin Cianfarini committed
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
        }

        return BencodedInt(value)
    }

    private fun decodeString(): BencodedString {
        val stringLength = readToNextToken(BencoderToken.STRING_SEPARATOR).run {
            slice(endIndex = size - 2).utf8.toInt()
        }

        return BencodedString(read(stringLength))
    }

    private fun decodeList(): BencodedList {
        readToNextToken(BencoderToken.LIST) // read and discard

        val list: MutableList<BencodedData> = mutableListOf()
        while (BencoderToken.fromToken(nextByte) != BencoderToken.END) {
            list.add(decode())
        }

        readToNextToken(BencoderToken.END) // read and discard
        return BencodedList(list)
    }

    private fun decodeDictionary(): BencodedDict {
        readToNextToken(BencoderToken.DICT) // read and discard

        val dict: MutableMap<BencodedString, BencodedData> = mutableMapOf()
        while (BencoderToken.fromToken(nextByte) != BencoderToken.END) {
            dict[decodeString()] = decode()
        }

        readToNextToken(BencoderToken.END) // read and discard
        return BencodedDict(dict)
    }
}