Last active
August 7, 2018 17:52
-
-
Save pgergis/b17d1c8c5051adf73abbcfb773419f27 to your computer and use it in GitHub Desktop.
bencode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import io | |
def _str_decode(fd, str_len): | |
len_digits = [str(str_len)] | |
char = fd.read(1) | |
while char != ':': | |
len_digits.append(char) | |
char = fd.read(1) | |
try: | |
str_len = int(''.join(len_digits)) | |
except ValueError: | |
print(f"Malformed bencode str: {''.join(len_digits)}") | |
return fd.read(str_len) | |
def _int_decode(fd): | |
num_digits = [] | |
char = fd.read(1) | |
while char and char != 'e': | |
num_digits.append(char) | |
char = fd.read(1) | |
try: | |
num = int(''.join(num_digits)) | |
return num | |
except ValueError: | |
print(f"Malformed bencode int: {str_num}") | |
def _list_decode(fd): | |
be_list = [] | |
e = decode(fd) | |
while e: | |
be_list.append(e) | |
e = decode(fd) | |
return be_list | |
def _dict_decode(fd): | |
be_dict = {} | |
key = "" | |
value = "" | |
while not key or not value: | |
if key: | |
value = decode(fd) | |
be_dict[key] = value | |
key = "" | |
value = "" | |
else: | |
key = decode(fd) | |
if not key: | |
return be_dict | |
def decode(fd): | |
char = fd.read(1) | |
if char == 'i': | |
return _int_decode(fd) | |
elif char == 'l': | |
return _list_decode(fd) | |
elif char == 'd': | |
return _dict_decode(fd) | |
elif char == 'e': | |
return '' | |
elif char == '': | |
return '' | |
else: | |
try: | |
strlen = int(char) | |
return _str_decode(fd, strlen) | |
except ValueError: | |
print(f"Malformed bencode input: {char}") | |
def filename_decode(filename): | |
with open(filename, 'r', encoding='latin1') as f: | |
s = f.read() | |
return string_decode(s) | |
def string_decode(string): | |
with io.StringIO(string) as s: | |
result = decode(s) | |
return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment