Created
January 9, 2020 12:35
-
-
Save evanxg852000/19852b124dfa8b3e95c0883b7f08746f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
def encode(data, simple_str=False): | |
if isinstance(data, ValueError): | |
return f'-{str(data)}\r\n' | |
elif isinstance(data, str) and simple_str: | |
return f'+{data}\r\n' | |
elif isinstance(data, int): | |
return f':{data}\r\n' | |
elif isinstance(data, str): | |
return f'${len(data)}\r\n{data}\r\n' | |
elif isinstance(data, list) or isinstance(data, tuple): | |
enc = f'*{len(data)}\r\n' | |
for itm in data: | |
enc += encode(itm) | |
return enc | |
def decode(data): | |
marker = data[0] | |
if marker == '-': | |
return str(data[1:-2]) | |
elif marker == '+': | |
return str(data[1:-2]) | |
elif marker == ':': | |
return int(data[1:-2]) | |
elif marker == '$': | |
parts = data[1:].split('\r\n') | |
ln = int(parts[0]) | |
if ln == -1: | |
return None | |
elif ln == 0: | |
return '' | |
else: | |
return str(parts[1]) | |
elif marker == '*': | |
parts = data[1:].split('\r\n') | |
ln = int(parts[0]) | |
items = [None] * ln | |
for i in range(1, 1+ln): | |
items[i-1] = decode(f'{parts[i]}\r\n') | |
return items | |
else: | |
raise Exception('resp decoding error') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment