##// END OF EJS Templates
revlog: properly detect corrupted revlog in `index_get_length`...
Boris Feld -
r40772:95913063 default
parent child Browse files
Show More
@@ -1,2849 +1,2856 b''
1 /*
1 /*
2 parsers.c - efficient content parsing
2 parsers.c - efficient content parsing
3
3
4 Copyright 2008 Matt Mackall <mpm@selenic.com> and others
4 Copyright 2008 Matt Mackall <mpm@selenic.com> and others
5
5
6 This software may be used and distributed according to the terms of
6 This software may be used and distributed according to the terms of
7 the GNU General Public License, incorporated herein by reference.
7 the GNU General Public License, incorporated herein by reference.
8 */
8 */
9
9
10 #include <Python.h>
10 #include <Python.h>
11 #include <assert.h>
11 #include <assert.h>
12 #include <ctype.h>
12 #include <ctype.h>
13 #include <limits.h>
13 #include <limits.h>
14 #include <stddef.h>
14 #include <stddef.h>
15 #include <stdlib.h>
15 #include <stdlib.h>
16 #include <string.h>
16 #include <string.h>
17
17
18 #include "bitmanipulation.h"
18 #include "bitmanipulation.h"
19 #include "charencode.h"
19 #include "charencode.h"
20 #include "util.h"
20 #include "util.h"
21
21
22 #ifdef IS_PY3K
22 #ifdef IS_PY3K
23 /* The mapping of Python types is meant to be temporary to get Python
23 /* The mapping of Python types is meant to be temporary to get Python
24 * 3 to compile. We should remove this once Python 3 support is fully
24 * 3 to compile. We should remove this once Python 3 support is fully
25 * supported and proper types are used in the extensions themselves. */
25 * supported and proper types are used in the extensions themselves. */
26 #define PyInt_Check PyLong_Check
26 #define PyInt_Check PyLong_Check
27 #define PyInt_FromLong PyLong_FromLong
27 #define PyInt_FromLong PyLong_FromLong
28 #define PyInt_FromSsize_t PyLong_FromSsize_t
28 #define PyInt_FromSsize_t PyLong_FromSsize_t
29 #define PyInt_AsLong PyLong_AsLong
29 #define PyInt_AsLong PyLong_AsLong
30 #endif
30 #endif
31
31
32 typedef struct indexObjectStruct indexObject;
32 typedef struct indexObjectStruct indexObject;
33
33
34 typedef struct {
34 typedef struct {
35 int children[16];
35 int children[16];
36 } nodetreenode;
36 } nodetreenode;
37
37
38 /*
38 /*
39 * A base-16 trie for fast node->rev mapping.
39 * A base-16 trie for fast node->rev mapping.
40 *
40 *
41 * Positive value is index of the next node in the trie
41 * Positive value is index of the next node in the trie
42 * Negative value is a leaf: -(rev + 2)
42 * Negative value is a leaf: -(rev + 2)
43 * Zero is empty
43 * Zero is empty
44 */
44 */
45 typedef struct {
45 typedef struct {
46 indexObject *index;
46 indexObject *index;
47 nodetreenode *nodes;
47 nodetreenode *nodes;
48 unsigned length; /* # nodes in use */
48 unsigned length; /* # nodes in use */
49 unsigned capacity; /* # nodes allocated */
49 unsigned capacity; /* # nodes allocated */
50 int depth; /* maximum depth of tree */
50 int depth; /* maximum depth of tree */
51 int splits; /* # splits performed */
51 int splits; /* # splits performed */
52 } nodetree;
52 } nodetree;
53
53
54 typedef struct {
54 typedef struct {
55 PyObject_HEAD /* ; */
55 PyObject_HEAD /* ; */
56 nodetree nt;
56 nodetree nt;
57 } nodetreeObject;
57 } nodetreeObject;
58
58
59 /*
59 /*
60 * This class has two behaviors.
60 * This class has two behaviors.
61 *
61 *
62 * When used in a list-like way (with integer keys), we decode an
62 * When used in a list-like way (with integer keys), we decode an
63 * entry in a RevlogNG index file on demand. Our last entry is a
63 * entry in a RevlogNG index file on demand. Our last entry is a
64 * sentinel, always a nullid. We have limited support for
64 * sentinel, always a nullid. We have limited support for
65 * integer-keyed insert and delete, only at elements right before the
65 * integer-keyed insert and delete, only at elements right before the
66 * sentinel.
66 * sentinel.
67 *
67 *
68 * With string keys, we lazily perform a reverse mapping from node to
68 * With string keys, we lazily perform a reverse mapping from node to
69 * rev, using a base-16 trie.
69 * rev, using a base-16 trie.
70 */
70 */
71 struct indexObjectStruct {
71 struct indexObjectStruct {
72 PyObject_HEAD
72 PyObject_HEAD
73 /* Type-specific fields go here. */
73 /* Type-specific fields go here. */
74 PyObject *data; /* raw bytes of index */
74 PyObject *data; /* raw bytes of index */
75 Py_buffer buf; /* buffer of data */
75 Py_buffer buf; /* buffer of data */
76 PyObject **cache; /* cached tuples */
76 PyObject **cache; /* cached tuples */
77 const char **offsets; /* populated on demand */
77 const char **offsets; /* populated on demand */
78 Py_ssize_t raw_length; /* original number of elements */
78 Py_ssize_t raw_length; /* original number of elements */
79 Py_ssize_t length; /* current number of elements */
79 Py_ssize_t length; /* current number of elements */
80 PyObject *added; /* populated on demand */
80 PyObject *added; /* populated on demand */
81 PyObject *headrevs; /* cache, invalidated on changes */
81 PyObject *headrevs; /* cache, invalidated on changes */
82 PyObject *filteredrevs; /* filtered revs set */
82 PyObject *filteredrevs; /* filtered revs set */
83 nodetree nt; /* base-16 trie */
83 nodetree nt; /* base-16 trie */
84 int ntinitialized; /* 0 or 1 */
84 int ntinitialized; /* 0 or 1 */
85 int ntrev; /* last rev scanned */
85 int ntrev; /* last rev scanned */
86 int ntlookups; /* # lookups */
86 int ntlookups; /* # lookups */
87 int ntmisses; /* # lookups that miss the cache */
87 int ntmisses; /* # lookups that miss the cache */
88 int inlined;
88 int inlined;
89 };
89 };
90
90
91 static Py_ssize_t index_length(const indexObject *self)
91 static Py_ssize_t index_length(const indexObject *self)
92 {
92 {
93 if (self->added == NULL)
93 if (self->added == NULL)
94 return self->length;
94 return self->length;
95 return self->length + PyList_GET_SIZE(self->added);
95 return self->length + PyList_GET_SIZE(self->added);
96 }
96 }
97
97
98 static PyObject *nullentry = NULL;
98 static PyObject *nullentry = NULL;
99 static const char nullid[20] = {0};
99 static const char nullid[20] = {0};
100
100
101 static Py_ssize_t inline_scan(indexObject *self, const char **offsets);
101 static Py_ssize_t inline_scan(indexObject *self, const char **offsets);
102
102
103 #if LONG_MAX == 0x7fffffffL
103 #if LONG_MAX == 0x7fffffffL
104 static const char *const tuple_format = PY23("Kiiiiiis#", "Kiiiiiiy#");
104 static const char *const tuple_format = PY23("Kiiiiiis#", "Kiiiiiiy#");
105 #else
105 #else
106 static const char *const tuple_format = PY23("kiiiiiis#", "kiiiiiiy#");
106 static const char *const tuple_format = PY23("kiiiiiis#", "kiiiiiiy#");
107 #endif
107 #endif
108
108
109 /* A RevlogNG v1 index entry is 64 bytes long. */
109 /* A RevlogNG v1 index entry is 64 bytes long. */
110 static const long v1_hdrsize = 64;
110 static const long v1_hdrsize = 64;
111
111
112 static void raise_revlog_error(void)
112 static void raise_revlog_error(void)
113 {
113 {
114 PyObject *mod = NULL, *dict = NULL, *errclass = NULL;
114 PyObject *mod = NULL, *dict = NULL, *errclass = NULL;
115
115
116 mod = PyImport_ImportModule("mercurial.error");
116 mod = PyImport_ImportModule("mercurial.error");
117 if (mod == NULL) {
117 if (mod == NULL) {
118 goto cleanup;
118 goto cleanup;
119 }
119 }
120
120
121 dict = PyModule_GetDict(mod);
121 dict = PyModule_GetDict(mod);
122 if (dict == NULL) {
122 if (dict == NULL) {
123 goto cleanup;
123 goto cleanup;
124 }
124 }
125 Py_INCREF(dict);
125 Py_INCREF(dict);
126
126
127 errclass = PyDict_GetItemString(dict, "RevlogError");
127 errclass = PyDict_GetItemString(dict, "RevlogError");
128 if (errclass == NULL) {
128 if (errclass == NULL) {
129 PyErr_SetString(PyExc_SystemError,
129 PyErr_SetString(PyExc_SystemError,
130 "could not find RevlogError");
130 "could not find RevlogError");
131 goto cleanup;
131 goto cleanup;
132 }
132 }
133
133
134 /* value of exception is ignored by callers */
134 /* value of exception is ignored by callers */
135 PyErr_SetString(errclass, "RevlogError");
135 PyErr_SetString(errclass, "RevlogError");
136
136
137 cleanup:
137 cleanup:
138 Py_XDECREF(dict);
138 Py_XDECREF(dict);
139 Py_XDECREF(mod);
139 Py_XDECREF(mod);
140 }
140 }
141
141
142 /*
142 /*
143 * Return a pointer to the beginning of a RevlogNG record.
143 * Return a pointer to the beginning of a RevlogNG record.
144 */
144 */
145 static const char *index_deref(indexObject *self, Py_ssize_t pos)
145 static const char *index_deref(indexObject *self, Py_ssize_t pos)
146 {
146 {
147 if (self->inlined && pos > 0) {
147 if (self->inlined && pos > 0) {
148 if (self->offsets == NULL) {
148 if (self->offsets == NULL) {
149 self->offsets = PyMem_Malloc(self->raw_length *
149 self->offsets = PyMem_Malloc(self->raw_length *
150 sizeof(*self->offsets));
150 sizeof(*self->offsets));
151 if (self->offsets == NULL)
151 if (self->offsets == NULL)
152 return (const char *)PyErr_NoMemory();
152 return (const char *)PyErr_NoMemory();
153 inline_scan(self, self->offsets);
153 inline_scan(self, self->offsets);
154 }
154 }
155 return self->offsets[pos];
155 return self->offsets[pos];
156 }
156 }
157
157
158 return (const char *)(self->buf.buf) + pos * v1_hdrsize;
158 return (const char *)(self->buf.buf) + pos * v1_hdrsize;
159 }
159 }
160
160
161 static inline int index_get_parents(indexObject *self, Py_ssize_t rev, int *ps,
161 static inline int index_get_parents(indexObject *self, Py_ssize_t rev, int *ps,
162 int maxrev)
162 int maxrev)
163 {
163 {
164 if (rev >= self->length) {
164 if (rev >= self->length) {
165 long tmp;
165 long tmp;
166 PyObject *tuple =
166 PyObject *tuple =
167 PyList_GET_ITEM(self->added, rev - self->length);
167 PyList_GET_ITEM(self->added, rev - self->length);
168 if (!pylong_to_long(PyTuple_GET_ITEM(tuple, 5), &tmp)) {
168 if (!pylong_to_long(PyTuple_GET_ITEM(tuple, 5), &tmp)) {
169 return -1;
169 return -1;
170 }
170 }
171 ps[0] = (int)tmp;
171 ps[0] = (int)tmp;
172 if (!pylong_to_long(PyTuple_GET_ITEM(tuple, 6), &tmp)) {
172 if (!pylong_to_long(PyTuple_GET_ITEM(tuple, 6), &tmp)) {
173 return -1;
173 return -1;
174 }
174 }
175 ps[1] = (int)tmp;
175 ps[1] = (int)tmp;
176 } else {
176 } else {
177 const char *data = index_deref(self, rev);
177 const char *data = index_deref(self, rev);
178 ps[0] = getbe32(data + 24);
178 ps[0] = getbe32(data + 24);
179 ps[1] = getbe32(data + 28);
179 ps[1] = getbe32(data + 28);
180 }
180 }
181 /* If index file is corrupted, ps[] may point to invalid revisions. So
181 /* If index file is corrupted, ps[] may point to invalid revisions. So
182 * there is a risk of buffer overflow to trust them unconditionally. */
182 * there is a risk of buffer overflow to trust them unconditionally. */
183 if (ps[0] > maxrev || ps[1] > maxrev) {
183 if (ps[0] > maxrev || ps[1] > maxrev) {
184 PyErr_SetString(PyExc_ValueError, "parent out of range");
184 PyErr_SetString(PyExc_ValueError, "parent out of range");
185 return -1;
185 return -1;
186 }
186 }
187 return 0;
187 return 0;
188 }
188 }
189
189
190 static inline int64_t index_get_start(indexObject *self, Py_ssize_t rev)
190 static inline int64_t index_get_start(indexObject *self, Py_ssize_t rev)
191 {
191 {
192 uint64_t offset;
192 uint64_t offset;
193 if (rev >= self->length) {
193 if (rev >= self->length) {
194 PyObject *tuple;
194 PyObject *tuple;
195 PyObject *pylong;
195 PyObject *pylong;
196 PY_LONG_LONG tmp;
196 PY_LONG_LONG tmp;
197 tuple = PyList_GET_ITEM(self->added, rev - self->length);
197 tuple = PyList_GET_ITEM(self->added, rev - self->length);
198 pylong = PyTuple_GET_ITEM(tuple, 0);
198 pylong = PyTuple_GET_ITEM(tuple, 0);
199 tmp = PyLong_AsLongLong(pylong);
199 tmp = PyLong_AsLongLong(pylong);
200 if (tmp == -1 && PyErr_Occurred()) {
200 if (tmp == -1 && PyErr_Occurred()) {
201 return -1;
201 return -1;
202 }
202 }
203 if (tmp < 0) {
203 if (tmp < 0) {
204 PyErr_Format(PyExc_OverflowError,
204 PyErr_Format(PyExc_OverflowError,
205 "revlog entry size out of bound (%lld)",
205 "revlog entry size out of bound (%lld)",
206 (long long)tmp);
206 (long long)tmp);
207 return -1;
207 return -1;
208 }
208 }
209 offset = (uint64_t)tmp;
209 offset = (uint64_t)tmp;
210 } else {
210 } else {
211 const char *data = index_deref(self, rev);
211 const char *data = index_deref(self, rev);
212 offset = getbe32(data + 4);
212 offset = getbe32(data + 4);
213 if (rev == 0) {
213 if (rev == 0) {
214 /* mask out version number for the first entry */
214 /* mask out version number for the first entry */
215 offset &= 0xFFFF;
215 offset &= 0xFFFF;
216 } else {
216 } else {
217 uint32_t offset_high = getbe32(data);
217 uint32_t offset_high = getbe32(data);
218 offset |= ((uint64_t)offset_high) << 32;
218 offset |= ((uint64_t)offset_high) << 32;
219 }
219 }
220 }
220 }
221 return (int64_t)(offset >> 16);
221 return (int64_t)(offset >> 16);
222 }
222 }
223
223
224 static inline int index_get_length(indexObject *self, Py_ssize_t rev)
224 static inline int index_get_length(indexObject *self, Py_ssize_t rev)
225 {
225 {
226 if (rev >= self->length) {
226 if (rev >= self->length) {
227 PyObject *tuple;
227 PyObject *tuple;
228 PyObject *pylong;
228 PyObject *pylong;
229 long ret;
229 long ret;
230 tuple = PyList_GET_ITEM(self->added, rev - self->length);
230 tuple = PyList_GET_ITEM(self->added, rev - self->length);
231 pylong = PyTuple_GET_ITEM(tuple, 1);
231 pylong = PyTuple_GET_ITEM(tuple, 1);
232 ret = PyInt_AsLong(pylong);
232 ret = PyInt_AsLong(pylong);
233 if (ret == -1 && PyErr_Occurred()) {
233 if (ret == -1 && PyErr_Occurred()) {
234 return -1;
234 return -1;
235 }
235 }
236 if (ret < 0 || ret > (long)INT_MAX) {
236 if (ret < 0 || ret > (long)INT_MAX) {
237 PyErr_Format(PyExc_OverflowError,
237 PyErr_Format(PyExc_OverflowError,
238 "revlog entry size out of bound (%ld)",
238 "revlog entry size out of bound (%ld)",
239 ret);
239 ret);
240 return -1;
240 return -1;
241 }
241 }
242 return (int)ret;
242 return (int)ret;
243 } else {
243 } else {
244 const char *data = index_deref(self, rev);
244 const char *data = index_deref(self, rev);
245 return (int)getbe32(data + 8);
245 int tmp = (int)getbe32(data + 8);
246 if (tmp < 0) {
247 PyErr_Format(PyExc_OverflowError,
248 "revlog entry size out of bound (%d)",
249 tmp);
250 return -1;
251 }
252 return tmp;
246 }
253 }
247 }
254 }
248
255
249 /*
256 /*
250 * RevlogNG format (all in big endian, data may be inlined):
257 * RevlogNG format (all in big endian, data may be inlined):
251 * 6 bytes: offset
258 * 6 bytes: offset
252 * 2 bytes: flags
259 * 2 bytes: flags
253 * 4 bytes: compressed length
260 * 4 bytes: compressed length
254 * 4 bytes: uncompressed length
261 * 4 bytes: uncompressed length
255 * 4 bytes: base revision
262 * 4 bytes: base revision
256 * 4 bytes: link revision
263 * 4 bytes: link revision
257 * 4 bytes: parent 1 revision
264 * 4 bytes: parent 1 revision
258 * 4 bytes: parent 2 revision
265 * 4 bytes: parent 2 revision
259 * 32 bytes: nodeid (only 20 bytes used)
266 * 32 bytes: nodeid (only 20 bytes used)
260 */
267 */
261 static PyObject *index_get(indexObject *self, Py_ssize_t pos)
268 static PyObject *index_get(indexObject *self, Py_ssize_t pos)
262 {
269 {
263 uint64_t offset_flags;
270 uint64_t offset_flags;
264 int comp_len, uncomp_len, base_rev, link_rev, parent_1, parent_2;
271 int comp_len, uncomp_len, base_rev, link_rev, parent_1, parent_2;
265 const char *c_node_id;
272 const char *c_node_id;
266 const char *data;
273 const char *data;
267 Py_ssize_t length = index_length(self);
274 Py_ssize_t length = index_length(self);
268 PyObject *entry;
275 PyObject *entry;
269
276
270 if (pos == -1) {
277 if (pos == -1) {
271 Py_INCREF(nullentry);
278 Py_INCREF(nullentry);
272 return nullentry;
279 return nullentry;
273 }
280 }
274
281
275 if (pos < 0 || pos >= length) {
282 if (pos < 0 || pos >= length) {
276 PyErr_SetString(PyExc_IndexError, "revlog index out of range");
283 PyErr_SetString(PyExc_IndexError, "revlog index out of range");
277 return NULL;
284 return NULL;
278 }
285 }
279
286
280 if (pos >= self->length) {
287 if (pos >= self->length) {
281 PyObject *obj;
288 PyObject *obj;
282 obj = PyList_GET_ITEM(self->added, pos - self->length);
289 obj = PyList_GET_ITEM(self->added, pos - self->length);
283 Py_INCREF(obj);
290 Py_INCREF(obj);
284 return obj;
291 return obj;
285 }
292 }
286
293
287 if (self->cache) {
294 if (self->cache) {
288 if (self->cache[pos]) {
295 if (self->cache[pos]) {
289 Py_INCREF(self->cache[pos]);
296 Py_INCREF(self->cache[pos]);
290 return self->cache[pos];
297 return self->cache[pos];
291 }
298 }
292 } else {
299 } else {
293 self->cache = calloc(self->raw_length, sizeof(PyObject *));
300 self->cache = calloc(self->raw_length, sizeof(PyObject *));
294 if (self->cache == NULL)
301 if (self->cache == NULL)
295 return PyErr_NoMemory();
302 return PyErr_NoMemory();
296 }
303 }
297
304
298 data = index_deref(self, pos);
305 data = index_deref(self, pos);
299 if (data == NULL)
306 if (data == NULL)
300 return NULL;
307 return NULL;
301
308
302 offset_flags = getbe32(data + 4);
309 offset_flags = getbe32(data + 4);
303 if (pos == 0) /* mask out version number for the first entry */
310 if (pos == 0) /* mask out version number for the first entry */
304 offset_flags &= 0xFFFF;
311 offset_flags &= 0xFFFF;
305 else {
312 else {
306 uint32_t offset_high = getbe32(data);
313 uint32_t offset_high = getbe32(data);
307 offset_flags |= ((uint64_t)offset_high) << 32;
314 offset_flags |= ((uint64_t)offset_high) << 32;
308 }
315 }
309
316
310 comp_len = getbe32(data + 8);
317 comp_len = getbe32(data + 8);
311 uncomp_len = getbe32(data + 12);
318 uncomp_len = getbe32(data + 12);
312 base_rev = getbe32(data + 16);
319 base_rev = getbe32(data + 16);
313 link_rev = getbe32(data + 20);
320 link_rev = getbe32(data + 20);
314 parent_1 = getbe32(data + 24);
321 parent_1 = getbe32(data + 24);
315 parent_2 = getbe32(data + 28);
322 parent_2 = getbe32(data + 28);
316 c_node_id = data + 32;
323 c_node_id = data + 32;
317
324
318 entry = Py_BuildValue(tuple_format, offset_flags, comp_len, uncomp_len,
325 entry = Py_BuildValue(tuple_format, offset_flags, comp_len, uncomp_len,
319 base_rev, link_rev, parent_1, parent_2, c_node_id,
326 base_rev, link_rev, parent_1, parent_2, c_node_id,
320 20);
327 20);
321
328
322 if (entry) {
329 if (entry) {
323 PyObject_GC_UnTrack(entry);
330 PyObject_GC_UnTrack(entry);
324 Py_INCREF(entry);
331 Py_INCREF(entry);
325 }
332 }
326
333
327 self->cache[pos] = entry;
334 self->cache[pos] = entry;
328
335
329 return entry;
336 return entry;
330 }
337 }
331
338
332 /*
339 /*
333 * Return the 20-byte SHA of the node corresponding to the given rev.
340 * Return the 20-byte SHA of the node corresponding to the given rev.
334 */
341 */
335 static const char *index_node(indexObject *self, Py_ssize_t pos)
342 static const char *index_node(indexObject *self, Py_ssize_t pos)
336 {
343 {
337 Py_ssize_t length = index_length(self);
344 Py_ssize_t length = index_length(self);
338 const char *data;
345 const char *data;
339
346
340 if (pos == -1)
347 if (pos == -1)
341 return nullid;
348 return nullid;
342
349
343 if (pos >= length)
350 if (pos >= length)
344 return NULL;
351 return NULL;
345
352
346 if (pos >= self->length) {
353 if (pos >= self->length) {
347 PyObject *tuple, *str;
354 PyObject *tuple, *str;
348 tuple = PyList_GET_ITEM(self->added, pos - self->length);
355 tuple = PyList_GET_ITEM(self->added, pos - self->length);
349 str = PyTuple_GetItem(tuple, 7);
356 str = PyTuple_GetItem(tuple, 7);
350 return str ? PyBytes_AS_STRING(str) : NULL;
357 return str ? PyBytes_AS_STRING(str) : NULL;
351 }
358 }
352
359
353 data = index_deref(self, pos);
360 data = index_deref(self, pos);
354 return data ? data + 32 : NULL;
361 return data ? data + 32 : NULL;
355 }
362 }
356
363
357 /*
364 /*
358 * Return the 20-byte SHA of the node corresponding to the given rev. The
365 * Return the 20-byte SHA of the node corresponding to the given rev. The
359 * rev is assumed to be existing. If not, an exception is set.
366 * rev is assumed to be existing. If not, an exception is set.
360 */
367 */
361 static const char *index_node_existing(indexObject *self, Py_ssize_t pos)
368 static const char *index_node_existing(indexObject *self, Py_ssize_t pos)
362 {
369 {
363 const char *node = index_node(self, pos);
370 const char *node = index_node(self, pos);
364 if (node == NULL) {
371 if (node == NULL) {
365 PyErr_Format(PyExc_IndexError, "could not access rev %d",
372 PyErr_Format(PyExc_IndexError, "could not access rev %d",
366 (int)pos);
373 (int)pos);
367 }
374 }
368 return node;
375 return node;
369 }
376 }
370
377
371 static int nt_insert(nodetree *self, const char *node, int rev);
378 static int nt_insert(nodetree *self, const char *node, int rev);
372
379
373 static int node_check(PyObject *obj, char **node)
380 static int node_check(PyObject *obj, char **node)
374 {
381 {
375 Py_ssize_t nodelen;
382 Py_ssize_t nodelen;
376 if (PyBytes_AsStringAndSize(obj, node, &nodelen) == -1)
383 if (PyBytes_AsStringAndSize(obj, node, &nodelen) == -1)
377 return -1;
384 return -1;
378 if (nodelen == 20)
385 if (nodelen == 20)
379 return 0;
386 return 0;
380 PyErr_SetString(PyExc_ValueError, "20-byte hash required");
387 PyErr_SetString(PyExc_ValueError, "20-byte hash required");
381 return -1;
388 return -1;
382 }
389 }
383
390
384 static PyObject *index_append(indexObject *self, PyObject *obj)
391 static PyObject *index_append(indexObject *self, PyObject *obj)
385 {
392 {
386 char *node;
393 char *node;
387 Py_ssize_t len;
394 Py_ssize_t len;
388
395
389 if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 8) {
396 if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 8) {
390 PyErr_SetString(PyExc_TypeError, "8-tuple required");
397 PyErr_SetString(PyExc_TypeError, "8-tuple required");
391 return NULL;
398 return NULL;
392 }
399 }
393
400
394 if (node_check(PyTuple_GET_ITEM(obj, 7), &node) == -1)
401 if (node_check(PyTuple_GET_ITEM(obj, 7), &node) == -1)
395 return NULL;
402 return NULL;
396
403
397 len = index_length(self);
404 len = index_length(self);
398
405
399 if (self->added == NULL) {
406 if (self->added == NULL) {
400 self->added = PyList_New(0);
407 self->added = PyList_New(0);
401 if (self->added == NULL)
408 if (self->added == NULL)
402 return NULL;
409 return NULL;
403 }
410 }
404
411
405 if (PyList_Append(self->added, obj) == -1)
412 if (PyList_Append(self->added, obj) == -1)
406 return NULL;
413 return NULL;
407
414
408 if (self->ntinitialized)
415 if (self->ntinitialized)
409 nt_insert(&self->nt, node, (int)len);
416 nt_insert(&self->nt, node, (int)len);
410
417
411 Py_CLEAR(self->headrevs);
418 Py_CLEAR(self->headrevs);
412 Py_RETURN_NONE;
419 Py_RETURN_NONE;
413 }
420 }
414
421
415 static PyObject *index_stats(indexObject *self)
422 static PyObject *index_stats(indexObject *self)
416 {
423 {
417 PyObject *obj = PyDict_New();
424 PyObject *obj = PyDict_New();
418 PyObject *s = NULL;
425 PyObject *s = NULL;
419 PyObject *t = NULL;
426 PyObject *t = NULL;
420
427
421 if (obj == NULL)
428 if (obj == NULL)
422 return NULL;
429 return NULL;
423
430
424 #define istat(__n, __d) \
431 #define istat(__n, __d) \
425 do { \
432 do { \
426 s = PyBytes_FromString(__d); \
433 s = PyBytes_FromString(__d); \
427 t = PyInt_FromSsize_t(self->__n); \
434 t = PyInt_FromSsize_t(self->__n); \
428 if (!s || !t) \
435 if (!s || !t) \
429 goto bail; \
436 goto bail; \
430 if (PyDict_SetItem(obj, s, t) == -1) \
437 if (PyDict_SetItem(obj, s, t) == -1) \
431 goto bail; \
438 goto bail; \
432 Py_CLEAR(s); \
439 Py_CLEAR(s); \
433 Py_CLEAR(t); \
440 Py_CLEAR(t); \
434 } while (0)
441 } while (0)
435
442
436 if (self->added) {
443 if (self->added) {
437 Py_ssize_t len = PyList_GET_SIZE(self->added);
444 Py_ssize_t len = PyList_GET_SIZE(self->added);
438 s = PyBytes_FromString("index entries added");
445 s = PyBytes_FromString("index entries added");
439 t = PyInt_FromSsize_t(len);
446 t = PyInt_FromSsize_t(len);
440 if (!s || !t)
447 if (!s || !t)
441 goto bail;
448 goto bail;
442 if (PyDict_SetItem(obj, s, t) == -1)
449 if (PyDict_SetItem(obj, s, t) == -1)
443 goto bail;
450 goto bail;
444 Py_CLEAR(s);
451 Py_CLEAR(s);
445 Py_CLEAR(t);
452 Py_CLEAR(t);
446 }
453 }
447
454
448 if (self->raw_length != self->length)
455 if (self->raw_length != self->length)
449 istat(raw_length, "revs on disk");
456 istat(raw_length, "revs on disk");
450 istat(length, "revs in memory");
457 istat(length, "revs in memory");
451 istat(ntlookups, "node trie lookups");
458 istat(ntlookups, "node trie lookups");
452 istat(ntmisses, "node trie misses");
459 istat(ntmisses, "node trie misses");
453 istat(ntrev, "node trie last rev scanned");
460 istat(ntrev, "node trie last rev scanned");
454 if (self->ntinitialized) {
461 if (self->ntinitialized) {
455 istat(nt.capacity, "node trie capacity");
462 istat(nt.capacity, "node trie capacity");
456 istat(nt.depth, "node trie depth");
463 istat(nt.depth, "node trie depth");
457 istat(nt.length, "node trie count");
464 istat(nt.length, "node trie count");
458 istat(nt.splits, "node trie splits");
465 istat(nt.splits, "node trie splits");
459 }
466 }
460
467
461 #undef istat
468 #undef istat
462
469
463 return obj;
470 return obj;
464
471
465 bail:
472 bail:
466 Py_XDECREF(obj);
473 Py_XDECREF(obj);
467 Py_XDECREF(s);
474 Py_XDECREF(s);
468 Py_XDECREF(t);
475 Py_XDECREF(t);
469 return NULL;
476 return NULL;
470 }
477 }
471
478
472 /*
479 /*
473 * When we cache a list, we want to be sure the caller can't mutate
480 * When we cache a list, we want to be sure the caller can't mutate
474 * the cached copy.
481 * the cached copy.
475 */
482 */
476 static PyObject *list_copy(PyObject *list)
483 static PyObject *list_copy(PyObject *list)
477 {
484 {
478 Py_ssize_t len = PyList_GET_SIZE(list);
485 Py_ssize_t len = PyList_GET_SIZE(list);
479 PyObject *newlist = PyList_New(len);
486 PyObject *newlist = PyList_New(len);
480 Py_ssize_t i;
487 Py_ssize_t i;
481
488
482 if (newlist == NULL)
489 if (newlist == NULL)
483 return NULL;
490 return NULL;
484
491
485 for (i = 0; i < len; i++) {
492 for (i = 0; i < len; i++) {
486 PyObject *obj = PyList_GET_ITEM(list, i);
493 PyObject *obj = PyList_GET_ITEM(list, i);
487 Py_INCREF(obj);
494 Py_INCREF(obj);
488 PyList_SET_ITEM(newlist, i, obj);
495 PyList_SET_ITEM(newlist, i, obj);
489 }
496 }
490
497
491 return newlist;
498 return newlist;
492 }
499 }
493
500
494 static int check_filter(PyObject *filter, Py_ssize_t arg)
501 static int check_filter(PyObject *filter, Py_ssize_t arg)
495 {
502 {
496 if (filter) {
503 if (filter) {
497 PyObject *arglist, *result;
504 PyObject *arglist, *result;
498 int isfiltered;
505 int isfiltered;
499
506
500 arglist = Py_BuildValue("(n)", arg);
507 arglist = Py_BuildValue("(n)", arg);
501 if (!arglist) {
508 if (!arglist) {
502 return -1;
509 return -1;
503 }
510 }
504
511
505 result = PyEval_CallObject(filter, arglist);
512 result = PyEval_CallObject(filter, arglist);
506 Py_DECREF(arglist);
513 Py_DECREF(arglist);
507 if (!result) {
514 if (!result) {
508 return -1;
515 return -1;
509 }
516 }
510
517
511 /* PyObject_IsTrue returns 1 if true, 0 if false, -1 if error,
518 /* PyObject_IsTrue returns 1 if true, 0 if false, -1 if error,
512 * same as this function, so we can just return it directly.*/
519 * same as this function, so we can just return it directly.*/
513 isfiltered = PyObject_IsTrue(result);
520 isfiltered = PyObject_IsTrue(result);
514 Py_DECREF(result);
521 Py_DECREF(result);
515 return isfiltered;
522 return isfiltered;
516 } else {
523 } else {
517 return 0;
524 return 0;
518 }
525 }
519 }
526 }
520
527
521 static Py_ssize_t add_roots_get_min(indexObject *self, PyObject *list,
528 static Py_ssize_t add_roots_get_min(indexObject *self, PyObject *list,
522 Py_ssize_t marker, char *phases)
529 Py_ssize_t marker, char *phases)
523 {
530 {
524 PyObject *iter = NULL;
531 PyObject *iter = NULL;
525 PyObject *iter_item = NULL;
532 PyObject *iter_item = NULL;
526 Py_ssize_t min_idx = index_length(self) + 2;
533 Py_ssize_t min_idx = index_length(self) + 2;
527 long iter_item_long;
534 long iter_item_long;
528
535
529 if (PyList_GET_SIZE(list) != 0) {
536 if (PyList_GET_SIZE(list) != 0) {
530 iter = PyObject_GetIter(list);
537 iter = PyObject_GetIter(list);
531 if (iter == NULL)
538 if (iter == NULL)
532 return -2;
539 return -2;
533 while ((iter_item = PyIter_Next(iter))) {
540 while ((iter_item = PyIter_Next(iter))) {
534 if (!pylong_to_long(iter_item, &iter_item_long)) {
541 if (!pylong_to_long(iter_item, &iter_item_long)) {
535 Py_DECREF(iter_item);
542 Py_DECREF(iter_item);
536 return -2;
543 return -2;
537 }
544 }
538 Py_DECREF(iter_item);
545 Py_DECREF(iter_item);
539 if (iter_item_long < min_idx)
546 if (iter_item_long < min_idx)
540 min_idx = iter_item_long;
547 min_idx = iter_item_long;
541 phases[iter_item_long] = (char)marker;
548 phases[iter_item_long] = (char)marker;
542 }
549 }
543 Py_DECREF(iter);
550 Py_DECREF(iter);
544 }
551 }
545
552
546 return min_idx;
553 return min_idx;
547 }
554 }
548
555
549 static inline void set_phase_from_parents(char *phases, int parent_1,
556 static inline void set_phase_from_parents(char *phases, int parent_1,
550 int parent_2, Py_ssize_t i)
557 int parent_2, Py_ssize_t i)
551 {
558 {
552 if (parent_1 >= 0 && phases[parent_1] > phases[i])
559 if (parent_1 >= 0 && phases[parent_1] > phases[i])
553 phases[i] = phases[parent_1];
560 phases[i] = phases[parent_1];
554 if (parent_2 >= 0 && phases[parent_2] > phases[i])
561 if (parent_2 >= 0 && phases[parent_2] > phases[i])
555 phases[i] = phases[parent_2];
562 phases[i] = phases[parent_2];
556 }
563 }
557
564
558 static PyObject *reachableroots2(indexObject *self, PyObject *args)
565 static PyObject *reachableroots2(indexObject *self, PyObject *args)
559 {
566 {
560
567
561 /* Input */
568 /* Input */
562 long minroot;
569 long minroot;
563 PyObject *includepatharg = NULL;
570 PyObject *includepatharg = NULL;
564 int includepath = 0;
571 int includepath = 0;
565 /* heads and roots are lists */
572 /* heads and roots are lists */
566 PyObject *heads = NULL;
573 PyObject *heads = NULL;
567 PyObject *roots = NULL;
574 PyObject *roots = NULL;
568 PyObject *reachable = NULL;
575 PyObject *reachable = NULL;
569
576
570 PyObject *val;
577 PyObject *val;
571 Py_ssize_t len = index_length(self);
578 Py_ssize_t len = index_length(self);
572 long revnum;
579 long revnum;
573 Py_ssize_t k;
580 Py_ssize_t k;
574 Py_ssize_t i;
581 Py_ssize_t i;
575 Py_ssize_t l;
582 Py_ssize_t l;
576 int r;
583 int r;
577 int parents[2];
584 int parents[2];
578
585
579 /* Internal data structure:
586 /* Internal data structure:
580 * tovisit: array of length len+1 (all revs + nullrev), filled upto
587 * tovisit: array of length len+1 (all revs + nullrev), filled upto
581 * lentovisit
588 * lentovisit
582 *
589 *
583 * revstates: array of length len+1 (all revs + nullrev) */
590 * revstates: array of length len+1 (all revs + nullrev) */
584 int *tovisit = NULL;
591 int *tovisit = NULL;
585 long lentovisit = 0;
592 long lentovisit = 0;
586 enum { RS_SEEN = 1, RS_ROOT = 2, RS_REACHABLE = 4 };
593 enum { RS_SEEN = 1, RS_ROOT = 2, RS_REACHABLE = 4 };
587 char *revstates = NULL;
594 char *revstates = NULL;
588
595
589 /* Get arguments */
596 /* Get arguments */
590 if (!PyArg_ParseTuple(args, "lO!O!O!", &minroot, &PyList_Type, &heads,
597 if (!PyArg_ParseTuple(args, "lO!O!O!", &minroot, &PyList_Type, &heads,
591 &PyList_Type, &roots, &PyBool_Type,
598 &PyList_Type, &roots, &PyBool_Type,
592 &includepatharg))
599 &includepatharg))
593 goto bail;
600 goto bail;
594
601
595 if (includepatharg == Py_True)
602 if (includepatharg == Py_True)
596 includepath = 1;
603 includepath = 1;
597
604
598 /* Initialize return set */
605 /* Initialize return set */
599 reachable = PyList_New(0);
606 reachable = PyList_New(0);
600 if (reachable == NULL)
607 if (reachable == NULL)
601 goto bail;
608 goto bail;
602
609
603 /* Initialize internal datastructures */
610 /* Initialize internal datastructures */
604 tovisit = (int *)malloc((len + 1) * sizeof(int));
611 tovisit = (int *)malloc((len + 1) * sizeof(int));
605 if (tovisit == NULL) {
612 if (tovisit == NULL) {
606 PyErr_NoMemory();
613 PyErr_NoMemory();
607 goto bail;
614 goto bail;
608 }
615 }
609
616
610 revstates = (char *)calloc(len + 1, 1);
617 revstates = (char *)calloc(len + 1, 1);
611 if (revstates == NULL) {
618 if (revstates == NULL) {
612 PyErr_NoMemory();
619 PyErr_NoMemory();
613 goto bail;
620 goto bail;
614 }
621 }
615
622
616 l = PyList_GET_SIZE(roots);
623 l = PyList_GET_SIZE(roots);
617 for (i = 0; i < l; i++) {
624 for (i = 0; i < l; i++) {
618 revnum = PyInt_AsLong(PyList_GET_ITEM(roots, i));
625 revnum = PyInt_AsLong(PyList_GET_ITEM(roots, i));
619 if (revnum == -1 && PyErr_Occurred())
626 if (revnum == -1 && PyErr_Occurred())
620 goto bail;
627 goto bail;
621 /* If root is out of range, e.g. wdir(), it must be unreachable
628 /* If root is out of range, e.g. wdir(), it must be unreachable
622 * from heads. So we can just ignore it. */
629 * from heads. So we can just ignore it. */
623 if (revnum + 1 < 0 || revnum + 1 >= len + 1)
630 if (revnum + 1 < 0 || revnum + 1 >= len + 1)
624 continue;
631 continue;
625 revstates[revnum + 1] |= RS_ROOT;
632 revstates[revnum + 1] |= RS_ROOT;
626 }
633 }
627
634
628 /* Populate tovisit with all the heads */
635 /* Populate tovisit with all the heads */
629 l = PyList_GET_SIZE(heads);
636 l = PyList_GET_SIZE(heads);
630 for (i = 0; i < l; i++) {
637 for (i = 0; i < l; i++) {
631 revnum = PyInt_AsLong(PyList_GET_ITEM(heads, i));
638 revnum = PyInt_AsLong(PyList_GET_ITEM(heads, i));
632 if (revnum == -1 && PyErr_Occurred())
639 if (revnum == -1 && PyErr_Occurred())
633 goto bail;
640 goto bail;
634 if (revnum + 1 < 0 || revnum + 1 >= len + 1) {
641 if (revnum + 1 < 0 || revnum + 1 >= len + 1) {
635 PyErr_SetString(PyExc_IndexError, "head out of range");
642 PyErr_SetString(PyExc_IndexError, "head out of range");
636 goto bail;
643 goto bail;
637 }
644 }
638 if (!(revstates[revnum + 1] & RS_SEEN)) {
645 if (!(revstates[revnum + 1] & RS_SEEN)) {
639 tovisit[lentovisit++] = (int)revnum;
646 tovisit[lentovisit++] = (int)revnum;
640 revstates[revnum + 1] |= RS_SEEN;
647 revstates[revnum + 1] |= RS_SEEN;
641 }
648 }
642 }
649 }
643
650
644 /* Visit the tovisit list and find the reachable roots */
651 /* Visit the tovisit list and find the reachable roots */
645 k = 0;
652 k = 0;
646 while (k < lentovisit) {
653 while (k < lentovisit) {
647 /* Add the node to reachable if it is a root*/
654 /* Add the node to reachable if it is a root*/
648 revnum = tovisit[k++];
655 revnum = tovisit[k++];
649 if (revstates[revnum + 1] & RS_ROOT) {
656 if (revstates[revnum + 1] & RS_ROOT) {
650 revstates[revnum + 1] |= RS_REACHABLE;
657 revstates[revnum + 1] |= RS_REACHABLE;
651 val = PyInt_FromLong(revnum);
658 val = PyInt_FromLong(revnum);
652 if (val == NULL)
659 if (val == NULL)
653 goto bail;
660 goto bail;
654 r = PyList_Append(reachable, val);
661 r = PyList_Append(reachable, val);
655 Py_DECREF(val);
662 Py_DECREF(val);
656 if (r < 0)
663 if (r < 0)
657 goto bail;
664 goto bail;
658 if (includepath == 0)
665 if (includepath == 0)
659 continue;
666 continue;
660 }
667 }
661
668
662 /* Add its parents to the list of nodes to visit */
669 /* Add its parents to the list of nodes to visit */
663 if (revnum == -1)
670 if (revnum == -1)
664 continue;
671 continue;
665 r = index_get_parents(self, revnum, parents, (int)len - 1);
672 r = index_get_parents(self, revnum, parents, (int)len - 1);
666 if (r < 0)
673 if (r < 0)
667 goto bail;
674 goto bail;
668 for (i = 0; i < 2; i++) {
675 for (i = 0; i < 2; i++) {
669 if (!(revstates[parents[i] + 1] & RS_SEEN) &&
676 if (!(revstates[parents[i] + 1] & RS_SEEN) &&
670 parents[i] >= minroot) {
677 parents[i] >= minroot) {
671 tovisit[lentovisit++] = parents[i];
678 tovisit[lentovisit++] = parents[i];
672 revstates[parents[i] + 1] |= RS_SEEN;
679 revstates[parents[i] + 1] |= RS_SEEN;
673 }
680 }
674 }
681 }
675 }
682 }
676
683
677 /* Find all the nodes in between the roots we found and the heads
684 /* Find all the nodes in between the roots we found and the heads
678 * and add them to the reachable set */
685 * and add them to the reachable set */
679 if (includepath == 1) {
686 if (includepath == 1) {
680 long minidx = minroot;
687 long minidx = minroot;
681 if (minidx < 0)
688 if (minidx < 0)
682 minidx = 0;
689 minidx = 0;
683 for (i = minidx; i < len; i++) {
690 for (i = minidx; i < len; i++) {
684 if (!(revstates[i + 1] & RS_SEEN))
691 if (!(revstates[i + 1] & RS_SEEN))
685 continue;
692 continue;
686 r = index_get_parents(self, i, parents, (int)len - 1);
693 r = index_get_parents(self, i, parents, (int)len - 1);
687 /* Corrupted index file, error is set from
694 /* Corrupted index file, error is set from
688 * index_get_parents */
695 * index_get_parents */
689 if (r < 0)
696 if (r < 0)
690 goto bail;
697 goto bail;
691 if (((revstates[parents[0] + 1] |
698 if (((revstates[parents[0] + 1] |
692 revstates[parents[1] + 1]) &
699 revstates[parents[1] + 1]) &
693 RS_REACHABLE) &&
700 RS_REACHABLE) &&
694 !(revstates[i + 1] & RS_REACHABLE)) {
701 !(revstates[i + 1] & RS_REACHABLE)) {
695 revstates[i + 1] |= RS_REACHABLE;
702 revstates[i + 1] |= RS_REACHABLE;
696 val = PyInt_FromSsize_t(i);
703 val = PyInt_FromSsize_t(i);
697 if (val == NULL)
704 if (val == NULL)
698 goto bail;
705 goto bail;
699 r = PyList_Append(reachable, val);
706 r = PyList_Append(reachable, val);
700 Py_DECREF(val);
707 Py_DECREF(val);
701 if (r < 0)
708 if (r < 0)
702 goto bail;
709 goto bail;
703 }
710 }
704 }
711 }
705 }
712 }
706
713
707 free(revstates);
714 free(revstates);
708 free(tovisit);
715 free(tovisit);
709 return reachable;
716 return reachable;
710 bail:
717 bail:
711 Py_XDECREF(reachable);
718 Py_XDECREF(reachable);
712 free(revstates);
719 free(revstates);
713 free(tovisit);
720 free(tovisit);
714 return NULL;
721 return NULL;
715 }
722 }
716
723
717 static PyObject *compute_phases_map_sets(indexObject *self, PyObject *args)
724 static PyObject *compute_phases_map_sets(indexObject *self, PyObject *args)
718 {
725 {
719 PyObject *roots = Py_None;
726 PyObject *roots = Py_None;
720 PyObject *ret = NULL;
727 PyObject *ret = NULL;
721 PyObject *phasessize = NULL;
728 PyObject *phasessize = NULL;
722 PyObject *phaseroots = NULL;
729 PyObject *phaseroots = NULL;
723 PyObject *phaseset = NULL;
730 PyObject *phaseset = NULL;
724 PyObject *phasessetlist = NULL;
731 PyObject *phasessetlist = NULL;
725 PyObject *rev = NULL;
732 PyObject *rev = NULL;
726 Py_ssize_t len = index_length(self);
733 Py_ssize_t len = index_length(self);
727 Py_ssize_t numphase = 0;
734 Py_ssize_t numphase = 0;
728 Py_ssize_t minrevallphases = 0;
735 Py_ssize_t minrevallphases = 0;
729 Py_ssize_t minrevphase = 0;
736 Py_ssize_t minrevphase = 0;
730 Py_ssize_t i = 0;
737 Py_ssize_t i = 0;
731 char *phases = NULL;
738 char *phases = NULL;
732 long phase;
739 long phase;
733
740
734 if (!PyArg_ParseTuple(args, "O", &roots))
741 if (!PyArg_ParseTuple(args, "O", &roots))
735 goto done;
742 goto done;
736 if (roots == NULL || !PyList_Check(roots)) {
743 if (roots == NULL || !PyList_Check(roots)) {
737 PyErr_SetString(PyExc_TypeError, "roots must be a list");
744 PyErr_SetString(PyExc_TypeError, "roots must be a list");
738 goto done;
745 goto done;
739 }
746 }
740
747
741 phases = calloc(
748 phases = calloc(
742 len, 1); /* phase per rev: {0: public, 1: draft, 2: secret} */
749 len, 1); /* phase per rev: {0: public, 1: draft, 2: secret} */
743 if (phases == NULL) {
750 if (phases == NULL) {
744 PyErr_NoMemory();
751 PyErr_NoMemory();
745 goto done;
752 goto done;
746 }
753 }
747 /* Put the phase information of all the roots in phases */
754 /* Put the phase information of all the roots in phases */
748 numphase = PyList_GET_SIZE(roots) + 1;
755 numphase = PyList_GET_SIZE(roots) + 1;
749 minrevallphases = len + 1;
756 minrevallphases = len + 1;
750 phasessetlist = PyList_New(numphase);
757 phasessetlist = PyList_New(numphase);
751 if (phasessetlist == NULL)
758 if (phasessetlist == NULL)
752 goto done;
759 goto done;
753
760
754 PyList_SET_ITEM(phasessetlist, 0, Py_None);
761 PyList_SET_ITEM(phasessetlist, 0, Py_None);
755 Py_INCREF(Py_None);
762 Py_INCREF(Py_None);
756
763
757 for (i = 0; i < numphase - 1; i++) {
764 for (i = 0; i < numphase - 1; i++) {
758 phaseroots = PyList_GET_ITEM(roots, i);
765 phaseroots = PyList_GET_ITEM(roots, i);
759 phaseset = PySet_New(NULL);
766 phaseset = PySet_New(NULL);
760 if (phaseset == NULL)
767 if (phaseset == NULL)
761 goto release;
768 goto release;
762 PyList_SET_ITEM(phasessetlist, i + 1, phaseset);
769 PyList_SET_ITEM(phasessetlist, i + 1, phaseset);
763 if (!PyList_Check(phaseroots)) {
770 if (!PyList_Check(phaseroots)) {
764 PyErr_SetString(PyExc_TypeError,
771 PyErr_SetString(PyExc_TypeError,
765 "roots item must be a list");
772 "roots item must be a list");
766 goto release;
773 goto release;
767 }
774 }
768 minrevphase =
775 minrevphase =
769 add_roots_get_min(self, phaseroots, i + 1, phases);
776 add_roots_get_min(self, phaseroots, i + 1, phases);
770 if (minrevphase == -2) /* Error from add_roots_get_min */
777 if (minrevphase == -2) /* Error from add_roots_get_min */
771 goto release;
778 goto release;
772 minrevallphases = MIN(minrevallphases, minrevphase);
779 minrevallphases = MIN(minrevallphases, minrevphase);
773 }
780 }
774 /* Propagate the phase information from the roots to the revs */
781 /* Propagate the phase information from the roots to the revs */
775 if (minrevallphases != -1) {
782 if (minrevallphases != -1) {
776 int parents[2];
783 int parents[2];
777 for (i = minrevallphases; i < len; i++) {
784 for (i = minrevallphases; i < len; i++) {
778 if (index_get_parents(self, i, parents, (int)len - 1) <
785 if (index_get_parents(self, i, parents, (int)len - 1) <
779 0)
786 0)
780 goto release;
787 goto release;
781 set_phase_from_parents(phases, parents[0], parents[1],
788 set_phase_from_parents(phases, parents[0], parents[1],
782 i);
789 i);
783 }
790 }
784 }
791 }
785 /* Transform phase list to a python list */
792 /* Transform phase list to a python list */
786 phasessize = PyInt_FromSsize_t(len);
793 phasessize = PyInt_FromSsize_t(len);
787 if (phasessize == NULL)
794 if (phasessize == NULL)
788 goto release;
795 goto release;
789 for (i = 0; i < len; i++) {
796 for (i = 0; i < len; i++) {
790 phase = phases[i];
797 phase = phases[i];
791 /* We only store the sets of phase for non public phase, the
798 /* We only store the sets of phase for non public phase, the
792 * public phase is computed as a difference */
799 * public phase is computed as a difference */
793 if (phase != 0) {
800 if (phase != 0) {
794 phaseset = PyList_GET_ITEM(phasessetlist, phase);
801 phaseset = PyList_GET_ITEM(phasessetlist, phase);
795 rev = PyInt_FromSsize_t(i);
802 rev = PyInt_FromSsize_t(i);
796 if (rev == NULL)
803 if (rev == NULL)
797 goto release;
804 goto release;
798 PySet_Add(phaseset, rev);
805 PySet_Add(phaseset, rev);
799 Py_XDECREF(rev);
806 Py_XDECREF(rev);
800 }
807 }
801 }
808 }
802 ret = PyTuple_Pack(2, phasessize, phasessetlist);
809 ret = PyTuple_Pack(2, phasessize, phasessetlist);
803
810
804 release:
811 release:
805 Py_XDECREF(phasessize);
812 Py_XDECREF(phasessize);
806 Py_XDECREF(phasessetlist);
813 Py_XDECREF(phasessetlist);
807 done:
814 done:
808 free(phases);
815 free(phases);
809 return ret;
816 return ret;
810 }
817 }
811
818
812 static PyObject *index_headrevs(indexObject *self, PyObject *args)
819 static PyObject *index_headrevs(indexObject *self, PyObject *args)
813 {
820 {
814 Py_ssize_t i, j, len;
821 Py_ssize_t i, j, len;
815 char *nothead = NULL;
822 char *nothead = NULL;
816 PyObject *heads = NULL;
823 PyObject *heads = NULL;
817 PyObject *filter = NULL;
824 PyObject *filter = NULL;
818 PyObject *filteredrevs = Py_None;
825 PyObject *filteredrevs = Py_None;
819
826
820 if (!PyArg_ParseTuple(args, "|O", &filteredrevs)) {
827 if (!PyArg_ParseTuple(args, "|O", &filteredrevs)) {
821 return NULL;
828 return NULL;
822 }
829 }
823
830
824 if (self->headrevs && filteredrevs == self->filteredrevs)
831 if (self->headrevs && filteredrevs == self->filteredrevs)
825 return list_copy(self->headrevs);
832 return list_copy(self->headrevs);
826
833
827 Py_DECREF(self->filteredrevs);
834 Py_DECREF(self->filteredrevs);
828 self->filteredrevs = filteredrevs;
835 self->filteredrevs = filteredrevs;
829 Py_INCREF(filteredrevs);
836 Py_INCREF(filteredrevs);
830
837
831 if (filteredrevs != Py_None) {
838 if (filteredrevs != Py_None) {
832 filter = PyObject_GetAttrString(filteredrevs, "__contains__");
839 filter = PyObject_GetAttrString(filteredrevs, "__contains__");
833 if (!filter) {
840 if (!filter) {
834 PyErr_SetString(
841 PyErr_SetString(
835 PyExc_TypeError,
842 PyExc_TypeError,
836 "filteredrevs has no attribute __contains__");
843 "filteredrevs has no attribute __contains__");
837 goto bail;
844 goto bail;
838 }
845 }
839 }
846 }
840
847
841 len = index_length(self);
848 len = index_length(self);
842 heads = PyList_New(0);
849 heads = PyList_New(0);
843 if (heads == NULL)
850 if (heads == NULL)
844 goto bail;
851 goto bail;
845 if (len == 0) {
852 if (len == 0) {
846 PyObject *nullid = PyInt_FromLong(-1);
853 PyObject *nullid = PyInt_FromLong(-1);
847 if (nullid == NULL || PyList_Append(heads, nullid) == -1) {
854 if (nullid == NULL || PyList_Append(heads, nullid) == -1) {
848 Py_XDECREF(nullid);
855 Py_XDECREF(nullid);
849 goto bail;
856 goto bail;
850 }
857 }
851 goto done;
858 goto done;
852 }
859 }
853
860
854 nothead = calloc(len, 1);
861 nothead = calloc(len, 1);
855 if (nothead == NULL) {
862 if (nothead == NULL) {
856 PyErr_NoMemory();
863 PyErr_NoMemory();
857 goto bail;
864 goto bail;
858 }
865 }
859
866
860 for (i = len - 1; i >= 0; i--) {
867 for (i = len - 1; i >= 0; i--) {
861 int isfiltered;
868 int isfiltered;
862 int parents[2];
869 int parents[2];
863
870
864 /* If nothead[i] == 1, it means we've seen an unfiltered child
871 /* If nothead[i] == 1, it means we've seen an unfiltered child
865 * of this node already, and therefore this node is not
872 * of this node already, and therefore this node is not
866 * filtered. So we can skip the expensive check_filter step.
873 * filtered. So we can skip the expensive check_filter step.
867 */
874 */
868 if (nothead[i] != 1) {
875 if (nothead[i] != 1) {
869 isfiltered = check_filter(filter, i);
876 isfiltered = check_filter(filter, i);
870 if (isfiltered == -1) {
877 if (isfiltered == -1) {
871 PyErr_SetString(PyExc_TypeError,
878 PyErr_SetString(PyExc_TypeError,
872 "unable to check filter");
879 "unable to check filter");
873 goto bail;
880 goto bail;
874 }
881 }
875
882
876 if (isfiltered) {
883 if (isfiltered) {
877 nothead[i] = 1;
884 nothead[i] = 1;
878 continue;
885 continue;
879 }
886 }
880 }
887 }
881
888
882 if (index_get_parents(self, i, parents, (int)len - 1) < 0)
889 if (index_get_parents(self, i, parents, (int)len - 1) < 0)
883 goto bail;
890 goto bail;
884 for (j = 0; j < 2; j++) {
891 for (j = 0; j < 2; j++) {
885 if (parents[j] >= 0)
892 if (parents[j] >= 0)
886 nothead[parents[j]] = 1;
893 nothead[parents[j]] = 1;
887 }
894 }
888 }
895 }
889
896
890 for (i = 0; i < len; i++) {
897 for (i = 0; i < len; i++) {
891 PyObject *head;
898 PyObject *head;
892
899
893 if (nothead[i])
900 if (nothead[i])
894 continue;
901 continue;
895 head = PyInt_FromSsize_t(i);
902 head = PyInt_FromSsize_t(i);
896 if (head == NULL || PyList_Append(heads, head) == -1) {
903 if (head == NULL || PyList_Append(heads, head) == -1) {
897 Py_XDECREF(head);
904 Py_XDECREF(head);
898 goto bail;
905 goto bail;
899 }
906 }
900 }
907 }
901
908
902 done:
909 done:
903 self->headrevs = heads;
910 self->headrevs = heads;
904 Py_XDECREF(filter);
911 Py_XDECREF(filter);
905 free(nothead);
912 free(nothead);
906 return list_copy(self->headrevs);
913 return list_copy(self->headrevs);
907 bail:
914 bail:
908 Py_XDECREF(filter);
915 Py_XDECREF(filter);
909 Py_XDECREF(heads);
916 Py_XDECREF(heads);
910 free(nothead);
917 free(nothead);
911 return NULL;
918 return NULL;
912 }
919 }
913
920
914 /**
921 /**
915 * Obtain the base revision index entry.
922 * Obtain the base revision index entry.
916 *
923 *
917 * Callers must ensure that rev >= 0 or illegal memory access may occur.
924 * Callers must ensure that rev >= 0 or illegal memory access may occur.
918 */
925 */
919 static inline int index_baserev(indexObject *self, int rev)
926 static inline int index_baserev(indexObject *self, int rev)
920 {
927 {
921 const char *data;
928 const char *data;
922
929
923 if (rev >= self->length) {
930 if (rev >= self->length) {
924 PyObject *tuple =
931 PyObject *tuple =
925 PyList_GET_ITEM(self->added, rev - self->length);
932 PyList_GET_ITEM(self->added, rev - self->length);
926 long ret;
933 long ret;
927 if (!pylong_to_long(PyTuple_GET_ITEM(tuple, 3), &ret)) {
934 if (!pylong_to_long(PyTuple_GET_ITEM(tuple, 3), &ret)) {
928 return -2;
935 return -2;
929 }
936 }
930 return (int)ret;
937 return (int)ret;
931 } else {
938 } else {
932 data = index_deref(self, rev);
939 data = index_deref(self, rev);
933 if (data == NULL) {
940 if (data == NULL) {
934 return -2;
941 return -2;
935 }
942 }
936
943
937 return getbe32(data + 16);
944 return getbe32(data + 16);
938 }
945 }
939 }
946 }
940
947
941 static PyObject *index_deltachain(indexObject *self, PyObject *args)
948 static PyObject *index_deltachain(indexObject *self, PyObject *args)
942 {
949 {
943 int rev, generaldelta;
950 int rev, generaldelta;
944 PyObject *stoparg;
951 PyObject *stoparg;
945 int stoprev, iterrev, baserev = -1;
952 int stoprev, iterrev, baserev = -1;
946 int stopped;
953 int stopped;
947 PyObject *chain = NULL, *result = NULL;
954 PyObject *chain = NULL, *result = NULL;
948 const Py_ssize_t length = index_length(self);
955 const Py_ssize_t length = index_length(self);
949
956
950 if (!PyArg_ParseTuple(args, "iOi", &rev, &stoparg, &generaldelta)) {
957 if (!PyArg_ParseTuple(args, "iOi", &rev, &stoparg, &generaldelta)) {
951 return NULL;
958 return NULL;
952 }
959 }
953
960
954 if (PyInt_Check(stoparg)) {
961 if (PyInt_Check(stoparg)) {
955 stoprev = (int)PyInt_AsLong(stoparg);
962 stoprev = (int)PyInt_AsLong(stoparg);
956 if (stoprev == -1 && PyErr_Occurred()) {
963 if (stoprev == -1 && PyErr_Occurred()) {
957 return NULL;
964 return NULL;
958 }
965 }
959 } else if (stoparg == Py_None) {
966 } else if (stoparg == Py_None) {
960 stoprev = -2;
967 stoprev = -2;
961 } else {
968 } else {
962 PyErr_SetString(PyExc_ValueError,
969 PyErr_SetString(PyExc_ValueError,
963 "stoprev must be integer or None");
970 "stoprev must be integer or None");
964 return NULL;
971 return NULL;
965 }
972 }
966
973
967 if (rev < 0 || rev >= length) {
974 if (rev < 0 || rev >= length) {
968 PyErr_SetString(PyExc_ValueError, "revlog index out of range");
975 PyErr_SetString(PyExc_ValueError, "revlog index out of range");
969 return NULL;
976 return NULL;
970 }
977 }
971
978
972 chain = PyList_New(0);
979 chain = PyList_New(0);
973 if (chain == NULL) {
980 if (chain == NULL) {
974 return NULL;
981 return NULL;
975 }
982 }
976
983
977 baserev = index_baserev(self, rev);
984 baserev = index_baserev(self, rev);
978
985
979 /* This should never happen. */
986 /* This should never happen. */
980 if (baserev <= -2) {
987 if (baserev <= -2) {
981 /* Error should be set by index_deref() */
988 /* Error should be set by index_deref() */
982 assert(PyErr_Occurred());
989 assert(PyErr_Occurred());
983 goto bail;
990 goto bail;
984 }
991 }
985
992
986 iterrev = rev;
993 iterrev = rev;
987
994
988 while (iterrev != baserev && iterrev != stoprev) {
995 while (iterrev != baserev && iterrev != stoprev) {
989 PyObject *value = PyInt_FromLong(iterrev);
996 PyObject *value = PyInt_FromLong(iterrev);
990 if (value == NULL) {
997 if (value == NULL) {
991 goto bail;
998 goto bail;
992 }
999 }
993 if (PyList_Append(chain, value)) {
1000 if (PyList_Append(chain, value)) {
994 Py_DECREF(value);
1001 Py_DECREF(value);
995 goto bail;
1002 goto bail;
996 }
1003 }
997 Py_DECREF(value);
1004 Py_DECREF(value);
998
1005
999 if (generaldelta) {
1006 if (generaldelta) {
1000 iterrev = baserev;
1007 iterrev = baserev;
1001 } else {
1008 } else {
1002 iterrev--;
1009 iterrev--;
1003 }
1010 }
1004
1011
1005 if (iterrev < 0) {
1012 if (iterrev < 0) {
1006 break;
1013 break;
1007 }
1014 }
1008
1015
1009 if (iterrev >= length) {
1016 if (iterrev >= length) {
1010 PyErr_SetString(PyExc_IndexError,
1017 PyErr_SetString(PyExc_IndexError,
1011 "revision outside index");
1018 "revision outside index");
1012 return NULL;
1019 return NULL;
1013 }
1020 }
1014
1021
1015 baserev = index_baserev(self, iterrev);
1022 baserev = index_baserev(self, iterrev);
1016
1023
1017 /* This should never happen. */
1024 /* This should never happen. */
1018 if (baserev <= -2) {
1025 if (baserev <= -2) {
1019 /* Error should be set by index_deref() */
1026 /* Error should be set by index_deref() */
1020 assert(PyErr_Occurred());
1027 assert(PyErr_Occurred());
1021 goto bail;
1028 goto bail;
1022 }
1029 }
1023 }
1030 }
1024
1031
1025 if (iterrev == stoprev) {
1032 if (iterrev == stoprev) {
1026 stopped = 1;
1033 stopped = 1;
1027 } else {
1034 } else {
1028 PyObject *value = PyInt_FromLong(iterrev);
1035 PyObject *value = PyInt_FromLong(iterrev);
1029 if (value == NULL) {
1036 if (value == NULL) {
1030 goto bail;
1037 goto bail;
1031 }
1038 }
1032 if (PyList_Append(chain, value)) {
1039 if (PyList_Append(chain, value)) {
1033 Py_DECREF(value);
1040 Py_DECREF(value);
1034 goto bail;
1041 goto bail;
1035 }
1042 }
1036 Py_DECREF(value);
1043 Py_DECREF(value);
1037
1044
1038 stopped = 0;
1045 stopped = 0;
1039 }
1046 }
1040
1047
1041 if (PyList_Reverse(chain)) {
1048 if (PyList_Reverse(chain)) {
1042 goto bail;
1049 goto bail;
1043 }
1050 }
1044
1051
1045 result = Py_BuildValue("OO", chain, stopped ? Py_True : Py_False);
1052 result = Py_BuildValue("OO", chain, stopped ? Py_True : Py_False);
1046 Py_DECREF(chain);
1053 Py_DECREF(chain);
1047 return result;
1054 return result;
1048
1055
1049 bail:
1056 bail:
1050 Py_DECREF(chain);
1057 Py_DECREF(chain);
1051 return NULL;
1058 return NULL;
1052 }
1059 }
1053
1060
1054 static inline int64_t
1061 static inline int64_t
1055 index_segment_span(indexObject *self, Py_ssize_t start_rev, Py_ssize_t end_rev)
1062 index_segment_span(indexObject *self, Py_ssize_t start_rev, Py_ssize_t end_rev)
1056 {
1063 {
1057 int64_t start_offset;
1064 int64_t start_offset;
1058 int64_t end_offset;
1065 int64_t end_offset;
1059 int end_size;
1066 int end_size;
1060 start_offset = index_get_start(self, start_rev);
1067 start_offset = index_get_start(self, start_rev);
1061 if (start_offset < 0) {
1068 if (start_offset < 0) {
1062 return -1;
1069 return -1;
1063 }
1070 }
1064 end_offset = index_get_start(self, end_rev);
1071 end_offset = index_get_start(self, end_rev);
1065 if (end_offset < 0) {
1072 if (end_offset < 0) {
1066 return -1;
1073 return -1;
1067 }
1074 }
1068 end_size = index_get_length(self, end_rev);
1075 end_size = index_get_length(self, end_rev);
1069 if (end_size < 0) {
1076 if (end_size < 0) {
1070 return -1;
1077 return -1;
1071 }
1078 }
1072 if (end_offset < start_offset) {
1079 if (end_offset < start_offset) {
1073 PyErr_Format(PyExc_ValueError,
1080 PyErr_Format(PyExc_ValueError,
1074 "corrupted revlog index: inconsistent offset "
1081 "corrupted revlog index: inconsistent offset "
1075 "between revisions (%zd) and (%zd)",
1082 "between revisions (%zd) and (%zd)",
1076 start_rev, end_rev);
1083 start_rev, end_rev);
1077 return -1;
1084 return -1;
1078 }
1085 }
1079 return (end_offset - start_offset) + (int64_t)end_size;
1086 return (end_offset - start_offset) + (int64_t)end_size;
1080 }
1087 }
1081
1088
1082 /* returns revs[startidx:endidx] without empty trailing revs */
1089 /* returns revs[startidx:endidx] without empty trailing revs */
1083 static Py_ssize_t trim_endidx(indexObject *self, const Py_ssize_t *revs,
1090 static Py_ssize_t trim_endidx(indexObject *self, const Py_ssize_t *revs,
1084 Py_ssize_t startidx, Py_ssize_t endidx)
1091 Py_ssize_t startidx, Py_ssize_t endidx)
1085 {
1092 {
1086 int length;
1093 int length;
1087 while (endidx > 1 && endidx > startidx) {
1094 while (endidx > 1 && endidx > startidx) {
1088 length = index_get_length(self, revs[endidx - 1]);
1095 length = index_get_length(self, revs[endidx - 1]);
1089 if (length < 0) {
1096 if (length < 0) {
1090 return -1;
1097 return -1;
1091 }
1098 }
1092 if (length != 0) {
1099 if (length != 0) {
1093 break;
1100 break;
1094 }
1101 }
1095 endidx -= 1;
1102 endidx -= 1;
1096 }
1103 }
1097 return endidx;
1104 return endidx;
1098 }
1105 }
1099
1106
1100 struct Gap {
1107 struct Gap {
1101 int64_t size;
1108 int64_t size;
1102 Py_ssize_t idx;
1109 Py_ssize_t idx;
1103 };
1110 };
1104
1111
1105 static int gap_compare(const void *left, const void *right)
1112 static int gap_compare(const void *left, const void *right)
1106 {
1113 {
1107 const struct Gap *l_left = ((const struct Gap *)left);
1114 const struct Gap *l_left = ((const struct Gap *)left);
1108 const struct Gap *l_right = ((const struct Gap *)right);
1115 const struct Gap *l_right = ((const struct Gap *)right);
1109 if (l_left->size < l_right->size) {
1116 if (l_left->size < l_right->size) {
1110 return -1;
1117 return -1;
1111 } else if (l_left->size > l_right->size) {
1118 } else if (l_left->size > l_right->size) {
1112 return 1;
1119 return 1;
1113 }
1120 }
1114 return 0;
1121 return 0;
1115 }
1122 }
1116 static int Py_ssize_t_compare(const void *left, const void *right)
1123 static int Py_ssize_t_compare(const void *left, const void *right)
1117 {
1124 {
1118 const Py_ssize_t l_left = *(const Py_ssize_t *)left;
1125 const Py_ssize_t l_left = *(const Py_ssize_t *)left;
1119 const Py_ssize_t l_right = *(const Py_ssize_t *)right;
1126 const Py_ssize_t l_right = *(const Py_ssize_t *)right;
1120 if (l_left < l_right) {
1127 if (l_left < l_right) {
1121 return -1;
1128 return -1;
1122 } else if (l_left > l_right) {
1129 } else if (l_left > l_right) {
1123 return 1;
1130 return 1;
1124 }
1131 }
1125 return 0;
1132 return 0;
1126 }
1133 }
1127
1134
1128 static PyObject *index_slicechunktodensity(indexObject *self, PyObject *args)
1135 static PyObject *index_slicechunktodensity(indexObject *self, PyObject *args)
1129 {
1136 {
1130 /* method arguments */
1137 /* method arguments */
1131 PyObject *list_revs = NULL; /* revisions in the chain */
1138 PyObject *list_revs = NULL; /* revisions in the chain */
1132 double targetdensity = 0; /* min density to achieve */
1139 double targetdensity = 0; /* min density to achieve */
1133 Py_ssize_t mingapsize = 0; /* threshold to ignore gaps */
1140 Py_ssize_t mingapsize = 0; /* threshold to ignore gaps */
1134
1141
1135 /* other core variables */
1142 /* other core variables */
1136 Py_ssize_t idxlen = index_length(self);
1143 Py_ssize_t idxlen = index_length(self);
1137 Py_ssize_t i; /* used for various iteration */
1144 Py_ssize_t i; /* used for various iteration */
1138 PyObject *result = NULL; /* the final return of the function */
1145 PyObject *result = NULL; /* the final return of the function */
1139
1146
1140 /* generic information about the delta chain being slice */
1147 /* generic information about the delta chain being slice */
1141 Py_ssize_t num_revs = 0; /* size of the full delta chain */
1148 Py_ssize_t num_revs = 0; /* size of the full delta chain */
1142 Py_ssize_t *revs = NULL; /* native array of revision in the chain */
1149 Py_ssize_t *revs = NULL; /* native array of revision in the chain */
1143 int64_t chainpayload = 0; /* sum of all delta in the chain */
1150 int64_t chainpayload = 0; /* sum of all delta in the chain */
1144 int64_t deltachainspan = 0; /* distance from first byte to last byte */
1151 int64_t deltachainspan = 0; /* distance from first byte to last byte */
1145
1152
1146 /* variable used for slicing the delta chain */
1153 /* variable used for slicing the delta chain */
1147 int64_t readdata = 0; /* amount of data currently planned to be read */
1154 int64_t readdata = 0; /* amount of data currently planned to be read */
1148 double density = 0; /* ration of payload data compared to read ones */
1155 double density = 0; /* ration of payload data compared to read ones */
1149 int64_t previous_end;
1156 int64_t previous_end;
1150 struct Gap *gaps = NULL; /* array of notable gap in the chain */
1157 struct Gap *gaps = NULL; /* array of notable gap in the chain */
1151 Py_ssize_t num_gaps =
1158 Py_ssize_t num_gaps =
1152 0; /* total number of notable gap recorded so far */
1159 0; /* total number of notable gap recorded so far */
1153 Py_ssize_t *selected_indices = NULL; /* indices of gap skipped over */
1160 Py_ssize_t *selected_indices = NULL; /* indices of gap skipped over */
1154 Py_ssize_t num_selected = 0; /* number of gaps skipped */
1161 Py_ssize_t num_selected = 0; /* number of gaps skipped */
1155 PyObject *chunk = NULL; /* individual slice */
1162 PyObject *chunk = NULL; /* individual slice */
1156 PyObject *allchunks = NULL; /* all slices */
1163 PyObject *allchunks = NULL; /* all slices */
1157 Py_ssize_t previdx;
1164 Py_ssize_t previdx;
1158
1165
1159 /* parsing argument */
1166 /* parsing argument */
1160 if (!PyArg_ParseTuple(args, "O!dn", &PyList_Type, &list_revs,
1167 if (!PyArg_ParseTuple(args, "O!dn", &PyList_Type, &list_revs,
1161 &targetdensity, &mingapsize)) {
1168 &targetdensity, &mingapsize)) {
1162 goto bail;
1169 goto bail;
1163 }
1170 }
1164
1171
1165 /* If the delta chain contains a single element, we do not need slicing
1172 /* If the delta chain contains a single element, we do not need slicing
1166 */
1173 */
1167 num_revs = PyList_GET_SIZE(list_revs);
1174 num_revs = PyList_GET_SIZE(list_revs);
1168 if (num_revs <= 1) {
1175 if (num_revs <= 1) {
1169 result = PyTuple_Pack(1, list_revs);
1176 result = PyTuple_Pack(1, list_revs);
1170 goto done;
1177 goto done;
1171 }
1178 }
1172
1179
1173 /* Turn the python list into a native integer array (for efficiency) */
1180 /* Turn the python list into a native integer array (for efficiency) */
1174 revs = (Py_ssize_t *)calloc(num_revs, sizeof(Py_ssize_t));
1181 revs = (Py_ssize_t *)calloc(num_revs, sizeof(Py_ssize_t));
1175 if (revs == NULL) {
1182 if (revs == NULL) {
1176 PyErr_NoMemory();
1183 PyErr_NoMemory();
1177 goto bail;
1184 goto bail;
1178 }
1185 }
1179 for (i = 0; i < num_revs; i++) {
1186 for (i = 0; i < num_revs; i++) {
1180 Py_ssize_t revnum = PyInt_AsLong(PyList_GET_ITEM(list_revs, i));
1187 Py_ssize_t revnum = PyInt_AsLong(PyList_GET_ITEM(list_revs, i));
1181 if (revnum == -1 && PyErr_Occurred()) {
1188 if (revnum == -1 && PyErr_Occurred()) {
1182 goto bail;
1189 goto bail;
1183 }
1190 }
1184 if (revnum < 0 || revnum >= idxlen) {
1191 if (revnum < 0 || revnum >= idxlen) {
1185 PyErr_SetString(PyExc_IndexError, "index out of range");
1192 PyErr_SetString(PyExc_IndexError, "index out of range");
1186 goto bail;
1193 goto bail;
1187 }
1194 }
1188 revs[i] = revnum;
1195 revs[i] = revnum;
1189 }
1196 }
1190
1197
1191 /* Compute and check various property of the unsliced delta chain */
1198 /* Compute and check various property of the unsliced delta chain */
1192 deltachainspan = index_segment_span(self, revs[0], revs[num_revs - 1]);
1199 deltachainspan = index_segment_span(self, revs[0], revs[num_revs - 1]);
1193 if (deltachainspan < 0) {
1200 if (deltachainspan < 0) {
1194 goto bail;
1201 goto bail;
1195 }
1202 }
1196
1203
1197 if (deltachainspan <= mingapsize) {
1204 if (deltachainspan <= mingapsize) {
1198 result = PyTuple_Pack(1, list_revs);
1205 result = PyTuple_Pack(1, list_revs);
1199 goto done;
1206 goto done;
1200 }
1207 }
1201 chainpayload = 0;
1208 chainpayload = 0;
1202 for (i = 0; i < num_revs; i++) {
1209 for (i = 0; i < num_revs; i++) {
1203 int tmp = index_get_length(self, revs[i]);
1210 int tmp = index_get_length(self, revs[i]);
1204 if (tmp < 0) {
1211 if (tmp < 0) {
1205 goto bail;
1212 goto bail;
1206 }
1213 }
1207 chainpayload += tmp;
1214 chainpayload += tmp;
1208 }
1215 }
1209
1216
1210 readdata = deltachainspan;
1217 readdata = deltachainspan;
1211 density = 1.0;
1218 density = 1.0;
1212
1219
1213 if (0 < deltachainspan) {
1220 if (0 < deltachainspan) {
1214 density = (double)chainpayload / (double)deltachainspan;
1221 density = (double)chainpayload / (double)deltachainspan;
1215 }
1222 }
1216
1223
1217 if (density >= targetdensity) {
1224 if (density >= targetdensity) {
1218 result = PyTuple_Pack(1, list_revs);
1225 result = PyTuple_Pack(1, list_revs);
1219 goto done;
1226 goto done;
1220 }
1227 }
1221
1228
1222 /* if chain is too sparse, look for relevant gaps */
1229 /* if chain is too sparse, look for relevant gaps */
1223 gaps = (struct Gap *)calloc(num_revs, sizeof(struct Gap));
1230 gaps = (struct Gap *)calloc(num_revs, sizeof(struct Gap));
1224 if (gaps == NULL) {
1231 if (gaps == NULL) {
1225 PyErr_NoMemory();
1232 PyErr_NoMemory();
1226 goto bail;
1233 goto bail;
1227 }
1234 }
1228
1235
1229 previous_end = -1;
1236 previous_end = -1;
1230 for (i = 0; i < num_revs; i++) {
1237 for (i = 0; i < num_revs; i++) {
1231 int64_t revstart;
1238 int64_t revstart;
1232 int revsize;
1239 int revsize;
1233 revstart = index_get_start(self, revs[i]);
1240 revstart = index_get_start(self, revs[i]);
1234 if (revstart < 0) {
1241 if (revstart < 0) {
1235 goto bail;
1242 goto bail;
1236 };
1243 };
1237 revsize = index_get_length(self, revs[i]);
1244 revsize = index_get_length(self, revs[i]);
1238 if (revsize < 0) {
1245 if (revsize < 0) {
1239 goto bail;
1246 goto bail;
1240 };
1247 };
1241 if (revsize == 0) {
1248 if (revsize == 0) {
1242 continue;
1249 continue;
1243 }
1250 }
1244 if (previous_end >= 0) {
1251 if (previous_end >= 0) {
1245 int64_t gapsize = revstart - previous_end;
1252 int64_t gapsize = revstart - previous_end;
1246 if (gapsize > mingapsize) {
1253 if (gapsize > mingapsize) {
1247 gaps[num_gaps].size = gapsize;
1254 gaps[num_gaps].size = gapsize;
1248 gaps[num_gaps].idx = i;
1255 gaps[num_gaps].idx = i;
1249 num_gaps += 1;
1256 num_gaps += 1;
1250 }
1257 }
1251 }
1258 }
1252 previous_end = revstart + revsize;
1259 previous_end = revstart + revsize;
1253 }
1260 }
1254 if (num_gaps == 0) {
1261 if (num_gaps == 0) {
1255 result = PyTuple_Pack(1, list_revs);
1262 result = PyTuple_Pack(1, list_revs);
1256 goto done;
1263 goto done;
1257 }
1264 }
1258 qsort(gaps, num_gaps, sizeof(struct Gap), &gap_compare);
1265 qsort(gaps, num_gaps, sizeof(struct Gap), &gap_compare);
1259
1266
1260 /* Slice the largest gap first, they improve the density the most */
1267 /* Slice the largest gap first, they improve the density the most */
1261 selected_indices =
1268 selected_indices =
1262 (Py_ssize_t *)malloc((num_gaps + 1) * sizeof(Py_ssize_t));
1269 (Py_ssize_t *)malloc((num_gaps + 1) * sizeof(Py_ssize_t));
1263 if (selected_indices == NULL) {
1270 if (selected_indices == NULL) {
1264 PyErr_NoMemory();
1271 PyErr_NoMemory();
1265 goto bail;
1272 goto bail;
1266 }
1273 }
1267
1274
1268 for (i = num_gaps - 1; i >= 0; i--) {
1275 for (i = num_gaps - 1; i >= 0; i--) {
1269 selected_indices[num_selected] = gaps[i].idx;
1276 selected_indices[num_selected] = gaps[i].idx;
1270 readdata -= gaps[i].size;
1277 readdata -= gaps[i].size;
1271 num_selected += 1;
1278 num_selected += 1;
1272 if (readdata <= 0) {
1279 if (readdata <= 0) {
1273 density = 1.0;
1280 density = 1.0;
1274 } else {
1281 } else {
1275 density = (double)chainpayload / (double)readdata;
1282 density = (double)chainpayload / (double)readdata;
1276 }
1283 }
1277 if (density >= targetdensity) {
1284 if (density >= targetdensity) {
1278 break;
1285 break;
1279 }
1286 }
1280 }
1287 }
1281 qsort(selected_indices, num_selected, sizeof(Py_ssize_t),
1288 qsort(selected_indices, num_selected, sizeof(Py_ssize_t),
1282 &Py_ssize_t_compare);
1289 &Py_ssize_t_compare);
1283
1290
1284 /* create the resulting slice */
1291 /* create the resulting slice */
1285 allchunks = PyList_New(0);
1292 allchunks = PyList_New(0);
1286 if (allchunks == NULL) {
1293 if (allchunks == NULL) {
1287 goto bail;
1294 goto bail;
1288 }
1295 }
1289 previdx = 0;
1296 previdx = 0;
1290 selected_indices[num_selected] = num_revs;
1297 selected_indices[num_selected] = num_revs;
1291 for (i = 0; i <= num_selected; i++) {
1298 for (i = 0; i <= num_selected; i++) {
1292 Py_ssize_t idx = selected_indices[i];
1299 Py_ssize_t idx = selected_indices[i];
1293 Py_ssize_t endidx = trim_endidx(self, revs, previdx, idx);
1300 Py_ssize_t endidx = trim_endidx(self, revs, previdx, idx);
1294 if (endidx < 0) {
1301 if (endidx < 0) {
1295 goto bail;
1302 goto bail;
1296 }
1303 }
1297 if (previdx < endidx) {
1304 if (previdx < endidx) {
1298 chunk = PyList_GetSlice(list_revs, previdx, endidx);
1305 chunk = PyList_GetSlice(list_revs, previdx, endidx);
1299 if (chunk == NULL) {
1306 if (chunk == NULL) {
1300 goto bail;
1307 goto bail;
1301 }
1308 }
1302 if (PyList_Append(allchunks, chunk) == -1) {
1309 if (PyList_Append(allchunks, chunk) == -1) {
1303 goto bail;
1310 goto bail;
1304 }
1311 }
1305 Py_DECREF(chunk);
1312 Py_DECREF(chunk);
1306 chunk = NULL;
1313 chunk = NULL;
1307 }
1314 }
1308 previdx = idx;
1315 previdx = idx;
1309 }
1316 }
1310 result = allchunks;
1317 result = allchunks;
1311 goto done;
1318 goto done;
1312
1319
1313 bail:
1320 bail:
1314 Py_XDECREF(allchunks);
1321 Py_XDECREF(allchunks);
1315 Py_XDECREF(chunk);
1322 Py_XDECREF(chunk);
1316 done:
1323 done:
1317 free(revs);
1324 free(revs);
1318 free(gaps);
1325 free(gaps);
1319 free(selected_indices);
1326 free(selected_indices);
1320 return result;
1327 return result;
1321 }
1328 }
1322
1329
1323 static inline int nt_level(const char *node, Py_ssize_t level)
1330 static inline int nt_level(const char *node, Py_ssize_t level)
1324 {
1331 {
1325 int v = node[level >> 1];
1332 int v = node[level >> 1];
1326 if (!(level & 1))
1333 if (!(level & 1))
1327 v >>= 4;
1334 v >>= 4;
1328 return v & 0xf;
1335 return v & 0xf;
1329 }
1336 }
1330
1337
1331 /*
1338 /*
1332 * Return values:
1339 * Return values:
1333 *
1340 *
1334 * -4: match is ambiguous (multiple candidates)
1341 * -4: match is ambiguous (multiple candidates)
1335 * -2: not found
1342 * -2: not found
1336 * rest: valid rev
1343 * rest: valid rev
1337 */
1344 */
1338 static int nt_find(nodetree *self, const char *node, Py_ssize_t nodelen,
1345 static int nt_find(nodetree *self, const char *node, Py_ssize_t nodelen,
1339 int hex)
1346 int hex)
1340 {
1347 {
1341 int (*getnybble)(const char *, Py_ssize_t) = hex ? hexdigit : nt_level;
1348 int (*getnybble)(const char *, Py_ssize_t) = hex ? hexdigit : nt_level;
1342 int level, maxlevel, off;
1349 int level, maxlevel, off;
1343
1350
1344 if (nodelen == 20 && node[0] == '\0' && memcmp(node, nullid, 20) == 0)
1351 if (nodelen == 20 && node[0] == '\0' && memcmp(node, nullid, 20) == 0)
1345 return -1;
1352 return -1;
1346
1353
1347 if (hex)
1354 if (hex)
1348 maxlevel = nodelen > 40 ? 40 : (int)nodelen;
1355 maxlevel = nodelen > 40 ? 40 : (int)nodelen;
1349 else
1356 else
1350 maxlevel = nodelen > 20 ? 40 : ((int)nodelen * 2);
1357 maxlevel = nodelen > 20 ? 40 : ((int)nodelen * 2);
1351
1358
1352 for (level = off = 0; level < maxlevel; level++) {
1359 for (level = off = 0; level < maxlevel; level++) {
1353 int k = getnybble(node, level);
1360 int k = getnybble(node, level);
1354 nodetreenode *n = &self->nodes[off];
1361 nodetreenode *n = &self->nodes[off];
1355 int v = n->children[k];
1362 int v = n->children[k];
1356
1363
1357 if (v < 0) {
1364 if (v < 0) {
1358 const char *n;
1365 const char *n;
1359 Py_ssize_t i;
1366 Py_ssize_t i;
1360
1367
1361 v = -(v + 2);
1368 v = -(v + 2);
1362 n = index_node(self->index, v);
1369 n = index_node(self->index, v);
1363 if (n == NULL)
1370 if (n == NULL)
1364 return -2;
1371 return -2;
1365 for (i = level; i < maxlevel; i++)
1372 for (i = level; i < maxlevel; i++)
1366 if (getnybble(node, i) != nt_level(n, i))
1373 if (getnybble(node, i) != nt_level(n, i))
1367 return -2;
1374 return -2;
1368 return v;
1375 return v;
1369 }
1376 }
1370 if (v == 0)
1377 if (v == 0)
1371 return -2;
1378 return -2;
1372 off = v;
1379 off = v;
1373 }
1380 }
1374 /* multiple matches against an ambiguous prefix */
1381 /* multiple matches against an ambiguous prefix */
1375 return -4;
1382 return -4;
1376 }
1383 }
1377
1384
1378 static int nt_new(nodetree *self)
1385 static int nt_new(nodetree *self)
1379 {
1386 {
1380 if (self->length == self->capacity) {
1387 if (self->length == self->capacity) {
1381 unsigned newcapacity;
1388 unsigned newcapacity;
1382 nodetreenode *newnodes;
1389 nodetreenode *newnodes;
1383 newcapacity = self->capacity * 2;
1390 newcapacity = self->capacity * 2;
1384 if (newcapacity >= INT_MAX / sizeof(nodetreenode)) {
1391 if (newcapacity >= INT_MAX / sizeof(nodetreenode)) {
1385 PyErr_SetString(PyExc_MemoryError,
1392 PyErr_SetString(PyExc_MemoryError,
1386 "overflow in nt_new");
1393 "overflow in nt_new");
1387 return -1;
1394 return -1;
1388 }
1395 }
1389 newnodes =
1396 newnodes =
1390 realloc(self->nodes, newcapacity * sizeof(nodetreenode));
1397 realloc(self->nodes, newcapacity * sizeof(nodetreenode));
1391 if (newnodes == NULL) {
1398 if (newnodes == NULL) {
1392 PyErr_SetString(PyExc_MemoryError, "out of memory");
1399 PyErr_SetString(PyExc_MemoryError, "out of memory");
1393 return -1;
1400 return -1;
1394 }
1401 }
1395 self->capacity = newcapacity;
1402 self->capacity = newcapacity;
1396 self->nodes = newnodes;
1403 self->nodes = newnodes;
1397 memset(&self->nodes[self->length], 0,
1404 memset(&self->nodes[self->length], 0,
1398 sizeof(nodetreenode) * (self->capacity - self->length));
1405 sizeof(nodetreenode) * (self->capacity - self->length));
1399 }
1406 }
1400 return self->length++;
1407 return self->length++;
1401 }
1408 }
1402
1409
1403 static int nt_insert(nodetree *self, const char *node, int rev)
1410 static int nt_insert(nodetree *self, const char *node, int rev)
1404 {
1411 {
1405 int level = 0;
1412 int level = 0;
1406 int off = 0;
1413 int off = 0;
1407
1414
1408 while (level < 40) {
1415 while (level < 40) {
1409 int k = nt_level(node, level);
1416 int k = nt_level(node, level);
1410 nodetreenode *n;
1417 nodetreenode *n;
1411 int v;
1418 int v;
1412
1419
1413 n = &self->nodes[off];
1420 n = &self->nodes[off];
1414 v = n->children[k];
1421 v = n->children[k];
1415
1422
1416 if (v == 0) {
1423 if (v == 0) {
1417 n->children[k] = -rev - 2;
1424 n->children[k] = -rev - 2;
1418 return 0;
1425 return 0;
1419 }
1426 }
1420 if (v < 0) {
1427 if (v < 0) {
1421 const char *oldnode =
1428 const char *oldnode =
1422 index_node_existing(self->index, -(v + 2));
1429 index_node_existing(self->index, -(v + 2));
1423 int noff;
1430 int noff;
1424
1431
1425 if (oldnode == NULL)
1432 if (oldnode == NULL)
1426 return -1;
1433 return -1;
1427 if (!memcmp(oldnode, node, 20)) {
1434 if (!memcmp(oldnode, node, 20)) {
1428 n->children[k] = -rev - 2;
1435 n->children[k] = -rev - 2;
1429 return 0;
1436 return 0;
1430 }
1437 }
1431 noff = nt_new(self);
1438 noff = nt_new(self);
1432 if (noff == -1)
1439 if (noff == -1)
1433 return -1;
1440 return -1;
1434 /* self->nodes may have been changed by realloc */
1441 /* self->nodes may have been changed by realloc */
1435 self->nodes[off].children[k] = noff;
1442 self->nodes[off].children[k] = noff;
1436 off = noff;
1443 off = noff;
1437 n = &self->nodes[off];
1444 n = &self->nodes[off];
1438 n->children[nt_level(oldnode, ++level)] = v;
1445 n->children[nt_level(oldnode, ++level)] = v;
1439 if (level > self->depth)
1446 if (level > self->depth)
1440 self->depth = level;
1447 self->depth = level;
1441 self->splits += 1;
1448 self->splits += 1;
1442 } else {
1449 } else {
1443 level += 1;
1450 level += 1;
1444 off = v;
1451 off = v;
1445 }
1452 }
1446 }
1453 }
1447
1454
1448 return -1;
1455 return -1;
1449 }
1456 }
1450
1457
1451 static PyObject *ntobj_insert(nodetreeObject *self, PyObject *args)
1458 static PyObject *ntobj_insert(nodetreeObject *self, PyObject *args)
1452 {
1459 {
1453 Py_ssize_t rev;
1460 Py_ssize_t rev;
1454 const char *node;
1461 const char *node;
1455 Py_ssize_t length;
1462 Py_ssize_t length;
1456 if (!PyArg_ParseTuple(args, "n", &rev))
1463 if (!PyArg_ParseTuple(args, "n", &rev))
1457 return NULL;
1464 return NULL;
1458 length = index_length(self->nt.index);
1465 length = index_length(self->nt.index);
1459 if (rev < 0 || rev >= length) {
1466 if (rev < 0 || rev >= length) {
1460 PyErr_SetString(PyExc_ValueError, "revlog index out of range");
1467 PyErr_SetString(PyExc_ValueError, "revlog index out of range");
1461 return NULL;
1468 return NULL;
1462 }
1469 }
1463 node = index_node_existing(self->nt.index, rev);
1470 node = index_node_existing(self->nt.index, rev);
1464 if (nt_insert(&self->nt, node, (int)rev) == -1)
1471 if (nt_insert(&self->nt, node, (int)rev) == -1)
1465 return NULL;
1472 return NULL;
1466 Py_RETURN_NONE;
1473 Py_RETURN_NONE;
1467 }
1474 }
1468
1475
1469 static int nt_delete_node(nodetree *self, const char *node)
1476 static int nt_delete_node(nodetree *self, const char *node)
1470 {
1477 {
1471 /* rev==-2 happens to get encoded as 0, which is interpreted as not set
1478 /* rev==-2 happens to get encoded as 0, which is interpreted as not set
1472 */
1479 */
1473 return nt_insert(self, node, -2);
1480 return nt_insert(self, node, -2);
1474 }
1481 }
1475
1482
1476 static int nt_init(nodetree *self, indexObject *index, unsigned capacity)
1483 static int nt_init(nodetree *self, indexObject *index, unsigned capacity)
1477 {
1484 {
1478 /* Initialize before overflow-checking to avoid nt_dealloc() crash. */
1485 /* Initialize before overflow-checking to avoid nt_dealloc() crash. */
1479 self->nodes = NULL;
1486 self->nodes = NULL;
1480
1487
1481 self->index = index;
1488 self->index = index;
1482 /* The input capacity is in terms of revisions, while the field is in
1489 /* The input capacity is in terms of revisions, while the field is in
1483 * terms of nodetree nodes. */
1490 * terms of nodetree nodes. */
1484 self->capacity = (capacity < 4 ? 4 : capacity / 2);
1491 self->capacity = (capacity < 4 ? 4 : capacity / 2);
1485 self->depth = 0;
1492 self->depth = 0;
1486 self->splits = 0;
1493 self->splits = 0;
1487 if ((size_t)self->capacity > INT_MAX / sizeof(nodetreenode)) {
1494 if ((size_t)self->capacity > INT_MAX / sizeof(nodetreenode)) {
1488 PyErr_SetString(PyExc_ValueError, "overflow in init_nt");
1495 PyErr_SetString(PyExc_ValueError, "overflow in init_nt");
1489 return -1;
1496 return -1;
1490 }
1497 }
1491 self->nodes = calloc(self->capacity, sizeof(nodetreenode));
1498 self->nodes = calloc(self->capacity, sizeof(nodetreenode));
1492 if (self->nodes == NULL) {
1499 if (self->nodes == NULL) {
1493 PyErr_NoMemory();
1500 PyErr_NoMemory();
1494 return -1;
1501 return -1;
1495 }
1502 }
1496 self->length = 1;
1503 self->length = 1;
1497 return 0;
1504 return 0;
1498 }
1505 }
1499
1506
1500 static PyTypeObject indexType;
1507 static PyTypeObject indexType;
1501
1508
1502 static int ntobj_init(nodetreeObject *self, PyObject *args)
1509 static int ntobj_init(nodetreeObject *self, PyObject *args)
1503 {
1510 {
1504 PyObject *index;
1511 PyObject *index;
1505 unsigned capacity;
1512 unsigned capacity;
1506 if (!PyArg_ParseTuple(args, "O!I", &indexType, &index, &capacity))
1513 if (!PyArg_ParseTuple(args, "O!I", &indexType, &index, &capacity))
1507 return -1;
1514 return -1;
1508 Py_INCREF(index);
1515 Py_INCREF(index);
1509 return nt_init(&self->nt, (indexObject *)index, capacity);
1516 return nt_init(&self->nt, (indexObject *)index, capacity);
1510 }
1517 }
1511
1518
1512 static int nt_partialmatch(nodetree *self, const char *node, Py_ssize_t nodelen)
1519 static int nt_partialmatch(nodetree *self, const char *node, Py_ssize_t nodelen)
1513 {
1520 {
1514 return nt_find(self, node, nodelen, 1);
1521 return nt_find(self, node, nodelen, 1);
1515 }
1522 }
1516
1523
1517 /*
1524 /*
1518 * Find the length of the shortest unique prefix of node.
1525 * Find the length of the shortest unique prefix of node.
1519 *
1526 *
1520 * Return values:
1527 * Return values:
1521 *
1528 *
1522 * -3: error (exception set)
1529 * -3: error (exception set)
1523 * -2: not found (no exception set)
1530 * -2: not found (no exception set)
1524 * rest: length of shortest prefix
1531 * rest: length of shortest prefix
1525 */
1532 */
1526 static int nt_shortest(nodetree *self, const char *node)
1533 static int nt_shortest(nodetree *self, const char *node)
1527 {
1534 {
1528 int level, off;
1535 int level, off;
1529
1536
1530 for (level = off = 0; level < 40; level++) {
1537 for (level = off = 0; level < 40; level++) {
1531 int k, v;
1538 int k, v;
1532 nodetreenode *n = &self->nodes[off];
1539 nodetreenode *n = &self->nodes[off];
1533 k = nt_level(node, level);
1540 k = nt_level(node, level);
1534 v = n->children[k];
1541 v = n->children[k];
1535 if (v < 0) {
1542 if (v < 0) {
1536 const char *n;
1543 const char *n;
1537 v = -(v + 2);
1544 v = -(v + 2);
1538 n = index_node_existing(self->index, v);
1545 n = index_node_existing(self->index, v);
1539 if (n == NULL)
1546 if (n == NULL)
1540 return -3;
1547 return -3;
1541 if (memcmp(node, n, 20) != 0)
1548 if (memcmp(node, n, 20) != 0)
1542 /*
1549 /*
1543 * Found a unique prefix, but it wasn't for the
1550 * Found a unique prefix, but it wasn't for the
1544 * requested node (i.e the requested node does
1551 * requested node (i.e the requested node does
1545 * not exist).
1552 * not exist).
1546 */
1553 */
1547 return -2;
1554 return -2;
1548 return level + 1;
1555 return level + 1;
1549 }
1556 }
1550 if (v == 0)
1557 if (v == 0)
1551 return -2;
1558 return -2;
1552 off = v;
1559 off = v;
1553 }
1560 }
1554 /*
1561 /*
1555 * The node was still not unique after 40 hex digits, so this won't
1562 * The node was still not unique after 40 hex digits, so this won't
1556 * happen. Also, if we get here, then there's a programming error in
1563 * happen. Also, if we get here, then there's a programming error in
1557 * this file that made us insert a node longer than 40 hex digits.
1564 * this file that made us insert a node longer than 40 hex digits.
1558 */
1565 */
1559 PyErr_SetString(PyExc_Exception, "broken node tree");
1566 PyErr_SetString(PyExc_Exception, "broken node tree");
1560 return -3;
1567 return -3;
1561 }
1568 }
1562
1569
1563 static PyObject *ntobj_shortest(nodetreeObject *self, PyObject *args)
1570 static PyObject *ntobj_shortest(nodetreeObject *self, PyObject *args)
1564 {
1571 {
1565 PyObject *val;
1572 PyObject *val;
1566 char *node;
1573 char *node;
1567 int length;
1574 int length;
1568
1575
1569 if (!PyArg_ParseTuple(args, "O", &val))
1576 if (!PyArg_ParseTuple(args, "O", &val))
1570 return NULL;
1577 return NULL;
1571 if (node_check(val, &node) == -1)
1578 if (node_check(val, &node) == -1)
1572 return NULL;
1579 return NULL;
1573
1580
1574 length = nt_shortest(&self->nt, node);
1581 length = nt_shortest(&self->nt, node);
1575 if (length == -3)
1582 if (length == -3)
1576 return NULL;
1583 return NULL;
1577 if (length == -2) {
1584 if (length == -2) {
1578 raise_revlog_error();
1585 raise_revlog_error();
1579 return NULL;
1586 return NULL;
1580 }
1587 }
1581 return PyInt_FromLong(length);
1588 return PyInt_FromLong(length);
1582 }
1589 }
1583
1590
1584 static void nt_dealloc(nodetree *self)
1591 static void nt_dealloc(nodetree *self)
1585 {
1592 {
1586 free(self->nodes);
1593 free(self->nodes);
1587 self->nodes = NULL;
1594 self->nodes = NULL;
1588 }
1595 }
1589
1596
1590 static void ntobj_dealloc(nodetreeObject *self)
1597 static void ntobj_dealloc(nodetreeObject *self)
1591 {
1598 {
1592 Py_XDECREF(self->nt.index);
1599 Py_XDECREF(self->nt.index);
1593 nt_dealloc(&self->nt);
1600 nt_dealloc(&self->nt);
1594 PyObject_Del(self);
1601 PyObject_Del(self);
1595 }
1602 }
1596
1603
1597 static PyMethodDef ntobj_methods[] = {
1604 static PyMethodDef ntobj_methods[] = {
1598 {"insert", (PyCFunction)ntobj_insert, METH_VARARGS,
1605 {"insert", (PyCFunction)ntobj_insert, METH_VARARGS,
1599 "insert an index entry"},
1606 "insert an index entry"},
1600 {"shortest", (PyCFunction)ntobj_shortest, METH_VARARGS,
1607 {"shortest", (PyCFunction)ntobj_shortest, METH_VARARGS,
1601 "find length of shortest hex nodeid of a binary ID"},
1608 "find length of shortest hex nodeid of a binary ID"},
1602 {NULL} /* Sentinel */
1609 {NULL} /* Sentinel */
1603 };
1610 };
1604
1611
1605 static PyTypeObject nodetreeType = {
1612 static PyTypeObject nodetreeType = {
1606 PyVarObject_HEAD_INIT(NULL, 0) /* header */
1613 PyVarObject_HEAD_INIT(NULL, 0) /* header */
1607 "parsers.nodetree", /* tp_name */
1614 "parsers.nodetree", /* tp_name */
1608 sizeof(nodetreeObject), /* tp_basicsize */
1615 sizeof(nodetreeObject), /* tp_basicsize */
1609 0, /* tp_itemsize */
1616 0, /* tp_itemsize */
1610 (destructor)ntobj_dealloc, /* tp_dealloc */
1617 (destructor)ntobj_dealloc, /* tp_dealloc */
1611 0, /* tp_print */
1618 0, /* tp_print */
1612 0, /* tp_getattr */
1619 0, /* tp_getattr */
1613 0, /* tp_setattr */
1620 0, /* tp_setattr */
1614 0, /* tp_compare */
1621 0, /* tp_compare */
1615 0, /* tp_repr */
1622 0, /* tp_repr */
1616 0, /* tp_as_number */
1623 0, /* tp_as_number */
1617 0, /* tp_as_sequence */
1624 0, /* tp_as_sequence */
1618 0, /* tp_as_mapping */
1625 0, /* tp_as_mapping */
1619 0, /* tp_hash */
1626 0, /* tp_hash */
1620 0, /* tp_call */
1627 0, /* tp_call */
1621 0, /* tp_str */
1628 0, /* tp_str */
1622 0, /* tp_getattro */
1629 0, /* tp_getattro */
1623 0, /* tp_setattro */
1630 0, /* tp_setattro */
1624 0, /* tp_as_buffer */
1631 0, /* tp_as_buffer */
1625 Py_TPFLAGS_DEFAULT, /* tp_flags */
1632 Py_TPFLAGS_DEFAULT, /* tp_flags */
1626 "nodetree", /* tp_doc */
1633 "nodetree", /* tp_doc */
1627 0, /* tp_traverse */
1634 0, /* tp_traverse */
1628 0, /* tp_clear */
1635 0, /* tp_clear */
1629 0, /* tp_richcompare */
1636 0, /* tp_richcompare */
1630 0, /* tp_weaklistoffset */
1637 0, /* tp_weaklistoffset */
1631 0, /* tp_iter */
1638 0, /* tp_iter */
1632 0, /* tp_iternext */
1639 0, /* tp_iternext */
1633 ntobj_methods, /* tp_methods */
1640 ntobj_methods, /* tp_methods */
1634 0, /* tp_members */
1641 0, /* tp_members */
1635 0, /* tp_getset */
1642 0, /* tp_getset */
1636 0, /* tp_base */
1643 0, /* tp_base */
1637 0, /* tp_dict */
1644 0, /* tp_dict */
1638 0, /* tp_descr_get */
1645 0, /* tp_descr_get */
1639 0, /* tp_descr_set */
1646 0, /* tp_descr_set */
1640 0, /* tp_dictoffset */
1647 0, /* tp_dictoffset */
1641 (initproc)ntobj_init, /* tp_init */
1648 (initproc)ntobj_init, /* tp_init */
1642 0, /* tp_alloc */
1649 0, /* tp_alloc */
1643 };
1650 };
1644
1651
1645 static int index_init_nt(indexObject *self)
1652 static int index_init_nt(indexObject *self)
1646 {
1653 {
1647 if (!self->ntinitialized) {
1654 if (!self->ntinitialized) {
1648 if (nt_init(&self->nt, self, (int)self->raw_length) == -1) {
1655 if (nt_init(&self->nt, self, (int)self->raw_length) == -1) {
1649 nt_dealloc(&self->nt);
1656 nt_dealloc(&self->nt);
1650 return -1;
1657 return -1;
1651 }
1658 }
1652 if (nt_insert(&self->nt, nullid, -1) == -1) {
1659 if (nt_insert(&self->nt, nullid, -1) == -1) {
1653 nt_dealloc(&self->nt);
1660 nt_dealloc(&self->nt);
1654 return -1;
1661 return -1;
1655 }
1662 }
1656 self->ntinitialized = 1;
1663 self->ntinitialized = 1;
1657 self->ntrev = (int)index_length(self);
1664 self->ntrev = (int)index_length(self);
1658 self->ntlookups = 1;
1665 self->ntlookups = 1;
1659 self->ntmisses = 0;
1666 self->ntmisses = 0;
1660 }
1667 }
1661 return 0;
1668 return 0;
1662 }
1669 }
1663
1670
1664 /*
1671 /*
1665 * Return values:
1672 * Return values:
1666 *
1673 *
1667 * -3: error (exception set)
1674 * -3: error (exception set)
1668 * -2: not found (no exception set)
1675 * -2: not found (no exception set)
1669 * rest: valid rev
1676 * rest: valid rev
1670 */
1677 */
1671 static int index_find_node(indexObject *self, const char *node,
1678 static int index_find_node(indexObject *self, const char *node,
1672 Py_ssize_t nodelen)
1679 Py_ssize_t nodelen)
1673 {
1680 {
1674 int rev;
1681 int rev;
1675
1682
1676 if (index_init_nt(self) == -1)
1683 if (index_init_nt(self) == -1)
1677 return -3;
1684 return -3;
1678
1685
1679 self->ntlookups++;
1686 self->ntlookups++;
1680 rev = nt_find(&self->nt, node, nodelen, 0);
1687 rev = nt_find(&self->nt, node, nodelen, 0);
1681 if (rev >= -1)
1688 if (rev >= -1)
1682 return rev;
1689 return rev;
1683
1690
1684 /*
1691 /*
1685 * For the first handful of lookups, we scan the entire index,
1692 * For the first handful of lookups, we scan the entire index,
1686 * and cache only the matching nodes. This optimizes for cases
1693 * and cache only the matching nodes. This optimizes for cases
1687 * like "hg tip", where only a few nodes are accessed.
1694 * like "hg tip", where only a few nodes are accessed.
1688 *
1695 *
1689 * After that, we cache every node we visit, using a single
1696 * After that, we cache every node we visit, using a single
1690 * scan amortized over multiple lookups. This gives the best
1697 * scan amortized over multiple lookups. This gives the best
1691 * bulk performance, e.g. for "hg log".
1698 * bulk performance, e.g. for "hg log".
1692 */
1699 */
1693 if (self->ntmisses++ < 4) {
1700 if (self->ntmisses++ < 4) {
1694 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1701 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1695 const char *n = index_node_existing(self, rev);
1702 const char *n = index_node_existing(self, rev);
1696 if (n == NULL)
1703 if (n == NULL)
1697 return -3;
1704 return -3;
1698 if (memcmp(node, n, nodelen > 20 ? 20 : nodelen) == 0) {
1705 if (memcmp(node, n, nodelen > 20 ? 20 : nodelen) == 0) {
1699 if (nt_insert(&self->nt, n, rev) == -1)
1706 if (nt_insert(&self->nt, n, rev) == -1)
1700 return -3;
1707 return -3;
1701 break;
1708 break;
1702 }
1709 }
1703 }
1710 }
1704 } else {
1711 } else {
1705 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1712 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1706 const char *n = index_node_existing(self, rev);
1713 const char *n = index_node_existing(self, rev);
1707 if (n == NULL)
1714 if (n == NULL)
1708 return -3;
1715 return -3;
1709 if (nt_insert(&self->nt, n, rev) == -1) {
1716 if (nt_insert(&self->nt, n, rev) == -1) {
1710 self->ntrev = rev + 1;
1717 self->ntrev = rev + 1;
1711 return -3;
1718 return -3;
1712 }
1719 }
1713 if (memcmp(node, n, nodelen > 20 ? 20 : nodelen) == 0) {
1720 if (memcmp(node, n, nodelen > 20 ? 20 : nodelen) == 0) {
1714 break;
1721 break;
1715 }
1722 }
1716 }
1723 }
1717 self->ntrev = rev;
1724 self->ntrev = rev;
1718 }
1725 }
1719
1726
1720 if (rev >= 0)
1727 if (rev >= 0)
1721 return rev;
1728 return rev;
1722 return -2;
1729 return -2;
1723 }
1730 }
1724
1731
1725 static PyObject *index_getitem(indexObject *self, PyObject *value)
1732 static PyObject *index_getitem(indexObject *self, PyObject *value)
1726 {
1733 {
1727 char *node;
1734 char *node;
1728 int rev;
1735 int rev;
1729
1736
1730 if (PyInt_Check(value)) {
1737 if (PyInt_Check(value)) {
1731 long idx;
1738 long idx;
1732 if (!pylong_to_long(value, &idx)) {
1739 if (!pylong_to_long(value, &idx)) {
1733 return NULL;
1740 return NULL;
1734 }
1741 }
1735 return index_get(self, idx);
1742 return index_get(self, idx);
1736 }
1743 }
1737
1744
1738 if (node_check(value, &node) == -1)
1745 if (node_check(value, &node) == -1)
1739 return NULL;
1746 return NULL;
1740 rev = index_find_node(self, node, 20);
1747 rev = index_find_node(self, node, 20);
1741 if (rev >= -1)
1748 if (rev >= -1)
1742 return PyInt_FromLong(rev);
1749 return PyInt_FromLong(rev);
1743 if (rev == -2)
1750 if (rev == -2)
1744 raise_revlog_error();
1751 raise_revlog_error();
1745 return NULL;
1752 return NULL;
1746 }
1753 }
1747
1754
1748 /*
1755 /*
1749 * Fully populate the radix tree.
1756 * Fully populate the radix tree.
1750 */
1757 */
1751 static int index_populate_nt(indexObject *self)
1758 static int index_populate_nt(indexObject *self)
1752 {
1759 {
1753 int rev;
1760 int rev;
1754 if (self->ntrev > 0) {
1761 if (self->ntrev > 0) {
1755 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1762 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1756 const char *n = index_node_existing(self, rev);
1763 const char *n = index_node_existing(self, rev);
1757 if (n == NULL)
1764 if (n == NULL)
1758 return -1;
1765 return -1;
1759 if (nt_insert(&self->nt, n, rev) == -1)
1766 if (nt_insert(&self->nt, n, rev) == -1)
1760 return -1;
1767 return -1;
1761 }
1768 }
1762 self->ntrev = -1;
1769 self->ntrev = -1;
1763 }
1770 }
1764 return 0;
1771 return 0;
1765 }
1772 }
1766
1773
1767 static PyObject *index_partialmatch(indexObject *self, PyObject *args)
1774 static PyObject *index_partialmatch(indexObject *self, PyObject *args)
1768 {
1775 {
1769 const char *fullnode;
1776 const char *fullnode;
1770 int nodelen;
1777 int nodelen;
1771 char *node;
1778 char *node;
1772 int rev, i;
1779 int rev, i;
1773
1780
1774 if (!PyArg_ParseTuple(args, PY23("s#", "y#"), &node, &nodelen))
1781 if (!PyArg_ParseTuple(args, PY23("s#", "y#"), &node, &nodelen))
1775 return NULL;
1782 return NULL;
1776
1783
1777 if (nodelen < 1) {
1784 if (nodelen < 1) {
1778 PyErr_SetString(PyExc_ValueError, "key too short");
1785 PyErr_SetString(PyExc_ValueError, "key too short");
1779 return NULL;
1786 return NULL;
1780 }
1787 }
1781
1788
1782 if (nodelen > 40) {
1789 if (nodelen > 40) {
1783 PyErr_SetString(PyExc_ValueError, "key too long");
1790 PyErr_SetString(PyExc_ValueError, "key too long");
1784 return NULL;
1791 return NULL;
1785 }
1792 }
1786
1793
1787 for (i = 0; i < nodelen; i++)
1794 for (i = 0; i < nodelen; i++)
1788 hexdigit(node, i);
1795 hexdigit(node, i);
1789 if (PyErr_Occurred()) {
1796 if (PyErr_Occurred()) {
1790 /* input contains non-hex characters */
1797 /* input contains non-hex characters */
1791 PyErr_Clear();
1798 PyErr_Clear();
1792 Py_RETURN_NONE;
1799 Py_RETURN_NONE;
1793 }
1800 }
1794
1801
1795 if (index_init_nt(self) == -1)
1802 if (index_init_nt(self) == -1)
1796 return NULL;
1803 return NULL;
1797 if (index_populate_nt(self) == -1)
1804 if (index_populate_nt(self) == -1)
1798 return NULL;
1805 return NULL;
1799 rev = nt_partialmatch(&self->nt, node, nodelen);
1806 rev = nt_partialmatch(&self->nt, node, nodelen);
1800
1807
1801 switch (rev) {
1808 switch (rev) {
1802 case -4:
1809 case -4:
1803 raise_revlog_error();
1810 raise_revlog_error();
1804 return NULL;
1811 return NULL;
1805 case -2:
1812 case -2:
1806 Py_RETURN_NONE;
1813 Py_RETURN_NONE;
1807 case -1:
1814 case -1:
1808 return PyBytes_FromStringAndSize(nullid, 20);
1815 return PyBytes_FromStringAndSize(nullid, 20);
1809 }
1816 }
1810
1817
1811 fullnode = index_node_existing(self, rev);
1818 fullnode = index_node_existing(self, rev);
1812 if (fullnode == NULL) {
1819 if (fullnode == NULL) {
1813 return NULL;
1820 return NULL;
1814 }
1821 }
1815 return PyBytes_FromStringAndSize(fullnode, 20);
1822 return PyBytes_FromStringAndSize(fullnode, 20);
1816 }
1823 }
1817
1824
1818 static PyObject *index_shortest(indexObject *self, PyObject *args)
1825 static PyObject *index_shortest(indexObject *self, PyObject *args)
1819 {
1826 {
1820 PyObject *val;
1827 PyObject *val;
1821 char *node;
1828 char *node;
1822 int length;
1829 int length;
1823
1830
1824 if (!PyArg_ParseTuple(args, "O", &val))
1831 if (!PyArg_ParseTuple(args, "O", &val))
1825 return NULL;
1832 return NULL;
1826 if (node_check(val, &node) == -1)
1833 if (node_check(val, &node) == -1)
1827 return NULL;
1834 return NULL;
1828
1835
1829 self->ntlookups++;
1836 self->ntlookups++;
1830 if (index_init_nt(self) == -1)
1837 if (index_init_nt(self) == -1)
1831 return NULL;
1838 return NULL;
1832 if (index_populate_nt(self) == -1)
1839 if (index_populate_nt(self) == -1)
1833 return NULL;
1840 return NULL;
1834 length = nt_shortest(&self->nt, node);
1841 length = nt_shortest(&self->nt, node);
1835 if (length == -3)
1842 if (length == -3)
1836 return NULL;
1843 return NULL;
1837 if (length == -2) {
1844 if (length == -2) {
1838 raise_revlog_error();
1845 raise_revlog_error();
1839 return NULL;
1846 return NULL;
1840 }
1847 }
1841 return PyInt_FromLong(length);
1848 return PyInt_FromLong(length);
1842 }
1849 }
1843
1850
1844 static PyObject *index_m_get(indexObject *self, PyObject *args)
1851 static PyObject *index_m_get(indexObject *self, PyObject *args)
1845 {
1852 {
1846 PyObject *val;
1853 PyObject *val;
1847 char *node;
1854 char *node;
1848 int rev;
1855 int rev;
1849
1856
1850 if (!PyArg_ParseTuple(args, "O", &val))
1857 if (!PyArg_ParseTuple(args, "O", &val))
1851 return NULL;
1858 return NULL;
1852 if (node_check(val, &node) == -1)
1859 if (node_check(val, &node) == -1)
1853 return NULL;
1860 return NULL;
1854 rev = index_find_node(self, node, 20);
1861 rev = index_find_node(self, node, 20);
1855 if (rev == -3)
1862 if (rev == -3)
1856 return NULL;
1863 return NULL;
1857 if (rev == -2)
1864 if (rev == -2)
1858 Py_RETURN_NONE;
1865 Py_RETURN_NONE;
1859 return PyInt_FromLong(rev);
1866 return PyInt_FromLong(rev);
1860 }
1867 }
1861
1868
1862 static int index_contains(indexObject *self, PyObject *value)
1869 static int index_contains(indexObject *self, PyObject *value)
1863 {
1870 {
1864 char *node;
1871 char *node;
1865
1872
1866 if (PyInt_Check(value)) {
1873 if (PyInt_Check(value)) {
1867 long rev;
1874 long rev;
1868 if (!pylong_to_long(value, &rev)) {
1875 if (!pylong_to_long(value, &rev)) {
1869 return -1;
1876 return -1;
1870 }
1877 }
1871 return rev >= -1 && rev < index_length(self);
1878 return rev >= -1 && rev < index_length(self);
1872 }
1879 }
1873
1880
1874 if (node_check(value, &node) == -1)
1881 if (node_check(value, &node) == -1)
1875 return -1;
1882 return -1;
1876
1883
1877 switch (index_find_node(self, node, 20)) {
1884 switch (index_find_node(self, node, 20)) {
1878 case -3:
1885 case -3:
1879 return -1;
1886 return -1;
1880 case -2:
1887 case -2:
1881 return 0;
1888 return 0;
1882 default:
1889 default:
1883 return 1;
1890 return 1;
1884 }
1891 }
1885 }
1892 }
1886
1893
1887 typedef uint64_t bitmask;
1894 typedef uint64_t bitmask;
1888
1895
1889 /*
1896 /*
1890 * Given a disjoint set of revs, return all candidates for the
1897 * Given a disjoint set of revs, return all candidates for the
1891 * greatest common ancestor. In revset notation, this is the set
1898 * greatest common ancestor. In revset notation, this is the set
1892 * "heads(::a and ::b and ...)"
1899 * "heads(::a and ::b and ...)"
1893 */
1900 */
1894 static PyObject *find_gca_candidates(indexObject *self, const int *revs,
1901 static PyObject *find_gca_candidates(indexObject *self, const int *revs,
1895 int revcount)
1902 int revcount)
1896 {
1903 {
1897 const bitmask allseen = (1ull << revcount) - 1;
1904 const bitmask allseen = (1ull << revcount) - 1;
1898 const bitmask poison = 1ull << revcount;
1905 const bitmask poison = 1ull << revcount;
1899 PyObject *gca = PyList_New(0);
1906 PyObject *gca = PyList_New(0);
1900 int i, v, interesting;
1907 int i, v, interesting;
1901 int maxrev = -1;
1908 int maxrev = -1;
1902 bitmask sp;
1909 bitmask sp;
1903 bitmask *seen;
1910 bitmask *seen;
1904
1911
1905 if (gca == NULL)
1912 if (gca == NULL)
1906 return PyErr_NoMemory();
1913 return PyErr_NoMemory();
1907
1914
1908 for (i = 0; i < revcount; i++) {
1915 for (i = 0; i < revcount; i++) {
1909 if (revs[i] > maxrev)
1916 if (revs[i] > maxrev)
1910 maxrev = revs[i];
1917 maxrev = revs[i];
1911 }
1918 }
1912
1919
1913 seen = calloc(sizeof(*seen), maxrev + 1);
1920 seen = calloc(sizeof(*seen), maxrev + 1);
1914 if (seen == NULL) {
1921 if (seen == NULL) {
1915 Py_DECREF(gca);
1922 Py_DECREF(gca);
1916 return PyErr_NoMemory();
1923 return PyErr_NoMemory();
1917 }
1924 }
1918
1925
1919 for (i = 0; i < revcount; i++)
1926 for (i = 0; i < revcount; i++)
1920 seen[revs[i]] = 1ull << i;
1927 seen[revs[i]] = 1ull << i;
1921
1928
1922 interesting = revcount;
1929 interesting = revcount;
1923
1930
1924 for (v = maxrev; v >= 0 && interesting; v--) {
1931 for (v = maxrev; v >= 0 && interesting; v--) {
1925 bitmask sv = seen[v];
1932 bitmask sv = seen[v];
1926 int parents[2];
1933 int parents[2];
1927
1934
1928 if (!sv)
1935 if (!sv)
1929 continue;
1936 continue;
1930
1937
1931 if (sv < poison) {
1938 if (sv < poison) {
1932 interesting -= 1;
1939 interesting -= 1;
1933 if (sv == allseen) {
1940 if (sv == allseen) {
1934 PyObject *obj = PyInt_FromLong(v);
1941 PyObject *obj = PyInt_FromLong(v);
1935 if (obj == NULL)
1942 if (obj == NULL)
1936 goto bail;
1943 goto bail;
1937 if (PyList_Append(gca, obj) == -1) {
1944 if (PyList_Append(gca, obj) == -1) {
1938 Py_DECREF(obj);
1945 Py_DECREF(obj);
1939 goto bail;
1946 goto bail;
1940 }
1947 }
1941 sv |= poison;
1948 sv |= poison;
1942 for (i = 0; i < revcount; i++) {
1949 for (i = 0; i < revcount; i++) {
1943 if (revs[i] == v)
1950 if (revs[i] == v)
1944 goto done;
1951 goto done;
1945 }
1952 }
1946 }
1953 }
1947 }
1954 }
1948 if (index_get_parents(self, v, parents, maxrev) < 0)
1955 if (index_get_parents(self, v, parents, maxrev) < 0)
1949 goto bail;
1956 goto bail;
1950
1957
1951 for (i = 0; i < 2; i++) {
1958 for (i = 0; i < 2; i++) {
1952 int p = parents[i];
1959 int p = parents[i];
1953 if (p == -1)
1960 if (p == -1)
1954 continue;
1961 continue;
1955 sp = seen[p];
1962 sp = seen[p];
1956 if (sv < poison) {
1963 if (sv < poison) {
1957 if (sp == 0) {
1964 if (sp == 0) {
1958 seen[p] = sv;
1965 seen[p] = sv;
1959 interesting++;
1966 interesting++;
1960 } else if (sp != sv)
1967 } else if (sp != sv)
1961 seen[p] |= sv;
1968 seen[p] |= sv;
1962 } else {
1969 } else {
1963 if (sp && sp < poison)
1970 if (sp && sp < poison)
1964 interesting--;
1971 interesting--;
1965 seen[p] = sv;
1972 seen[p] = sv;
1966 }
1973 }
1967 }
1974 }
1968 }
1975 }
1969
1976
1970 done:
1977 done:
1971 free(seen);
1978 free(seen);
1972 return gca;
1979 return gca;
1973 bail:
1980 bail:
1974 free(seen);
1981 free(seen);
1975 Py_XDECREF(gca);
1982 Py_XDECREF(gca);
1976 return NULL;
1983 return NULL;
1977 }
1984 }
1978
1985
1979 /*
1986 /*
1980 * Given a disjoint set of revs, return the subset with the longest
1987 * Given a disjoint set of revs, return the subset with the longest
1981 * path to the root.
1988 * path to the root.
1982 */
1989 */
1983 static PyObject *find_deepest(indexObject *self, PyObject *revs)
1990 static PyObject *find_deepest(indexObject *self, PyObject *revs)
1984 {
1991 {
1985 const Py_ssize_t revcount = PyList_GET_SIZE(revs);
1992 const Py_ssize_t revcount = PyList_GET_SIZE(revs);
1986 static const Py_ssize_t capacity = 24;
1993 static const Py_ssize_t capacity = 24;
1987 int *depth, *interesting = NULL;
1994 int *depth, *interesting = NULL;
1988 int i, j, v, ninteresting;
1995 int i, j, v, ninteresting;
1989 PyObject *dict = NULL, *keys = NULL;
1996 PyObject *dict = NULL, *keys = NULL;
1990 long *seen = NULL;
1997 long *seen = NULL;
1991 int maxrev = -1;
1998 int maxrev = -1;
1992 long final;
1999 long final;
1993
2000
1994 if (revcount > capacity) {
2001 if (revcount > capacity) {
1995 PyErr_Format(PyExc_OverflowError,
2002 PyErr_Format(PyExc_OverflowError,
1996 "bitset size (%ld) > capacity (%ld)",
2003 "bitset size (%ld) > capacity (%ld)",
1997 (long)revcount, (long)capacity);
2004 (long)revcount, (long)capacity);
1998 return NULL;
2005 return NULL;
1999 }
2006 }
2000
2007
2001 for (i = 0; i < revcount; i++) {
2008 for (i = 0; i < revcount; i++) {
2002 int n = (int)PyInt_AsLong(PyList_GET_ITEM(revs, i));
2009 int n = (int)PyInt_AsLong(PyList_GET_ITEM(revs, i));
2003 if (n > maxrev)
2010 if (n > maxrev)
2004 maxrev = n;
2011 maxrev = n;
2005 }
2012 }
2006
2013
2007 depth = calloc(sizeof(*depth), maxrev + 1);
2014 depth = calloc(sizeof(*depth), maxrev + 1);
2008 if (depth == NULL)
2015 if (depth == NULL)
2009 return PyErr_NoMemory();
2016 return PyErr_NoMemory();
2010
2017
2011 seen = calloc(sizeof(*seen), maxrev + 1);
2018 seen = calloc(sizeof(*seen), maxrev + 1);
2012 if (seen == NULL) {
2019 if (seen == NULL) {
2013 PyErr_NoMemory();
2020 PyErr_NoMemory();
2014 goto bail;
2021 goto bail;
2015 }
2022 }
2016
2023
2017 interesting = calloc(sizeof(*interesting), ((size_t)1) << revcount);
2024 interesting = calloc(sizeof(*interesting), ((size_t)1) << revcount);
2018 if (interesting == NULL) {
2025 if (interesting == NULL) {
2019 PyErr_NoMemory();
2026 PyErr_NoMemory();
2020 goto bail;
2027 goto bail;
2021 }
2028 }
2022
2029
2023 if (PyList_Sort(revs) == -1)
2030 if (PyList_Sort(revs) == -1)
2024 goto bail;
2031 goto bail;
2025
2032
2026 for (i = 0; i < revcount; i++) {
2033 for (i = 0; i < revcount; i++) {
2027 int n = (int)PyInt_AsLong(PyList_GET_ITEM(revs, i));
2034 int n = (int)PyInt_AsLong(PyList_GET_ITEM(revs, i));
2028 long b = 1l << i;
2035 long b = 1l << i;
2029 depth[n] = 1;
2036 depth[n] = 1;
2030 seen[n] = b;
2037 seen[n] = b;
2031 interesting[b] = 1;
2038 interesting[b] = 1;
2032 }
2039 }
2033
2040
2034 /* invariant: ninteresting is the number of non-zero entries in
2041 /* invariant: ninteresting is the number of non-zero entries in
2035 * interesting. */
2042 * interesting. */
2036 ninteresting = (int)revcount;
2043 ninteresting = (int)revcount;
2037
2044
2038 for (v = maxrev; v >= 0 && ninteresting > 1; v--) {
2045 for (v = maxrev; v >= 0 && ninteresting > 1; v--) {
2039 int dv = depth[v];
2046 int dv = depth[v];
2040 int parents[2];
2047 int parents[2];
2041 long sv;
2048 long sv;
2042
2049
2043 if (dv == 0)
2050 if (dv == 0)
2044 continue;
2051 continue;
2045
2052
2046 sv = seen[v];
2053 sv = seen[v];
2047 if (index_get_parents(self, v, parents, maxrev) < 0)
2054 if (index_get_parents(self, v, parents, maxrev) < 0)
2048 goto bail;
2055 goto bail;
2049
2056
2050 for (i = 0; i < 2; i++) {
2057 for (i = 0; i < 2; i++) {
2051 int p = parents[i];
2058 int p = parents[i];
2052 long sp;
2059 long sp;
2053 int dp;
2060 int dp;
2054
2061
2055 if (p == -1)
2062 if (p == -1)
2056 continue;
2063 continue;
2057
2064
2058 dp = depth[p];
2065 dp = depth[p];
2059 sp = seen[p];
2066 sp = seen[p];
2060 if (dp <= dv) {
2067 if (dp <= dv) {
2061 depth[p] = dv + 1;
2068 depth[p] = dv + 1;
2062 if (sp != sv) {
2069 if (sp != sv) {
2063 interesting[sv] += 1;
2070 interesting[sv] += 1;
2064 seen[p] = sv;
2071 seen[p] = sv;
2065 if (sp) {
2072 if (sp) {
2066 interesting[sp] -= 1;
2073 interesting[sp] -= 1;
2067 if (interesting[sp] == 0)
2074 if (interesting[sp] == 0)
2068 ninteresting -= 1;
2075 ninteresting -= 1;
2069 }
2076 }
2070 }
2077 }
2071 } else if (dv == dp - 1) {
2078 } else if (dv == dp - 1) {
2072 long nsp = sp | sv;
2079 long nsp = sp | sv;
2073 if (nsp == sp)
2080 if (nsp == sp)
2074 continue;
2081 continue;
2075 seen[p] = nsp;
2082 seen[p] = nsp;
2076 interesting[sp] -= 1;
2083 interesting[sp] -= 1;
2077 if (interesting[sp] == 0)
2084 if (interesting[sp] == 0)
2078 ninteresting -= 1;
2085 ninteresting -= 1;
2079 if (interesting[nsp] == 0)
2086 if (interesting[nsp] == 0)
2080 ninteresting += 1;
2087 ninteresting += 1;
2081 interesting[nsp] += 1;
2088 interesting[nsp] += 1;
2082 }
2089 }
2083 }
2090 }
2084 interesting[sv] -= 1;
2091 interesting[sv] -= 1;
2085 if (interesting[sv] == 0)
2092 if (interesting[sv] == 0)
2086 ninteresting -= 1;
2093 ninteresting -= 1;
2087 }
2094 }
2088
2095
2089 final = 0;
2096 final = 0;
2090 j = ninteresting;
2097 j = ninteresting;
2091 for (i = 0; i < (int)(2 << revcount) && j > 0; i++) {
2098 for (i = 0; i < (int)(2 << revcount) && j > 0; i++) {
2092 if (interesting[i] == 0)
2099 if (interesting[i] == 0)
2093 continue;
2100 continue;
2094 final |= i;
2101 final |= i;
2095 j -= 1;
2102 j -= 1;
2096 }
2103 }
2097 if (final == 0) {
2104 if (final == 0) {
2098 keys = PyList_New(0);
2105 keys = PyList_New(0);
2099 goto bail;
2106 goto bail;
2100 }
2107 }
2101
2108
2102 dict = PyDict_New();
2109 dict = PyDict_New();
2103 if (dict == NULL)
2110 if (dict == NULL)
2104 goto bail;
2111 goto bail;
2105
2112
2106 for (i = 0; i < revcount; i++) {
2113 for (i = 0; i < revcount; i++) {
2107 PyObject *key;
2114 PyObject *key;
2108
2115
2109 if ((final & (1 << i)) == 0)
2116 if ((final & (1 << i)) == 0)
2110 continue;
2117 continue;
2111
2118
2112 key = PyList_GET_ITEM(revs, i);
2119 key = PyList_GET_ITEM(revs, i);
2113 Py_INCREF(key);
2120 Py_INCREF(key);
2114 Py_INCREF(Py_None);
2121 Py_INCREF(Py_None);
2115 if (PyDict_SetItem(dict, key, Py_None) == -1) {
2122 if (PyDict_SetItem(dict, key, Py_None) == -1) {
2116 Py_DECREF(key);
2123 Py_DECREF(key);
2117 Py_DECREF(Py_None);
2124 Py_DECREF(Py_None);
2118 goto bail;
2125 goto bail;
2119 }
2126 }
2120 }
2127 }
2121
2128
2122 keys = PyDict_Keys(dict);
2129 keys = PyDict_Keys(dict);
2123
2130
2124 bail:
2131 bail:
2125 free(depth);
2132 free(depth);
2126 free(seen);
2133 free(seen);
2127 free(interesting);
2134 free(interesting);
2128 Py_XDECREF(dict);
2135 Py_XDECREF(dict);
2129
2136
2130 return keys;
2137 return keys;
2131 }
2138 }
2132
2139
2133 /*
2140 /*
2134 * Given a (possibly overlapping) set of revs, return all the
2141 * Given a (possibly overlapping) set of revs, return all the
2135 * common ancestors heads: heads(::args[0] and ::a[1] and ...)
2142 * common ancestors heads: heads(::args[0] and ::a[1] and ...)
2136 */
2143 */
2137 static PyObject *index_commonancestorsheads(indexObject *self, PyObject *args)
2144 static PyObject *index_commonancestorsheads(indexObject *self, PyObject *args)
2138 {
2145 {
2139 PyObject *ret = NULL;
2146 PyObject *ret = NULL;
2140 Py_ssize_t argcount, i, len;
2147 Py_ssize_t argcount, i, len;
2141 bitmask repeat = 0;
2148 bitmask repeat = 0;
2142 int revcount = 0;
2149 int revcount = 0;
2143 int *revs;
2150 int *revs;
2144
2151
2145 argcount = PySequence_Length(args);
2152 argcount = PySequence_Length(args);
2146 revs = PyMem_Malloc(argcount * sizeof(*revs));
2153 revs = PyMem_Malloc(argcount * sizeof(*revs));
2147 if (argcount > 0 && revs == NULL)
2154 if (argcount > 0 && revs == NULL)
2148 return PyErr_NoMemory();
2155 return PyErr_NoMemory();
2149 len = index_length(self);
2156 len = index_length(self);
2150
2157
2151 for (i = 0; i < argcount; i++) {
2158 for (i = 0; i < argcount; i++) {
2152 static const int capacity = 24;
2159 static const int capacity = 24;
2153 PyObject *obj = PySequence_GetItem(args, i);
2160 PyObject *obj = PySequence_GetItem(args, i);
2154 bitmask x;
2161 bitmask x;
2155 long val;
2162 long val;
2156
2163
2157 if (!PyInt_Check(obj)) {
2164 if (!PyInt_Check(obj)) {
2158 PyErr_SetString(PyExc_TypeError,
2165 PyErr_SetString(PyExc_TypeError,
2159 "arguments must all be ints");
2166 "arguments must all be ints");
2160 Py_DECREF(obj);
2167 Py_DECREF(obj);
2161 goto bail;
2168 goto bail;
2162 }
2169 }
2163 val = PyInt_AsLong(obj);
2170 val = PyInt_AsLong(obj);
2164 Py_DECREF(obj);
2171 Py_DECREF(obj);
2165 if (val == -1) {
2172 if (val == -1) {
2166 ret = PyList_New(0);
2173 ret = PyList_New(0);
2167 goto done;
2174 goto done;
2168 }
2175 }
2169 if (val < 0 || val >= len) {
2176 if (val < 0 || val >= len) {
2170 PyErr_SetString(PyExc_IndexError, "index out of range");
2177 PyErr_SetString(PyExc_IndexError, "index out of range");
2171 goto bail;
2178 goto bail;
2172 }
2179 }
2173 /* this cheesy bloom filter lets us avoid some more
2180 /* this cheesy bloom filter lets us avoid some more
2174 * expensive duplicate checks in the common set-is-disjoint
2181 * expensive duplicate checks in the common set-is-disjoint
2175 * case */
2182 * case */
2176 x = 1ull << (val & 0x3f);
2183 x = 1ull << (val & 0x3f);
2177 if (repeat & x) {
2184 if (repeat & x) {
2178 int k;
2185 int k;
2179 for (k = 0; k < revcount; k++) {
2186 for (k = 0; k < revcount; k++) {
2180 if (val == revs[k])
2187 if (val == revs[k])
2181 goto duplicate;
2188 goto duplicate;
2182 }
2189 }
2183 } else
2190 } else
2184 repeat |= x;
2191 repeat |= x;
2185 if (revcount >= capacity) {
2192 if (revcount >= capacity) {
2186 PyErr_Format(PyExc_OverflowError,
2193 PyErr_Format(PyExc_OverflowError,
2187 "bitset size (%d) > capacity (%d)",
2194 "bitset size (%d) > capacity (%d)",
2188 revcount, capacity);
2195 revcount, capacity);
2189 goto bail;
2196 goto bail;
2190 }
2197 }
2191 revs[revcount++] = (int)val;
2198 revs[revcount++] = (int)val;
2192 duplicate:;
2199 duplicate:;
2193 }
2200 }
2194
2201
2195 if (revcount == 0) {
2202 if (revcount == 0) {
2196 ret = PyList_New(0);
2203 ret = PyList_New(0);
2197 goto done;
2204 goto done;
2198 }
2205 }
2199 if (revcount == 1) {
2206 if (revcount == 1) {
2200 PyObject *obj;
2207 PyObject *obj;
2201 ret = PyList_New(1);
2208 ret = PyList_New(1);
2202 if (ret == NULL)
2209 if (ret == NULL)
2203 goto bail;
2210 goto bail;
2204 obj = PyInt_FromLong(revs[0]);
2211 obj = PyInt_FromLong(revs[0]);
2205 if (obj == NULL)
2212 if (obj == NULL)
2206 goto bail;
2213 goto bail;
2207 PyList_SET_ITEM(ret, 0, obj);
2214 PyList_SET_ITEM(ret, 0, obj);
2208 goto done;
2215 goto done;
2209 }
2216 }
2210
2217
2211 ret = find_gca_candidates(self, revs, revcount);
2218 ret = find_gca_candidates(self, revs, revcount);
2212 if (ret == NULL)
2219 if (ret == NULL)
2213 goto bail;
2220 goto bail;
2214
2221
2215 done:
2222 done:
2216 PyMem_Free(revs);
2223 PyMem_Free(revs);
2217 return ret;
2224 return ret;
2218
2225
2219 bail:
2226 bail:
2220 PyMem_Free(revs);
2227 PyMem_Free(revs);
2221 Py_XDECREF(ret);
2228 Py_XDECREF(ret);
2222 return NULL;
2229 return NULL;
2223 }
2230 }
2224
2231
2225 /*
2232 /*
2226 * Given a (possibly overlapping) set of revs, return the greatest
2233 * Given a (possibly overlapping) set of revs, return the greatest
2227 * common ancestors: those with the longest path to the root.
2234 * common ancestors: those with the longest path to the root.
2228 */
2235 */
2229 static PyObject *index_ancestors(indexObject *self, PyObject *args)
2236 static PyObject *index_ancestors(indexObject *self, PyObject *args)
2230 {
2237 {
2231 PyObject *ret;
2238 PyObject *ret;
2232 PyObject *gca = index_commonancestorsheads(self, args);
2239 PyObject *gca = index_commonancestorsheads(self, args);
2233 if (gca == NULL)
2240 if (gca == NULL)
2234 return NULL;
2241 return NULL;
2235
2242
2236 if (PyList_GET_SIZE(gca) <= 1) {
2243 if (PyList_GET_SIZE(gca) <= 1) {
2237 return gca;
2244 return gca;
2238 }
2245 }
2239
2246
2240 ret = find_deepest(self, gca);
2247 ret = find_deepest(self, gca);
2241 Py_DECREF(gca);
2248 Py_DECREF(gca);
2242 return ret;
2249 return ret;
2243 }
2250 }
2244
2251
2245 /*
2252 /*
2246 * Invalidate any trie entries introduced by added revs.
2253 * Invalidate any trie entries introduced by added revs.
2247 */
2254 */
2248 static void index_invalidate_added(indexObject *self, Py_ssize_t start)
2255 static void index_invalidate_added(indexObject *self, Py_ssize_t start)
2249 {
2256 {
2250 Py_ssize_t i, len = PyList_GET_SIZE(self->added);
2257 Py_ssize_t i, len = PyList_GET_SIZE(self->added);
2251
2258
2252 for (i = start; i < len; i++) {
2259 for (i = start; i < len; i++) {
2253 PyObject *tuple = PyList_GET_ITEM(self->added, i);
2260 PyObject *tuple = PyList_GET_ITEM(self->added, i);
2254 PyObject *node = PyTuple_GET_ITEM(tuple, 7);
2261 PyObject *node = PyTuple_GET_ITEM(tuple, 7);
2255
2262
2256 nt_delete_node(&self->nt, PyBytes_AS_STRING(node));
2263 nt_delete_node(&self->nt, PyBytes_AS_STRING(node));
2257 }
2264 }
2258
2265
2259 if (start == 0)
2266 if (start == 0)
2260 Py_CLEAR(self->added);
2267 Py_CLEAR(self->added);
2261 }
2268 }
2262
2269
2263 /*
2270 /*
2264 * Delete a numeric range of revs, which must be at the end of the
2271 * Delete a numeric range of revs, which must be at the end of the
2265 * range, but exclude the sentinel nullid entry.
2272 * range, but exclude the sentinel nullid entry.
2266 */
2273 */
2267 static int index_slice_del(indexObject *self, PyObject *item)
2274 static int index_slice_del(indexObject *self, PyObject *item)
2268 {
2275 {
2269 Py_ssize_t start, stop, step, slicelength;
2276 Py_ssize_t start, stop, step, slicelength;
2270 Py_ssize_t length = index_length(self) + 1;
2277 Py_ssize_t length = index_length(self) + 1;
2271 int ret = 0;
2278 int ret = 0;
2272
2279
2273 /* Argument changed from PySliceObject* to PyObject* in Python 3. */
2280 /* Argument changed from PySliceObject* to PyObject* in Python 3. */
2274 #ifdef IS_PY3K
2281 #ifdef IS_PY3K
2275 if (PySlice_GetIndicesEx(item, length, &start, &stop, &step,
2282 if (PySlice_GetIndicesEx(item, length, &start, &stop, &step,
2276 &slicelength) < 0)
2283 &slicelength) < 0)
2277 #else
2284 #else
2278 if (PySlice_GetIndicesEx((PySliceObject *)item, length, &start, &stop,
2285 if (PySlice_GetIndicesEx((PySliceObject *)item, length, &start, &stop,
2279 &step, &slicelength) < 0)
2286 &step, &slicelength) < 0)
2280 #endif
2287 #endif
2281 return -1;
2288 return -1;
2282
2289
2283 if (slicelength <= 0)
2290 if (slicelength <= 0)
2284 return 0;
2291 return 0;
2285
2292
2286 if ((step < 0 && start < stop) || (step > 0 && start > stop))
2293 if ((step < 0 && start < stop) || (step > 0 && start > stop))
2287 stop = start;
2294 stop = start;
2288
2295
2289 if (step < 0) {
2296 if (step < 0) {
2290 stop = start + 1;
2297 stop = start + 1;
2291 start = stop + step * (slicelength - 1) - 1;
2298 start = stop + step * (slicelength - 1) - 1;
2292 step = -step;
2299 step = -step;
2293 }
2300 }
2294
2301
2295 if (step != 1) {
2302 if (step != 1) {
2296 PyErr_SetString(PyExc_ValueError,
2303 PyErr_SetString(PyExc_ValueError,
2297 "revlog index delete requires step size of 1");
2304 "revlog index delete requires step size of 1");
2298 return -1;
2305 return -1;
2299 }
2306 }
2300
2307
2301 if (stop != length - 1) {
2308 if (stop != length - 1) {
2302 PyErr_SetString(PyExc_IndexError,
2309 PyErr_SetString(PyExc_IndexError,
2303 "revlog index deletion indices are invalid");
2310 "revlog index deletion indices are invalid");
2304 return -1;
2311 return -1;
2305 }
2312 }
2306
2313
2307 if (start < self->length) {
2314 if (start < self->length) {
2308 if (self->ntinitialized) {
2315 if (self->ntinitialized) {
2309 Py_ssize_t i;
2316 Py_ssize_t i;
2310
2317
2311 for (i = start + 1; i < self->length; i++) {
2318 for (i = start + 1; i < self->length; i++) {
2312 const char *node = index_node_existing(self, i);
2319 const char *node = index_node_existing(self, i);
2313 if (node == NULL)
2320 if (node == NULL)
2314 return -1;
2321 return -1;
2315
2322
2316 nt_delete_node(&self->nt, node);
2323 nt_delete_node(&self->nt, node);
2317 }
2324 }
2318 if (self->added)
2325 if (self->added)
2319 index_invalidate_added(self, 0);
2326 index_invalidate_added(self, 0);
2320 if (self->ntrev > start)
2327 if (self->ntrev > start)
2321 self->ntrev = (int)start;
2328 self->ntrev = (int)start;
2322 }
2329 }
2323 self->length = start;
2330 self->length = start;
2324 if (start < self->raw_length) {
2331 if (start < self->raw_length) {
2325 if (self->cache) {
2332 if (self->cache) {
2326 Py_ssize_t i;
2333 Py_ssize_t i;
2327 for (i = start; i < self->raw_length; i++)
2334 for (i = start; i < self->raw_length; i++)
2328 Py_CLEAR(self->cache[i]);
2335 Py_CLEAR(self->cache[i]);
2329 }
2336 }
2330 self->raw_length = start;
2337 self->raw_length = start;
2331 }
2338 }
2332 goto done;
2339 goto done;
2333 }
2340 }
2334
2341
2335 if (self->ntinitialized) {
2342 if (self->ntinitialized) {
2336 index_invalidate_added(self, start - self->length);
2343 index_invalidate_added(self, start - self->length);
2337 if (self->ntrev > start)
2344 if (self->ntrev > start)
2338 self->ntrev = (int)start;
2345 self->ntrev = (int)start;
2339 }
2346 }
2340 if (self->added)
2347 if (self->added)
2341 ret = PyList_SetSlice(self->added, start - self->length,
2348 ret = PyList_SetSlice(self->added, start - self->length,
2342 PyList_GET_SIZE(self->added), NULL);
2349 PyList_GET_SIZE(self->added), NULL);
2343 done:
2350 done:
2344 Py_CLEAR(self->headrevs);
2351 Py_CLEAR(self->headrevs);
2345 return ret;
2352 return ret;
2346 }
2353 }
2347
2354
2348 /*
2355 /*
2349 * Supported ops:
2356 * Supported ops:
2350 *
2357 *
2351 * slice deletion
2358 * slice deletion
2352 * string assignment (extend node->rev mapping)
2359 * string assignment (extend node->rev mapping)
2353 * string deletion (shrink node->rev mapping)
2360 * string deletion (shrink node->rev mapping)
2354 */
2361 */
2355 static int index_assign_subscript(indexObject *self, PyObject *item,
2362 static int index_assign_subscript(indexObject *self, PyObject *item,
2356 PyObject *value)
2363 PyObject *value)
2357 {
2364 {
2358 char *node;
2365 char *node;
2359 long rev;
2366 long rev;
2360
2367
2361 if (PySlice_Check(item) && value == NULL)
2368 if (PySlice_Check(item) && value == NULL)
2362 return index_slice_del(self, item);
2369 return index_slice_del(self, item);
2363
2370
2364 if (node_check(item, &node) == -1)
2371 if (node_check(item, &node) == -1)
2365 return -1;
2372 return -1;
2366
2373
2367 if (value == NULL)
2374 if (value == NULL)
2368 return self->ntinitialized ? nt_delete_node(&self->nt, node)
2375 return self->ntinitialized ? nt_delete_node(&self->nt, node)
2369 : 0;
2376 : 0;
2370 rev = PyInt_AsLong(value);
2377 rev = PyInt_AsLong(value);
2371 if (rev > INT_MAX || rev < 0) {
2378 if (rev > INT_MAX || rev < 0) {
2372 if (!PyErr_Occurred())
2379 if (!PyErr_Occurred())
2373 PyErr_SetString(PyExc_ValueError, "rev out of range");
2380 PyErr_SetString(PyExc_ValueError, "rev out of range");
2374 return -1;
2381 return -1;
2375 }
2382 }
2376
2383
2377 if (index_init_nt(self) == -1)
2384 if (index_init_nt(self) == -1)
2378 return -1;
2385 return -1;
2379 return nt_insert(&self->nt, node, (int)rev);
2386 return nt_insert(&self->nt, node, (int)rev);
2380 }
2387 }
2381
2388
2382 /*
2389 /*
2383 * Find all RevlogNG entries in an index that has inline data. Update
2390 * Find all RevlogNG entries in an index that has inline data. Update
2384 * the optional "offsets" table with those entries.
2391 * the optional "offsets" table with those entries.
2385 */
2392 */
2386 static Py_ssize_t inline_scan(indexObject *self, const char **offsets)
2393 static Py_ssize_t inline_scan(indexObject *self, const char **offsets)
2387 {
2394 {
2388 const char *data = (const char *)self->buf.buf;
2395 const char *data = (const char *)self->buf.buf;
2389 Py_ssize_t pos = 0;
2396 Py_ssize_t pos = 0;
2390 Py_ssize_t end = self->buf.len;
2397 Py_ssize_t end = self->buf.len;
2391 long incr = v1_hdrsize;
2398 long incr = v1_hdrsize;
2392 Py_ssize_t len = 0;
2399 Py_ssize_t len = 0;
2393
2400
2394 while (pos + v1_hdrsize <= end && pos >= 0) {
2401 while (pos + v1_hdrsize <= end && pos >= 0) {
2395 uint32_t comp_len;
2402 uint32_t comp_len;
2396 /* 3rd element of header is length of compressed inline data */
2403 /* 3rd element of header is length of compressed inline data */
2397 comp_len = getbe32(data + pos + 8);
2404 comp_len = getbe32(data + pos + 8);
2398 incr = v1_hdrsize + comp_len;
2405 incr = v1_hdrsize + comp_len;
2399 if (offsets)
2406 if (offsets)
2400 offsets[len] = data + pos;
2407 offsets[len] = data + pos;
2401 len++;
2408 len++;
2402 pos += incr;
2409 pos += incr;
2403 }
2410 }
2404
2411
2405 if (pos != end) {
2412 if (pos != end) {
2406 if (!PyErr_Occurred())
2413 if (!PyErr_Occurred())
2407 PyErr_SetString(PyExc_ValueError, "corrupt index file");
2414 PyErr_SetString(PyExc_ValueError, "corrupt index file");
2408 return -1;
2415 return -1;
2409 }
2416 }
2410
2417
2411 return len;
2418 return len;
2412 }
2419 }
2413
2420
2414 static int index_init(indexObject *self, PyObject *args)
2421 static int index_init(indexObject *self, PyObject *args)
2415 {
2422 {
2416 PyObject *data_obj, *inlined_obj;
2423 PyObject *data_obj, *inlined_obj;
2417 Py_ssize_t size;
2424 Py_ssize_t size;
2418
2425
2419 /* Initialize before argument-checking to avoid index_dealloc() crash.
2426 /* Initialize before argument-checking to avoid index_dealloc() crash.
2420 */
2427 */
2421 self->raw_length = 0;
2428 self->raw_length = 0;
2422 self->added = NULL;
2429 self->added = NULL;
2423 self->cache = NULL;
2430 self->cache = NULL;
2424 self->data = NULL;
2431 self->data = NULL;
2425 memset(&self->buf, 0, sizeof(self->buf));
2432 memset(&self->buf, 0, sizeof(self->buf));
2426 self->headrevs = NULL;
2433 self->headrevs = NULL;
2427 self->filteredrevs = Py_None;
2434 self->filteredrevs = Py_None;
2428 Py_INCREF(Py_None);
2435 Py_INCREF(Py_None);
2429 self->ntinitialized = 0;
2436 self->ntinitialized = 0;
2430 self->offsets = NULL;
2437 self->offsets = NULL;
2431
2438
2432 if (!PyArg_ParseTuple(args, "OO", &data_obj, &inlined_obj))
2439 if (!PyArg_ParseTuple(args, "OO", &data_obj, &inlined_obj))
2433 return -1;
2440 return -1;
2434 if (!PyObject_CheckBuffer(data_obj)) {
2441 if (!PyObject_CheckBuffer(data_obj)) {
2435 PyErr_SetString(PyExc_TypeError,
2442 PyErr_SetString(PyExc_TypeError,
2436 "data does not support buffer interface");
2443 "data does not support buffer interface");
2437 return -1;
2444 return -1;
2438 }
2445 }
2439
2446
2440 if (PyObject_GetBuffer(data_obj, &self->buf, PyBUF_SIMPLE) == -1)
2447 if (PyObject_GetBuffer(data_obj, &self->buf, PyBUF_SIMPLE) == -1)
2441 return -1;
2448 return -1;
2442 size = self->buf.len;
2449 size = self->buf.len;
2443
2450
2444 self->inlined = inlined_obj && PyObject_IsTrue(inlined_obj);
2451 self->inlined = inlined_obj && PyObject_IsTrue(inlined_obj);
2445 self->data = data_obj;
2452 self->data = data_obj;
2446
2453
2447 self->ntlookups = self->ntmisses = 0;
2454 self->ntlookups = self->ntmisses = 0;
2448 self->ntrev = -1;
2455 self->ntrev = -1;
2449 Py_INCREF(self->data);
2456 Py_INCREF(self->data);
2450
2457
2451 if (self->inlined) {
2458 if (self->inlined) {
2452 Py_ssize_t len = inline_scan(self, NULL);
2459 Py_ssize_t len = inline_scan(self, NULL);
2453 if (len == -1)
2460 if (len == -1)
2454 goto bail;
2461 goto bail;
2455 self->raw_length = len;
2462 self->raw_length = len;
2456 self->length = len;
2463 self->length = len;
2457 } else {
2464 } else {
2458 if (size % v1_hdrsize) {
2465 if (size % v1_hdrsize) {
2459 PyErr_SetString(PyExc_ValueError, "corrupt index file");
2466 PyErr_SetString(PyExc_ValueError, "corrupt index file");
2460 goto bail;
2467 goto bail;
2461 }
2468 }
2462 self->raw_length = size / v1_hdrsize;
2469 self->raw_length = size / v1_hdrsize;
2463 self->length = self->raw_length;
2470 self->length = self->raw_length;
2464 }
2471 }
2465
2472
2466 return 0;
2473 return 0;
2467 bail:
2474 bail:
2468 return -1;
2475 return -1;
2469 }
2476 }
2470
2477
2471 static PyObject *index_nodemap(indexObject *self)
2478 static PyObject *index_nodemap(indexObject *self)
2472 {
2479 {
2473 Py_INCREF(self);
2480 Py_INCREF(self);
2474 return (PyObject *)self;
2481 return (PyObject *)self;
2475 }
2482 }
2476
2483
2477 static void _index_clearcaches(indexObject *self)
2484 static void _index_clearcaches(indexObject *self)
2478 {
2485 {
2479 if (self->cache) {
2486 if (self->cache) {
2480 Py_ssize_t i;
2487 Py_ssize_t i;
2481
2488
2482 for (i = 0; i < self->raw_length; i++)
2489 for (i = 0; i < self->raw_length; i++)
2483 Py_CLEAR(self->cache[i]);
2490 Py_CLEAR(self->cache[i]);
2484 free(self->cache);
2491 free(self->cache);
2485 self->cache = NULL;
2492 self->cache = NULL;
2486 }
2493 }
2487 if (self->offsets) {
2494 if (self->offsets) {
2488 PyMem_Free((void *)self->offsets);
2495 PyMem_Free((void *)self->offsets);
2489 self->offsets = NULL;
2496 self->offsets = NULL;
2490 }
2497 }
2491 if (self->ntinitialized) {
2498 if (self->ntinitialized) {
2492 nt_dealloc(&self->nt);
2499 nt_dealloc(&self->nt);
2493 }
2500 }
2494 self->ntinitialized = 0;
2501 self->ntinitialized = 0;
2495 Py_CLEAR(self->headrevs);
2502 Py_CLEAR(self->headrevs);
2496 }
2503 }
2497
2504
2498 static PyObject *index_clearcaches(indexObject *self)
2505 static PyObject *index_clearcaches(indexObject *self)
2499 {
2506 {
2500 _index_clearcaches(self);
2507 _index_clearcaches(self);
2501 self->ntrev = -1;
2508 self->ntrev = -1;
2502 self->ntlookups = self->ntmisses = 0;
2509 self->ntlookups = self->ntmisses = 0;
2503 Py_RETURN_NONE;
2510 Py_RETURN_NONE;
2504 }
2511 }
2505
2512
2506 static void index_dealloc(indexObject *self)
2513 static void index_dealloc(indexObject *self)
2507 {
2514 {
2508 _index_clearcaches(self);
2515 _index_clearcaches(self);
2509 Py_XDECREF(self->filteredrevs);
2516 Py_XDECREF(self->filteredrevs);
2510 if (self->buf.buf) {
2517 if (self->buf.buf) {
2511 PyBuffer_Release(&self->buf);
2518 PyBuffer_Release(&self->buf);
2512 memset(&self->buf, 0, sizeof(self->buf));
2519 memset(&self->buf, 0, sizeof(self->buf));
2513 }
2520 }
2514 Py_XDECREF(self->data);
2521 Py_XDECREF(self->data);
2515 Py_XDECREF(self->added);
2522 Py_XDECREF(self->added);
2516 PyObject_Del(self);
2523 PyObject_Del(self);
2517 }
2524 }
2518
2525
2519 static PySequenceMethods index_sequence_methods = {
2526 static PySequenceMethods index_sequence_methods = {
2520 (lenfunc)index_length, /* sq_length */
2527 (lenfunc)index_length, /* sq_length */
2521 0, /* sq_concat */
2528 0, /* sq_concat */
2522 0, /* sq_repeat */
2529 0, /* sq_repeat */
2523 (ssizeargfunc)index_get, /* sq_item */
2530 (ssizeargfunc)index_get, /* sq_item */
2524 0, /* sq_slice */
2531 0, /* sq_slice */
2525 0, /* sq_ass_item */
2532 0, /* sq_ass_item */
2526 0, /* sq_ass_slice */
2533 0, /* sq_ass_slice */
2527 (objobjproc)index_contains, /* sq_contains */
2534 (objobjproc)index_contains, /* sq_contains */
2528 };
2535 };
2529
2536
2530 static PyMappingMethods index_mapping_methods = {
2537 static PyMappingMethods index_mapping_methods = {
2531 (lenfunc)index_length, /* mp_length */
2538 (lenfunc)index_length, /* mp_length */
2532 (binaryfunc)index_getitem, /* mp_subscript */
2539 (binaryfunc)index_getitem, /* mp_subscript */
2533 (objobjargproc)index_assign_subscript, /* mp_ass_subscript */
2540 (objobjargproc)index_assign_subscript, /* mp_ass_subscript */
2534 };
2541 };
2535
2542
2536 static PyMethodDef index_methods[] = {
2543 static PyMethodDef index_methods[] = {
2537 {"ancestors", (PyCFunction)index_ancestors, METH_VARARGS,
2544 {"ancestors", (PyCFunction)index_ancestors, METH_VARARGS,
2538 "return the gca set of the given revs"},
2545 "return the gca set of the given revs"},
2539 {"commonancestorsheads", (PyCFunction)index_commonancestorsheads,
2546 {"commonancestorsheads", (PyCFunction)index_commonancestorsheads,
2540 METH_VARARGS,
2547 METH_VARARGS,
2541 "return the heads of the common ancestors of the given revs"},
2548 "return the heads of the common ancestors of the given revs"},
2542 {"clearcaches", (PyCFunction)index_clearcaches, METH_NOARGS,
2549 {"clearcaches", (PyCFunction)index_clearcaches, METH_NOARGS,
2543 "clear the index caches"},
2550 "clear the index caches"},
2544 {"get", (PyCFunction)index_m_get, METH_VARARGS, "get an index entry"},
2551 {"get", (PyCFunction)index_m_get, METH_VARARGS, "get an index entry"},
2545 {"computephasesmapsets", (PyCFunction)compute_phases_map_sets, METH_VARARGS,
2552 {"computephasesmapsets", (PyCFunction)compute_phases_map_sets, METH_VARARGS,
2546 "compute phases"},
2553 "compute phases"},
2547 {"reachableroots2", (PyCFunction)reachableroots2, METH_VARARGS,
2554 {"reachableroots2", (PyCFunction)reachableroots2, METH_VARARGS,
2548 "reachableroots"},
2555 "reachableroots"},
2549 {"headrevs", (PyCFunction)index_headrevs, METH_VARARGS,
2556 {"headrevs", (PyCFunction)index_headrevs, METH_VARARGS,
2550 "get head revisions"}, /* Can do filtering since 3.2 */
2557 "get head revisions"}, /* Can do filtering since 3.2 */
2551 {"headrevsfiltered", (PyCFunction)index_headrevs, METH_VARARGS,
2558 {"headrevsfiltered", (PyCFunction)index_headrevs, METH_VARARGS,
2552 "get filtered head revisions"}, /* Can always do filtering */
2559 "get filtered head revisions"}, /* Can always do filtering */
2553 {"deltachain", (PyCFunction)index_deltachain, METH_VARARGS,
2560 {"deltachain", (PyCFunction)index_deltachain, METH_VARARGS,
2554 "determine revisions with deltas to reconstruct fulltext"},
2561 "determine revisions with deltas to reconstruct fulltext"},
2555 {"slicechunktodensity", (PyCFunction)index_slicechunktodensity,
2562 {"slicechunktodensity", (PyCFunction)index_slicechunktodensity,
2556 METH_VARARGS, "determine revisions with deltas to reconstruct fulltext"},
2563 METH_VARARGS, "determine revisions with deltas to reconstruct fulltext"},
2557 {"append", (PyCFunction)index_append, METH_O, "append an index entry"},
2564 {"append", (PyCFunction)index_append, METH_O, "append an index entry"},
2558 {"partialmatch", (PyCFunction)index_partialmatch, METH_VARARGS,
2565 {"partialmatch", (PyCFunction)index_partialmatch, METH_VARARGS,
2559 "match a potentially ambiguous node ID"},
2566 "match a potentially ambiguous node ID"},
2560 {"shortest", (PyCFunction)index_shortest, METH_VARARGS,
2567 {"shortest", (PyCFunction)index_shortest, METH_VARARGS,
2561 "find length of shortest hex nodeid of a binary ID"},
2568 "find length of shortest hex nodeid of a binary ID"},
2562 {"stats", (PyCFunction)index_stats, METH_NOARGS, "stats for the index"},
2569 {"stats", (PyCFunction)index_stats, METH_NOARGS, "stats for the index"},
2563 {NULL} /* Sentinel */
2570 {NULL} /* Sentinel */
2564 };
2571 };
2565
2572
2566 static PyGetSetDef index_getset[] = {
2573 static PyGetSetDef index_getset[] = {
2567 {"nodemap", (getter)index_nodemap, NULL, "nodemap", NULL},
2574 {"nodemap", (getter)index_nodemap, NULL, "nodemap", NULL},
2568 {NULL} /* Sentinel */
2575 {NULL} /* Sentinel */
2569 };
2576 };
2570
2577
2571 static PyTypeObject indexType = {
2578 static PyTypeObject indexType = {
2572 PyVarObject_HEAD_INIT(NULL, 0) /* header */
2579 PyVarObject_HEAD_INIT(NULL, 0) /* header */
2573 "parsers.index", /* tp_name */
2580 "parsers.index", /* tp_name */
2574 sizeof(indexObject), /* tp_basicsize */
2581 sizeof(indexObject), /* tp_basicsize */
2575 0, /* tp_itemsize */
2582 0, /* tp_itemsize */
2576 (destructor)index_dealloc, /* tp_dealloc */
2583 (destructor)index_dealloc, /* tp_dealloc */
2577 0, /* tp_print */
2584 0, /* tp_print */
2578 0, /* tp_getattr */
2585 0, /* tp_getattr */
2579 0, /* tp_setattr */
2586 0, /* tp_setattr */
2580 0, /* tp_compare */
2587 0, /* tp_compare */
2581 0, /* tp_repr */
2588 0, /* tp_repr */
2582 0, /* tp_as_number */
2589 0, /* tp_as_number */
2583 &index_sequence_methods, /* tp_as_sequence */
2590 &index_sequence_methods, /* tp_as_sequence */
2584 &index_mapping_methods, /* tp_as_mapping */
2591 &index_mapping_methods, /* tp_as_mapping */
2585 0, /* tp_hash */
2592 0, /* tp_hash */
2586 0, /* tp_call */
2593 0, /* tp_call */
2587 0, /* tp_str */
2594 0, /* tp_str */
2588 0, /* tp_getattro */
2595 0, /* tp_getattro */
2589 0, /* tp_setattro */
2596 0, /* tp_setattro */
2590 0, /* tp_as_buffer */
2597 0, /* tp_as_buffer */
2591 Py_TPFLAGS_DEFAULT, /* tp_flags */
2598 Py_TPFLAGS_DEFAULT, /* tp_flags */
2592 "revlog index", /* tp_doc */
2599 "revlog index", /* tp_doc */
2593 0, /* tp_traverse */
2600 0, /* tp_traverse */
2594 0, /* tp_clear */
2601 0, /* tp_clear */
2595 0, /* tp_richcompare */
2602 0, /* tp_richcompare */
2596 0, /* tp_weaklistoffset */
2603 0, /* tp_weaklistoffset */
2597 0, /* tp_iter */
2604 0, /* tp_iter */
2598 0, /* tp_iternext */
2605 0, /* tp_iternext */
2599 index_methods, /* tp_methods */
2606 index_methods, /* tp_methods */
2600 0, /* tp_members */
2607 0, /* tp_members */
2601 index_getset, /* tp_getset */
2608 index_getset, /* tp_getset */
2602 0, /* tp_base */
2609 0, /* tp_base */
2603 0, /* tp_dict */
2610 0, /* tp_dict */
2604 0, /* tp_descr_get */
2611 0, /* tp_descr_get */
2605 0, /* tp_descr_set */
2612 0, /* tp_descr_set */
2606 0, /* tp_dictoffset */
2613 0, /* tp_dictoffset */
2607 (initproc)index_init, /* tp_init */
2614 (initproc)index_init, /* tp_init */
2608 0, /* tp_alloc */
2615 0, /* tp_alloc */
2609 };
2616 };
2610
2617
2611 /*
2618 /*
2612 * returns a tuple of the form (index, index, cache) with elements as
2619 * returns a tuple of the form (index, index, cache) with elements as
2613 * follows:
2620 * follows:
2614 *
2621 *
2615 * index: an index object that lazily parses RevlogNG records
2622 * index: an index object that lazily parses RevlogNG records
2616 * cache: if data is inlined, a tuple (0, index_file_content), else None
2623 * cache: if data is inlined, a tuple (0, index_file_content), else None
2617 * index_file_content could be a string, or a buffer
2624 * index_file_content could be a string, or a buffer
2618 *
2625 *
2619 * added complications are for backwards compatibility
2626 * added complications are for backwards compatibility
2620 */
2627 */
2621 PyObject *parse_index2(PyObject *self, PyObject *args)
2628 PyObject *parse_index2(PyObject *self, PyObject *args)
2622 {
2629 {
2623 PyObject *tuple = NULL, *cache = NULL;
2630 PyObject *tuple = NULL, *cache = NULL;
2624 indexObject *idx;
2631 indexObject *idx;
2625 int ret;
2632 int ret;
2626
2633
2627 idx = PyObject_New(indexObject, &indexType);
2634 idx = PyObject_New(indexObject, &indexType);
2628 if (idx == NULL)
2635 if (idx == NULL)
2629 goto bail;
2636 goto bail;
2630
2637
2631 ret = index_init(idx, args);
2638 ret = index_init(idx, args);
2632 if (ret == -1)
2639 if (ret == -1)
2633 goto bail;
2640 goto bail;
2634
2641
2635 if (idx->inlined) {
2642 if (idx->inlined) {
2636 cache = Py_BuildValue("iO", 0, idx->data);
2643 cache = Py_BuildValue("iO", 0, idx->data);
2637 if (cache == NULL)
2644 if (cache == NULL)
2638 goto bail;
2645 goto bail;
2639 } else {
2646 } else {
2640 cache = Py_None;
2647 cache = Py_None;
2641 Py_INCREF(cache);
2648 Py_INCREF(cache);
2642 }
2649 }
2643
2650
2644 tuple = Py_BuildValue("NN", idx, cache);
2651 tuple = Py_BuildValue("NN", idx, cache);
2645 if (!tuple)
2652 if (!tuple)
2646 goto bail;
2653 goto bail;
2647 return tuple;
2654 return tuple;
2648
2655
2649 bail:
2656 bail:
2650 Py_XDECREF(idx);
2657 Py_XDECREF(idx);
2651 Py_XDECREF(cache);
2658 Py_XDECREF(cache);
2652 Py_XDECREF(tuple);
2659 Py_XDECREF(tuple);
2653 return NULL;
2660 return NULL;
2654 }
2661 }
2655
2662
2656 #ifdef WITH_RUST
2663 #ifdef WITH_RUST
2657
2664
2658 /* rustlazyancestors: iteration over ancestors implemented in Rust
2665 /* rustlazyancestors: iteration over ancestors implemented in Rust
2659 *
2666 *
2660 * This class holds a reference to an index and to the Rust iterator.
2667 * This class holds a reference to an index and to the Rust iterator.
2661 */
2668 */
2662 typedef struct rustlazyancestorsObjectStruct rustlazyancestorsObject;
2669 typedef struct rustlazyancestorsObjectStruct rustlazyancestorsObject;
2663
2670
2664 struct rustlazyancestorsObjectStruct {
2671 struct rustlazyancestorsObjectStruct {
2665 PyObject_HEAD
2672 PyObject_HEAD
2666 /* Type-specific fields go here. */
2673 /* Type-specific fields go here. */
2667 indexObject *index; /* Ref kept to avoid GC'ing the index */
2674 indexObject *index; /* Ref kept to avoid GC'ing the index */
2668 void *iter; /* Rust iterator */
2675 void *iter; /* Rust iterator */
2669 };
2676 };
2670
2677
2671 /* FFI exposed from Rust code */
2678 /* FFI exposed from Rust code */
2672 rustlazyancestorsObject *
2679 rustlazyancestorsObject *
2673 rustlazyancestors_init(indexObject *index,
2680 rustlazyancestors_init(indexObject *index,
2674 /* to pass index_get_parents() */
2681 /* to pass index_get_parents() */
2675 int (*)(indexObject *, Py_ssize_t, int *, int),
2682 int (*)(indexObject *, Py_ssize_t, int *, int),
2676 /* intrevs vector */
2683 /* intrevs vector */
2677 Py_ssize_t initrevslen, long *initrevs, long stoprev,
2684 Py_ssize_t initrevslen, long *initrevs, long stoprev,
2678 int inclusive);
2685 int inclusive);
2679 void rustlazyancestors_drop(rustlazyancestorsObject *self);
2686 void rustlazyancestors_drop(rustlazyancestorsObject *self);
2680 int rustlazyancestors_next(rustlazyancestorsObject *self);
2687 int rustlazyancestors_next(rustlazyancestorsObject *self);
2681 int rustlazyancestors_contains(rustlazyancestorsObject *self, long rev);
2688 int rustlazyancestors_contains(rustlazyancestorsObject *self, long rev);
2682
2689
2683 /* CPython instance methods */
2690 /* CPython instance methods */
2684 static int rustla_init(rustlazyancestorsObject *self, PyObject *args)
2691 static int rustla_init(rustlazyancestorsObject *self, PyObject *args)
2685 {
2692 {
2686 PyObject *initrevsarg = NULL;
2693 PyObject *initrevsarg = NULL;
2687 PyObject *inclusivearg = NULL;
2694 PyObject *inclusivearg = NULL;
2688 long stoprev = 0;
2695 long stoprev = 0;
2689 long *initrevs = NULL;
2696 long *initrevs = NULL;
2690 int inclusive = 0;
2697 int inclusive = 0;
2691 Py_ssize_t i;
2698 Py_ssize_t i;
2692
2699
2693 indexObject *index;
2700 indexObject *index;
2694 if (!PyArg_ParseTuple(args, "O!O!lO!", &indexType, &index, &PyList_Type,
2701 if (!PyArg_ParseTuple(args, "O!O!lO!", &indexType, &index, &PyList_Type,
2695 &initrevsarg, &stoprev, &PyBool_Type,
2702 &initrevsarg, &stoprev, &PyBool_Type,
2696 &inclusivearg))
2703 &inclusivearg))
2697 return -1;
2704 return -1;
2698
2705
2699 Py_INCREF(index);
2706 Py_INCREF(index);
2700 self->index = index;
2707 self->index = index;
2701
2708
2702 if (inclusivearg == Py_True)
2709 if (inclusivearg == Py_True)
2703 inclusive = 1;
2710 inclusive = 1;
2704
2711
2705 Py_ssize_t linit = PyList_GET_SIZE(initrevsarg);
2712 Py_ssize_t linit = PyList_GET_SIZE(initrevsarg);
2706
2713
2707 initrevs = (long *)calloc(linit, sizeof(long));
2714 initrevs = (long *)calloc(linit, sizeof(long));
2708
2715
2709 if (initrevs == NULL) {
2716 if (initrevs == NULL) {
2710 PyErr_NoMemory();
2717 PyErr_NoMemory();
2711 goto bail;
2718 goto bail;
2712 }
2719 }
2713
2720
2714 for (i = 0; i < linit; i++) {
2721 for (i = 0; i < linit; i++) {
2715 initrevs[i] = PyInt_AsLong(PyList_GET_ITEM(initrevsarg, i));
2722 initrevs[i] = PyInt_AsLong(PyList_GET_ITEM(initrevsarg, i));
2716 }
2723 }
2717 if (PyErr_Occurred())
2724 if (PyErr_Occurred())
2718 goto bail;
2725 goto bail;
2719
2726
2720 self->iter = rustlazyancestors_init(index, index_get_parents, linit,
2727 self->iter = rustlazyancestors_init(index, index_get_parents, linit,
2721 initrevs, stoprev, inclusive);
2728 initrevs, stoprev, inclusive);
2722 if (self->iter == NULL) {
2729 if (self->iter == NULL) {
2723 /* if this is because of GraphError::ParentOutOfRange
2730 /* if this is because of GraphError::ParentOutOfRange
2724 * index_get_parents() has already set the proper ValueError */
2731 * index_get_parents() has already set the proper ValueError */
2725 goto bail;
2732 goto bail;
2726 }
2733 }
2727
2734
2728 free(initrevs);
2735 free(initrevs);
2729 return 0;
2736 return 0;
2730
2737
2731 bail:
2738 bail:
2732 free(initrevs);
2739 free(initrevs);
2733 return -1;
2740 return -1;
2734 };
2741 };
2735
2742
2736 static void rustla_dealloc(rustlazyancestorsObject *self)
2743 static void rustla_dealloc(rustlazyancestorsObject *self)
2737 {
2744 {
2738 Py_XDECREF(self->index);
2745 Py_XDECREF(self->index);
2739 if (self->iter != NULL) { /* can happen if rustla_init failed */
2746 if (self->iter != NULL) { /* can happen if rustla_init failed */
2740 rustlazyancestors_drop(self->iter);
2747 rustlazyancestors_drop(self->iter);
2741 }
2748 }
2742 PyObject_Del(self);
2749 PyObject_Del(self);
2743 }
2750 }
2744
2751
2745 static PyObject *rustla_next(rustlazyancestorsObject *self)
2752 static PyObject *rustla_next(rustlazyancestorsObject *self)
2746 {
2753 {
2747 int res = rustlazyancestors_next(self->iter);
2754 int res = rustlazyancestors_next(self->iter);
2748 if (res == -1) {
2755 if (res == -1) {
2749 /* Setting an explicit exception seems unnecessary
2756 /* Setting an explicit exception seems unnecessary
2750 * as examples from Python source code (Objects/rangeobjets.c
2757 * as examples from Python source code (Objects/rangeobjets.c
2751 * and Modules/_io/stringio.c) seem to demonstrate.
2758 * and Modules/_io/stringio.c) seem to demonstrate.
2752 */
2759 */
2753 return NULL;
2760 return NULL;
2754 }
2761 }
2755 return PyInt_FromLong(res);
2762 return PyInt_FromLong(res);
2756 }
2763 }
2757
2764
2758 static int rustla_contains(rustlazyancestorsObject *self, PyObject *rev)
2765 static int rustla_contains(rustlazyancestorsObject *self, PyObject *rev)
2759 {
2766 {
2760 long lrev;
2767 long lrev;
2761 if (!pylong_to_long(rev, &lrev)) {
2768 if (!pylong_to_long(rev, &lrev)) {
2762 PyErr_Clear();
2769 PyErr_Clear();
2763 return 0;
2770 return 0;
2764 }
2771 }
2765 return rustlazyancestors_contains(self->iter, lrev);
2772 return rustlazyancestors_contains(self->iter, lrev);
2766 }
2773 }
2767
2774
2768 static PySequenceMethods rustla_sequence_methods = {
2775 static PySequenceMethods rustla_sequence_methods = {
2769 0, /* sq_length */
2776 0, /* sq_length */
2770 0, /* sq_concat */
2777 0, /* sq_concat */
2771 0, /* sq_repeat */
2778 0, /* sq_repeat */
2772 0, /* sq_item */
2779 0, /* sq_item */
2773 0, /* sq_slice */
2780 0, /* sq_slice */
2774 0, /* sq_ass_item */
2781 0, /* sq_ass_item */
2775 0, /* sq_ass_slice */
2782 0, /* sq_ass_slice */
2776 (objobjproc)rustla_contains, /* sq_contains */
2783 (objobjproc)rustla_contains, /* sq_contains */
2777 };
2784 };
2778
2785
2779 static PyTypeObject rustlazyancestorsType = {
2786 static PyTypeObject rustlazyancestorsType = {
2780 PyVarObject_HEAD_INIT(NULL, 0) /* header */
2787 PyVarObject_HEAD_INIT(NULL, 0) /* header */
2781 "parsers.rustlazyancestors", /* tp_name */
2788 "parsers.rustlazyancestors", /* tp_name */
2782 sizeof(rustlazyancestorsObject), /* tp_basicsize */
2789 sizeof(rustlazyancestorsObject), /* tp_basicsize */
2783 0, /* tp_itemsize */
2790 0, /* tp_itemsize */
2784 (destructor)rustla_dealloc, /* tp_dealloc */
2791 (destructor)rustla_dealloc, /* tp_dealloc */
2785 0, /* tp_print */
2792 0, /* tp_print */
2786 0, /* tp_getattr */
2793 0, /* tp_getattr */
2787 0, /* tp_setattr */
2794 0, /* tp_setattr */
2788 0, /* tp_compare */
2795 0, /* tp_compare */
2789 0, /* tp_repr */
2796 0, /* tp_repr */
2790 0, /* tp_as_number */
2797 0, /* tp_as_number */
2791 &rustla_sequence_methods, /* tp_as_sequence */
2798 &rustla_sequence_methods, /* tp_as_sequence */
2792 0, /* tp_as_mapping */
2799 0, /* tp_as_mapping */
2793 0, /* tp_hash */
2800 0, /* tp_hash */
2794 0, /* tp_call */
2801 0, /* tp_call */
2795 0, /* tp_str */
2802 0, /* tp_str */
2796 0, /* tp_getattro */
2803 0, /* tp_getattro */
2797 0, /* tp_setattro */
2804 0, /* tp_setattro */
2798 0, /* tp_as_buffer */
2805 0, /* tp_as_buffer */
2799 Py_TPFLAGS_DEFAULT, /* tp_flags */
2806 Py_TPFLAGS_DEFAULT, /* tp_flags */
2800 "Iterator over ancestors, implemented in Rust", /* tp_doc */
2807 "Iterator over ancestors, implemented in Rust", /* tp_doc */
2801 0, /* tp_traverse */
2808 0, /* tp_traverse */
2802 0, /* tp_clear */
2809 0, /* tp_clear */
2803 0, /* tp_richcompare */
2810 0, /* tp_richcompare */
2804 0, /* tp_weaklistoffset */
2811 0, /* tp_weaklistoffset */
2805 0, /* tp_iter */
2812 0, /* tp_iter */
2806 (iternextfunc)rustla_next, /* tp_iternext */
2813 (iternextfunc)rustla_next, /* tp_iternext */
2807 0, /* tp_methods */
2814 0, /* tp_methods */
2808 0, /* tp_members */
2815 0, /* tp_members */
2809 0, /* tp_getset */
2816 0, /* tp_getset */
2810 0, /* tp_base */
2817 0, /* tp_base */
2811 0, /* tp_dict */
2818 0, /* tp_dict */
2812 0, /* tp_descr_get */
2819 0, /* tp_descr_get */
2813 0, /* tp_descr_set */
2820 0, /* tp_descr_set */
2814 0, /* tp_dictoffset */
2821 0, /* tp_dictoffset */
2815 (initproc)rustla_init, /* tp_init */
2822 (initproc)rustla_init, /* tp_init */
2816 0, /* tp_alloc */
2823 0, /* tp_alloc */
2817 };
2824 };
2818 #endif /* WITH_RUST */
2825 #endif /* WITH_RUST */
2819
2826
2820 void revlog_module_init(PyObject *mod)
2827 void revlog_module_init(PyObject *mod)
2821 {
2828 {
2822 indexType.tp_new = PyType_GenericNew;
2829 indexType.tp_new = PyType_GenericNew;
2823 if (PyType_Ready(&indexType) < 0)
2830 if (PyType_Ready(&indexType) < 0)
2824 return;
2831 return;
2825 Py_INCREF(&indexType);
2832 Py_INCREF(&indexType);
2826 PyModule_AddObject(mod, "index", (PyObject *)&indexType);
2833 PyModule_AddObject(mod, "index", (PyObject *)&indexType);
2827
2834
2828 nodetreeType.tp_new = PyType_GenericNew;
2835 nodetreeType.tp_new = PyType_GenericNew;
2829 if (PyType_Ready(&nodetreeType) < 0)
2836 if (PyType_Ready(&nodetreeType) < 0)
2830 return;
2837 return;
2831 Py_INCREF(&nodetreeType);
2838 Py_INCREF(&nodetreeType);
2832 PyModule_AddObject(mod, "nodetree", (PyObject *)&nodetreeType);
2839 PyModule_AddObject(mod, "nodetree", (PyObject *)&nodetreeType);
2833
2840
2834 if (!nullentry) {
2841 if (!nullentry) {
2835 nullentry = Py_BuildValue(PY23("iiiiiiis#", "iiiiiiiy#"), 0, 0,
2842 nullentry = Py_BuildValue(PY23("iiiiiiis#", "iiiiiiiy#"), 0, 0,
2836 0, -1, -1, -1, -1, nullid, 20);
2843 0, -1, -1, -1, -1, nullid, 20);
2837 }
2844 }
2838 if (nullentry)
2845 if (nullentry)
2839 PyObject_GC_UnTrack(nullentry);
2846 PyObject_GC_UnTrack(nullentry);
2840
2847
2841 #ifdef WITH_RUST
2848 #ifdef WITH_RUST
2842 rustlazyancestorsType.tp_new = PyType_GenericNew;
2849 rustlazyancestorsType.tp_new = PyType_GenericNew;
2843 if (PyType_Ready(&rustlazyancestorsType) < 0)
2850 if (PyType_Ready(&rustlazyancestorsType) < 0)
2844 return;
2851 return;
2845 Py_INCREF(&rustlazyancestorsType);
2852 Py_INCREF(&rustlazyancestorsType);
2846 PyModule_AddObject(mod, "rustlazyancestors",
2853 PyModule_AddObject(mod, "rustlazyancestors",
2847 (PyObject *)&rustlazyancestorsType);
2854 (PyObject *)&rustlazyancestorsType);
2848 #endif
2855 #endif
2849 }
2856 }
General Comments 0
You need to be logged in to leave comments. Login now