1 # http://effbot.org/zone/bencode.htm
2 # http://effbot.org/zone/copyright.htm
4 # Copyright (C) 1995-2013 by Fredrik Lundh
6 # By obtaining, using, and/or copying this software and/or its associated
7 # documentation, you agree that you have read, understood, and will comply with
8 # the following terms and conditions:
10 # Permission to use, copy, modify, and distribute this software and its
11 # associated documentation for any purpose and without fee is hereby granted,
12 # provided that the above copyright notice appears in all copies, and that both
13 # that copyright notice and this permission notice appear in supporting
14 # documentation, and that the name of Secret Labs AB or the author not be used
15 # in advertising or publicity pertaining to distribution of the software
16 # without specific, written prior permission.
18 # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
19 # SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
20 # NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR ANY SPECIAL,
21 # INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
22 # LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
23 # OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
24 # PERFORMANCE OF THIS SOFTWARE.
28 def tokenize(text, match=re.compile("([idel])|(\d+):|(-?\d+)").match):
32 s = m.group(m.lastindex)
36 yield text[i:i+int(s)]
41 def decode_item(next, token):
43 # integer: "i" value "e"
48 # string: "s" value (virtual tokens)
50 elif token == "l" or token == "d":
51 # container: "l" (or "d") values "e"
55 data.append(decode_item(next, tok))
58 data = dict(zip(data[0::2], data[1::2]))
66 data = decode_item(src.next, src.next())
67 for token in src: # look for more tokens
68 raise SyntaxError("trailing junk")
69 except (AttributeError, ValueError, StopIteration):
70 raise SyntaxError("syntax error")