Skip to content

Add converters #2

Open
Open
@batyrmastyr

Description

@batyrmastyr

I propose to add several converters to make code more readable.

Having this

converter toBencodeType(s: string) : BencodeType {.inline} =
 return BencodeType(kind: btString, s: s)
converter toBencodeType(i: int) : BencodeType {.inline} =
 return BencodeType(kind: btInt, i: i)
converter toBencodeType(seq: seq[BencodeType]) : BencodeType {.inline} =
 return BencodeType(kind: btList, l: seq)
converter toBencodeType(t: OrderedTable[BencodeType, BencodeType]) : BencodeType {.inline} =
 return BencodeType(kind: btDict, d: t)

will allow to rewrite

var btDictSample1 = initOrderedTable[BencodeType, BencodeType]()
btDictSample1[BencodeType(kind:btString, s:"name")] = BencodeType(kind:btString, s:"dmdm")
btDictSample1[BencodeType(kind:btString, s:"lang")] = BencodeType(kind:btString, s:"nim")
btDictSample1[BencodeType(kind:btString, s:"age")] = BencodeType(kind:btInt, i:50)
btDictSample1[BencodeType(kind:btString, s:"alist")] = BencodeType(kind:btList, l:btListSample1)

var testObjects = initOrderedTable[BencodeType, string]()
testObjects[BencodeType(kind: btInt, i:12345)] = "i12345e"
testObjects[BencodeType(kind: btList, l:btListSample1)] = "li1e2:hie"
testObjects[BencodeType(kind:btDict, d:btDictSample1)] = "d4:name4:dmdm4:lang3:nim3:agei50e5:alistli1e2:hiee"

in more compact way:

var btDictSample1 = initOrderedTable[BencodeType, BencodeType]()
btDictSample1["name"] = "dmdm"
btDictSample1["lang"] = "nim"
btDictSample1["age"] = 50
btDictSample1["alist"] = btListSample1

var testObjects = initOrderedTable[BencodeType, string]()
testObjects[12345] = "i12345e"
testObjects[btListSample1] = "li1e2:hie"
testObjects[btDictSample1] = "d4:name4:dmdm4:lang3:nim3:agei50e5:alistli1e2:hiee"

Well, the last two are quite code-specific, but it's better to have int and string converters out of the box.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions