Include small upstream bencode fix and flake8 file

This commit is contained in:
Calum Lind 2014-02-03 13:37:22 +00:00
parent d9ce4ff634
commit b193d87499
1 changed files with 16 additions and 2 deletions

View File

@ -12,6 +12,7 @@
# Minor modifications made by Andrew Resch to replace the BTFailure errors with Exceptions
def decode_int(x, f):
f += 1
newf = x.index('e', f)
@ -23,6 +24,7 @@ def decode_int(x, f):
raise ValueError
return (n, newf+1)
def decode_string(x, f):
colon = x.index(':', f)
n = int(x[f:colon])
@ -31,6 +33,7 @@ def decode_string(x, f):
colon += 1
return (x[colon:colon+n], colon+n)
def decode_list(x, f):
r, f = [], f+1
while x[f] != 'e':
@ -38,6 +41,7 @@ def decode_list(x, f):
r.append(v)
return (r, f + 1)
def decode_dict(x, f):
r, f = {}, f+1
while x[f] != 'e':
@ -60,11 +64,14 @@ decode_func['7'] = decode_string
decode_func['8'] = decode_string
decode_func['9'] = decode_string
def bdecode(x):
try:
r, l = decode_func[x[0]](x, 0)
except (IndexError, KeyError, ValueError):
raise Exception("not a valid bencoded string")
if l != len(x):
raise Exception("invalid bencoded value (data after valid prefix)")
return r
@ -78,28 +85,34 @@ class Bencached(object):
def __init__(self, s):
self.bencoded = s
def encode_bencached(x,r):
def encode_bencached(x, r):
r.append(x.bencoded)
def encode_int(x, r):
r.extend(('i', str(x), 'e'))
def encode_bool(x, r):
if x:
encode_int(1, r)
else:
encode_int(0, r)
def encode_string(x, r):
r.extend((str(len(x)), ':', x))
def encode_list(x, r):
r.append('l')
for i in x:
encode_func[type(i)](i, r)
r.append('e')
def encode_dict(x,r):
def encode_dict(x, r):
r.append('d')
ilist = x.items()
ilist.sort()
@ -123,6 +136,7 @@ try:
except ImportError:
pass
def bencode(x):
r = []
encode_func[type(x)](x, r)