|
12 | 12 |
|
13 | 13 | # Based on https://github.com/karamanolev/bencode3/blob/master/bencode.py |
14 | 14 |
|
| 15 | +import sys |
| 16 | +IS_PY2 = sys.version[0] == '2' |
| 17 | + |
| 18 | +if IS_PY2: |
| 19 | + END_CHAR = 'e' |
| 20 | +else: |
| 21 | + END_CHAR = ord('e') |
| 22 | + |
| 23 | + |
15 | 24 | class BTFailure(Exception): |
16 | 25 | pass |
17 | 26 |
|
@@ -39,42 +48,42 @@ def decode_string(bytes x, int f): |
39 | 48 |
|
40 | 49 | def decode_list(bytes x, int f): |
41 | 50 | r, f = [], f + 1 |
42 | | - while x[f] != ord('e'): |
| 51 | + while x[f] != END_CHAR: |
43 | 52 | v, f = decode_func[x[f]](x, f) |
44 | 53 | r.append(v) |
45 | 54 | return r, f + 1 |
46 | 55 |
|
47 | 56 |
|
48 | 57 | def decode_dict(bytes x, int f): |
49 | 58 | r, f = {}, f + 1 |
50 | | - while x[f] != ord('e'): |
| 59 | + while x[f] != END_CHAR: |
51 | 60 | k, f = decode_string(x, f) |
52 | 61 | r[k], f = decode_func[x[f]](x, f) |
53 | 62 | return r, f + 1 |
54 | 63 |
|
55 | 64 |
|
56 | | -decode_func = { |
57 | | - ord('l'): decode_list, |
58 | | - ord('d'): decode_dict, |
59 | | - ord('i'): decode_int, |
60 | | - ord('1'): decode_string, |
61 | | - ord('2'): decode_string, |
62 | | - ord('0'): decode_string, |
63 | | - ord('3'): decode_string, |
64 | | - ord('4'): decode_string, |
65 | | - ord('5'): decode_string, |
66 | | - ord('6'): decode_string, |
67 | | - ord('7'): decode_string, |
68 | | - ord('8'): decode_string, |
69 | | - ord('9'): decode_string, |
70 | | -} |
| 65 | +decode_func = dict() |
| 66 | + |
| 67 | +for func, keys in [ |
| 68 | + (decode_list, 'l'), |
| 69 | + (decode_dict, 'd'), |
| 70 | + (decode_int, 'i'), |
| 71 | + (decode_string, [str(x) for x in range(10)]) |
| 72 | +]: |
| 73 | + for key in keys: |
| 74 | + if IS_PY2: |
| 75 | + decode_func[key] = func |
| 76 | + else: |
| 77 | + decode_func[ord(key)] = func |
| 78 | + |
71 | 79 |
|
72 | 80 |
|
73 | 81 | def bdecode(bytes x): |
74 | 82 | try: |
75 | 83 | r, l = decode_func[x[0]](x, 0) |
76 | | - except (IndexError, KeyError, ValueError): |
77 | | - raise BTFailure("not a valid bencoded string") |
| 84 | + except (IndexError, KeyError, ValueError) as e: |
| 85 | + raise e |
| 86 | +# raise BTFailure("not a valid bencoded string") |
78 | 87 | if l != len(x): |
79 | 88 | raise BTFailure("invalid bencoded value (data after valid prefix)") |
80 | 89 | return r |
|
0 commit comments