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