-
Notifications
You must be signed in to change notification settings - Fork 0
/
readbabashkainput.nim
73 lines (65 loc) · 1.54 KB
/
readbabashkainput.nim
1
2
3
4
5
6
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
39
40
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
import strutils, tables
type
BKind = enum Int, String, List, Dict
B* = object
case kind*: BKind:
of Int:
i*: int
of String:
s*: string
of List:
l*: seq[B]
of Dict:
d*: Table[string, B]
proc bdecode(start: char): B
proc bdecodeInt(): B =
var s = ""
while true:
let c = stdin.readChar
if c == 'e':
break
s.add($c)
return B(kind: Int, i: parseInt(s))
proc bdecodeDict(): B =
var d = initTable[string, B]()
while true:
let c = stdin.readChar
if c == 'e':
break
let key = bdecode(c)
let value = bdecode(stdin.readChar)
d[key.s] = value # key is expected to be of kind String
return B(kind: Dict, d: d)
proc bdecodeList(): B =
var l = newSeq[B]()
while true:
let c = stdin.readChar
if c == 'e':
break
l.add(bdecode(c))
return B(kind: List, l: l)
proc bdecodeString(start: char): B =
var len = $start
while true:
let c = stdin.readChar
case c:
of ':':
break
else: # one of '0' '1' '2' '3' '4' '5' '6' '7' '8' '9'
len.add($c)
var s = ""
for i in 1..parseInt(len):
s.add($stdin.readChar)
return B(kind: String, s: s)
proc bdecode(start: char): B =
case start:
of 'i':
return bdecodeInt()
of 'd':
return bdecodeDict()
of 'l':
return bdecodeList()
else: # one of '0' '1' '2' '3' '4' '5' '6' '7' '8' '9'
return bdecodeString(start)
proc readInput*(): B =
return bdecode(stdin.readChar)