/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/_bencode_pyx.pyx

  • Committer: Breezy landing bot
  • Author(s): Colin Watson
  • Date: 2020-11-16 21:47:08 UTC
  • mfrom: (7521.1.1 remove-lp-workaround)
  • Revision ID: breezy.the.bot@gmail.com-20201116214708-jos209mgxi41oy15
Remove breezy.git workaround for bazaar.launchpad.net.

Merged from https://code.launchpad.net/~cjwatson/brz/remove-lp-workaround/+merge/393710

Show diffs side-by-side

added added

removed removed

Lines of Context:
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
#
 
17
# cython: language_level=3
16
18
 
17
19
"""Pyrex implementation for bencode coder/decoder"""
18
20
 
19
 
 
20
 
cdef extern from "stddef.h":
21
 
    ctypedef unsigned int size_t
 
21
from cpython.bool cimport (
 
22
    PyBool_Check,
 
23
    )
 
24
from cpython.bytes cimport (
 
25
    PyBytes_CheckExact,
 
26
    PyBytes_FromStringAndSize,
 
27
    PyBytes_AS_STRING,
 
28
    PyBytes_GET_SIZE,
 
29
    )
 
30
from cpython.dict cimport (
 
31
    PyDict_CheckExact,
 
32
    )
 
33
from cpython.int cimport (
 
34
    PyInt_CheckExact,
 
35
    PyInt_FromString,
 
36
    )
 
37
from cpython.list cimport (
 
38
    PyList_CheckExact,
 
39
    PyList_Append,
 
40
    )
 
41
from cpython.long cimport (
 
42
    PyLong_CheckExact,
 
43
    )
 
44
from cpython.mem cimport (
 
45
    PyMem_Free,
 
46
    PyMem_Malloc,
 
47
    PyMem_Realloc,
 
48
    )
 
49
from cpython.tuple cimport (
 
50
    PyTuple_CheckExact,
 
51
    )
 
52
 
 
53
from libc.stdlib cimport (
 
54
    strtol,
 
55
    )
 
56
from libc.string cimport (
 
57
    memcpy,
 
58
    )
 
59
 
 
60
cdef extern from "python-compat.h":
 
61
    int snprintf(char* buffer, size_t nsize, char* fmt, ...)
 
62
    # Use wrapper with inverted error return so Cython can propogate
 
63
    int BrzPy_EnterRecursiveCall(char *) except 0
22
64
 
23
65
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)
33
 
    char *PyString_AS_STRING(object o) except NULL
34
 
    Py_ssize_t PyString_GET_SIZE(object o) except -1
35
 
    object PyInt_FromString(char *str, char **pend, int base)
36
 
    int Py_GetRecursionLimit()
37
 
    int Py_EnterRecursiveCall(char *)
38
66
    void Py_LeaveRecursiveCall()
39
67
 
40
 
    int PyList_Append(object, object) except -1
41
 
 
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)
46
 
    long strtol(char *, char **, int)
47
 
 
48
 
cdef extern from "string.h":
49
 
    void *memcpy(void *dest, void *src, size_t count)
50
 
 
51
 
cdef extern from "python-compat.h":
52
 
    int snprintf(char* buffer, size_t nsize, char* fmt, ...)
53
 
 
54
68
cdef class Decoder
55
69
cdef class Encoder
56
70
 
58
72
    void D_UPDATE_TAIL(Decoder, int n)
59
73
    void E_UPDATE_TAIL(Encoder, int n)
60
74
 
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, \
 
75
from ._static_tuple_c cimport StaticTuple, StaticTuple_CheckExact, \
64
76
    import_static_tuple_c
65
77
 
66
78
import_static_tuple_c()
78
90
        """Initialize decoder engine.
79
91
        @param  s:  Python string.
80
92
        """
81
 
        if not PyString_CheckExact(s):
82
 
            raise TypeError("String required")
 
93
        if not PyBytes_CheckExact(s):
 
94
            raise TypeError("bytes required")
83
95
 
84
96
        self.text = s
85
 
        self.tail = PyString_AS_STRING(s)
86
 
        self.size = PyString_GET_SIZE(s)
 
97
        self.tail = PyBytes_AS_STRING(s)
 
98
        self.size = PyBytes_GET_SIZE(s)
87
99
        self._yield_tuples = int(yield_tuples)
88
100
 
89
101
    def decode(self):
101
113
        if 0 == self.size:
102
114
            raise ValueError('stream underflow')
103
115
 
104
 
        if Py_EnterRecursiveCall("_decode_object"):
105
 
            raise RuntimeError("too deeply nested")
 
116
        BrzPy_EnterRecursiveCall(" while bencode decoding")
106
117
        try:
107
118
            ch = self.tail[0]
108
119
            if c'0' <= ch <= c'9':
116
127
            elif ch == c'd':
117
128
                D_UPDATE_TAIL(self, 1)
118
129
                return self._decode_dict()
119
 
            else:
120
 
                raise ValueError('unknown object type identifier %r' % ch)
121
130
        finally:
122
131
            Py_LeaveRecursiveCall()
 
132
        raise ValueError('unknown object type identifier %r' % ch)
123
133
 
124
134
    cdef int _read_digits(self, char stop_char) except -1:
125
135
        cdef int i
166
176
            raise ValueError('leading zeros are not allowed')
167
177
        D_UPDATE_TAIL(self, next_tail - self.tail + 1)
168
178
        if n == 0:
169
 
            return ''
 
179
            return b''
170
180
        if n > self.size:
171
181
            raise ValueError('stream underflow')
172
182
        if n < 0:
173
183
            raise ValueError('string size below zero: %d' % n)
174
184
 
175
 
        result = PyString_FromStringAndSize(self.tail, n)
 
185
        result = PyBytes_FromStringAndSize(self.tail, n)
176
186
        D_UPDATE_TAIL(self, n)
177
187
        return result
178
188
 
210
220
                if self.tail[0] < c'0' or self.tail[0] > c'9':
211
221
                    raise ValueError('key was not a simple string.')
212
222
                key = self._decode_string()
213
 
                if lastkey >= key:
 
223
                if lastkey is not None and lastkey >= key:
214
224
                    raise ValueError('dict keys disordered')
215
225
                else:
216
226
                    lastkey = key
260
270
        self.size = 0
261
271
        self.tail = NULL
262
272
 
263
 
        p = <char*>malloc(maxsize)
 
273
        p = <char*>PyMem_Malloc(maxsize)
264
274
        if p == NULL:
265
275
            raise MemoryError('Not enough memory to allocate buffer '
266
276
                              'for encoder')
269
279
        self.tail = p
270
280
 
271
281
    def __dealloc__(self):
272
 
        free(self.buffer)
 
282
        PyMem_Free(self.buffer)
273
283
        self.buffer = NULL
274
284
        self.maxsize = 0
275
285
 
276
 
    def __str__(self):
 
286
    def to_bytes(self):
277
287
        if self.buffer != NULL and self.size != 0:
278
 
            return PyString_FromStringAndSize(self.buffer, self.size)
279
 
        else:
280
 
            return ''
 
288
            return PyBytes_FromStringAndSize(self.buffer, self.size)
 
289
        return b''
281
290
 
282
291
    cdef int _ensure_buffer(self, int required) except 0:
283
292
        """Ensure that tail of CharTail buffer has enough size.
293
302
        new_size = self.maxsize
294
303
        while new_size < self.size + required:
295
304
            new_size = new_size * 2
296
 
        new_buffer = <char*>realloc(self.buffer, <size_t>new_size)
 
305
        new_buffer = <char*>PyMem_Realloc(self.buffer, <size_t>new_size)
297
306
        if new_buffer == NULL:
298
307
            raise MemoryError('Cannot realloc buffer for encoder')
299
308
 
308
317
        """
309
318
        cdef int n
310
319
        self._ensure_buffer(INT_BUF_SIZE)
311
 
        n = snprintf(self.tail, INT_BUF_SIZE, "i%de", x)
 
320
        n = snprintf(self.tail, INT_BUF_SIZE, b"i%de", x)
312
321
        if n < 0:
313
322
            raise MemoryError('int %d too big to encode' % x)
314
323
        E_UPDATE_TAIL(self, n)
315
324
        return 1
316
325
 
317
326
    cdef int _encode_long(self, x) except 0:
318
 
        return self._append_string(''.join(('i', str(x), 'e')))
 
327
        return self._append_string(b'i%de' % x)
319
328
 
320
329
    cdef int _append_string(self, s) except 0:
321
330
        cdef Py_ssize_t n
322
 
        n = PyString_GET_SIZE(s)
 
331
        n = PyBytes_GET_SIZE(s)
323
332
        self._ensure_buffer(n)
324
 
        memcpy(self.tail, PyString_AS_STRING(s), n)
 
333
        memcpy(self.tail, PyBytes_AS_STRING(s), n)
325
334
        E_UPDATE_TAIL(self, n)
326
335
        return 1
327
336
 
328
337
    cdef int _encode_string(self, x) except 0:
329
338
        cdef int n
330
339
        cdef Py_ssize_t x_len
331
 
        x_len = PyString_GET_SIZE(x)
 
340
        x_len = PyBytes_GET_SIZE(x)
332
341
        self._ensure_buffer(x_len + INT_BUF_SIZE)
333
 
        n = snprintf(self.tail, INT_BUF_SIZE, '%d:', x_len)
 
342
        n = snprintf(self.tail, INT_BUF_SIZE, b'%ld:', x_len)
334
343
        if n < 0:
335
344
            raise MemoryError('string %s too big to encode' % x)
336
 
        memcpy(<void *>(self.tail+n), PyString_AS_STRING(x), x_len)
 
345
        memcpy(<void *>(self.tail+n), PyBytes_AS_STRING(x), x_len)
337
346
        E_UPDATE_TAIL(self, n + x_len)
338
347
        return 1
339
348
 
355
364
        self.tail[0] = c'd'
356
365
        E_UPDATE_TAIL(self, 1)
357
366
 
358
 
        keys = x.keys()
359
 
        keys.sort()
360
 
        for k in keys:
361
 
            if not PyString_CheckExact(k):
 
367
        for k in sorted(x):
 
368
            if not PyBytes_CheckExact(k):
362
369
                raise TypeError('key in dict should be string')
363
370
            self._encode_string(k)
364
371
            self.process(x[k])
368
375
        E_UPDATE_TAIL(self, 1)
369
376
        return 1
370
377
 
371
 
    def process(self, object x):
372
 
        if Py_EnterRecursiveCall("encode"):
373
 
            raise RuntimeError("too deeply nested")
 
378
    cpdef object process(self, object x):
 
379
        BrzPy_EnterRecursiveCall(" while bencode encoding")
374
380
        try:
375
 
            if PyString_CheckExact(x):
 
381
            if PyBytes_CheckExact(x):
376
382
                self._encode_string(x)
377
 
            elif PyInt_CheckExact(x):
 
383
            elif PyInt_CheckExact(x) and x.bit_length() < 32:
378
384
                self._encode_int(x)
379
385
            elif PyLong_CheckExact(x):
380
386
                self._encode_long(x)
381
387
            elif (PyList_CheckExact(x) or PyTuple_CheckExact(x)
382
 
                  or StaticTuple_CheckExact(x)):
 
388
                  or isinstance(x, StaticTuple)):
383
389
                self._encode_list(x)
384
390
            elif PyDict_CheckExact(x):
385
391
                self._encode_dict(x)
397
403
    """Encode Python object x to string"""
398
404
    encoder = Encoder()
399
405
    encoder.process(x)
400
 
    return str(encoder)
 
406
    return encoder.to_bytes()