From b193d874990e8c572719346e352a2b48c48de723 Mon Sep 17 00:00:00 2001 From: Calum Lind Date: Mon, 3 Feb 2014 13:37:22 +0000 Subject: [PATCH] Include small upstream bencode fix and flake8 file --- deluge/bencode.py | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/deluge/bencode.py b/deluge/bencode.py index e61f2bf0c..a17ce918e 100644 --- a/deluge/bencode.py +++ b/deluge/bencode.py @@ -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)