Overview

HunnyB (de|en)coder

HunnyB implements the bencode encoding/decoding originally created by Petru Paler for use in the guts of BitTorrent, brainchild of Bram Cohen.

>>> import hunnyb

Import of the hunnyb module will register the encode/decode functions with the standard library codecs module, meaning strings may be encoded in one of the following ways:

>>> "foobaz hambones".encode('hunnyb')
'15:foobaz hambones'
>>> "foobaz hambones".encode('hb')
'15:foobaz hambones'
>>> "foobaz hambones".encode('bencode')
'15:foobaz hambones'
>>> "foobaz hambones".encode('b')
'15:foobaz hambones'

Likewise, bencoded strings may be decoded, although the result will always be a string (a requirement of codecs), meaning one will have to eval() said result if not of string type.

>>> enc_str = "ForkingHam BIZZYBONE RazzMATAZZ".encode('hb')
>>> print enc_str
31:ForkingHam BIZZYBONE RazzMATAZZ
>>> enc_str.decode('hb')
'ForkingHam BIZZYBONE RazzMATAZZ'
>>> enc_dict = hunnyb.encode({'foo': 99000, 0: [99, 8, 'bobob']})
>>> print enc_dict
d1:0li99ei8e5:bobobe3:fooi99000ee
>>> enc_dict.decode('bencode')
"{'0': [99, 8, 'bobob'], 'foo': 99000}"

Alternatively, the encode and decode functions available in hunnyb may be used directly, with decoding always returning a given object's Python equivalent.

>>> hunnyb.decode(enc_dict)
{'0': [99, 8, 'bobob'], 'foo': 99000}