]> git.phdru.name Git - extfs.d.git/blob - eff_bdecode.py
Remove update script
[extfs.d.git] / eff_bdecode.py
1 # http://effbot.org/zone/bencode.htm
2 # http://effbot.org/zone/copyright.htm
3 #
4 # Copyright (C) 1995-2013 by Fredrik Lundh
5 #
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:
9 #
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.
17 #
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.
25
26 import re
27
28 def tokenize(text, match=re.compile("([idel])|(\d+):|(-?\d+)").match):
29     i = 0
30     while i < len(text):
31         m = match(text, i)
32         s = m.group(m.lastindex)
33         i = m.end()
34         if m.lastindex == 2:
35             yield "s"
36             yield text[i:i+int(s)]
37             i = i + int(s)
38         else:
39             yield s
40
41 def decode_item(next, token):
42     if token == "i":
43         # integer: "i" value "e"
44         data = int(next())
45         if next() != "e":
46             raise ValueError
47     elif token == "s":
48         # string: "s" value (virtual tokens)
49         data = next()
50     elif token == "l" or token == "d":
51         # container: "l" (or "d") values "e"
52         data = []
53         tok = next()
54         while tok != "e":
55             data.append(decode_item(next, tok))
56             tok = next()
57         if token == "d":
58             data = dict(zip(data[0::2], data[1::2]))
59     else:
60         raise ValueError
61     return data
62
63 def decode(text):
64     try:
65         src = tokenize(text)
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")
71     return data