-
Notifications
You must be signed in to change notification settings - Fork 0
/
bencode.py
118 lines (83 loc) · 2.87 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
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import re
from pprint import pprint
class Bencode:
def __init__(self, str):
self.data = str
self.idx = 0
def decode(self):
'''
Treat the byte string self.data as bencoded
and decode it
'''
if self.idx >= len(self.data):
raise IndexError
if self.data[self.idx] in b'0123456789':
'''
String
'''
strlen = (re.search(b"^\d+", self.data[self.idx:])).group()
self.idx += (len(strlen)+1) # 1 is for the :
to_ret = self.data[self.idx: self.idx + int(strlen)]
self.idx += int(strlen)
try:
to_ret = to_ret.decode()
except UnicodeDecodeError:
pass
return to_ret
elif self.data[self.idx] == (b'i')[0]:
'''
Int
'''
self.idx += 1
strint = re.search(b"^-?\d+", self.data[self.idx:]).group()
self.idx += len(strint)
if self.data[self.idx] != (b'e')[0]:
raise ValueError("Input Not Correct")
self.idx += 1
return int(strint)
elif self.data[self.idx] == (b'l')[0]:
'''
List
'''
l = []
self.idx += 1
while self.data[self.idx] != (b'e')[0]:
l.append(self.decode())
self.idx += 1
return l
elif self.data[self.idx] == (b'd')[0]:
'''
Dictionary
'''
d = {}
self.idx += 1
while self.data[self.idx] != (b'e')[0]:
getnextkey = self.decode()
getnextval = self.decode()
d[getnextkey] = getnextval
self.idx += 1
return d
else:
raise ValueError("This is not a valid bencoded string")
def encode(self):
if isinstance(self.data, int):
return b"i" + str(self.data).encode() + b"e"
elif isinstance(self.data, str):
return (str(len(self.data)) + ':' + self.data).encode()
elif isinstance(self.data, list):
to_ret = b"l"
for elem in self.data:
to_ret += Bencode(elem).encode()
to_ret += b"e"
elif isinstance(self.data, dict):
to_ret = b"d"
for k,v in self.data.items():
to_ret += Bencode(k).encode()
to_ret += Bencode(v).encode()
to_ret += b"e"
elif isinstance(self.data, bytes):
return str(len(self.data)).encode() + b':' + self.data
else:
print(self.data)
raise ValueError('Cant B Encode Data')
return to_ret