/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 bzrlib/_bencode_pyx.pyx

  • Committer: Richard Wilbur
  • Date: 2016-02-04 19:07:28 UTC
  • mto: This revision was merged to the branch mainline in revision 6618.
  • Revision ID: richard.wilbur@gmail.com-20160204190728-p0zvfii6zase0fw7
Update COPYING.txt from the original http://www.gnu.org/licenses/gpl-2.0.txt  (Only differences were in whitespace.)  Thanks to Petr Stodulka for pointing out the discrepancy.

Show diffs side-by-side

added added

removed removed

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