/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
4763.2.4 by John Arbash Meinel
merge bzr.2.1 in preparation for NEWS entry.
1
# Copyright (C) 2007, 2009, 2010 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
7059.1.3 by Martin
Fix recursion check in C bencode implementation
19
from cpython.bool cimport (
20
    PyBool_Check,
21
    )
6715.2.1 by Martin
Switch _bencode_pyx to modern Cython style to compile on Python 3
22
from cpython.bytes cimport (
23
    PyBytes_CheckExact,
24
    PyBytes_FromStringAndSize,
25
    PyBytes_AS_STRING,
26
    PyBytes_GET_SIZE,
27
    )
7059.1.3 by Martin
Fix recursion check in C bencode implementation
28
from cpython.dict cimport (
29
    PyDict_CheckExact,
6715.2.1 by Martin
Switch _bencode_pyx to modern Cython style to compile on Python 3
30
    )
31
from cpython.int cimport (
32
    PyInt_CheckExact,
33
    PyInt_FromString,
34
    )
35
from cpython.list cimport (
36
    PyList_CheckExact,
37
    PyList_Append,
38
    )
7059.1.3 by Martin
Fix recursion check in C bencode implementation
39
from cpython.long cimport (
40
    PyLong_CheckExact,
6715.2.1 by Martin
Switch _bencode_pyx to modern Cython style to compile on Python 3
41
    )
6715.2.2 by Martin
Switch to PyMem functions in _bencode_pyx
42
from cpython.mem cimport (
43
    PyMem_Free,
44
    PyMem_Malloc,
45
    PyMem_Realloc,
46
    )
7059.1.3 by Martin
Fix recursion check in C bencode implementation
47
from cpython.tuple cimport (
48
    PyTuple_CheckExact,
49
    )
2694.5.20 by Jelmer Vernooij
add handling of deep nesting.
50
6715.2.3 by Martin
Use cimport from libc in _bencode_pyx
51
from libc.stdlib cimport (
52
    strtol,
53
    )
54
from libc.string cimport (
55
    memcpy,
56
    )
57
7059.1.3 by Martin
Fix recursion check in C bencode implementation
58
cdef extern from "python-compat.h":
59
    int snprintf(char* buffer, size_t nsize, char* fmt, ...)
60
    # Use wrapper with inverted error return so Cython can propogate
61
    int BrzPy_EnterRecursiveCall(char *) except 0
62
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
63
cdef extern from "Python.h":
2694.5.20 by Jelmer Vernooij
add handling of deep nesting.
64
    void Py_LeaveRecursiveCall()
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
65
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.
66
cdef class Decoder
67
cdef class Encoder
4398.5.10 by John Arbash Meinel
Move self._update_tail into a macro for UPDATE_TAIL.
68
69
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.
70
    void D_UPDATE_TAIL(Decoder, int n)
71
    void E_UPDATE_TAIL(Encoder, int n)
72
6656.2.2 by Jelmer Vernooij
Use absolute_import.
73
from ._static_tuple_c cimport StaticTuple, StaticTuple_CheckExact, \
4679.8.10 by John Arbash Meinel
quick patch to allow bencode to handle StaticTuple objects.
74
    import_static_tuple_c
75
76
import_static_tuple_c()
77
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.
78
79
cdef class Decoder:
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
80
    """Bencode decoder"""
81
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.
82
    cdef readonly char *tail
83
    cdef readonly int size
2694.5.20 by Jelmer Vernooij
add handling of deep nesting.
84
    cdef readonly int _yield_tuples
2694.5.21 by Jelmer Vernooij
Review feedback from Alexander.
85
    cdef object text
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
86
2694.5.5 by Jelmer Vernooij
Support bdecode_as_tuple.
87
    def __init__(self, s, yield_tuples=0):
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
88
        """Initialize decoder engine.
89
        @param  s:  Python string.
90
        """
6715.2.1 by Martin
Switch _bencode_pyx to modern Cython style to compile on Python 3
91
        if not PyBytes_CheckExact(s):
92
            raise TypeError("bytes required")
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
93
2694.5.21 by Jelmer Vernooij
Review feedback from Alexander.
94
        self.text = s
6715.2.1 by Martin
Switch _bencode_pyx to modern Cython style to compile on Python 3
95
        self.tail = PyBytes_AS_STRING(s)
96
        self.size = PyBytes_GET_SIZE(s)
2694.5.5 by Jelmer Vernooij
Support bdecode_as_tuple.
97
        self._yield_tuples = int(yield_tuples)
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
98
99
    def decode(self):
4398.5.11 by John Arbash Meinel
Turn Decoder.decode_object into _decode_object.
100
        result = self._decode_object()
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
101
        if self.size != 0:
102
            raise ValueError('junk in stream')
103
        return result
104
105
    def decode_object(self):
4398.5.11 by John Arbash Meinel
Turn Decoder.decode_object into _decode_object.
106
        return self._decode_object()
107
108
    cdef object _decode_object(self):
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
109
        cdef char ch
110
111
        if 0 == self.size:
112
            raise ValueError('stream underflow')
113
7059.1.3 by Martin
Fix recursion check in C bencode implementation
114
        BrzPy_EnterRecursiveCall(" while bencode decoding")
2694.5.20 by Jelmer Vernooij
add handling of deep nesting.
115
        try:
116
            ch = self.tail[0]
4398.5.14 by John Arbash Meinel
Some small tweaks to decoding strings (avoid passing over the length 2x)
117
            if c'0' <= ch <= c'9':
2694.5.20 by Jelmer Vernooij
add handling of deep nesting.
118
                return self._decode_string()
119
            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.
120
                D_UPDATE_TAIL(self, 1)
2694.5.20 by Jelmer Vernooij
add handling of deep nesting.
121
                return self._decode_list()
4398.5.14 by John Arbash Meinel
Some small tweaks to decoding strings (avoid passing over the length 2x)
122
            elif ch == c'i':
123
                D_UPDATE_TAIL(self, 1)
124
                return self._decode_int()
2694.5.20 by Jelmer Vernooij
add handling of deep nesting.
125
            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.
126
                D_UPDATE_TAIL(self, 1)
2694.5.20 by Jelmer Vernooij
add handling of deep nesting.
127
                return self._decode_dict()
128
        finally:
129
            Py_LeaveRecursiveCall()
7059.1.3 by Martin
Fix recursion check in C bencode implementation
130
        raise ValueError('unknown object type identifier %r' % ch)
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
131
2694.5.17 by Jelmer Vernooij
Avoid using malloc in the inner loop.
132
    cdef int _read_digits(self, char stop_char) except -1:
133
        cdef int i
2694.5.16 by Jelmer Vernooij
Simplify the code a bit more.
134
        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.
135
        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.
136
               self.tail[i] == c'-') and i < self.size:
2694.5.18 by Alexander Belchenko
Fix pyrex compatibility.
137
            i = i + 1
2694.5.16 by Jelmer Vernooij
Simplify the code a bit more.
138
139
        if self.tail[i] != stop_char:
140
            raise ValueError("Stop character %c not found: %c" % 
141
                (stop_char, self.tail[i]))
142
        if (self.tail[0] == c'0' or 
143
                (self.tail[0] == c'-' and self.tail[1] == c'0')):
144
            if i == 1:
2694.5.17 by Jelmer Vernooij
Avoid using malloc in the inner loop.
145
                return i
2694.5.16 by Jelmer Vernooij
Simplify the code a bit more.
146
            else:
147
                raise ValueError # leading zeroes are not allowed
2694.5.17 by Jelmer Vernooij
Avoid using malloc in the inner loop.
148
        return i
149
150
    cdef object _decode_int(self):
151
        cdef int i
152
        i = self._read_digits(c'e')
2694.5.21 by Jelmer Vernooij
Review feedback from Alexander.
153
        self.tail[i] = 0
154
        try:
155
            ret = PyInt_FromString(self.tail, NULL, 10)
156
        finally:
157
            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.
158
        D_UPDATE_TAIL(self, i+1)
2694.5.16 by Jelmer Vernooij
Simplify the code a bit more.
159
        return ret
160
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
161
    cdef object _decode_string(self):
4398.5.14 by John Arbash Meinel
Some small tweaks to decoding strings (avoid passing over the length 2x)
162
        cdef int n
163
        cdef char *next_tail
164
        # strtol allows leading whitespace, negatives, and leading zeros
165
        # however, all callers have already checked that '0' <= tail[0] <= '9'
166
        # or they wouldn't have called _decode_string
167
        # strtol will stop at trailing whitespace, etc
168
        n = strtol(self.tail, &next_tail, 10)
169
        if next_tail == NULL or next_tail[0] != c':':
170
            raise ValueError('string len not terminated by ":"')
171
        # strtol allows leading zeros, so validate that we don't have that
172
        if (self.tail[0] == c'0'
173
            and (n != 0 or (next_tail - self.tail != 1))):
174
            raise ValueError('leading zeros are not allowed')
175
        D_UPDATE_TAIL(self, next_tail - self.tail + 1)
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
176
        if n == 0:
6715.2.1 by Martin
Switch _bencode_pyx to modern Cython style to compile on Python 3
177
            return b''
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
178
        if n > self.size:
179
            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.
180
        if n < 0:
181
            raise ValueError('string size below zero: %d' % n)
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
182
6715.2.1 by Martin
Switch _bencode_pyx to modern Cython style to compile on Python 3
183
        result = PyBytes_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.
184
        D_UPDATE_TAIL(self, n)
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
185
        return result
186
187
    cdef object _decode_list(self):
188
        result = []
189
190
        while self.size > 0:
2694.5.7 by Jelmer Vernooij
use C character constants rather than a custom enum.
191
            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.
192
                D_UPDATE_TAIL(self, 1)
2694.5.5 by Jelmer Vernooij
Support bdecode_as_tuple.
193
                if self._yield_tuples:
194
                    return tuple(result)
195
                else:
196
                    return result
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
197
            else:
4398.5.14 by John Arbash Meinel
Some small tweaks to decoding strings (avoid passing over the length 2x)
198
                # As a quick shortcut, check to see if the next object is a
199
                # string, since we know that won't be creating recursion
200
                # 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.
201
                PyList_Append(result, self._decode_object())
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
202
203
        raise ValueError('malformed list')
204
205
    cdef object _decode_dict(self):
206
        cdef char ch
207
208
        result = {}
209
        lastkey = None
210
211
        while self.size > 0:
212
            ch = self.tail[0]
2694.5.7 by Jelmer Vernooij
use C character constants rather than a custom enum.
213
            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.
214
                D_UPDATE_TAIL(self, 1)
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
215
                return result
2694.5.15 by Jelmer Vernooij
Simplify dict parsing.
216
            else:
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
217
                # keys should be strings only
4398.5.14 by John Arbash Meinel
Some small tweaks to decoding strings (avoid passing over the length 2x)
218
                if self.tail[0] < c'0' or self.tail[0] > c'9':
219
                    raise ValueError('key was not a simple string.')
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
220
                key = self._decode_string()
6715.2.1 by Martin
Switch _bencode_pyx to modern Cython style to compile on Python 3
221
                if lastkey is not None and lastkey >= key:
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
222
                    raise ValueError('dict keys disordered')
223
                else:
224
                    lastkey = key
4398.5.11 by John Arbash Meinel
Turn Decoder.decode_object into _decode_object.
225
                value = self._decode_object()
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
226
                result[key] = value
227
228
        raise ValueError('malformed dict')
229
230
231
def bdecode(object s):
232
    """Decode string x to Python object"""
233
    return Decoder(s).decode()
234
235
2694.5.5 by Jelmer Vernooij
Support bdecode_as_tuple.
236
def bdecode_as_tuple(object s):
237
    """Decode string x to Python object, using tuples rather than lists."""
238
    return Decoder(s, True).decode()
239
240
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
241
class Bencached(object):
242
    __slots__ = ['bencoded']
243
244
    def __init__(self, s):
245
        self.bencoded = s
246
247
248
cdef enum:
249
    INITSIZE = 1024     # initial size for encoder buffer
2694.5.22 by Jelmer Vernooij
Review feedback from bialix:
250
    INT_BUF_SIZE = 32
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
251
252
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.
253
cdef class Encoder:
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
254
    """Bencode encoder"""
255
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.
256
    cdef readonly char *tail
257
    cdef readonly int size
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
258
    cdef readonly char *buffer
2694.5.20 by Jelmer Vernooij
add handling of deep nesting.
259
    cdef readonly int maxsize
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
260
261
    def __init__(self, int maxsize=INITSIZE):
262
        """Initialize encoder engine
263
        @param  maxsize:    initial size of internal char buffer
264
        """
265
        cdef char *p
266
267
        self.maxsize = 0
268
        self.size = 0
269
        self.tail = NULL
270
6715.2.2 by Martin
Switch to PyMem functions in _bencode_pyx
271
        p = <char*>PyMem_Malloc(maxsize)
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
272
        if p == NULL:
2694.5.6 by Jelmer Vernooij
Use MemoryError rather than custom exception.
273
            raise MemoryError('Not enough memory to allocate buffer '
274
                              'for encoder')
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
275
        self.buffer = p
276
        self.maxsize = maxsize
277
        self.tail = p
278
4634.112.1 by John Arbash Meinel
bencode.Encoder should use __dealloc__ to free C level resources.
279
    def __dealloc__(self):
6715.2.2 by Martin
Switch to PyMem functions in _bencode_pyx
280
        PyMem_Free(self.buffer)
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
281
        self.buffer = NULL
282
        self.maxsize = 0
283
6715.2.1 by Martin
Switch _bencode_pyx to modern Cython style to compile on Python 3
284
    def to_bytes(self):
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
285
        if self.buffer != NULL and self.size != 0:
6715.2.1 by Martin
Switch _bencode_pyx to modern Cython style to compile on Python 3
286
            return PyBytes_FromStringAndSize(self.buffer, self.size)
287
        return b''
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
288
289
    cdef int _ensure_buffer(self, int required) except 0:
290
        """Ensure that tail of CharTail buffer has enough size.
291
        If buffer is not big enough then function try to
292
        realloc buffer.
293
        """
294
        cdef char *new_buffer
295
        cdef int   new_size
296
297
        if self.size + required < self.maxsize:
298
            return 1
299
300
        new_size = self.maxsize
301
        while new_size < self.size + required:
302
            new_size = new_size * 2
6715.2.2 by Martin
Switch to PyMem functions in _bencode_pyx
303
        new_buffer = <char*>PyMem_Realloc(self.buffer, <size_t>new_size)
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
304
        if new_buffer == NULL:
2694.5.6 by Jelmer Vernooij
Use MemoryError rather than custom exception.
305
            raise MemoryError('Cannot realloc buffer for encoder')
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
306
307
        self.buffer = new_buffer
308
        self.maxsize = new_size
309
        self.tail = &new_buffer[self.size]
310
        return 1
311
312
    cdef int _encode_int(self, int x) except 0:
313
        """Encode int to bencode string iNNNe
314
        @param  x:  value to encode
315
        """
316
        cdef int n
2694.5.22 by Jelmer Vernooij
Review feedback from bialix:
317
        self._ensure_buffer(INT_BUF_SIZE)
6715.2.1 by Martin
Switch _bencode_pyx to modern Cython style to compile on Python 3
318
        n = snprintf(self.tail, INT_BUF_SIZE, b"i%de", x)
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
319
        if n < 0:
2694.5.6 by Jelmer Vernooij
Use MemoryError rather than custom exception.
320
            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.
321
        E_UPDATE_TAIL(self, n)
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
322
        return 1
323
324
    cdef int _encode_long(self, x) except 0:
6715.2.1 by Martin
Switch _bencode_pyx to modern Cython style to compile on Python 3
325
        return self._append_string(b'i%de' % x)
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
326
327
    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.
328
        cdef Py_ssize_t n
6715.2.1 by Martin
Switch _bencode_pyx to modern Cython style to compile on Python 3
329
        n = PyBytes_GET_SIZE(s)
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
        self._ensure_buffer(n)
6715.2.1 by Martin
Switch _bencode_pyx to modern Cython style to compile on Python 3
331
        memcpy(self.tail, PyBytes_AS_STRING(s), 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.
332
        E_UPDATE_TAIL(self, n)
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
333
        return 1
334
335
    cdef int _encode_string(self, x) except 0:
336
        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.
337
        cdef Py_ssize_t x_len
6715.2.1 by Martin
Switch _bencode_pyx to modern Cython style to compile on Python 3
338
        x_len = PyBytes_GET_SIZE(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.
339
        self._ensure_buffer(x_len + INT_BUF_SIZE)
7059.1.3 by Martin
Fix recursion check in C bencode implementation
340
        n = snprintf(self.tail, INT_BUF_SIZE, b'%ld:', x_len)
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
341
        if n < 0:
2694.5.6 by Jelmer Vernooij
Use MemoryError rather than custom exception.
342
            raise MemoryError('string %s too big to encode' % x)
6715.2.1 by Martin
Switch _bencode_pyx to modern Cython style to compile on Python 3
343
        memcpy(<void *>(self.tail+n), PyBytes_AS_STRING(x), x_len)
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.
344
        E_UPDATE_TAIL(self, n + x_len)
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
345
        return 1
346
347
    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.
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'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.
350
        E_UPDATE_TAIL(self, 1)
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
351
352
        for i in x:
353
            self.process(i)
354
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.
355
        self._ensure_buffer(1)
2694.5.7 by Jelmer Vernooij
use C character constants rather than a custom enum.
356
        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.
357
        E_UPDATE_TAIL(self, 1)
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
358
        return 1
359
360
    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.
361
        self._ensure_buffer(1)
2694.5.7 by Jelmer Vernooij
use C character constants rather than a custom enum.
362
        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.
363
        E_UPDATE_TAIL(self, 1)
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
364
6715.2.1 by Martin
Switch _bencode_pyx to modern Cython style to compile on Python 3
365
        for k in sorted(x):
366
            if not PyBytes_CheckExact(k):
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
367
                raise TypeError('key in dict should be string')
368
            self._encode_string(k)
369
            self.process(x[k])
370
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.
371
        self._ensure_buffer(1)
2694.5.7 by Jelmer Vernooij
use C character constants rather than a custom enum.
372
        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.
373
        E_UPDATE_TAIL(self, 1)
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
374
        return 1
375
7059.1.3 by Martin
Fix recursion check in C bencode implementation
376
    cpdef object process(self, object x):
377
        BrzPy_EnterRecursiveCall(" while bencode encoding")
2694.5.20 by Jelmer Vernooij
add handling of deep nesting.
378
        try:
6715.2.1 by Martin
Switch _bencode_pyx to modern Cython style to compile on Python 3
379
            if PyBytes_CheckExact(x):
2694.5.20 by Jelmer Vernooij
add handling of deep nesting.
380
                self._encode_string(x)
6715.2.4 by Martin
Correct bit_length compare
381
            elif PyInt_CheckExact(x) and x.bit_length() < 32:
2694.5.20 by Jelmer Vernooij
add handling of deep nesting.
382
                self._encode_int(x)
383
            elif PyLong_CheckExact(x):
384
                self._encode_long(x)
4679.8.10 by John Arbash Meinel
quick patch to allow bencode to handle StaticTuple objects.
385
            elif (PyList_CheckExact(x) or PyTuple_CheckExact(x)
6715.2.1 by Martin
Switch _bencode_pyx to modern Cython style to compile on Python 3
386
                  or isinstance(x, StaticTuple)):
2694.5.20 by Jelmer Vernooij
add handling of deep nesting.
387
                self._encode_list(x)
388
            elif PyDict_CheckExact(x):
389
                self._encode_dict(x)
390
            elif PyBool_Check(x):
391
                self._encode_int(int(x))
392
            elif isinstance(x, Bencached):
393
                self._append_string(x.bencoded)
394
            else:
395
                raise TypeError('unsupported type %r' % x)
396
        finally:
397
            Py_LeaveRecursiveCall()
2694.5.1 by Alexander Belchenko
pyrex bencode (without benchmarks)
398
399
400
def bencode(x):
401
    """Encode Python object x to string"""
402
    encoder = Encoder()
403
    encoder.process(x)
6715.2.1 by Martin
Switch _bencode_pyx to modern Cython style to compile on Python 3
404
    return encoder.to_bytes()