bzr branch
http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
| 
2694.5.8
by Jelmer Vernooij
 Use standard infrastructure for testing python and pyrex bencode implementations.  | 
1  | 
# Copyright (C) 2007,2009 Canonical Ltd
 | 
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
2  | 
#
 | 
3  | 
# This program is free software; you can redistribute it and/or modify
 | 
|
4  | 
# it under the terms of the GNU General Public License as published by
 | 
|
5  | 
# the Free Software Foundation; either version 2 of the License, or
 | 
|
6  | 
# (at your option) any later version.
 | 
|
7  | 
#
 | 
|
8  | 
# This program is distributed in the hope that it will be useful,
 | 
|
9  | 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 | 
|
10  | 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 | 
|
11  | 
# GNU General Public License for more details.
 | 
|
12  | 
#
 | 
|
13  | 
# You should have received a copy of the GNU General Public License
 | 
|
14  | 
# along with this program; if not, write to the Free Software
 | 
|
| 
4398.5.20
by John Arbash Meinel
 Fix the GPL header  | 
15  | 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 | 
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
16  | 
|
17  | 
"""Pyrex implementation for bencode coder/decoder"""
 | 
|
18  | 
||
19  | 
||
| 
2694.5.20
by Jelmer Vernooij
 add handling of deep nesting.  | 
20  | 
cdef extern from "stddef.h":  | 
21  | 
ctypedef unsigned int size_t  | 
|
22  | 
||
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
23  | 
cdef extern from "Python.h":  | 
24  | 
ctypedef int Py_ssize_t  | 
|
25  | 
int PyInt_CheckExact(object o)  | 
|
26  | 
int PyLong_CheckExact(object o)  | 
|
27  | 
int PyString_CheckExact(object o)  | 
|
28  | 
int PyTuple_CheckExact(object o)  | 
|
29  | 
int PyList_CheckExact(object o)  | 
|
30  | 
int PyDict_CheckExact(object o)  | 
|
31  | 
int PyBool_Check(object o)  | 
|
32  | 
object PyString_FromStringAndSize(char *v, Py_ssize_t len)  | 
|
| 
2694.5.12
by Jelmer Vernooij
 Avoid using snprintf for strings, use memcpy instead.  | 
33  | 
char *PyString_AS_STRING(object o) except NULL  | 
34  | 
Py_ssize_t PyString_GET_SIZE(object o) except -1  | 
|
| 
2694.5.17
by Jelmer Vernooij
 Avoid using malloc in the inner loop.  | 
35  | 
object PyInt_FromString(char *str, char **pend, int base)  | 
| 
2694.5.20
by Jelmer Vernooij
 add handling of deep nesting.  | 
36  | 
int Py_GetRecursionLimit()  | 
37  | 
int Py_EnterRecursiveCall(char *)  | 
|
38  | 
void Py_LeaveRecursiveCall()  | 
|
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
39  | 
|
| 
4398.5.12
by John Arbash Meinel
 One of the biggest wins to date, use PyList_Append directly.  | 
40  | 
int PyList_Append(object, object) except -1  | 
41  | 
||
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
42  | 
cdef extern from "stdlib.h":  | 
43  | 
void free(void *memblock)  | 
|
44  | 
void *malloc(size_t size)  | 
|
45  | 
void *realloc(void *memblock, size_t size)  | 
|
| 
2694.5.16
by Jelmer Vernooij
 Simplify the code a bit more.  | 
46  | 
long strtol(char *, char **, int)  | 
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
47  | 
|
48  | 
cdef extern from "string.h":  | 
|
49  | 
void *memcpy(void *dest, void *src, size_t count)  | 
|
50  | 
||
| 
2694.5.11
by Jelmer Vernooij
 Use global python-compat.  | 
51  | 
cdef extern from "python-compat.h":  | 
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
52  | 
int snprintf(char* buffer, size_t nsize, char* fmt, ...)  | 
53  | 
||
| 
4398.5.13
by John Arbash Meinel
 We don't need a base Coder class, because Decoder._update_tail is different than Encoder._update_tail.  | 
54  | 
cdef class Decoder  | 
55  | 
cdef class Encoder  | 
|
| 
4398.5.10
by John Arbash Meinel
 Move self._update_tail into a macro for UPDATE_TAIL.  | 
56  | 
|
57  | 
cdef extern from "_bencode_pyx.h":  | 
|
| 
4398.5.13
by John Arbash Meinel
 We don't need a base Coder class, because Decoder._update_tail is different than Encoder._update_tail.  | 
58  | 
void D_UPDATE_TAIL(Decoder, int n)  | 
59  | 
void E_UPDATE_TAIL(Encoder, int n)  | 
|
60  | 
||
| 
4679.8.15
by John Arbash Meinel
 Use the relative import of '_static_tuple_c.pxd' to handle old pyrex versions.  | 
61  | 
# To maintain compatibility with older versions of pyrex, we have to use the
 | 
62  | 
# relative import here, rather than 'bzrlib._static_tuple_c'
 | 
|
63  | 
from _static_tuple_c cimport StaticTuple, StaticTuple_CheckExact, \  | 
|
| 
4679.8.10
by John Arbash Meinel
 quick patch to allow bencode to handle StaticTuple objects.  | 
64  | 
    import_static_tuple_c
 | 
65  | 
||
66  | 
import_static_tuple_c()  | 
|
67  | 
||
| 
4398.5.13
by John Arbash Meinel
 We don't need a base Coder class, because Decoder._update_tail is different than Encoder._update_tail.  | 
68  | 
|
69  | 
cdef class Decoder:  | 
|
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
70  | 
"""Bencode decoder"""  | 
71  | 
||
| 
4398.5.13
by John Arbash Meinel
 We don't need a base Coder class, because Decoder._update_tail is different than Encoder._update_tail.  | 
72  | 
cdef readonly char *tail  | 
73  | 
cdef readonly int size  | 
|
| 
2694.5.20
by Jelmer Vernooij
 add handling of deep nesting.  | 
74  | 
cdef readonly int _yield_tuples  | 
| 
2694.5.21
by Jelmer Vernooij
 Review feedback from Alexander.  | 
75  | 
cdef object text  | 
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
76  | 
|
| 
2694.5.5
by Jelmer Vernooij
 Support bdecode_as_tuple.  | 
77  | 
def __init__(self, s, yield_tuples=0):  | 
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
78  | 
"""Initialize decoder engine.  | 
79  | 
        @param  s:  Python string.
 | 
|
80  | 
        """
 | 
|
81  | 
if not PyString_CheckExact(s):  | 
|
| 
2694.5.9
by Jelmer Vernooij
 Fix tests.  | 
82  | 
raise TypeError("String required")  | 
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
83  | 
|
| 
2694.5.21
by Jelmer Vernooij
 Review feedback from Alexander.  | 
84  | 
self.text = s  | 
| 
2694.5.12
by Jelmer Vernooij
 Avoid using snprintf for strings, use memcpy instead.  | 
85  | 
self.tail = PyString_AS_STRING(s)  | 
86  | 
self.size = PyString_GET_SIZE(s)  | 
|
| 
2694.5.5
by Jelmer Vernooij
 Support bdecode_as_tuple.  | 
87  | 
self._yield_tuples = int(yield_tuples)  | 
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
88  | 
|
89  | 
def decode(self):  | 
|
| 
4398.5.11
by John Arbash Meinel
 Turn Decoder.decode_object into _decode_object.  | 
90  | 
result = self._decode_object()  | 
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
91  | 
if self.size != 0:  | 
92  | 
raise ValueError('junk in stream')  | 
|
93  | 
return result  | 
|
94  | 
||
95  | 
def decode_object(self):  | 
|
| 
4398.5.11
by John Arbash Meinel
 Turn Decoder.decode_object into _decode_object.  | 
96  | 
return self._decode_object()  | 
97  | 
||
98  | 
cdef object _decode_object(self):  | 
|
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
99  | 
cdef char ch  | 
100  | 
||
101  | 
if 0 == self.size:  | 
|
102  | 
raise ValueError('stream underflow')  | 
|
103  | 
||
| 
4398.5.11
by John Arbash Meinel
 Turn Decoder.decode_object into _decode_object.  | 
104  | 
if Py_EnterRecursiveCall("_decode_object"):  | 
| 
2694.5.20
by Jelmer Vernooij
 add handling of deep nesting.  | 
105  | 
raise RuntimeError("too deeply nested")  | 
106  | 
try:  | 
|
107  | 
ch = self.tail[0]  | 
|
| 
4398.5.14
by John Arbash Meinel
 Some small tweaks to decoding strings (avoid passing over the length 2x)  | 
108  | 
if c'0' <= ch <= c'9':  | 
| 
2694.5.20
by Jelmer Vernooij
 add handling of deep nesting.  | 
109  | 
return self._decode_string()  | 
110  | 
elif ch == c'l':  | 
|
| 
4398.5.13
by John Arbash Meinel
 We don't need a base Coder class, because Decoder._update_tail is different than Encoder._update_tail.  | 
111  | 
D_UPDATE_TAIL(self, 1)  | 
| 
2694.5.20
by Jelmer Vernooij
 add handling of deep nesting.  | 
112  | 
return self._decode_list()  | 
| 
4398.5.14
by John Arbash Meinel
 Some small tweaks to decoding strings (avoid passing over the length 2x)  | 
113  | 
elif ch == c'i':  | 
114  | 
D_UPDATE_TAIL(self, 1)  | 
|
115  | 
return self._decode_int()  | 
|
| 
2694.5.20
by Jelmer Vernooij
 add handling of deep nesting.  | 
116  | 
elif ch == c'd':  | 
| 
4398.5.13
by John Arbash Meinel
 We don't need a base Coder class, because Decoder._update_tail is different than Encoder._update_tail.  | 
117  | 
D_UPDATE_TAIL(self, 1)  | 
| 
2694.5.20
by Jelmer Vernooij
 add handling of deep nesting.  | 
118  | 
return self._decode_dict()  | 
119  | 
else:  | 
|
120  | 
raise ValueError('unknown object type identifier %r' % ch)  | 
|
121  | 
finally:  | 
|
122  | 
Py_LeaveRecursiveCall()  | 
|
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
123  | 
|
| 
2694.5.17
by Jelmer Vernooij
 Avoid using malloc in the inner loop.  | 
124  | 
cdef int _read_digits(self, char stop_char) except -1:  | 
125  | 
cdef int i  | 
|
| 
2694.5.16
by Jelmer Vernooij
 Simplify the code a bit more.  | 
126  | 
i = 0  | 
| 
4398.5.13
by John Arbash Meinel
 We don't need a base Coder class, because Decoder._update_tail is different than Encoder._update_tail.  | 
127  | 
while ((self.tail[i] >= c'0' and self.tail[i] <= c'9') or  | 
| 
2694.5.16
by Jelmer Vernooij
 Simplify the code a bit more.  | 
128  | 
self.tail[i] == c'-') and i < self.size:  | 
| 
2694.5.18
by Alexander Belchenko
 Fix pyrex compatibility.  | 
129  | 
i = i + 1  | 
| 
2694.5.16
by Jelmer Vernooij
 Simplify the code a bit more.  | 
130  | 
|
131  | 
if self.tail[i] != stop_char:  | 
|
132  | 
raise ValueError("Stop character %c not found: %c" %  | 
|
133  | 
(stop_char, self.tail[i]))  | 
|
134  | 
if (self.tail[0] == c'0' or  | 
|
135  | 
(self.tail[0] == c'-' and self.tail[1] == c'0')):  | 
|
136  | 
if i == 1:  | 
|
| 
2694.5.17
by Jelmer Vernooij
 Avoid using malloc in the inner loop.  | 
137  | 
return i  | 
| 
2694.5.16
by Jelmer Vernooij
 Simplify the code a bit more.  | 
138  | 
else:  | 
139  | 
raise ValueError # leading zeroes are not allowed  | 
|
| 
2694.5.17
by Jelmer Vernooij
 Avoid using malloc in the inner loop.  | 
140  | 
return i  | 
141  | 
||
142  | 
cdef object _decode_int(self):  | 
|
143  | 
cdef int i  | 
|
144  | 
i = self._read_digits(c'e')  | 
|
| 
2694.5.21
by Jelmer Vernooij
 Review feedback from Alexander.  | 
145  | 
self.tail[i] = 0  | 
146  | 
try:  | 
|
147  | 
ret = PyInt_FromString(self.tail, NULL, 10)  | 
|
148  | 
finally:  | 
|
149  | 
self.tail[i] = c'e'  | 
|
| 
4398.5.13
by John Arbash Meinel
 We don't need a base Coder class, because Decoder._update_tail is different than Encoder._update_tail.  | 
150  | 
D_UPDATE_TAIL(self, i+1)  | 
| 
2694.5.16
by Jelmer Vernooij
 Simplify the code a bit more.  | 
151  | 
return ret  | 
152  | 
||
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
153  | 
cdef object _decode_string(self):  | 
| 
4398.5.14
by John Arbash Meinel
 Some small tweaks to decoding strings (avoid passing over the length 2x)  | 
154  | 
cdef int n  | 
155  | 
cdef char *next_tail  | 
|
156  | 
        # strtol allows leading whitespace, negatives, and leading zeros
 | 
|
157  | 
        # however, all callers have already checked that '0' <= tail[0] <= '9'
 | 
|
158  | 
        # or they wouldn't have called _decode_string
 | 
|
159  | 
        # strtol will stop at trailing whitespace, etc
 | 
|
160  | 
n = strtol(self.tail, &next_tail, 10)  | 
|
161  | 
if next_tail == NULL or next_tail[0] != c':':  | 
|
162  | 
raise ValueError('string len not terminated by ":"')  | 
|
163  | 
        # strtol allows leading zeros, so validate that we don't have that
 | 
|
164  | 
if (self.tail[0] == c'0'  | 
|
165  | 
and (n != 0 or (next_tail - self.tail != 1))):  | 
|
166  | 
raise ValueError('leading zeros are not allowed')  | 
|
167  | 
D_UPDATE_TAIL(self, next_tail - self.tail + 1)  | 
|
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
168  | 
if n == 0:  | 
169  | 
return ''  | 
|
170  | 
if n > self.size:  | 
|
171  | 
raise ValueError('stream underflow')  | 
|
| 
2694.5.13
by Jelmer Vernooij
 Always checks for strings first since they're more common, make sure sizes of strings are never below zero.  | 
172  | 
if n < 0:  | 
173  | 
raise ValueError('string size below zero: %d' % n)  | 
|
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
174  | 
|
175  | 
result = PyString_FromStringAndSize(self.tail, n)  | 
|
| 
4398.5.13
by John Arbash Meinel
 We don't need a base Coder class, because Decoder._update_tail is different than Encoder._update_tail.  | 
176  | 
D_UPDATE_TAIL(self, n)  | 
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
177  | 
return result  | 
178  | 
||
179  | 
cdef object _decode_list(self):  | 
|
180  | 
result = []  | 
|
181  | 
||
182  | 
while self.size > 0:  | 
|
| 
2694.5.7
by Jelmer Vernooij
 use C character constants rather than a custom enum.  | 
183  | 
if self.tail[0] == c'e':  | 
| 
4398.5.13
by John Arbash Meinel
 We don't need a base Coder class, because Decoder._update_tail is different than Encoder._update_tail.  | 
184  | 
D_UPDATE_TAIL(self, 1)  | 
| 
2694.5.5
by Jelmer Vernooij
 Support bdecode_as_tuple.  | 
185  | 
if self._yield_tuples:  | 
186  | 
return tuple(result)  | 
|
187  | 
else:  | 
|
188  | 
return result  | 
|
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
189  | 
else:  | 
| 
4398.5.14
by John Arbash Meinel
 Some small tweaks to decoding strings (avoid passing over the length 2x)  | 
190  | 
                # As a quick shortcut, check to see if the next object is a
 | 
191  | 
                # string, since we know that won't be creating recursion
 | 
|
192  | 
                # if self.tail[0] >= c'0' and self.tail[0] <= c'9':
 | 
|
| 
4398.5.12
by John Arbash Meinel
 One of the biggest wins to date, use PyList_Append directly.  | 
193  | 
PyList_Append(result, self._decode_object())  | 
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
194  | 
|
195  | 
raise ValueError('malformed list')  | 
|
196  | 
||
197  | 
cdef object _decode_dict(self):  | 
|
198  | 
cdef char ch  | 
|
199  | 
||
200  | 
result = {}  | 
|
201  | 
lastkey = None  | 
|
202  | 
||
203  | 
while self.size > 0:  | 
|
204  | 
ch = self.tail[0]  | 
|
| 
2694.5.7
by Jelmer Vernooij
 use C character constants rather than a custom enum.  | 
205  | 
if ch == c'e':  | 
| 
4398.5.13
by John Arbash Meinel
 We don't need a base Coder class, because Decoder._update_tail is different than Encoder._update_tail.  | 
206  | 
D_UPDATE_TAIL(self, 1)  | 
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
207  | 
return result  | 
| 
2694.5.15
by Jelmer Vernooij
 Simplify dict parsing.  | 
208  | 
else:  | 
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
209  | 
                # keys should be strings only
 | 
| 
4398.5.14
by John Arbash Meinel
 Some small tweaks to decoding strings (avoid passing over the length 2x)  | 
210  | 
if self.tail[0] < c'0' or self.tail[0] > c'9':  | 
211  | 
raise ValueError('key was not a simple string.')  | 
|
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
212  | 
key = self._decode_string()  | 
213  | 
if lastkey >= key:  | 
|
214  | 
raise ValueError('dict keys disordered')  | 
|
215  | 
else:  | 
|
216  | 
lastkey = key  | 
|
| 
4398.5.11
by John Arbash Meinel
 Turn Decoder.decode_object into _decode_object.  | 
217  | 
value = self._decode_object()  | 
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
218  | 
result[key] = value  | 
219  | 
||
220  | 
raise ValueError('malformed dict')  | 
|
221  | 
||
222  | 
||
223  | 
def bdecode(object s):  | 
|
224  | 
"""Decode string x to Python object"""  | 
|
225  | 
return Decoder(s).decode()  | 
|
226  | 
||
227  | 
||
| 
2694.5.5
by Jelmer Vernooij
 Support bdecode_as_tuple.  | 
228  | 
def bdecode_as_tuple(object s):  | 
229  | 
"""Decode string x to Python object, using tuples rather than lists."""  | 
|
230  | 
return Decoder(s, True).decode()  | 
|
231  | 
||
232  | 
||
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
233  | 
class Bencached(object):  | 
234  | 
__slots__ = ['bencoded']  | 
|
235  | 
||
236  | 
def __init__(self, s):  | 
|
237  | 
self.bencoded = s  | 
|
238  | 
||
239  | 
||
240  | 
cdef enum:  | 
|
241  | 
INITSIZE = 1024 # initial size for encoder buffer  | 
|
| 
2694.5.22
by Jelmer Vernooij
 Review feedback from bialix:  | 
242  | 
INT_BUF_SIZE = 32  | 
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
243  | 
|
244  | 
||
| 
4398.5.13
by John Arbash Meinel
 We don't need a base Coder class, because Decoder._update_tail is different than Encoder._update_tail.  | 
245  | 
cdef class Encoder:  | 
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
246  | 
"""Bencode encoder"""  | 
247  | 
||
| 
4398.5.13
by John Arbash Meinel
 We don't need a base Coder class, because Decoder._update_tail is different than Encoder._update_tail.  | 
248  | 
cdef readonly char *tail  | 
249  | 
cdef readonly int size  | 
|
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
250  | 
cdef readonly char *buffer  | 
| 
2694.5.20
by Jelmer Vernooij
 add handling of deep nesting.  | 
251  | 
cdef readonly int maxsize  | 
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
252  | 
|
253  | 
def __init__(self, int maxsize=INITSIZE):  | 
|
254  | 
"""Initialize encoder engine  | 
|
255  | 
        @param  maxsize:    initial size of internal char buffer
 | 
|
256  | 
        """
 | 
|
257  | 
cdef char *p  | 
|
258  | 
||
259  | 
self.maxsize = 0  | 
|
260  | 
self.size = 0  | 
|
261  | 
self.tail = NULL  | 
|
262  | 
||
263  | 
p = <char*>malloc(maxsize)  | 
|
264  | 
if p == NULL:  | 
|
| 
2694.5.6
by Jelmer Vernooij
 Use MemoryError rather than custom exception.  | 
265  | 
raise MemoryError('Not enough memory to allocate buffer '  | 
266  | 
'for encoder')  | 
|
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
267  | 
self.buffer = p  | 
268  | 
self.maxsize = maxsize  | 
|
269  | 
self.tail = p  | 
|
270  | 
||
| 
4634.112.1
by John Arbash Meinel
 bencode.Encoder should use __dealloc__ to free C level resources.  | 
271  | 
def __dealloc__(self):  | 
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
272  | 
free(self.buffer)  | 
273  | 
self.buffer = NULL  | 
|
274  | 
self.maxsize = 0  | 
|
275  | 
||
276  | 
def __str__(self):  | 
|
277  | 
if self.buffer != NULL and self.size != 0:  | 
|
278  | 
return PyString_FromStringAndSize(self.buffer, self.size)  | 
|
279  | 
else:  | 
|
280  | 
return ''  | 
|
281  | 
||
282  | 
cdef int _ensure_buffer(self, int required) except 0:  | 
|
283  | 
"""Ensure that tail of CharTail buffer has enough size.  | 
|
284  | 
        If buffer is not big enough then function try to
 | 
|
285  | 
        realloc buffer.
 | 
|
286  | 
        """
 | 
|
287  | 
cdef char *new_buffer  | 
|
288  | 
cdef int new_size  | 
|
289  | 
||
290  | 
if self.size + required < self.maxsize:  | 
|
291  | 
return 1  | 
|
292  | 
||
293  | 
new_size = self.maxsize  | 
|
294  | 
while new_size < self.size + required:  | 
|
295  | 
new_size = new_size * 2  | 
|
296  | 
new_buffer = <char*>realloc(self.buffer, <size_t>new_size)  | 
|
297  | 
if new_buffer == NULL:  | 
|
| 
2694.5.6
by Jelmer Vernooij
 Use MemoryError rather than custom exception.  | 
298  | 
raise MemoryError('Cannot realloc buffer for encoder')  | 
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
299  | 
|
300  | 
self.buffer = new_buffer  | 
|
301  | 
self.maxsize = new_size  | 
|
302  | 
self.tail = &new_buffer[self.size]  | 
|
303  | 
return 1  | 
|
304  | 
||
305  | 
cdef int _encode_int(self, int x) except 0:  | 
|
306  | 
"""Encode int to bencode string iNNNe  | 
|
307  | 
        @param  x:  value to encode
 | 
|
308  | 
        """
 | 
|
309  | 
cdef int n  | 
|
| 
2694.5.22
by Jelmer Vernooij
 Review feedback from bialix:  | 
310  | 
self._ensure_buffer(INT_BUF_SIZE)  | 
311  | 
n = snprintf(self.tail, INT_BUF_SIZE, "i%de", x)  | 
|
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
312  | 
if n < 0:  | 
| 
2694.5.6
by Jelmer Vernooij
 Use MemoryError rather than custom exception.  | 
313  | 
raise MemoryError('int %d too big to encode' % x)  | 
| 
4398.5.13
by John Arbash Meinel
 We don't need a base Coder class, because Decoder._update_tail is different than Encoder._update_tail.  | 
314  | 
E_UPDATE_TAIL(self, n)  | 
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
315  | 
return 1  | 
316  | 
||
317  | 
cdef int _encode_long(self, x) except 0:  | 
|
318  | 
return self._append_string(''.join(('i', str(x), 'e')))  | 
|
319  | 
||
320  | 
cdef int _append_string(self, s) except 0:  | 
|
| 
4398.5.13
by John Arbash Meinel
 We don't need a base Coder class, because Decoder._update_tail is different than Encoder._update_tail.  | 
321  | 
cdef Py_ssize_t n  | 
322  | 
n = PyString_GET_SIZE(s)  | 
|
323  | 
self._ensure_buffer(n)  | 
|
324  | 
memcpy(self.tail, PyString_AS_STRING(s), n)  | 
|
325  | 
E_UPDATE_TAIL(self, n)  | 
|
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
326  | 
return 1  | 
327  | 
||
328  | 
cdef int _encode_string(self, x) except 0:  | 
|
329  | 
cdef int n  | 
|
| 
4398.5.13
by John Arbash Meinel
 We don't need a base Coder class, because Decoder._update_tail is different than Encoder._update_tail.  | 
330  | 
cdef Py_ssize_t x_len  | 
331  | 
x_len = PyString_GET_SIZE(x)  | 
|
332  | 
self._ensure_buffer(x_len + INT_BUF_SIZE)  | 
|
333  | 
n = snprintf(self.tail, INT_BUF_SIZE, '%d:', x_len)  | 
|
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
334  | 
if n < 0:  | 
| 
2694.5.6
by Jelmer Vernooij
 Use MemoryError rather than custom exception.  | 
335  | 
raise MemoryError('string %s too big to encode' % x)  | 
| 
4398.5.13
by John Arbash Meinel
 We don't need a base Coder class, because Decoder._update_tail is different than Encoder._update_tail.  | 
336  | 
memcpy(<void *>(self.tail+n), PyString_AS_STRING(x), x_len)  | 
337  | 
E_UPDATE_TAIL(self, n + x_len)  | 
|
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
338  | 
return 1  | 
339  | 
||
340  | 
cdef int _encode_list(self, x) except 0:  | 
|
| 
4398.5.13
by John Arbash Meinel
 We don't need a base Coder class, because Decoder._update_tail is different than Encoder._update_tail.  | 
341  | 
self._ensure_buffer(1)  | 
| 
2694.5.7
by Jelmer Vernooij
 use C character constants rather than a custom enum.  | 
342  | 
self.tail[0] = c'l'  | 
| 
4398.5.13
by John Arbash Meinel
 We don't need a base Coder class, because Decoder._update_tail is different than Encoder._update_tail.  | 
343  | 
E_UPDATE_TAIL(self, 1)  | 
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
344  | 
|
345  | 
for i in x:  | 
|
346  | 
self.process(i)  | 
|
347  | 
||
| 
4398.5.13
by John Arbash Meinel
 We don't need a base Coder class, because Decoder._update_tail is different than Encoder._update_tail.  | 
348  | 
self._ensure_buffer(1)  | 
| 
2694.5.7
by Jelmer Vernooij
 use C character constants rather than a custom enum.  | 
349  | 
self.tail[0] = c'e'  | 
| 
4398.5.13
by John Arbash Meinel
 We don't need a base Coder class, because Decoder._update_tail is different than Encoder._update_tail.  | 
350  | 
E_UPDATE_TAIL(self, 1)  | 
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
351  | 
return 1  | 
352  | 
||
353  | 
cdef int _encode_dict(self, x) except 0:  | 
|
| 
4398.5.13
by John Arbash Meinel
 We don't need a base Coder class, because Decoder._update_tail is different than Encoder._update_tail.  | 
354  | 
self._ensure_buffer(1)  | 
| 
2694.5.7
by Jelmer Vernooij
 use C character constants rather than a custom enum.  | 
355  | 
self.tail[0] = c'd'  | 
| 
4398.5.13
by John Arbash Meinel
 We don't need a base Coder class, because Decoder._update_tail is different than Encoder._update_tail.  | 
356  | 
E_UPDATE_TAIL(self, 1)  | 
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
357  | 
|
358  | 
keys = x.keys()  | 
|
359  | 
keys.sort()  | 
|
360  | 
for k in keys:  | 
|
361  | 
if not PyString_CheckExact(k):  | 
|
362  | 
raise TypeError('key in dict should be string')  | 
|
363  | 
self._encode_string(k)  | 
|
364  | 
self.process(x[k])  | 
|
365  | 
||
| 
4398.5.13
by John Arbash Meinel
 We don't need a base Coder class, because Decoder._update_tail is different than Encoder._update_tail.  | 
366  | 
self._ensure_buffer(1)  | 
| 
2694.5.7
by Jelmer Vernooij
 use C character constants rather than a custom enum.  | 
367  | 
self.tail[0] = c'e'  | 
| 
4398.5.13
by John Arbash Meinel
 We don't need a base Coder class, because Decoder._update_tail is different than Encoder._update_tail.  | 
368  | 
E_UPDATE_TAIL(self, 1)  | 
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
369  | 
return 1  | 
370  | 
||
371  | 
def process(self, object x):  | 
|
| 
2694.5.20
by Jelmer Vernooij
 add handling of deep nesting.  | 
372  | 
if Py_EnterRecursiveCall("encode"):  | 
373  | 
raise RuntimeError("too deeply nested")  | 
|
374  | 
try:  | 
|
375  | 
if PyString_CheckExact(x):  | 
|
376  | 
self._encode_string(x)  | 
|
377  | 
elif PyInt_CheckExact(x):  | 
|
378  | 
self._encode_int(x)  | 
|
379  | 
elif PyLong_CheckExact(x):  | 
|
380  | 
self._encode_long(x)  | 
|
| 
4679.8.10
by John Arbash Meinel
 quick patch to allow bencode to handle StaticTuple objects.  | 
381  | 
elif (PyList_CheckExact(x) or PyTuple_CheckExact(x)  | 
382  | 
or StaticTuple_CheckExact(x)):  | 
|
| 
2694.5.20
by Jelmer Vernooij
 add handling of deep nesting.  | 
383  | 
self._encode_list(x)  | 
384  | 
elif PyDict_CheckExact(x):  | 
|
385  | 
self._encode_dict(x)  | 
|
386  | 
elif PyBool_Check(x):  | 
|
387  | 
self._encode_int(int(x))  | 
|
388  | 
elif isinstance(x, Bencached):  | 
|
389  | 
self._append_string(x.bencoded)  | 
|
390  | 
else:  | 
|
391  | 
raise TypeError('unsupported type %r' % x)  | 
|
392  | 
finally:  | 
|
393  | 
Py_LeaveRecursiveCall()  | 
|
| 
2694.5.1
by Alexander Belchenko
 pyrex bencode (without benchmarks)  | 
394  | 
|
395  | 
||
396  | 
def bencode(x):  | 
|
397  | 
"""Encode Python object x to string"""  | 
|
398  | 
encoder = Encoder()  | 
|
399  | 
encoder.process(x)  | 
|
400  | 
return str(encoder)  |