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