17
17
"""Pyrex implementation for bencode coder/decoder"""
20
cdef extern from "stddef.h":
21
ctypedef unsigned int size_t
19
from cpython.bool cimport (
22
from cpython.bytes cimport (
24
PyBytes_FromStringAndSize,
28
from cpython.dict cimport (
31
from cpython.int cimport (
35
from cpython.list cimport (
39
from cpython.long cimport (
42
from cpython.mem cimport (
47
from cpython.tuple cimport (
51
from libc.stdlib cimport (
54
from libc.string cimport (
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
23
63
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
64
void Py_LeaveRecursiveCall()
40
int PyList_Append(object, object) except -1
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)
48
cdef extern from "string.h":
49
void *memcpy(void *dest, void *src, size_t count)
51
cdef extern from "python-compat.h":
52
int snprintf(char* buffer, size_t nsize, char* fmt, ...)
58
70
void D_UPDATE_TAIL(Decoder, int n)
59
71
void E_UPDATE_TAIL(Encoder, int n)
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, \
73
from ._static_tuple_c cimport StaticTuple, StaticTuple_CheckExact, \
64
74
import_static_tuple_c
66
76
import_static_tuple_c()
78
88
"""Initialize decoder engine.
79
89
@param s: Python string.
81
if not PyString_CheckExact(s):
82
raise TypeError("String required")
91
if not PyBytes_CheckExact(s):
92
raise TypeError("bytes required")
85
self.tail = PyString_AS_STRING(s)
86
self.size = PyString_GET_SIZE(s)
95
self.tail = PyBytes_AS_STRING(s)
96
self.size = PyBytes_GET_SIZE(s)
87
97
self._yield_tuples = int(yield_tuples)
166
174
raise ValueError('leading zeros are not allowed')
167
175
D_UPDATE_TAIL(self, next_tail - self.tail + 1)
170
178
if n > self.size:
171
179
raise ValueError('stream underflow')
173
181
raise ValueError('string size below zero: %d' % n)
175
result = PyString_FromStringAndSize(self.tail, n)
183
result = PyBytes_FromStringAndSize(self.tail, n)
176
184
D_UPDATE_TAIL(self, n)
271
279
def __dealloc__(self):
280
PyMem_Free(self.buffer)
273
281
self.buffer = NULL
277
285
if self.buffer != NULL and self.size != 0:
278
return PyString_FromStringAndSize(self.buffer, self.size)
286
return PyBytes_FromStringAndSize(self.buffer, self.size)
282
289
cdef int _ensure_buffer(self, int required) except 0:
283
290
"""Ensure that tail of CharTail buffer has enough size.
310
317
self._ensure_buffer(INT_BUF_SIZE)
311
n = snprintf(self.tail, INT_BUF_SIZE, "i%de", x)
318
n = snprintf(self.tail, INT_BUF_SIZE, b"i%de", x)
313
320
raise MemoryError('int %d too big to encode' % x)
314
321
E_UPDATE_TAIL(self, n)
317
324
cdef int _encode_long(self, x) except 0:
318
return self._append_string(''.join(('i', str(x), 'e')))
325
return self._append_string(b'i%de' % x)
320
327
cdef int _append_string(self, s) except 0:
321
328
cdef Py_ssize_t n
322
n = PyString_GET_SIZE(s)
329
n = PyBytes_GET_SIZE(s)
323
330
self._ensure_buffer(n)
324
memcpy(self.tail, PyString_AS_STRING(s), n)
331
memcpy(self.tail, PyBytes_AS_STRING(s), n)
325
332
E_UPDATE_TAIL(self, n)
328
335
cdef int _encode_string(self, x) except 0:
330
337
cdef Py_ssize_t x_len
331
x_len = PyString_GET_SIZE(x)
338
x_len = PyBytes_GET_SIZE(x)
332
339
self._ensure_buffer(x_len + INT_BUF_SIZE)
333
n = snprintf(self.tail, INT_BUF_SIZE, '%d:', x_len)
340
n = snprintf(self.tail, INT_BUF_SIZE, b'%ld:', x_len)
335
342
raise MemoryError('string %s too big to encode' % x)
336
memcpy(<void *>(self.tail+n), PyString_AS_STRING(x), x_len)
343
memcpy(<void *>(self.tail+n), PyBytes_AS_STRING(x), x_len)
337
344
E_UPDATE_TAIL(self, n + x_len)
368
373
E_UPDATE_TAIL(self, 1)
371
def process(self, object x):
372
if Py_EnterRecursiveCall("encode"):
373
raise RuntimeError("too deeply nested")
376
cpdef object process(self, object x):
377
BrzPy_EnterRecursiveCall(" while bencode encoding")
375
if PyString_CheckExact(x):
379
if PyBytes_CheckExact(x):
376
380
self._encode_string(x)
377
elif PyInt_CheckExact(x):
381
elif PyInt_CheckExact(x) and x.bit_length() < 32:
378
382
self._encode_int(x)
379
383
elif PyLong_CheckExact(x):
380
384
self._encode_long(x)
381
385
elif (PyList_CheckExact(x) or PyTuple_CheckExact(x)
382
or StaticTuple_CheckExact(x)):
386
or isinstance(x, StaticTuple)):
383
387
self._encode_list(x)
384
388
elif PyDict_CheckExact(x):
385
389
self._encode_dict(x)