/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/_chk_map_pyx.pyx

  • Committer: John Arbash Meinel
  • Date: 2010-05-11 14:13:31 UTC
  • mto: (5218.2.2 bytes_to_entry_c)
  • mto: This revision was merged to the branch mainline in revision 5225.
  • Revision ID: john@arbash-meinel.com-20100511141331-rizo2ez6bze3ao66
Some small tweaks to the chk_map code.

Find out that we actually weren't using the global definition because we
were assigning inside the if block. So factor that out into a helper.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2009, 2010 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
    ctypedef struct PyObject:
 
33
        pass
 
34
    int PyTuple_CheckExact(object p)
 
35
    Py_ssize_t PyTuple_GET_SIZE(object t)
 
36
    int PyString_CheckExact(object)
 
37
    char *PyString_AS_STRING(object s)
 
38
    Py_ssize_t PyString_GET_SIZE(object)
 
39
    unsigned long PyInt_AsUnsignedLongMask(object) except? -1
 
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
# cimport all of the definitions we will need to access
 
56
from _static_tuple_c cimport StaticTuple,\
 
57
    import_static_tuple_c, StaticTuple_New, \
 
58
    StaticTuple_Intern, StaticTuple_SET_ITEM, StaticTuple_CheckExact, \
 
59
    StaticTuple_GET_SIZE
 
60
 
 
61
cdef extern from "_static_tuple_c.h":
 
62
    # Defined explicitly rather than cimport-ing. Trying to use cimport, the
 
63
    # type for PyObject is a different class that happens to have the same
 
64
    # name...
 
65
    PyObject * StaticTuple_GET_ITEM_ptr "StaticTuple_GET_ITEM" (StaticTuple,
 
66
                                                                Py_ssize_t)
 
67
 
 
68
cdef object crc32
 
69
from zlib import crc32
 
70
 
 
71
 
 
72
# Set up the StaticTuple C_API functionality
 
73
import_static_tuple_c()
 
74
 
 
75
cdef object _LeafNode
 
76
_LeafNode = None
 
77
cdef object _InternalNode
 
78
_InternalNode = None
 
79
cdef object _unknown
 
80
_unknown = None
 
81
 
 
82
# We shouldn't just copy this from _dirstate_helpers_pyx
 
83
cdef void* _my_memrchr(void *s, int c, size_t n): # cannot_raise
 
84
    # memrchr seems to be a GNU extension, so we have to implement it ourselves
 
85
    cdef char *pos
 
86
    cdef char *start
 
87
 
 
88
    start = <char*>s
 
89
    pos = start + n - 1
 
90
    while pos >= start:
 
91
        if pos[0] == c:
 
92
            return <void*>pos
 
93
        pos = pos - 1
 
94
    return NULL
 
95
 
 
96
 
 
97
def _search_key_16(key):
 
98
    """See chk_map._search_key_16."""
 
99
    cdef Py_ssize_t num_bits
 
100
    cdef Py_ssize_t i, j
 
101
    cdef Py_ssize_t num_out_bytes
 
102
    cdef unsigned long crc_val
 
103
    cdef Py_ssize_t out_off
 
104
    cdef char *c_out
 
105
 
 
106
    num_bits = len(key)
 
107
    # 4 bytes per crc32, and another 1 byte between bits
 
108
    num_out_bytes = (9 * num_bits) - 1
 
109
    out = PyString_FromStringAndSize(NULL, num_out_bytes)
 
110
    c_out = PyString_AS_STRING(out)
 
111
    for i from 0 <= i < num_bits:
 
112
        if i > 0:
 
113
            c_out[0] = c'\x00'
 
114
            c_out = c_out + 1
 
115
        crc_val = PyInt_AsUnsignedLongMask(crc32(key[i]))
 
116
        # Hex(val) order
 
117
        sprintf(c_out, '%08X', crc_val)
 
118
        c_out = c_out + 8
 
119
    return out
 
120
 
 
121
 
 
122
def _search_key_255(key):
 
123
    """See chk_map._search_key_255."""
 
124
    cdef Py_ssize_t num_bits
 
125
    cdef Py_ssize_t i, j
 
126
    cdef Py_ssize_t num_out_bytes
 
127
    cdef unsigned long crc_val
 
128
    cdef Py_ssize_t out_off
 
129
    cdef char *c_out
 
130
 
 
131
    num_bits = len(key)
 
132
    # 4 bytes per crc32, and another 1 byte between bits
 
133
    num_out_bytes = (5 * num_bits) - 1
 
134
    out = PyString_FromStringAndSize(NULL, num_out_bytes)
 
135
    c_out = PyString_AS_STRING(out)
 
136
    for i from 0 <= i < num_bits:
 
137
        if i > 0:
 
138
            c_out[0] = c'\x00'
 
139
            c_out = c_out + 1
 
140
        crc_val = PyInt_AsUnsignedLongMask(crc32(key[i]))
 
141
        # MSB order
 
142
        c_out[0] = (crc_val >> 24) & 0xFF
 
143
        c_out[1] = (crc_val >> 16) & 0xFF
 
144
        c_out[2] = (crc_val >> 8) & 0xFF
 
145
        c_out[3] = (crc_val >> 0) & 0xFF
 
146
        for j from 0 <= j < 4:
 
147
            if c_out[j] == c'\n':
 
148
                c_out[j] = c'_'
 
149
        c_out = c_out + 4
 
150
    return out
 
151
 
 
152
 
 
153
cdef int _get_int_from_line(char **cur, char *end, char *message) except -1:
 
154
    """Read a positive integer from the data stream.
 
155
 
 
156
    :param cur: The start of the data, this will be moved to after the
 
157
        trailing newline when done.
 
158
    :param end: Do not parse any data past this byte.
 
159
    :return: The integer stored in those bytes
 
160
    """
 
161
    cdef int value
 
162
    cdef char *next_line, *next
 
163
 
 
164
    next_line = <char *>memchr(cur[0], c'\n', end - cur[0])
 
165
    if next_line == NULL:
 
166
        raise ValueError("Missing %s line\n" % message)
 
167
 
 
168
    value = strtol(cur[0], &next, 10)
 
169
    if next != next_line:
 
170
        raise ValueError("%s line not a proper int\n" % message)
 
171
    cur[0] = next_line + 1
 
172
    return value
 
173
 
 
174
 
 
175
cdef _import_globals():
 
176
    """Set the global attributes. Done lazy to avoid recursive import loops."""
 
177
    global _LeafNode, _InternalNode, _unknown
 
178
 
 
179
    from bzrlib import chk_map
 
180
    _LeafNode = chk_map.LeafNode
 
181
    _InternalNode = chk_map.InternalNode
 
182
    _unknown = chk_map._unknown
 
183
 
 
184
 
 
185
def _deserialise_leaf_node(bytes, key, search_key_func=None):
 
186
    """Deserialise bytes, with key key, into a LeafNode.
 
187
 
 
188
    :param bytes: The bytes of the node.
 
189
    :param key: The key that the serialised node has.
 
190
    """
 
191
    cdef char *c_bytes, *cur, *next, *end
 
192
    cdef char *next_line
 
193
    cdef Py_ssize_t c_bytes_len, prefix_length, items_length
 
194
    cdef int maximum_size, width, length, i, prefix_tail_len
 
195
    cdef int num_value_lines, num_prefix_bits
 
196
    cdef char *prefix, *value_start, *prefix_tail
 
197
    cdef char *next_null, *last_null, *line_start
 
198
    cdef char *c_entry, *entry_start
 
199
    cdef StaticTuple entry_bits
 
200
 
 
201
    if _LeafNode is None:
 
202
        _import_globals()
 
203
 
 
204
    result = _LeafNode(search_key_func=search_key_func)
 
205
    # Splitlines can split on '\r' so don't use it, split('\n') adds an
 
206
    # extra '' if the bytes ends in a final newline.
 
207
    if not PyString_CheckExact(bytes):
 
208
        raise TypeError('bytes must be a plain string not %s' % (type(bytes),))
 
209
 
 
210
    c_bytes = PyString_AS_STRING(bytes)
 
211
    c_bytes_len = PyString_GET_SIZE(bytes)
 
212
 
 
213
    if c_bytes_len < 9 or memcmp(c_bytes, "chkleaf:\n", 9) != 0:
 
214
        raise ValueError("not a serialised leaf node: %r" % bytes)
 
215
    if c_bytes[c_bytes_len - 1] != c'\n':
 
216
        raise ValueError("bytes does not end in a newline")
 
217
 
 
218
    end = c_bytes + c_bytes_len
 
219
    cur = c_bytes + 9
 
220
    maximum_size = _get_int_from_line(&cur, end, "maximum_size")
 
221
    width = _get_int_from_line(&cur, end, "width")
 
222
    length = _get_int_from_line(&cur, end, "length")
 
223
 
 
224
    next_line = <char *>memchr(cur, c'\n', end - cur)
 
225
    if next_line == NULL:
 
226
        raise ValueError('Missing the prefix line\n')
 
227
    prefix = cur
 
228
    prefix_length = next_line - cur
 
229
    cur = next_line + 1
 
230
 
 
231
    prefix_bits = []
 
232
    prefix_tail = prefix
 
233
    num_prefix_bits = 0
 
234
    next_null = <char *>memchr(prefix, c'\0', prefix_length)
 
235
    while next_null != NULL:
 
236
        num_prefix_bits = num_prefix_bits + 1
 
237
        prefix_bits.append(
 
238
            PyString_FromStringAndSize(prefix_tail, next_null - prefix_tail))
 
239
        prefix_tail = next_null + 1
 
240
        next_null = <char *>memchr(prefix_tail, c'\0', next_line - prefix_tail)
 
241
    prefix_tail_len = next_line - prefix_tail
 
242
 
 
243
    if num_prefix_bits >= width:
 
244
        raise ValueError('Prefix has too many nulls versus width')
 
245
 
 
246
    items_length = end - cur
 
247
    items = {}
 
248
    while cur < end:
 
249
        line_start = cur
 
250
        next_line = <char *>memchr(cur, c'\n', end - cur)
 
251
        if next_line == NULL:
 
252
            raise ValueError('null line\n')
 
253
        last_null = <char *>_my_memrchr(cur, c'\0', next_line - cur)
 
254
        if last_null == NULL:
 
255
            raise ValueError('fail to find the num value lines null')
 
256
        next_null = last_null + 1 # move past NULL
 
257
        num_value_lines = _get_int_from_line(&next_null, next_line + 1,
 
258
                                             "num value lines")
 
259
        cur = next_line + 1
 
260
        value_start = cur
 
261
        # Walk num_value_lines forward
 
262
        for i from 0 <= i < num_value_lines:
 
263
            next_line = <char *>memchr(cur, c'\n', end - cur)
 
264
            if next_line == NULL:
 
265
                raise ValueError('missing trailing newline')
 
266
            cur = next_line + 1
 
267
        entry_bits = StaticTuple_New(width)
 
268
        for i from 0 <= i < num_prefix_bits:
 
269
            # TODO: Use PyList_GetItem, or turn prefix_bits into a
 
270
            #       tuple/StaticTuple
 
271
            entry = prefix_bits[i]
 
272
            # SET_ITEM 'steals' a reference
 
273
            Py_INCREF(entry)
 
274
            StaticTuple_SET_ITEM(entry_bits, i, entry)
 
275
        value = PyString_FromStringAndSize(value_start, next_line - value_start)
 
276
        # The next entry bit needs the 'tail' from the prefix, and first part
 
277
        # of the line
 
278
        entry_start = line_start
 
279
        next_null = <char *>memchr(entry_start, c'\0',
 
280
                                   last_null - entry_start + 1)
 
281
        if next_null == NULL:
 
282
            raise ValueError('bad no null, bad')
 
283
        entry = PyString_FromStringAndSize(NULL,
 
284
                    prefix_tail_len + next_null - line_start)
 
285
        c_entry = PyString_AS_STRING(entry)
 
286
        if prefix_tail_len > 0:
 
287
            memcpy(c_entry, prefix_tail, prefix_tail_len)
 
288
        if next_null - line_start > 0:
 
289
            memcpy(c_entry + prefix_tail_len, line_start, next_null - line_start)
 
290
        Py_INCREF(entry)
 
291
        i = num_prefix_bits
 
292
        StaticTuple_SET_ITEM(entry_bits, i, entry)
 
293
        while next_null != last_null: # We have remaining bits
 
294
            i = i + 1
 
295
            if i > width:
 
296
                raise ValueError("Too many bits for entry")
 
297
            entry_start = next_null + 1
 
298
            next_null = <char *>memchr(entry_start, c'\0',
 
299
                                       last_null - entry_start + 1)
 
300
            if next_null == NULL:
 
301
                raise ValueError('bad no null')
 
302
            entry = PyString_FromStringAndSize(entry_start,
 
303
                                               next_null - entry_start)
 
304
            Py_INCREF(entry)
 
305
            StaticTuple_SET_ITEM(entry_bits, i, entry)
 
306
        if StaticTuple_GET_SIZE(entry_bits) != width:
 
307
            raise AssertionError(
 
308
                'Incorrect number of elements (%d vs %d)'
 
309
                % (len(entry_bits)+1, width + 1))
 
310
        entry_bits = StaticTuple_Intern(entry_bits)
 
311
        PyDict_SetItem(items, entry_bits, value)
 
312
    if len(items) != length:
 
313
        raise ValueError("item count (%d) mismatch for key %s,"
 
314
                         " bytes %r" % (length, entry_bits, bytes))
 
315
    result._items = items
 
316
    result._len = length
 
317
    result._maximum_size = maximum_size
 
318
    result._key = key
 
319
    result._key_width = width
 
320
    result._raw_size = items_length + length * prefix_length
 
321
    if length == 0:
 
322
        result._search_prefix = None
 
323
        result._common_serialised_prefix = None
 
324
    else:
 
325
        result._search_prefix = _unknown
 
326
        result._common_serialised_prefix = PyString_FromStringAndSize(prefix,
 
327
                                                prefix_length)
 
328
    if c_bytes_len != result._current_size():
 
329
        raise AssertionError('_current_size computed incorrectly %d != %d',
 
330
            c_bytes_len, result._current_size())
 
331
    return result
 
332
 
 
333
 
 
334
def _deserialise_internal_node(bytes, key, search_key_func=None):
 
335
    cdef char *c_bytes, *cur, *next, *end
 
336
    cdef char *next_line
 
337
    cdef Py_ssize_t c_bytes_len, prefix_length
 
338
    cdef int maximum_size, width, length, i, prefix_tail_len
 
339
    cdef char *prefix, *line_prefix, *next_null, *c_item_prefix
 
340
 
 
341
    if _InternalNode is None:
 
342
        _import_globals()
 
343
    result = _InternalNode(search_key_func=search_key_func)
 
344
 
 
345
    if not StaticTuple_CheckExact(key):
 
346
        raise TypeError('key %r is not a StaticTuple' % (key,))
 
347
    if not PyString_CheckExact(bytes):
 
348
        raise TypeError('bytes must be a plain string not %s' % (type(bytes),))
 
349
 
 
350
    c_bytes = PyString_AS_STRING(bytes)
 
351
    c_bytes_len = PyString_GET_SIZE(bytes)
 
352
 
 
353
    if c_bytes_len < 9 or memcmp(c_bytes, "chknode:\n", 9) != 0:
 
354
        raise ValueError("not a serialised internal node: %r" % bytes)
 
355
    if c_bytes[c_bytes_len - 1] != c'\n':
 
356
        raise ValueError("bytes does not end in a newline")
 
357
 
 
358
    items = {}
 
359
    cur = c_bytes + 9
 
360
    end = c_bytes + c_bytes_len
 
361
    maximum_size = _get_int_from_line(&cur, end, "maximum_size")
 
362
    width = _get_int_from_line(&cur, end, "width")
 
363
    length = _get_int_from_line(&cur, end, "length")
 
364
 
 
365
    next_line = <char *>memchr(cur, c'\n', end - cur)
 
366
    if next_line == NULL:
 
367
        raise ValueError('Missing the prefix line\n')
 
368
    prefix = cur
 
369
    prefix_length = next_line - cur
 
370
    cur = next_line + 1
 
371
 
 
372
    while cur < end:
 
373
        # Find the null separator
 
374
        next_line = <char *>memchr(cur, c'\n', end - cur)
 
375
        if next_line == NULL:
 
376
            raise ValueError('missing trailing newline')
 
377
        next_null = <char *>_my_memrchr(cur, c'\0', next_line - cur)
 
378
        if next_null == NULL:
 
379
            raise ValueError('bad no null')
 
380
        item_prefix = PyString_FromStringAndSize(NULL,
 
381
            prefix_length + next_null - cur)
 
382
        c_item_prefix = PyString_AS_STRING(item_prefix)
 
383
        if prefix_length:
 
384
            memcpy(c_item_prefix, prefix, prefix_length)
 
385
        memcpy(c_item_prefix + prefix_length, cur, next_null - cur)
 
386
        flat_key = PyString_FromStringAndSize(next_null + 1,
 
387
                                              next_line - next_null - 1)
 
388
        flat_key = StaticTuple(flat_key).intern()
 
389
        PyDict_SetItem(items, item_prefix, flat_key)
 
390
        cur = next_line + 1
 
391
    assert len(items) > 0
 
392
    result._items = items
 
393
    result._len = length
 
394
    result._maximum_size = maximum_size
 
395
    result._key = key
 
396
    result._key_width = width
 
397
    # XXX: InternalNodes don't really care about their size, and this will
 
398
    #      change if we add prefix compression
 
399
    result._raw_size = None # len(bytes)
 
400
    result._node_width = len(item_prefix)
 
401
    result._search_prefix = PyString_FromStringAndSize(prefix, prefix_length)
 
402
    return result