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