Encoder.kt 1.7 KB
Newer Older
Kevin Cianfarini's avatar
Kevin Cianfarini committed
1 2 3
package com.corbit.bencoding

import com.corbit.binary.BinaryString
4
import com.corbit.binary.BinaryStringBuilder
Kevin Cianfarini's avatar
Kevin Cianfarini committed
5 6
import com.corbit.binary.asBinaryString
import com.corbit.binary.buildBinaryString
Kevin Cianfarini's avatar
Kevin Cianfarini committed
7 8 9

internal class Encoder(private val source: BencodedData) {

10 11 12
    fun encode(): BinaryString = buildBinaryString {
        encodeValue(source, this)
    }
Kevin Cianfarini's avatar
Kevin Cianfarini committed
13

14 15 16 17 18 19 20
    private fun encodeValue(value: BencodedData, builder: BinaryStringBuilder) {
        when (value) {
            is BencodedInt -> encodeInt(value, builder)
            is BencodedString -> encodeString(value, builder)
            is BencodedList -> encodeList(value, builder)
            is BencodedDict -> encodeDict(value, builder)
        }
Kevin Cianfarini's avatar
Kevin Cianfarini committed
21 22
    }

23
    private fun encodeInt(data: BencodedInt, builder: BinaryStringBuilder) = with(builder) {
Kevin Cianfarini's avatar
Kevin Cianfarini committed
24 25 26 27 28
        append(BencoderToken.INTEGER.token)
        append(data.value.toString().asBinaryString())
        append(BencoderToken.END.token)
    }

29
    private fun encodeString(data: BencodedString, builder: BinaryStringBuilder) = with(builder) {
Kevin Cianfarini's avatar
Kevin Cianfarini committed
30 31 32 33 34
        append(data.value.size.toString().asBinaryString())
        append(BencoderToken.STRING_SEPARATOR.token)
        append(data.value)
    }

35
    private fun encodeList(data: BencodedList, builder: BinaryStringBuilder) = with(builder) {
Kevin Cianfarini's avatar
Kevin Cianfarini committed
36
        append(BencoderToken.LIST.token)
37
        data.forEach { encodeValue(it, builder) }
Kevin Cianfarini's avatar
Kevin Cianfarini committed
38 39 40
        append(BencoderToken.END.token)
    }

41
    private fun encodeDict(data: BencodedDict, builder: BinaryStringBuilder) = with(builder) {
Kevin Cianfarini's avatar
Kevin Cianfarini committed
42 43 44
        append(BencoderToken.DICT.token)

        data.forEach { (key, value) ->
45 46
            encodeValue(key, builder)
            encodeValue(value, builder)
Kevin Cianfarini's avatar
Kevin Cianfarini committed
47 48 49 50
        }

        append(BencoderToken.END.token)
    }
Kevin Cianfarini's avatar
Kevin Cianfarini committed
51
}