1
# Copyright (C) 2008, 2009 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
18
"""Pyrex extensions to btree node parsing."""
21
cdef extern from "python-compat.h":
24
cdef extern from "stdlib.h":
25
ctypedef unsigned size_t
27
cdef extern from "Python.h":
28
ctypedef int Py_ssize_t # Required for older pyrex versions
29
ctypedef struct PyObject:
31
int PyList_Append(object lst, object item) except -1
33
char *PyString_AsString(object p) except NULL
34
object PyString_FromStringAndSize(char *, Py_ssize_t)
35
PyObject *PyString_FromStringAndSize_ptr "PyString_FromStringAndSize" (char *, Py_ssize_t)
36
int PyString_CheckExact(object s)
37
int PyString_CheckExact_ptr "PyString_CheckExact" (PyObject *)
38
Py_ssize_t PyString_Size(object p)
39
Py_ssize_t PyString_GET_SIZE_ptr "PyString_GET_SIZE" (PyObject *)
40
char * PyString_AS_STRING_ptr "PyString_AS_STRING" (PyObject *)
41
char * PyString_AS_STRING(object)
42
Py_ssize_t PyString_GET_SIZE(object)
43
int PyString_AsStringAndSize_ptr(PyObject *, char **buf, Py_ssize_t *len)
44
void PyString_InternInPlace(PyObject **)
45
int PyTuple_CheckExact(object t)
46
object PyTuple_New(Py_ssize_t n_entries)
47
void PyTuple_SET_ITEM(object, Py_ssize_t offset, object) # steals the ref
48
Py_ssize_t PyTuple_GET_SIZE(object t)
49
PyObject *PyTuple_GET_ITEM_ptr_object "PyTuple_GET_ITEM" (object tpl, int index)
50
void Py_INCREF(object)
51
void Py_DECREF_ptr "Py_DECREF" (PyObject *)
53
cdef extern from "string.h":
54
void *memcpy(void *dest, void *src, size_t n)
55
void *memchr(void *s, int c, size_t n)
57
# void *memrchr(void *s, int c, size_t n)
58
int strncmp(char *s1, char *s2, size_t n)
60
# It seems we need to import the definitions so that the pyrex compiler has
61
# local names to access them.
62
from _static_tuple_c cimport StaticTuple, \
63
import_static_tuple_c, STATIC_TUPLE_ALL_STRING, StaticTuple_New, \
64
StaticTuple_Intern, StaticTuple_SET_ITEM, StaticTuple_CheckExact
67
# TODO: Find some way to import this from _dirstate_helpers
68
cdef void* _my_memrchr(void *s, int c, size_t n):
69
# memrchr seems to be a GNU extension, so we have to implement it ourselves
70
# It is not present in any win32 standard library
82
# TODO: Import this from _dirstate_helpers when it is merged
83
cdef object safe_string_from_size(char *s, Py_ssize_t size):
86
'tried to create a string with an invalid size: %d @0x%x'
88
return PyString_FromStringAndSize(s, size)
91
cdef object safe_interned_string_from_size(char *s, Py_ssize_t size):
95
'tried to create a string with an invalid size: %d @0x%x'
97
py_str = PyString_FromStringAndSize_ptr(s, size)
98
PyString_InternInPlace(&py_str)
99
result = <object>py_str
100
# Casting a PyObject* to an <object> triggers an INCREF from Pyrex, so we
101
# DECREF it to avoid geting immortal strings
102
Py_DECREF_ptr(py_str)
105
from bzrlib import _static_tuple_c
107
_ST = _static_tuple_c.StaticTuple
108
# This sets up the StaticTuple C_API functionality
109
import_static_tuple_c()
112
cdef class BTreeLeafParser:
113
"""Parse the leaf nodes of a BTree index.
115
:ivar bytes: The PyString object containing the uncompressed text for the
117
:ivar key_length: An integer describing how many pieces the keys have for
119
:ivar ref_list_length: An integer describing how many references this index
121
:ivar keys: A PyList of keys found in this node.
123
:ivar _cur_str: A pointer to the start of the next line to parse
124
:ivar _end_str: A pointer to the end of bytes
125
:ivar _start: Pointer to the location within the current line while
127
:ivar _header_found: True when we have parsed the header for this node
132
cdef int ref_list_length
137
# The current start point for parsing
140
cdef int _header_found
142
def __init__(self, bytes, key_length, ref_list_length):
144
self.key_length = key_length
145
self.ref_list_length = ref_list_length
149
self._header_found = 0
152
cdef extract_key(self, char * last):
155
:param last: points at the byte after the last byte permitted for the
159
cdef int loop_counter
162
key = StaticTuple_New(self.key_length)
163
for loop_counter from 0 <= loop_counter < self.key_length:
165
temp_ptr = <char*>memchr(self._start, c'\0', last - self._start)
167
if loop_counter + 1 == self.key_length:
172
failure_string = ("invalid key, wanted segment from " +
173
repr(safe_string_from_size(self._start,
174
last - self._start)))
175
raise AssertionError(failure_string)
176
# capture the key string
177
if (self.key_length == 1
178
and (temp_ptr - self._start) == 45
179
and strncmp(self._start, 'sha1:', 5) == 0):
180
key_element = safe_string_from_size(self._start,
181
temp_ptr - self._start)
183
key_element = safe_interned_string_from_size(self._start,
184
temp_ptr - self._start)
185
# advance our pointer
186
self._start = temp_ptr + 1
187
Py_INCREF(key_element)
188
StaticTuple_SET_ITEM(key, loop_counter, key_element)
189
# key->flags = key->flags | STATIC_TUPLE_ALL_STRING
190
key = StaticTuple_Intern(key)
193
cdef int process_line(self) except -1:
194
"""Process a line in the bytes."""
198
cdef char *next_start
199
cdef int loop_counter
201
self._start = self._cur_str
202
# Find the next newline
203
last = <char*>memchr(self._start, c'\n', self._end_str - self._start)
205
# Process until the end of the file
207
self._cur_str = self._end_str
209
# And the next string is right after it
210
self._cur_str = last + 1
211
# The last character is right before the '\n'
214
if last == self._start:
217
if last < self._start:
218
# Unexpected error condition - fail
220
if 0 == self._header_found:
221
# The first line in a leaf node is the header "type=leaf\n"
222
if strncmp("type=leaf", self._start, last - self._start) == 0:
223
self._header_found = 1
226
raise AssertionError('Node did not start with "type=leaf": %r'
227
% (safe_string_from_size(self._start, last - self._start)))
230
key = self.extract_key(last)
231
# find the value area
232
temp_ptr = <char*>_my_memrchr(self._start, c'\0', last - self._start)
237
# capture the value string
238
value = safe_string_from_size(temp_ptr + 1, last - temp_ptr - 1)
239
# shrink the references end point
241
if self.ref_list_length:
244
while loop_counter < self.ref_list_length:
246
# extract a reference list
247
loop_counter = loop_counter + 1
248
if last < self._start:
250
# find the next reference list end point:
251
temp_ptr = <char*>memchr(self._start, c'\t', last - self._start)
253
# Only valid for the last list
254
if loop_counter != self.ref_list_length:
257
raise AssertionError("invalid key")
259
# scan to the end of the ref list area
263
# scan to the end of this ref list
265
next_start = temp_ptr + 1
266
# Now, there may be multiple keys in the ref list.
267
while self._start < ref_ptr:
268
# loop finding keys and extracting them
269
temp_ptr = <char*>memchr(self._start, c'\r',
270
ref_ptr - self._start)
272
# key runs to the end
274
PyList_Append(ref_list, self.extract_key(temp_ptr))
275
ref_list = StaticTuple_Intern(StaticTuple(*ref_list))
276
PyList_Append(ref_lists, ref_list)
277
# prepare for the next reference list
278
self._start = next_start
279
ref_lists = StaticTuple(*ref_lists)
280
node_value = StaticTuple(value, ref_lists)
282
if last != self._start:
283
# unexpected reference data present
285
node_value = StaticTuple(value, StaticTuple())
286
PyList_Append(self.keys, StaticTuple(key, node_value))
290
cdef Py_ssize_t byte_count
291
if not PyString_CheckExact(self.bytes):
292
raise AssertionError('self.bytes is not a string.')
293
byte_count = PyString_Size(self.bytes)
294
self._cur_str = PyString_AsString(self.bytes)
295
# This points to the last character in the string
296
self._end_str = self._cur_str + byte_count
297
while self._cur_str < self._end_str:
302
def _parse_leaf_lines(bytes, key_length, ref_list_length):
303
parser = BTreeLeafParser(bytes, key_length, ref_list_length)
304
return parser.parse()
307
def _flatten_node(node, reference_lists):
308
"""Convert a node into the serialized form.
310
:param node: A tuple representing a node:
311
(index, key_tuple, value, references)
312
:param reference_lists: Does this index have reference lists?
313
:return: (string_key, flattened)
314
string_key The serialized key for referencing this node
315
flattened A string with the serialized form for the contents
317
cdef int have_reference_lists
318
cdef Py_ssize_t flat_len
319
cdef Py_ssize_t key_len
320
cdef Py_ssize_t node_len
322
cdef Py_ssize_t value_len
324
cdef Py_ssize_t refs_len
325
cdef Py_ssize_t next_len
326
cdef int first_ref_list
327
cdef int first_reference
329
cdef Py_ssize_t ref_bit_len
331
if not PyTuple_CheckExact(node) and not StaticTuple_CheckExact(node):
332
raise TypeError('We expected a tuple() or StaticTuple() for node not: %s'
335
have_reference_lists = reference_lists
336
if have_reference_lists:
338
raise ValueError('With ref_lists, we expected 4 entries not: %s'
341
raise ValueError('Without ref_lists, we need at least 3 entries not: %s'
343
# I don't expect that we can do faster than string.join()
344
string_key = '\0'.join(node[1])# <object>PyTuple_GET_ITEM_ptr_object(node, 1))
346
# TODO: instead of using string joins, precompute the final string length,
347
# and then malloc a single string and copy everything in.
349
# TODO: We probably want to use PySequenceFast, because we have lists and
350
# tuples, but we aren't sure which we will get.
352
# line := string_key NULL flat_refs NULL value LF
353
# string_key := BYTES (NULL BYTES)*
354
# flat_refs := ref_list (TAB ref_list)*
355
# ref_list := ref (CR ref)*
356
# ref := BYTES (NULL BYTES)*
359
if have_reference_lists:
360
# Figure out how many bytes it will take to store the references
361
ref_lists = node[3]# <object>PyTuple_GET_ITEM_ptr_object(node, 3)
362
next_len = len(ref_lists) # TODO: use a Py function
364
# If there are no nodes, we don't need to do any work
365
# Otherwise we will need (len - 1) '\t' characters to separate
366
# the reference lists
367
refs_len = refs_len + (next_len - 1)
368
for ref_list in ref_lists:
369
next_len = len(ref_list)
371
# We will need (len - 1) '\r' characters to separate the
373
refs_len = refs_len + (next_len - 1)
374
for reference in ref_list:
375
if (not PyTuple_CheckExact(reference)
376
and not StaticTuple_CheckExact(reference)):
378
'We expect references to be tuples not: %s'
380
next_len = len(reference)
382
# We will need (len - 1) '\x00' characters to
383
# separate the reference key
384
refs_len = refs_len + (next_len - 1)
385
for i from 0 <= i < next_len:
386
ref_bit = reference[i]
387
if not PyString_CheckExact(ref_bit):
388
raise TypeError('We expect reference bits'
389
' to be strings not: %s'
390
% type(<object>ref_bit))
391
refs_len = refs_len + PyString_GET_SIZE(ref_bit)
393
# So we have the (key NULL refs NULL value LF)
394
key_len = PyString_Size(string_key)
395
val = node[2] # PyTuple_GET_ITEM_ptr_object(node, 2)
396
if not PyString_CheckExact(val):
397
raise TypeError('Expected a plain str for value not: %s'
399
value = PyString_AS_STRING(val)
400
value_len = PyString_GET_SIZE(val)
401
flat_len = (key_len + 1 + refs_len + 1 + value_len + 1)
402
line = PyString_FromStringAndSize(NULL, flat_len)
403
# Get a pointer to the new buffer
404
out = PyString_AsString(line)
405
memcpy(out, PyString_AsString(string_key), key_len)
411
for ref_list in ref_lists:
412
if first_ref_list == 0:
417
for reference in ref_list:
418
if first_reference == 0:
422
next_len = len(reference)
423
for i from 0 <= i < next_len:
427
ref_bit = reference[i] #PyTuple_GET_ITEM_ptr_object(reference, i)
428
ref_bit_len = PyString_GET_SIZE(ref_bit)
429
memcpy(out, PyString_AS_STRING(ref_bit), ref_bit_len)
430
out = out + ref_bit_len
433
memcpy(out, value, value_len)
434
out = out + value_len
436
return string_key, line