~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/_chk_map_pyx.pyx

Some code cleanup passes.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2009 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
 
 
18
#python2.4 support
 
19
cdef extern from "python-compat.h":
 
20
    pass
 
21
 
 
22
cdef extern from *:
 
23
    ctypedef unsigned int size_t
 
24
    int memcmp(void *, void*, size_t)
 
25
    void memcpy(void *, void*, size_t)
 
26
    void *memchr(void *s, int c, size_t len)
 
27
    long strtol(char *, char **, int)
 
28
    void sprintf(char *, char *, ...)
 
29
 
 
30
cdef extern from "Python.h":
 
31
    ctypedef int Py_ssize_t # Required for older pyrex versions
 
32
    struct _PyObject:
 
33
        pass
 
34
    ctypedef _PyObject PyObject
 
35
    int PyTuple_CheckExact(object p)
 
36
    Py_ssize_t PyTuple_GET_SIZE(object t)
 
37
    int PyString_CheckExact(object)
 
38
    char *PyString_AS_STRING(object s)
 
39
    Py_ssize_t PyString_GET_SIZE(object)
 
40
 
 
41
    int PyDict_SetItem(object d, object k, object v) except -1
 
42
 
 
43
    object PyTuple_New(Py_ssize_t count)
 
44
    void PyTuple_SET_ITEM(object t, Py_ssize_t offset, object)
 
45
 
 
46
    void Py_INCREF(object)
 
47
 
 
48
    PyObject * PyTuple_GET_ITEM_ptr "PyTuple_GET_ITEM" (object t,
 
49
                                                        Py_ssize_t offset)
 
50
    int PyString_CheckExact_ptr "PyString_CheckExact" (PyObject *p)
 
51
    Py_ssize_t PyString_GET_SIZE_ptr "PyString_GET_SIZE" (PyObject *s)
 
52
    char *PyString_AS_STRING_ptr "PyString_AS_STRING" (PyObject *s)
 
53
    object PyString_FromStringAndSize(char*, Py_ssize_t)
 
54
 
 
55
cdef extern from "zlib.h":
 
56
    ctypedef unsigned long uLong
 
57
    ctypedef unsigned int uInt
 
58
    ctypedef unsigned char Bytef
 
59
 
 
60
    uLong crc32(uLong crc, Bytef *buf, uInt len)
 
61
 
 
62
# It seems we need to import the definitions so that the pyrex compiler has
 
63
# local names to access them.
 
64
from _static_tuple_c cimport StaticTuple,\
 
65
    import_static_tuple_c, StaticTuple_New, \
 
66
    StaticTuple_Intern, StaticTuple_SET_ITEM, StaticTuple_CheckExact
 
67
 
 
68
 
 
69
# This sets up the StaticTuple C_API functionality
 
70
if import_static_tuple_c() != 0:
 
71
    raise ImportError('der borken')
 
72
 
 
73
cdef object _LeafNode
 
74
_LeafNode = None
 
75
cdef object _InternalNode
 
76
_InternalNode = None
 
77
cdef object _unknown
 
78
_unknown = None
 
79
 
 
80
# We shouldn't just copy this from _dirstate_helpers_pyx
 
81
cdef void* _my_memrchr(void *s, int c, size_t n):
 
82
    # memrchr seems to be a GNU extension, so we have to implement it ourselves
 
83
    cdef char *pos
 
84
    cdef char *start
 
85
 
 
86
    start = <char*>s
 
87
    pos = start + n - 1
 
88
    while pos >= start:
 
89
        if pos[0] == c:
 
90
            return <void*>pos
 
91
        pos = pos - 1
 
92
    return NULL
 
93
 
 
94
 
 
95
def _search_key_16(key):
 
96
    """See chk_map._search_key_16."""
 
97
    cdef Py_ssize_t num_bits
 
98
    cdef Py_ssize_t i, j
 
99
    cdef Py_ssize_t num_out_bytes
 
100
    cdef Bytef *c_bit
 
101
    cdef uLong c_len
 
102
    cdef uInt crc_val
 
103
    cdef Py_ssize_t out_off
 
104
    cdef char *c_out
 
105
    # cdef PyObject *bit
 
106
 
 
107
    if not PyTuple_CheckExact(key) and not StaticTuple_CheckExact(key):
 
108
        raise TypeError('key %r is not a tuple' % (key,))
 
109
    num_bits = len(key)
 
110
    # 4 bytes per crc32, and another 1 byte between bits
 
111
    num_out_bytes = (9 * num_bits) - 1
 
112
    out = PyString_FromStringAndSize(NULL, num_out_bytes)
 
113
    c_out = PyString_AS_STRING(out)
 
114
    for i from 0 <= i < num_bits:
 
115
        if i > 0:
 
116
            c_out[0] = c'\x00'
 
117
            c_out = c_out + 1
 
118
        # We use the _ptr variant, because GET_ITEM returns a borrowed
 
119
        # reference, and Pyrex assumes that returned 'object' are a new
 
120
        # reference
 
121
        # XXX: This needs to be updated for PySequence_GetItem since both
 
122
        #      PyTuple and StaticTuple support that api
 
123
        bit = key[i]# PyTuple_GET_ITEM_ptr(key, i)
 
124
        if not PyString_CheckExact(bit):
 
125
            raise TypeError('Bit %d of %r is not a string' % (i, key))
 
126
        c_bit = <Bytef *>PyString_AS_STRING(bit)
 
127
        c_len = PyString_GET_SIZE(bit)
 
128
        crc_val = crc32(0, c_bit, c_len)
 
129
        # Hex(val) order
 
130
        sprintf(c_out, '%08X', crc_val)
 
131
        c_out = c_out + 8
 
132
    return out
 
133
 
 
134
 
 
135
def _search_key_255(key):
 
136
    """See chk_map._search_key_255."""
 
137
    cdef Py_ssize_t num_bits
 
138
    cdef Py_ssize_t i, j
 
139
    cdef Py_ssize_t num_out_bytes
 
140
    cdef Bytef *c_bit
 
141
    cdef uLong c_len
 
142
    cdef uInt crc_val
 
143
    cdef Py_ssize_t out_off
 
144
    cdef char *c_out
 
145
    # cdef PyObject *bit
 
146
 
 
147
    if not PyTuple_CheckExact(key) and not StaticTuple_CheckExact(key):
 
148
        raise TypeError('key %r is not a tuple' % (key,))
 
149
    num_bits = len(key)
 
150
    # 4 bytes per crc32, and another 1 byte between bits
 
151
    num_out_bytes = (5 * num_bits) - 1
 
152
    out = PyString_FromStringAndSize(NULL, num_out_bytes)
 
153
    c_out = PyString_AS_STRING(out)
 
154
    for i from 0 <= i < num_bits:
 
155
        if i > 0:
 
156
            c_out[0] = c'\x00'
 
157
            c_out = c_out + 1
 
158
        bit = key[i] # PyTuple_GET_ITEM_ptr(key, i)
 
159
        if not PyString_CheckExact(bit):
 
160
            raise TypeError('Bit %d of %r is not a string: %r' % (i, key,
 
161
            bit))
 
162
        c_bit = <Bytef *>PyString_AS_STRING(bit)
 
163
        c_len = PyString_GET_SIZE(bit)
 
164
        crc_val = crc32(0, c_bit, c_len)
 
165
        # MSB order
 
166
        c_out[0] = (crc_val >> 24) & 0xFF
 
167
        c_out[1] = (crc_val >> 16) & 0xFF
 
168
        c_out[2] = (crc_val >> 8) & 0xFF
 
169
        c_out[3] = (crc_val >> 0) & 0xFF
 
170
        for j from 0 <= j < 4:
 
171
            if c_out[j] == c'\n':
 
172
                c_out[j] = c'_'
 
173
        c_out = c_out + 4
 
174
    return out
 
175
 
 
176
 
 
177
cdef int _get_int_from_line(char **cur, char *end, char *message) except -1:
 
178
    """Read a positive integer from the data stream.
 
179
 
 
180
    :param cur: The start of the data, this will be moved to after the
 
181
        trailing newline when done.
 
182
    :param end: Do not parse any data past this byte.
 
183
    :return: The integer stored in those bytes
 
184
    """
 
185
    cdef int value
 
186
    cdef char *next_line, *next
 
187
 
 
188
    next_line = <char *>memchr(cur[0], c'\n', end - cur[0])
 
189
    if next_line == NULL:
 
190
        raise ValueError("Missing %s line\n" % message)
 
191
 
 
192
    value = strtol(cur[0], &next, 10)
 
193
    if next != next_line:
 
194
        raise ValueError("%s line not a proper int\n" % message)
 
195
    cur[0] = next_line + 1
 
196
    return value
 
197
 
 
198
 
 
199
def _deserialise_leaf_node(bytes, key, search_key_func=None):
 
200
    """Deserialise bytes, with key key, into a LeafNode.
 
201
 
 
202
    :param bytes: The bytes of the node.
 
203
    :param key: The key that the serialised node has.
 
204
    """
 
205
    cdef char *c_bytes, *cur, *next, *end
 
206
    cdef char *next_line
 
207
    cdef Py_ssize_t c_bytes_len, prefix_length, items_length
 
208
    cdef int maximum_size, width, length, i, prefix_tail_len
 
209
    cdef int num_value_lines, num_prefix_bits
 
210
    cdef char *prefix, *value_start, *prefix_tail
 
211
    cdef char *next_null, *last_null, *line_start
 
212
    cdef char *c_entry, *entry_start
 
213
    cdef StaticTuple entry_bits
 
214
 
 
215
    if _LeafNode is None:
 
216
        from bzrlib import chk_map
 
217
        _LeafNode = chk_map.LeafNode
 
218
        _InternalNode = chk_map.InternalNode
 
219
        _unknown = chk_map._unknown
 
220
 
 
221
    result = _LeafNode(search_key_func=search_key_func)
 
222
    # Splitlines can split on '\r' so don't use it, split('\n') adds an
 
223
    # extra '' if the bytes ends in a final newline.
 
224
    if not PyString_CheckExact(bytes):
 
225
        raise TypeError('bytes must be a plain string not %s' % (type(bytes),))
 
226
 
 
227
    c_bytes = PyString_AS_STRING(bytes)
 
228
    c_bytes_len = PyString_GET_SIZE(bytes)
 
229
 
 
230
    if c_bytes_len < 9 or memcmp(c_bytes, "chkleaf:\n", 9) != 0:
 
231
        raise ValueError("not a serialised leaf node: %r" % bytes)
 
232
    if c_bytes[c_bytes_len - 1] != c'\n':
 
233
        raise ValueError("bytes does not end in a newline")
 
234
 
 
235
    end = c_bytes + c_bytes_len
 
236
    cur = c_bytes + 9
 
237
    maximum_size = _get_int_from_line(&cur, end, "maximum_size")
 
238
    width = _get_int_from_line(&cur, end, "width")
 
239
    length = _get_int_from_line(&cur, end, "length")
 
240
 
 
241
    next_line = <char *>memchr(cur, c'\n', end - cur)
 
242
    if next_line == NULL:
 
243
        raise ValueError('Missing the prefix line\n')
 
244
    prefix = cur
 
245
    prefix_length = next_line - cur
 
246
    cur = next_line + 1
 
247
 
 
248
    prefix_bits = []
 
249
    prefix_tail = prefix
 
250
    num_prefix_bits = 0
 
251
    next_null = <char *>memchr(prefix, c'\0', prefix_length)
 
252
    while next_null != NULL:
 
253
        num_prefix_bits = num_prefix_bits + 1
 
254
        prefix_bits.append(
 
255
            PyString_FromStringAndSize(prefix_tail, next_null - prefix_tail))
 
256
        prefix_tail = next_null + 1
 
257
        next_null = <char *>memchr(prefix_tail, c'\0', next_line - prefix_tail)
 
258
    prefix_tail_len = next_line - prefix_tail
 
259
 
 
260
    if num_prefix_bits >= width:
 
261
        raise ValueError('Prefix has too many nulls versus width')
 
262
 
 
263
    items_length = end - cur
 
264
    items = {}
 
265
    while cur < end:
 
266
        line_start = cur
 
267
        next_line = <char *>memchr(cur, c'\n', end - cur)
 
268
        if next_line == NULL:
 
269
            raise ValueError('null line\n')
 
270
        last_null = <char *>_my_memrchr(cur, c'\0', next_line - cur)
 
271
        if last_null == NULL:
 
272
            raise ValueError('fail to find the num value lines null')
 
273
        next_null = last_null + 1 # move past NULL
 
274
        num_value_lines = _get_int_from_line(&next_null, next_line + 1,
 
275
                                             "num value lines")
 
276
        cur = next_line + 1
 
277
        value_start = cur
 
278
        # Walk num_value_lines forward
 
279
        for i from 0 <= i < num_value_lines:
 
280
            next_line = <char *>memchr(cur, c'\n', end - cur)
 
281
            if next_line == NULL:
 
282
                raise ValueError('missing trailing newline')
 
283
            cur = next_line + 1
 
284
        entry_bits = StaticTuple_New(width)
 
285
        for i from 0 <= i < num_prefix_bits:
 
286
            entry = prefix_bits[i]
 
287
            # SET_ITEM 'steals' a reference
 
288
            Py_INCREF(entry)
 
289
            StaticTuple_SET_ITEM(entry_bits, i, entry)
 
290
        value = PyString_FromStringAndSize(value_start, next_line - value_start)
 
291
        # The next entry bit needs the 'tail' from the prefix, and first part
 
292
        # of the line
 
293
        entry_start = line_start
 
294
        next_null = <char *>memchr(entry_start, c'\0',
 
295
                                   last_null - entry_start + 1)
 
296
        if next_null == NULL:
 
297
            raise ValueError('bad no null, bad')
 
298
        entry = PyString_FromStringAndSize(NULL,
 
299
                    prefix_tail_len + next_null - line_start)
 
300
        c_entry = PyString_AS_STRING(entry)
 
301
        if prefix_tail_len > 0:
 
302
            memcpy(c_entry, prefix_tail, prefix_tail_len)
 
303
        if next_null - line_start > 0:
 
304
            memcpy(c_entry + prefix_tail_len, line_start, next_null - line_start)
 
305
        Py_INCREF(entry)
 
306
        i = num_prefix_bits
 
307
        StaticTuple_SET_ITEM(entry_bits, i, entry)
 
308
        while next_null != last_null: # We have remaining bits
 
309
            i = i + 1
 
310
            if i > width:
 
311
                raise ValueError("Too many bits for entry")
 
312
            entry_start = next_null + 1
 
313
            next_null = <char *>memchr(entry_start, c'\0',
 
314
                                       last_null - entry_start + 1)
 
315
            if next_null == NULL:
 
316
                raise ValueError('bad no null')
 
317
            entry = PyString_FromStringAndSize(entry_start,
 
318
                                               next_null - entry_start)
 
319
            Py_INCREF(entry)
 
320
            StaticTuple_SET_ITEM(entry_bits, i, entry)
 
321
        if len(entry_bits) != width:
 
322
            raise AssertionError(
 
323
                'Incorrect number of elements (%d vs %d)'
 
324
                % (len(entry_bits)+1, width + 1))
 
325
        entry_bits = StaticTuple_Intern(entry_bits)
 
326
        PyDict_SetItem(items, entry_bits, value)
 
327
    if len(items) != length:
 
328
        raise ValueError("item count (%d) mismatch for key %s,"
 
329
                         " bytes %r" % (length, entry_bits, bytes))
 
330
    result._items = items
 
331
    result._len = length
 
332
    result._maximum_size = maximum_size
 
333
    result._key = key
 
334
    result._key_width = width
 
335
    result._raw_size = items_length + length * prefix_length
 
336
    if length == 0:
 
337
        result._search_prefix = None
 
338
        result._common_serialised_prefix = None
 
339
    else:
 
340
        result._search_prefix = _unknown
 
341
        result._common_serialised_prefix = PyString_FromStringAndSize(prefix,
 
342
                                                prefix_length)
 
343
    if c_bytes_len != result._current_size():
 
344
        raise AssertionError('_current_size computed incorrectly %d != %d',
 
345
            c_bytes_len, result._current_size())
 
346
    return result
 
347
 
 
348
 
 
349
def _deserialise_internal_node(bytes, key, search_key_func=None):
 
350
    cdef char *c_bytes, *cur, *next, *end
 
351
    cdef char *next_line
 
352
    cdef Py_ssize_t c_bytes_len, prefix_length
 
353
    cdef int maximum_size, width, length, i, prefix_tail_len
 
354
    cdef char *prefix, *line_prefix, *next_null, *c_item_prefix
 
355
 
 
356
    if _InternalNode is None:
 
357
        from bzrlib import chk_map
 
358
        _LeafNode = chk_map.LeafNode
 
359
        _InternalNode = chk_map.InternalNode
 
360
        _unknown = chk_map._unknown
 
361
    result = _InternalNode(search_key_func=search_key_func)
 
362
 
 
363
    if not PyString_CheckExact(bytes):
 
364
        raise TypeError('bytes must be a plain string not %s' % (type(bytes),))
 
365
 
 
366
    c_bytes = PyString_AS_STRING(bytes)
 
367
    c_bytes_len = PyString_GET_SIZE(bytes)
 
368
 
 
369
    if c_bytes_len < 9 or memcmp(c_bytes, "chknode:\n", 9) != 0:
 
370
        raise ValueError("not a serialised internal node: %r" % bytes)
 
371
    if c_bytes[c_bytes_len - 1] != c'\n':
 
372
        raise ValueError("bytes does not end in a newline")
 
373
 
 
374
    items = {}
 
375
    cur = c_bytes + 9
 
376
    end = c_bytes + c_bytes_len
 
377
    maximum_size = _get_int_from_line(&cur, end, "maximum_size")
 
378
    width = _get_int_from_line(&cur, end, "width")
 
379
    length = _get_int_from_line(&cur, end, "length")
 
380
 
 
381
    next_line = <char *>memchr(cur, c'\n', end - cur)
 
382
    if next_line == NULL:
 
383
        raise ValueError('Missing the prefix line\n')
 
384
    prefix = cur
 
385
    prefix_length = next_line - cur
 
386
    cur = next_line + 1
 
387
 
 
388
    while cur < end:
 
389
        # Find the null separator
 
390
        next_line = <char *>memchr(cur, c'\n', end - cur)
 
391
        if next_line == NULL:
 
392
            raise ValueError('missing trailing newline')
 
393
        next_null = <char *>_my_memrchr(cur, c'\0', next_line - cur)
 
394
        if next_null == NULL:
 
395
            raise ValueError('bad no null')
 
396
        item_prefix = PyString_FromStringAndSize(NULL,
 
397
            prefix_length + next_null - cur)
 
398
        c_item_prefix = PyString_AS_STRING(item_prefix)
 
399
        if prefix_length:
 
400
            memcpy(c_item_prefix, prefix, prefix_length)
 
401
        memcpy(c_item_prefix + prefix_length, cur, next_null - cur)
 
402
        flat_key = PyString_FromStringAndSize(next_null + 1,
 
403
                                              next_line - next_null - 1)
 
404
        flat_key = StaticTuple(flat_key).intern()
 
405
        PyDict_SetItem(items, item_prefix, flat_key)
 
406
        cur = next_line + 1
 
407
    assert len(items) > 0
 
408
    result._items = items
 
409
    result._len = length
 
410
    result._maximum_size = maximum_size
 
411
    result._key = key
 
412
    result._key_width = width
 
413
    # XXX: InternalNodes don't really care about their size, and this will
 
414
    #      change if we add prefix compression
 
415
    result._raw_size = None # len(bytes)
 
416
    result._node_width = len(item_prefix)
 
417
    result._search_prefix = PyString_FromStringAndSize(prefix, prefix_length)
 
418
    return result
 
419
 
 
420
 
 
421
_key_type = StaticTuple