/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: Jelmer Vernooij
  • Date: 2017-07-23 22:06:41 UTC
  • mfrom: (6738 trunk)
  • mto: This revision was merged to the branch mainline in revision 6739.
  • Revision ID: jelmer@jelmer.uk-20170723220641-69eczax9bmv8d6kk
Merge trunk, address review comments.

Show diffs side-by-side

added added

removed removed

Lines of Context:
18
18
 
19
19
from __future__ import absolute_import
20
20
 
 
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
    )
 
47
from cpython.mem cimport (
 
48
    PyMem_Free,
 
49
    PyMem_Malloc,
 
50
    PyMem_Realloc,
 
51
    )
21
52
 
22
 
cdef extern from "stddef.h":
23
 
    ctypedef unsigned int size_t
 
53
from libc.stdlib cimport (
 
54
    strtol,
 
55
    )
 
56
from libc.string cimport (
 
57
    memcpy,
 
58
    )
24
59
 
25
60
cdef extern from "Python.h":
26
 
    ctypedef int  Py_ssize_t
27
 
    int PyInt_CheckExact(object o)
28
 
    int PyLong_CheckExact(object o)
29
 
    int PyString_CheckExact(object o)
30
 
    int PyTuple_CheckExact(object o)
31
 
    int PyList_CheckExact(object o)
32
 
    int PyDict_CheckExact(object o)
33
 
    int PyBool_Check(object o)
34
 
    object PyString_FromStringAndSize(char *v, Py_ssize_t len)
35
 
    char *PyString_AS_STRING(object o) except NULL
36
 
    Py_ssize_t PyString_GET_SIZE(object o) except -1
37
 
    object PyInt_FromString(char *str, char **pend, int base)
 
61
    # There is no cython module for ceval.h for some reason
38
62
    int Py_GetRecursionLimit()
39
63
    int Py_EnterRecursiveCall(char *)
40
64
    void Py_LeaveRecursiveCall()
41
65
 
42
 
    int PyList_Append(object, object) except -1
43
 
 
44
 
cdef extern from "stdlib.h":
45
 
    void free(void *memblock)
46
 
    void *malloc(size_t size)
47
 
    void *realloc(void *memblock, size_t size)
48
 
    long strtol(char *, char **, int)
49
 
 
50
 
cdef extern from "string.h":
51
 
    void *memcpy(void *dest, void *src, size_t count)
52
 
 
53
66
cdef extern from "python-compat.h":
54
67
    int snprintf(char* buffer, size_t nsize, char* fmt, ...)
55
68
 
78
91
        """Initialize decoder engine.
79
92
        @param  s:  Python string.
80
93
        """
81
 
        if not PyString_CheckExact(s):
82
 
            raise TypeError("String required")
 
94
        if not PyBytes_CheckExact(s):
 
95
            raise TypeError("bytes required")
83
96
 
84
97
        self.text = s
85
 
        self.tail = PyString_AS_STRING(s)
86
 
        self.size = PyString_GET_SIZE(s)
 
98
        self.tail = PyBytes_AS_STRING(s)
 
99
        self.size = PyBytes_GET_SIZE(s)
87
100
        self._yield_tuples = int(yield_tuples)
88
101
 
89
102
    def decode(self):
166
179
            raise ValueError('leading zeros are not allowed')
167
180
        D_UPDATE_TAIL(self, next_tail - self.tail + 1)
168
181
        if n == 0:
169
 
            return ''
 
182
            return b''
170
183
        if n > self.size:
171
184
            raise ValueError('stream underflow')
172
185
        if n < 0:
173
186
            raise ValueError('string size below zero: %d' % n)
174
187
 
175
 
        result = PyString_FromStringAndSize(self.tail, n)
 
188
        result = PyBytes_FromStringAndSize(self.tail, n)
176
189
        D_UPDATE_TAIL(self, n)
177
190
        return result
178
191
 
210
223
                if self.tail[0] < c'0' or self.tail[0] > c'9':
211
224
                    raise ValueError('key was not a simple string.')
212
225
                key = self._decode_string()
213
 
                if lastkey >= key:
 
226
                if lastkey is not None and lastkey >= key:
214
227
                    raise ValueError('dict keys disordered')
215
228
                else:
216
229
                    lastkey = key
260
273
        self.size = 0
261
274
        self.tail = NULL
262
275
 
263
 
        p = <char*>malloc(maxsize)
 
276
        p = <char*>PyMem_Malloc(maxsize)
264
277
        if p == NULL:
265
278
            raise MemoryError('Not enough memory to allocate buffer '
266
279
                              'for encoder')
269
282
        self.tail = p
270
283
 
271
284
    def __dealloc__(self):
272
 
        free(self.buffer)
 
285
        PyMem_Free(self.buffer)
273
286
        self.buffer = NULL
274
287
        self.maxsize = 0
275
288
 
276
 
    def __str__(self):
 
289
    def to_bytes(self):
277
290
        if self.buffer != NULL and self.size != 0:
278
 
            return PyString_FromStringAndSize(self.buffer, self.size)
279
 
        else:
280
 
            return ''
 
291
            return PyBytes_FromStringAndSize(self.buffer, self.size)
 
292
        return b''
281
293
 
282
294
    cdef int _ensure_buffer(self, int required) except 0:
283
295
        """Ensure that tail of CharTail buffer has enough size.
293
305
        new_size = self.maxsize
294
306
        while new_size < self.size + required:
295
307
            new_size = new_size * 2
296
 
        new_buffer = <char*>realloc(self.buffer, <size_t>new_size)
 
308
        new_buffer = <char*>PyMem_Realloc(self.buffer, <size_t>new_size)
297
309
        if new_buffer == NULL:
298
310
            raise MemoryError('Cannot realloc buffer for encoder')
299
311
 
308
320
        """
309
321
        cdef int n
310
322
        self._ensure_buffer(INT_BUF_SIZE)
311
 
        n = snprintf(self.tail, INT_BUF_SIZE, "i%de", x)
 
323
        n = snprintf(self.tail, INT_BUF_SIZE, b"i%de", x)
312
324
        if n < 0:
313
325
            raise MemoryError('int %d too big to encode' % x)
314
326
        E_UPDATE_TAIL(self, n)
315
327
        return 1
316
328
 
317
329
    cdef int _encode_long(self, x) except 0:
318
 
        return self._append_string(''.join(('i', str(x), 'e')))
 
330
        return self._append_string(b'i%de' % x)
319
331
 
320
332
    cdef int _append_string(self, s) except 0:
321
333
        cdef Py_ssize_t n
322
 
        n = PyString_GET_SIZE(s)
 
334
        n = PyBytes_GET_SIZE(s)
323
335
        self._ensure_buffer(n)
324
 
        memcpy(self.tail, PyString_AS_STRING(s), n)
 
336
        memcpy(self.tail, PyBytes_AS_STRING(s), n)
325
337
        E_UPDATE_TAIL(self, n)
326
338
        return 1
327
339
 
328
340
    cdef int _encode_string(self, x) except 0:
329
341
        cdef int n
330
342
        cdef Py_ssize_t x_len
331
 
        x_len = PyString_GET_SIZE(x)
 
343
        x_len = PyBytes_GET_SIZE(x)
332
344
        self._ensure_buffer(x_len + INT_BUF_SIZE)
333
 
        n = snprintf(self.tail, INT_BUF_SIZE, '%d:', x_len)
 
345
        n = snprintf(self.tail, INT_BUF_SIZE, b'%d:', x_len)
334
346
        if n < 0:
335
347
            raise MemoryError('string %s too big to encode' % x)
336
 
        memcpy(<void *>(self.tail+n), PyString_AS_STRING(x), x_len)
 
348
        memcpy(<void *>(self.tail+n), PyBytes_AS_STRING(x), x_len)
337
349
        E_UPDATE_TAIL(self, n + x_len)
338
350
        return 1
339
351
 
355
367
        self.tail[0] = c'd'
356
368
        E_UPDATE_TAIL(self, 1)
357
369
 
358
 
        keys = x.keys()
359
 
        keys.sort()
360
 
        for k in keys:
361
 
            if not PyString_CheckExact(k):
 
370
        for k in sorted(x):
 
371
            if not PyBytes_CheckExact(k):
362
372
                raise TypeError('key in dict should be string')
363
373
            self._encode_string(k)
364
374
            self.process(x[k])
372
382
        if Py_EnterRecursiveCall("encode"):
373
383
            raise RuntimeError("too deeply nested")
374
384
        try:
375
 
            if PyString_CheckExact(x):
 
385
            if PyBytes_CheckExact(x):
376
386
                self._encode_string(x)
377
 
            elif PyInt_CheckExact(x):
 
387
            elif PyInt_CheckExact(x) and x.bit_length() < 32:
378
388
                self._encode_int(x)
379
389
            elif PyLong_CheckExact(x):
380
390
                self._encode_long(x)
381
391
            elif (PyList_CheckExact(x) or PyTuple_CheckExact(x)
382
 
                  or StaticTuple_CheckExact(x)):
 
392
                  or isinstance(x, StaticTuple)):
383
393
                self._encode_list(x)
384
394
            elif PyDict_CheckExact(x):
385
395
                self._encode_dict(x)
397
407
    """Encode Python object x to string"""
398
408
    encoder = Encoder()
399
409
    encoder.process(x)
400
 
    return str(encoder)
 
410
    return encoder.to_bytes()