All pastes #821255 Raw Edit

Python bencode/decode

public python v1 · immutable
·published 2007-12-18 00:24 UTC
rendered paste body
def encode(arg):    ''' Given that we're converting between variable formats,        manual typechecking seems excusable here '''    return {        int : lambda x: 'i%ie' % x,        str : lambda x: '%i:%s' % (len(x), x),        list : lambda x: 'l%se' % ''.join(map(encode, arg)),        dict : lambda x: 'd%se' % ''.join(''.join(map(encode, i)) for i in arg.items())    }[type(arg)](arg)def _eat_str(s):    length,s = s.split(':', 1)    length = int(length)    return (s[:length], s[length:])def _eat_int(s):    val, s = s.split('e', 1)    return int(val), sdef _eat_list(s):    r = []    while s[0] is not 'e':        val, s = _eat_all(s)        r.append(val)    return r, s[1:]def _eat_dict(s):    r = {}    while s[0] is not 'e':        k,s = _eat_all(s)        v,s = _eat_all(s)                r[k] = v    return r, s[1:]    def _eat_all(s):    if s[0] in 'lid':        val, s = {'l': _eat_list,         'i': _eat_int,         'd': _eat_dict}[s[0]](s[1:])    else:        val, s = _eat_str(s)    if len(s):        return (val, s)    return valdef decode(s):    try:        val = _eat_all(s)        if type(val) is tuple:            #should NOT be a tuple, _eat_all would only return a list, dict,            #or scalar            raise ValueError, val[1]        return val    except ValueError, e:        raise ValueError, 'Error somewhere in "%s"' % e