/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: Robert Collins
  • Date: 2010-05-06 23:41:35 UTC
  • mto: This revision was merged to the branch mainline in revision 5223.
  • Revision ID: robertc@robertcollins.net-20100506234135-yivbzczw1sejxnxc
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
expected to return an object which can be used to unlock them. This reduces
duplicate code when using cleanups. The previous 'tokens's returned by
``Branch.lock_write`` and ``Repository.lock_write`` are now attributes
on the result of the lock_write. ``repository.RepositoryWriteLockResult``
and ``branch.BranchWriteLockResult`` document this. (Robert Collins)

``log._get_info_for_log_files`` now takes an add_cleanup callable.
(Robert Collins)

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