Created
September 4, 2010 16:01
-
-
Save itsbth/565287 to your computer and use it in GitHub Desktop.
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
''' | |
Created on 3. sep. 2010 | |
@author: itsbth | |
''' | |
import re | |
_ESCAPE_STRING_RE = re.compile('([\1\2])') | |
def encode(data): | |
t = type(data) | |
if t == unicode: | |
data = data.encode('latin_1') | |
t = str | |
if t == str: | |
return '\7' + _ESCAPE_STRING_RE.sub("\1\\1", data) + '\1' | |
if t == int or t == float: | |
return '\6' + str(data) + '\1' | |
if t == list or t == tuple: | |
buff = ['\3'] | |
for item in data: | |
buff.append(encode(item)) | |
buff.append('\1') | |
return ''.join(buff) | |
if t == dict: | |
buff = ['\2'] | |
for k, v in data.items(): | |
buff.append(encode(k)) | |
buff.append(encode(v)) | |
buff.append('\1') | |
return ''.join(buff) | |
if t == bool: | |
return '\5' if data else '\4' | |
return '\7<unk(%s)>\1' % t |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment