-
Notifications
You must be signed in to change notification settings - Fork 0
/
bencode.py
47 lines (44 loc) · 1.15 KB
/
bencode.py
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
import re
decimal_match = re.compile(r'\d')
def bdecode(data):
'''Main function to decode bencoded data'''
chunks = list(data)
chunks.reverse()
root = _dechunk(chunks)
return root
def _dechunk(chunks):
item = chunks.pop()
if item == 'd':
item = chunks.pop()
hash = {}
while item != 'e':
chunks.append(item)
key = _dechunk(chunks)
hash[key] = _dechunk(chunks)
item = chunks.pop()
return hash
elif item == 'l':
item = chunks.pop()
list = []
while item != 'e':
chunks.append(item)
list.append(_dechunk(chunks))
item = chunks.pop()
return list
elif item == 'i':
item = chunks.pop()
num = ''
while item != 'e':
num += item
item = chunks.pop()
return int(num)
elif decimal_match.search(item):
num = ''
while decimal_match.search(item):
num += item
item = chunks.pop()
line = ''
for i in range(int(num)):
line += chunks.pop()
return line
raise 'Invalid input!'