Skip to content

Instantly share code, notes, and snippets.

@pandada8
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pandada8/92dd82fe599537e34196 to your computer and use it in GitHub Desktop.
Save pandada8/92dd82fe599537e34196 to your computer and use it in GitHub Desktop.
Bencode Decode
# Here c refer to content ,p refer to the pointer
# or the length of parsed text
DEBUG = True
decode_func = {}
def print_debug(fn):
def wrapper(c,p):
if DEBUG:
print(fn.__name__)
return fn(c,p)
return wrapper
@print_debug
def decode_int(c,p):
p += 1
end = c.index(b'e',p)
num = int(c[p:end])
if c[p+1] == b'-':
if c[p+2] == b'0':
raise ValueError
num = -num
return num,end+1
@print_debug
def decode_string(c,p):
colon = c.index(b':',p)
length = int(c[p:colon])
string = c[colon+1:colon+1+length]
return string,colon+length+1
@print_debug
def decode_list(c,p):
result = []
p += 1
while c[p] != ord(b'e'):
t,p = decode_func[c[p]](c,p)
result.append(t)
return result,p+1
@print_debug
def decode_dict(c,p):
result = {}
p += 1
while c[p] != ord(b'e'):
key,p = decode_string(c,p)
value,p = decode_func[c[p]](c,p)
result[key] = value
return result,p+1
def decode(c):
p = 0
return decode_func[c[p]](c,p)[0]
decode_func[ord(b'i')] = decode_int
decode_func[ord(b'l')] = decode_list
decode_func[ord(b'd')] = decode_dict
for i in b'0123456789':
decode_func[i] = decode_string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment