1
# Copyright (C) 2009, 2010 Canonical Ltd
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.
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.
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
19
cdef extern from "python-compat.h":
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 *, ...)
30
cdef extern from "Python.h":
31
ctypedef int Py_ssize_t # Required for older pyrex versions
32
ctypedef struct PyObject:
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
41
int PyDict_SetItem(object d, object k, object v) except -1
43
object PyTuple_New(Py_ssize_t count)
44
void PyTuple_SET_ITEM(object t, Py_ssize_t offset, object)
46
void Py_INCREF(object)
48
PyObject * PyTuple_GET_ITEM_ptr "PyTuple_GET_ITEM" (object t,
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)
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, \
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
65
PyObject * StaticTuple_GET_ITEM_ptr "StaticTuple_GET_ITEM" (StaticTuple,
69
from zlib import crc32
72
# Set up the StaticTuple C_API functionality
73
import_static_tuple_c()
77
cdef object _InternalNode
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
97
def _search_key_16(key):
98
"""See chk_map._search_key_16."""
99
cdef Py_ssize_t num_bits
101
cdef Py_ssize_t num_out_bytes
102
cdef unsigned long crc_val
103
cdef Py_ssize_t out_off
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:
115
crc_val = PyInt_AsUnsignedLongMask(crc32(key[i]))
117
sprintf(c_out, '%08X', crc_val)
122
def _search_key_255(key):
123
"""See chk_map._search_key_255."""
124
cdef Py_ssize_t num_bits
126
cdef Py_ssize_t num_out_bytes
127
cdef unsigned long crc_val
128
cdef Py_ssize_t out_off
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:
140
crc_val = PyInt_AsUnsignedLongMask(crc32(key[i]))
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':
153
cdef int _get_int_from_line(char **cur, char *end, char *message) except -1:
154
"""Read a positive integer from the data stream.
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
162
cdef char *next_line, *next
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)
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
175
cdef _import_globals():
176
"""Set the global attributes. Done lazy to avoid recursive import loops."""
177
global _LeafNode, _InternalNode, _unknown
179
from bzrlib import chk_map
180
_LeafNode = chk_map.LeafNode
181
_InternalNode = chk_map.InternalNode
182
_unknown = chk_map._unknown
185
def _deserialise_leaf_node(bytes, key, search_key_func=None):
186
"""Deserialise bytes, with key key, into a LeafNode.
188
:param bytes: The bytes of the node.
189
:param key: The key that the serialised node has.
191
cdef char *c_bytes, *cur, *next, *end
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
201
if _LeafNode is None:
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),))
210
c_bytes = PyString_AS_STRING(bytes)
211
c_bytes_len = PyString_GET_SIZE(bytes)
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")
218
end = c_bytes + c_bytes_len
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")
224
next_line = <char *>memchr(cur, c'\n', end - cur)
225
if next_line == NULL:
226
raise ValueError('Missing the prefix line\n')
228
prefix_length = next_line - cur
234
next_null = <char *>memchr(prefix, c'\0', prefix_length)
235
while next_null != NULL:
236
num_prefix_bits = num_prefix_bits + 1
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
243
if num_prefix_bits >= width:
244
raise ValueError('Prefix has too many nulls versus width')
246
items_length = end - 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,
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')
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
271
entry = prefix_bits[i]
272
# SET_ITEM 'steals' a reference
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
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)
292
StaticTuple_SET_ITEM(entry_bits, i, entry)
293
while next_null != last_null: # We have remaining bits
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)
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
317
result._maximum_size = maximum_size
319
result._key_width = width
320
result._raw_size = items_length + length * prefix_length
322
result._search_prefix = None
323
result._common_serialised_prefix = None
325
result._search_prefix = _unknown
326
result._common_serialised_prefix = PyString_FromStringAndSize(prefix,
328
if c_bytes_len != result._current_size():
329
raise AssertionError('_current_size computed incorrectly %d != %d',
330
c_bytes_len, result._current_size())
334
def _deserialise_internal_node(bytes, key, search_key_func=None):
335
cdef char *c_bytes, *cur, *next, *end
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
341
if _InternalNode is None:
343
result = _InternalNode(search_key_func=search_key_func)
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),))
350
c_bytes = PyString_AS_STRING(bytes)
351
c_bytes_len = PyString_GET_SIZE(bytes)
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")
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")
365
next_line = <char *>memchr(cur, c'\n', end - cur)
366
if next_line == NULL:
367
raise ValueError('Missing the prefix line\n')
369
prefix_length = next_line - cur
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)
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)
391
assert len(items) > 0
392
result._items = items
394
result._maximum_size = maximum_size
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)