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