Skip to content

Commit

Permalink
Replace magic chars with an enum
Browse files Browse the repository at this point in the history
  • Loading branch information
z------------- committed May 2, 2023
1 parent 2fc5b5e commit 117ee20
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 11 deletions.
8 changes: 5 additions & 3 deletions src/bencode.nim
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,20 @@ when isMainModule:
stderr.writeLine(msg)
quit(code)

proc parseFormatArg(arg: string): char =
proc parseFormatArg(arg: string): BencodeFormat =
if arg.len < 2: die("Invalid argument.")
let c = arg[1]
case c
of 'u', 'd', 'x': c
of 'u': Normal
of 'd': Decimal
of 'x': Hexadecimal
else: die("Invalid format argument '" & arg & "'.")

let (filename, format) = case paramCount()
of 0:
die("Filename required.")
of 1:
(paramStr(1), 'u')
(paramStr(1), Normal)
else:
block:
let fnIdx = if paramStr(1)[0] == '-': 2 else: 1
Expand Down
20 changes: 12 additions & 8 deletions src/bencodepkg/types.nim
Original file line number Diff line number Diff line change
Expand Up @@ -23,32 +23,36 @@ type
l*: seq[BencodeObj]
of bkDict:
d*: OrderedTable[string, BencodeObj]
BencodeFormat* = enum
Normal
Hexadecimal
Decimal

# $ #

func toString*(a: BencodeObj; f = 'u'): string
func toString*(a: BencodeObj; f = Normal): string

func toString(str: string; f = 'u'): string =
func toString(str: string; f = Normal): string =
case f
of 'x': str.map(c => "\\x" & ord(c).toHex(2)).join("")
of 'd': str.map(c => "\\d" & ord(c).`$`.align(4, '0')).join("")
of Hexadecimal: str.map(c => "\\x" & ord(c).toHex(2)).join("")
of Decimal: str.map(c => "\\d" & ord(c).`$`.align(4, '0')).join("")
else: str

func toString(l: seq[BencodeObj]; f = 'u'): string =
func toString(l: seq[BencodeObj]; f = Normal): string =
"@[" & l.map(obj => obj.toString(f)).join(", ") & "]"

func toString(d: OrderedTable[string, BencodeObj]; f = 'u'): string =
func toString(d: OrderedTable[string, BencodeObj]; f = Normal): string =
"{ " & collect(newSeq, for k, v in d.pairs: k.toString(f) & ": " & v.toString(f)).join(", ") & " }"

func toString*(a: BencodeObj; f = 'u'): string =
func toString*(a: BencodeObj; f = Normal): string =
case a.kind
of bkStr: '"' & a.s.toString(f) & '"'
of bkInt: $a.i
of bkList: a.l.toString(f)
of bkDict: a.d.toString(f)

func `$`*(a: BencodeObj): string =
a.toString('u')
a.toString(Normal)

# equality #

Expand Down

0 comments on commit 117ee20

Please sign in to comment.