##// END OF EJS Templates
parsers.c: avoid implicit conversion loses integer warnings...
André Sintzoff -
r24499:90db70de default
parent child Browse files
Show More
@@ -1,2516 +1,2516
1 /*
1 /*
2 parsers.c - efficient content parsing
2 parsers.c - efficient content parsing
3
3
4 Copyright 2008 Matt Mackall <mpm@selenic.com> and others
4 Copyright 2008 Matt Mackall <mpm@selenic.com> and others
5
5
6 This software may be used and distributed according to the terms of
6 This software may be used and distributed according to the terms of
7 the GNU General Public License, incorporated herein by reference.
7 the GNU General Public License, incorporated herein by reference.
8 */
8 */
9
9
10 #include <Python.h>
10 #include <Python.h>
11 #include <ctype.h>
11 #include <ctype.h>
12 #include <stddef.h>
12 #include <stddef.h>
13 #include <string.h>
13 #include <string.h>
14
14
15 #include "util.h"
15 #include "util.h"
16
16
17 static char *versionerrortext = "Python minor version mismatch";
17 static char *versionerrortext = "Python minor version mismatch";
18
18
19 static int8_t hextable[256] = {
19 static int8_t hextable[256] = {
20 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
20 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
21 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
21 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
22 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
22 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
23 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, /* 0-9 */
23 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, /* 0-9 */
24 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* A-F */
24 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* A-F */
25 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
25 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
26 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* a-f */
26 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* a-f */
27 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
27 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
28 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
28 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
29 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
29 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
30 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
30 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
31 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
31 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
32 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
32 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
33 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
33 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
34 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
34 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
35 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
35 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
36 };
36 };
37
37
38 static char lowertable[128] = {
38 static char lowertable[128] = {
39 '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07',
39 '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07',
40 '\x08', '\x09', '\x0a', '\x0b', '\x0c', '\x0d', '\x0e', '\x0f',
40 '\x08', '\x09', '\x0a', '\x0b', '\x0c', '\x0d', '\x0e', '\x0f',
41 '\x10', '\x11', '\x12', '\x13', '\x14', '\x15', '\x16', '\x17',
41 '\x10', '\x11', '\x12', '\x13', '\x14', '\x15', '\x16', '\x17',
42 '\x18', '\x19', '\x1a', '\x1b', '\x1c', '\x1d', '\x1e', '\x1f',
42 '\x18', '\x19', '\x1a', '\x1b', '\x1c', '\x1d', '\x1e', '\x1f',
43 '\x20', '\x21', '\x22', '\x23', '\x24', '\x25', '\x26', '\x27',
43 '\x20', '\x21', '\x22', '\x23', '\x24', '\x25', '\x26', '\x27',
44 '\x28', '\x29', '\x2a', '\x2b', '\x2c', '\x2d', '\x2e', '\x2f',
44 '\x28', '\x29', '\x2a', '\x2b', '\x2c', '\x2d', '\x2e', '\x2f',
45 '\x30', '\x31', '\x32', '\x33', '\x34', '\x35', '\x36', '\x37',
45 '\x30', '\x31', '\x32', '\x33', '\x34', '\x35', '\x36', '\x37',
46 '\x38', '\x39', '\x3a', '\x3b', '\x3c', '\x3d', '\x3e', '\x3f',
46 '\x38', '\x39', '\x3a', '\x3b', '\x3c', '\x3d', '\x3e', '\x3f',
47 '\x40',
47 '\x40',
48 '\x61', '\x62', '\x63', '\x64', '\x65', '\x66', '\x67', /* A-G */
48 '\x61', '\x62', '\x63', '\x64', '\x65', '\x66', '\x67', /* A-G */
49 '\x68', '\x69', '\x6a', '\x6b', '\x6c', '\x6d', '\x6e', '\x6f', /* H-O */
49 '\x68', '\x69', '\x6a', '\x6b', '\x6c', '\x6d', '\x6e', '\x6f', /* H-O */
50 '\x70', '\x71', '\x72', '\x73', '\x74', '\x75', '\x76', '\x77', /* P-W */
50 '\x70', '\x71', '\x72', '\x73', '\x74', '\x75', '\x76', '\x77', /* P-W */
51 '\x78', '\x79', '\x7a', /* X-Z */
51 '\x78', '\x79', '\x7a', /* X-Z */
52 '\x5b', '\x5c', '\x5d', '\x5e', '\x5f',
52 '\x5b', '\x5c', '\x5d', '\x5e', '\x5f',
53 '\x60', '\x61', '\x62', '\x63', '\x64', '\x65', '\x66', '\x67',
53 '\x60', '\x61', '\x62', '\x63', '\x64', '\x65', '\x66', '\x67',
54 '\x68', '\x69', '\x6a', '\x6b', '\x6c', '\x6d', '\x6e', '\x6f',
54 '\x68', '\x69', '\x6a', '\x6b', '\x6c', '\x6d', '\x6e', '\x6f',
55 '\x70', '\x71', '\x72', '\x73', '\x74', '\x75', '\x76', '\x77',
55 '\x70', '\x71', '\x72', '\x73', '\x74', '\x75', '\x76', '\x77',
56 '\x78', '\x79', '\x7a', '\x7b', '\x7c', '\x7d', '\x7e', '\x7f'
56 '\x78', '\x79', '\x7a', '\x7b', '\x7c', '\x7d', '\x7e', '\x7f'
57 };
57 };
58
58
59 static inline int hexdigit(const char *p, Py_ssize_t off)
59 static inline int hexdigit(const char *p, Py_ssize_t off)
60 {
60 {
61 int8_t val = hextable[(unsigned char)p[off]];
61 int8_t val = hextable[(unsigned char)p[off]];
62
62
63 if (val >= 0) {
63 if (val >= 0) {
64 return val;
64 return val;
65 }
65 }
66
66
67 PyErr_SetString(PyExc_ValueError, "input contains non-hex character");
67 PyErr_SetString(PyExc_ValueError, "input contains non-hex character");
68 return 0;
68 return 0;
69 }
69 }
70
70
71 /*
71 /*
72 * Turn a hex-encoded string into binary.
72 * Turn a hex-encoded string into binary.
73 */
73 */
74 PyObject *unhexlify(const char *str, int len)
74 PyObject *unhexlify(const char *str, int len)
75 {
75 {
76 PyObject *ret;
76 PyObject *ret;
77 char *d;
77 char *d;
78 int i;
78 int i;
79
79
80 ret = PyBytes_FromStringAndSize(NULL, len / 2);
80 ret = PyBytes_FromStringAndSize(NULL, len / 2);
81
81
82 if (!ret)
82 if (!ret)
83 return NULL;
83 return NULL;
84
84
85 d = PyBytes_AsString(ret);
85 d = PyBytes_AsString(ret);
86
86
87 for (i = 0; i < len;) {
87 for (i = 0; i < len;) {
88 int hi = hexdigit(str, i++);
88 int hi = hexdigit(str, i++);
89 int lo = hexdigit(str, i++);
89 int lo = hexdigit(str, i++);
90 *d++ = (hi << 4) | lo;
90 *d++ = (hi << 4) | lo;
91 }
91 }
92
92
93 return ret;
93 return ret;
94 }
94 }
95
95
96 static PyObject *asciilower(PyObject *self, PyObject *args)
96 static PyObject *asciilower(PyObject *self, PyObject *args)
97 {
97 {
98 char *str, *newstr;
98 char *str, *newstr;
99 int i, len;
99 int i, len;
100 PyObject *newobj = NULL;
100 PyObject *newobj = NULL;
101
101
102 if (!PyArg_ParseTuple(args, "s#", &str, &len))
102 if (!PyArg_ParseTuple(args, "s#", &str, &len))
103 goto quit;
103 goto quit;
104
104
105 newobj = PyBytes_FromStringAndSize(NULL, len);
105 newobj = PyBytes_FromStringAndSize(NULL, len);
106 if (!newobj)
106 if (!newobj)
107 goto quit;
107 goto quit;
108
108
109 newstr = PyBytes_AS_STRING(newobj);
109 newstr = PyBytes_AS_STRING(newobj);
110
110
111 for (i = 0; i < len; i++) {
111 for (i = 0; i < len; i++) {
112 char c = str[i];
112 char c = str[i];
113 if (c & 0x80) {
113 if (c & 0x80) {
114 PyObject *err = PyUnicodeDecodeError_Create(
114 PyObject *err = PyUnicodeDecodeError_Create(
115 "ascii", str, len, i, (i + 1),
115 "ascii", str, len, i, (i + 1),
116 "unexpected code byte");
116 "unexpected code byte");
117 PyErr_SetObject(PyExc_UnicodeDecodeError, err);
117 PyErr_SetObject(PyExc_UnicodeDecodeError, err);
118 Py_XDECREF(err);
118 Py_XDECREF(err);
119 goto quit;
119 goto quit;
120 }
120 }
121 newstr[i] = lowertable[(unsigned char)c];
121 newstr[i] = lowertable[(unsigned char)c];
122 }
122 }
123
123
124 return newobj;
124 return newobj;
125 quit:
125 quit:
126 Py_XDECREF(newobj);
126 Py_XDECREF(newobj);
127 return NULL;
127 return NULL;
128 }
128 }
129
129
130 /*
130 /*
131 * This code assumes that a manifest is stitched together with newline
131 * This code assumes that a manifest is stitched together with newline
132 * ('\n') characters.
132 * ('\n') characters.
133 */
133 */
134 static PyObject *parse_manifest(PyObject *self, PyObject *args)
134 static PyObject *parse_manifest(PyObject *self, PyObject *args)
135 {
135 {
136 PyObject *mfdict, *fdict;
136 PyObject *mfdict, *fdict;
137 char *str, *start, *end;
137 char *str, *start, *end;
138 int len;
138 int len;
139
139
140 if (!PyArg_ParseTuple(args, "O!O!s#:parse_manifest",
140 if (!PyArg_ParseTuple(args, "O!O!s#:parse_manifest",
141 &PyDict_Type, &mfdict,
141 &PyDict_Type, &mfdict,
142 &PyDict_Type, &fdict,
142 &PyDict_Type, &fdict,
143 &str, &len))
143 &str, &len))
144 goto quit;
144 goto quit;
145
145
146 start = str;
146 start = str;
147 end = str + len;
147 end = str + len;
148 while (start < end) {
148 while (start < end) {
149 PyObject *file = NULL, *node = NULL;
149 PyObject *file = NULL, *node = NULL;
150 PyObject *flags = NULL;
150 PyObject *flags = NULL;
151 char *zero = NULL, *newline = NULL;
151 char *zero = NULL, *newline = NULL;
152 ptrdiff_t nlen;
152 ptrdiff_t nlen;
153
153
154 zero = memchr(start, '\0', end - start);
154 zero = memchr(start, '\0', end - start);
155 if (!zero) {
155 if (!zero) {
156 PyErr_SetString(PyExc_ValueError,
156 PyErr_SetString(PyExc_ValueError,
157 "manifest entry has no separator");
157 "manifest entry has no separator");
158 goto quit;
158 goto quit;
159 }
159 }
160
160
161 newline = memchr(zero + 1, '\n', end - (zero + 1));
161 newline = memchr(zero + 1, '\n', end - (zero + 1));
162 if (!newline) {
162 if (!newline) {
163 PyErr_SetString(PyExc_ValueError,
163 PyErr_SetString(PyExc_ValueError,
164 "manifest contains trailing garbage");
164 "manifest contains trailing garbage");
165 goto quit;
165 goto quit;
166 }
166 }
167
167
168 file = PyBytes_FromStringAndSize(start, zero - start);
168 file = PyBytes_FromStringAndSize(start, zero - start);
169
169
170 if (!file)
170 if (!file)
171 goto bail;
171 goto bail;
172
172
173 nlen = newline - zero - 1;
173 nlen = newline - zero - 1;
174
174
175 node = unhexlify(zero + 1, nlen > 40 ? 40 : (int)nlen);
175 node = unhexlify(zero + 1, nlen > 40 ? 40 : (int)nlen);
176 if (!node)
176 if (!node)
177 goto bail;
177 goto bail;
178
178
179 if (nlen > 40) {
179 if (nlen > 40) {
180 flags = PyBytes_FromStringAndSize(zero + 41,
180 flags = PyBytes_FromStringAndSize(zero + 41,
181 nlen - 40);
181 nlen - 40);
182 if (!flags)
182 if (!flags)
183 goto bail;
183 goto bail;
184
184
185 if (PyDict_SetItem(fdict, file, flags) == -1)
185 if (PyDict_SetItem(fdict, file, flags) == -1)
186 goto bail;
186 goto bail;
187 }
187 }
188
188
189 if (PyDict_SetItem(mfdict, file, node) == -1)
189 if (PyDict_SetItem(mfdict, file, node) == -1)
190 goto bail;
190 goto bail;
191
191
192 start = newline + 1;
192 start = newline + 1;
193
193
194 Py_XDECREF(flags);
194 Py_XDECREF(flags);
195 Py_XDECREF(node);
195 Py_XDECREF(node);
196 Py_XDECREF(file);
196 Py_XDECREF(file);
197 continue;
197 continue;
198 bail:
198 bail:
199 Py_XDECREF(flags);
199 Py_XDECREF(flags);
200 Py_XDECREF(node);
200 Py_XDECREF(node);
201 Py_XDECREF(file);
201 Py_XDECREF(file);
202 goto quit;
202 goto quit;
203 }
203 }
204
204
205 Py_INCREF(Py_None);
205 Py_INCREF(Py_None);
206 return Py_None;
206 return Py_None;
207 quit:
207 quit:
208 return NULL;
208 return NULL;
209 }
209 }
210
210
211 static inline dirstateTupleObject *make_dirstate_tuple(char state, int mode,
211 static inline dirstateTupleObject *make_dirstate_tuple(char state, int mode,
212 int size, int mtime)
212 int size, int mtime)
213 {
213 {
214 dirstateTupleObject *t = PyObject_New(dirstateTupleObject,
214 dirstateTupleObject *t = PyObject_New(dirstateTupleObject,
215 &dirstateTupleType);
215 &dirstateTupleType);
216 if (!t)
216 if (!t)
217 return NULL;
217 return NULL;
218 t->state = state;
218 t->state = state;
219 t->mode = mode;
219 t->mode = mode;
220 t->size = size;
220 t->size = size;
221 t->mtime = mtime;
221 t->mtime = mtime;
222 return t;
222 return t;
223 }
223 }
224
224
225 static PyObject *dirstate_tuple_new(PyTypeObject *subtype, PyObject *args,
225 static PyObject *dirstate_tuple_new(PyTypeObject *subtype, PyObject *args,
226 PyObject *kwds)
226 PyObject *kwds)
227 {
227 {
228 /* We do all the initialization here and not a tp_init function because
228 /* We do all the initialization here and not a tp_init function because
229 * dirstate_tuple is immutable. */
229 * dirstate_tuple is immutable. */
230 dirstateTupleObject *t;
230 dirstateTupleObject *t;
231 char state;
231 char state;
232 int size, mode, mtime;
232 int size, mode, mtime;
233 if (!PyArg_ParseTuple(args, "ciii", &state, &mode, &size, &mtime))
233 if (!PyArg_ParseTuple(args, "ciii", &state, &mode, &size, &mtime))
234 return NULL;
234 return NULL;
235
235
236 t = (dirstateTupleObject *)subtype->tp_alloc(subtype, 1);
236 t = (dirstateTupleObject *)subtype->tp_alloc(subtype, 1);
237 if (!t)
237 if (!t)
238 return NULL;
238 return NULL;
239 t->state = state;
239 t->state = state;
240 t->mode = mode;
240 t->mode = mode;
241 t->size = size;
241 t->size = size;
242 t->mtime = mtime;
242 t->mtime = mtime;
243
243
244 return (PyObject *)t;
244 return (PyObject *)t;
245 }
245 }
246
246
247 static void dirstate_tuple_dealloc(PyObject *o)
247 static void dirstate_tuple_dealloc(PyObject *o)
248 {
248 {
249 PyObject_Del(o);
249 PyObject_Del(o);
250 }
250 }
251
251
252 static Py_ssize_t dirstate_tuple_length(PyObject *o)
252 static Py_ssize_t dirstate_tuple_length(PyObject *o)
253 {
253 {
254 return 4;
254 return 4;
255 }
255 }
256
256
257 static PyObject *dirstate_tuple_item(PyObject *o, Py_ssize_t i)
257 static PyObject *dirstate_tuple_item(PyObject *o, Py_ssize_t i)
258 {
258 {
259 dirstateTupleObject *t = (dirstateTupleObject *)o;
259 dirstateTupleObject *t = (dirstateTupleObject *)o;
260 switch (i) {
260 switch (i) {
261 case 0:
261 case 0:
262 return PyBytes_FromStringAndSize(&t->state, 1);
262 return PyBytes_FromStringAndSize(&t->state, 1);
263 case 1:
263 case 1:
264 return PyInt_FromLong(t->mode);
264 return PyInt_FromLong(t->mode);
265 case 2:
265 case 2:
266 return PyInt_FromLong(t->size);
266 return PyInt_FromLong(t->size);
267 case 3:
267 case 3:
268 return PyInt_FromLong(t->mtime);
268 return PyInt_FromLong(t->mtime);
269 default:
269 default:
270 PyErr_SetString(PyExc_IndexError, "index out of range");
270 PyErr_SetString(PyExc_IndexError, "index out of range");
271 return NULL;
271 return NULL;
272 }
272 }
273 }
273 }
274
274
275 static PySequenceMethods dirstate_tuple_sq = {
275 static PySequenceMethods dirstate_tuple_sq = {
276 dirstate_tuple_length, /* sq_length */
276 dirstate_tuple_length, /* sq_length */
277 0, /* sq_concat */
277 0, /* sq_concat */
278 0, /* sq_repeat */
278 0, /* sq_repeat */
279 dirstate_tuple_item, /* sq_item */
279 dirstate_tuple_item, /* sq_item */
280 0, /* sq_ass_item */
280 0, /* sq_ass_item */
281 0, /* sq_contains */
281 0, /* sq_contains */
282 0, /* sq_inplace_concat */
282 0, /* sq_inplace_concat */
283 0 /* sq_inplace_repeat */
283 0 /* sq_inplace_repeat */
284 };
284 };
285
285
286 PyTypeObject dirstateTupleType = {
286 PyTypeObject dirstateTupleType = {
287 PyVarObject_HEAD_INIT(NULL, 0)
287 PyVarObject_HEAD_INIT(NULL, 0)
288 "dirstate_tuple", /* tp_name */
288 "dirstate_tuple", /* tp_name */
289 sizeof(dirstateTupleObject),/* tp_basicsize */
289 sizeof(dirstateTupleObject),/* tp_basicsize */
290 0, /* tp_itemsize */
290 0, /* tp_itemsize */
291 (destructor)dirstate_tuple_dealloc, /* tp_dealloc */
291 (destructor)dirstate_tuple_dealloc, /* tp_dealloc */
292 0, /* tp_print */
292 0, /* tp_print */
293 0, /* tp_getattr */
293 0, /* tp_getattr */
294 0, /* tp_setattr */
294 0, /* tp_setattr */
295 0, /* tp_compare */
295 0, /* tp_compare */
296 0, /* tp_repr */
296 0, /* tp_repr */
297 0, /* tp_as_number */
297 0, /* tp_as_number */
298 &dirstate_tuple_sq, /* tp_as_sequence */
298 &dirstate_tuple_sq, /* tp_as_sequence */
299 0, /* tp_as_mapping */
299 0, /* tp_as_mapping */
300 0, /* tp_hash */
300 0, /* tp_hash */
301 0, /* tp_call */
301 0, /* tp_call */
302 0, /* tp_str */
302 0, /* tp_str */
303 0, /* tp_getattro */
303 0, /* tp_getattro */
304 0, /* tp_setattro */
304 0, /* tp_setattro */
305 0, /* tp_as_buffer */
305 0, /* tp_as_buffer */
306 Py_TPFLAGS_DEFAULT, /* tp_flags */
306 Py_TPFLAGS_DEFAULT, /* tp_flags */
307 "dirstate tuple", /* tp_doc */
307 "dirstate tuple", /* tp_doc */
308 0, /* tp_traverse */
308 0, /* tp_traverse */
309 0, /* tp_clear */
309 0, /* tp_clear */
310 0, /* tp_richcompare */
310 0, /* tp_richcompare */
311 0, /* tp_weaklistoffset */
311 0, /* tp_weaklistoffset */
312 0, /* tp_iter */
312 0, /* tp_iter */
313 0, /* tp_iternext */
313 0, /* tp_iternext */
314 0, /* tp_methods */
314 0, /* tp_methods */
315 0, /* tp_members */
315 0, /* tp_members */
316 0, /* tp_getset */
316 0, /* tp_getset */
317 0, /* tp_base */
317 0, /* tp_base */
318 0, /* tp_dict */
318 0, /* tp_dict */
319 0, /* tp_descr_get */
319 0, /* tp_descr_get */
320 0, /* tp_descr_set */
320 0, /* tp_descr_set */
321 0, /* tp_dictoffset */
321 0, /* tp_dictoffset */
322 0, /* tp_init */
322 0, /* tp_init */
323 0, /* tp_alloc */
323 0, /* tp_alloc */
324 dirstate_tuple_new, /* tp_new */
324 dirstate_tuple_new, /* tp_new */
325 };
325 };
326
326
327 static PyObject *parse_dirstate(PyObject *self, PyObject *args)
327 static PyObject *parse_dirstate(PyObject *self, PyObject *args)
328 {
328 {
329 PyObject *dmap, *cmap, *parents = NULL, *ret = NULL;
329 PyObject *dmap, *cmap, *parents = NULL, *ret = NULL;
330 PyObject *fname = NULL, *cname = NULL, *entry = NULL;
330 PyObject *fname = NULL, *cname = NULL, *entry = NULL;
331 char state, *cur, *str, *cpos;
331 char state, *cur, *str, *cpos;
332 int mode, size, mtime;
332 int mode, size, mtime;
333 unsigned int flen, len, pos = 40;
333 unsigned int flen, len, pos = 40;
334 int readlen;
334 int readlen;
335
335
336 if (!PyArg_ParseTuple(args, "O!O!s#:parse_dirstate",
336 if (!PyArg_ParseTuple(args, "O!O!s#:parse_dirstate",
337 &PyDict_Type, &dmap,
337 &PyDict_Type, &dmap,
338 &PyDict_Type, &cmap,
338 &PyDict_Type, &cmap,
339 &str, &readlen))
339 &str, &readlen))
340 goto quit;
340 goto quit;
341
341
342 if (readlen < 0)
342 if (readlen < 0)
343 goto quit;
343 goto quit;
344
344
345 len = readlen;
345 len = readlen;
346
346
347 /* read parents */
347 /* read parents */
348 if (len < 40)
348 if (len < 40)
349 goto quit;
349 goto quit;
350
350
351 parents = Py_BuildValue("s#s#", str, 20, str + 20, 20);
351 parents = Py_BuildValue("s#s#", str, 20, str + 20, 20);
352 if (!parents)
352 if (!parents)
353 goto quit;
353 goto quit;
354
354
355 /* read filenames */
355 /* read filenames */
356 while (pos >= 40 && pos < len) {
356 while (pos >= 40 && pos < len) {
357 cur = str + pos;
357 cur = str + pos;
358 /* unpack header */
358 /* unpack header */
359 state = *cur;
359 state = *cur;
360 mode = getbe32(cur + 1);
360 mode = getbe32(cur + 1);
361 size = getbe32(cur + 5);
361 size = getbe32(cur + 5);
362 mtime = getbe32(cur + 9);
362 mtime = getbe32(cur + 9);
363 flen = getbe32(cur + 13);
363 flen = getbe32(cur + 13);
364 pos += 17;
364 pos += 17;
365 cur += 17;
365 cur += 17;
366 if (flen > len - pos) {
366 if (flen > len - pos) {
367 PyErr_SetString(PyExc_ValueError, "overflow in dirstate");
367 PyErr_SetString(PyExc_ValueError, "overflow in dirstate");
368 goto quit;
368 goto quit;
369 }
369 }
370
370
371 entry = (PyObject *)make_dirstate_tuple(state, mode, size,
371 entry = (PyObject *)make_dirstate_tuple(state, mode, size,
372 mtime);
372 mtime);
373 cpos = memchr(cur, 0, flen);
373 cpos = memchr(cur, 0, flen);
374 if (cpos) {
374 if (cpos) {
375 fname = PyBytes_FromStringAndSize(cur, cpos - cur);
375 fname = PyBytes_FromStringAndSize(cur, cpos - cur);
376 cname = PyBytes_FromStringAndSize(cpos + 1,
376 cname = PyBytes_FromStringAndSize(cpos + 1,
377 flen - (cpos - cur) - 1);
377 flen - (cpos - cur) - 1);
378 if (!fname || !cname ||
378 if (!fname || !cname ||
379 PyDict_SetItem(cmap, fname, cname) == -1 ||
379 PyDict_SetItem(cmap, fname, cname) == -1 ||
380 PyDict_SetItem(dmap, fname, entry) == -1)
380 PyDict_SetItem(dmap, fname, entry) == -1)
381 goto quit;
381 goto quit;
382 Py_DECREF(cname);
382 Py_DECREF(cname);
383 } else {
383 } else {
384 fname = PyBytes_FromStringAndSize(cur, flen);
384 fname = PyBytes_FromStringAndSize(cur, flen);
385 if (!fname ||
385 if (!fname ||
386 PyDict_SetItem(dmap, fname, entry) == -1)
386 PyDict_SetItem(dmap, fname, entry) == -1)
387 goto quit;
387 goto quit;
388 }
388 }
389 Py_DECREF(fname);
389 Py_DECREF(fname);
390 Py_DECREF(entry);
390 Py_DECREF(entry);
391 fname = cname = entry = NULL;
391 fname = cname = entry = NULL;
392 pos += flen;
392 pos += flen;
393 }
393 }
394
394
395 ret = parents;
395 ret = parents;
396 Py_INCREF(ret);
396 Py_INCREF(ret);
397 quit:
397 quit:
398 Py_XDECREF(fname);
398 Py_XDECREF(fname);
399 Py_XDECREF(cname);
399 Py_XDECREF(cname);
400 Py_XDECREF(entry);
400 Py_XDECREF(entry);
401 Py_XDECREF(parents);
401 Py_XDECREF(parents);
402 return ret;
402 return ret;
403 }
403 }
404
404
405 /*
405 /*
406 * Efficiently pack a dirstate object into its on-disk format.
406 * Efficiently pack a dirstate object into its on-disk format.
407 */
407 */
408 static PyObject *pack_dirstate(PyObject *self, PyObject *args)
408 static PyObject *pack_dirstate(PyObject *self, PyObject *args)
409 {
409 {
410 PyObject *packobj = NULL;
410 PyObject *packobj = NULL;
411 PyObject *map, *copymap, *pl, *mtime_unset = NULL;
411 PyObject *map, *copymap, *pl, *mtime_unset = NULL;
412 Py_ssize_t nbytes, pos, l;
412 Py_ssize_t nbytes, pos, l;
413 PyObject *k, *v = NULL, *pn;
413 PyObject *k, *v = NULL, *pn;
414 char *p, *s;
414 char *p, *s;
415 double now;
415 double now;
416
416
417 if (!PyArg_ParseTuple(args, "O!O!Od:pack_dirstate",
417 if (!PyArg_ParseTuple(args, "O!O!Od:pack_dirstate",
418 &PyDict_Type, &map, &PyDict_Type, &copymap,
418 &PyDict_Type, &map, &PyDict_Type, &copymap,
419 &pl, &now))
419 &pl, &now))
420 return NULL;
420 return NULL;
421
421
422 if (!PySequence_Check(pl) || PySequence_Size(pl) != 2) {
422 if (!PySequence_Check(pl) || PySequence_Size(pl) != 2) {
423 PyErr_SetString(PyExc_TypeError, "expected 2-element sequence");
423 PyErr_SetString(PyExc_TypeError, "expected 2-element sequence");
424 return NULL;
424 return NULL;
425 }
425 }
426
426
427 /* Figure out how much we need to allocate. */
427 /* Figure out how much we need to allocate. */
428 for (nbytes = 40, pos = 0; PyDict_Next(map, &pos, &k, &v);) {
428 for (nbytes = 40, pos = 0; PyDict_Next(map, &pos, &k, &v);) {
429 PyObject *c;
429 PyObject *c;
430 if (!PyString_Check(k)) {
430 if (!PyString_Check(k)) {
431 PyErr_SetString(PyExc_TypeError, "expected string key");
431 PyErr_SetString(PyExc_TypeError, "expected string key");
432 goto bail;
432 goto bail;
433 }
433 }
434 nbytes += PyString_GET_SIZE(k) + 17;
434 nbytes += PyString_GET_SIZE(k) + 17;
435 c = PyDict_GetItem(copymap, k);
435 c = PyDict_GetItem(copymap, k);
436 if (c) {
436 if (c) {
437 if (!PyString_Check(c)) {
437 if (!PyString_Check(c)) {
438 PyErr_SetString(PyExc_TypeError,
438 PyErr_SetString(PyExc_TypeError,
439 "expected string key");
439 "expected string key");
440 goto bail;
440 goto bail;
441 }
441 }
442 nbytes += PyString_GET_SIZE(c) + 1;
442 nbytes += PyString_GET_SIZE(c) + 1;
443 }
443 }
444 }
444 }
445
445
446 packobj = PyString_FromStringAndSize(NULL, nbytes);
446 packobj = PyString_FromStringAndSize(NULL, nbytes);
447 if (packobj == NULL)
447 if (packobj == NULL)
448 goto bail;
448 goto bail;
449
449
450 p = PyString_AS_STRING(packobj);
450 p = PyString_AS_STRING(packobj);
451
451
452 pn = PySequence_ITEM(pl, 0);
452 pn = PySequence_ITEM(pl, 0);
453 if (PyString_AsStringAndSize(pn, &s, &l) == -1 || l != 20) {
453 if (PyString_AsStringAndSize(pn, &s, &l) == -1 || l != 20) {
454 PyErr_SetString(PyExc_TypeError, "expected a 20-byte hash");
454 PyErr_SetString(PyExc_TypeError, "expected a 20-byte hash");
455 goto bail;
455 goto bail;
456 }
456 }
457 memcpy(p, s, l);
457 memcpy(p, s, l);
458 p += 20;
458 p += 20;
459 pn = PySequence_ITEM(pl, 1);
459 pn = PySequence_ITEM(pl, 1);
460 if (PyString_AsStringAndSize(pn, &s, &l) == -1 || l != 20) {
460 if (PyString_AsStringAndSize(pn, &s, &l) == -1 || l != 20) {
461 PyErr_SetString(PyExc_TypeError, "expected a 20-byte hash");
461 PyErr_SetString(PyExc_TypeError, "expected a 20-byte hash");
462 goto bail;
462 goto bail;
463 }
463 }
464 memcpy(p, s, l);
464 memcpy(p, s, l);
465 p += 20;
465 p += 20;
466
466
467 for (pos = 0; PyDict_Next(map, &pos, &k, &v); ) {
467 for (pos = 0; PyDict_Next(map, &pos, &k, &v); ) {
468 dirstateTupleObject *tuple;
468 dirstateTupleObject *tuple;
469 char state;
469 char state;
470 uint32_t mode, size, mtime;
470 uint32_t mode, size, mtime;
471 Py_ssize_t len, l;
471 Py_ssize_t len, l;
472 PyObject *o;
472 PyObject *o;
473 char *t;
473 char *t;
474
474
475 if (!dirstate_tuple_check(v)) {
475 if (!dirstate_tuple_check(v)) {
476 PyErr_SetString(PyExc_TypeError,
476 PyErr_SetString(PyExc_TypeError,
477 "expected a dirstate tuple");
477 "expected a dirstate tuple");
478 goto bail;
478 goto bail;
479 }
479 }
480 tuple = (dirstateTupleObject *)v;
480 tuple = (dirstateTupleObject *)v;
481
481
482 state = tuple->state;
482 state = tuple->state;
483 mode = tuple->mode;
483 mode = tuple->mode;
484 size = tuple->size;
484 size = tuple->size;
485 mtime = tuple->mtime;
485 mtime = tuple->mtime;
486 if (state == 'n' && mtime == (uint32_t)now) {
486 if (state == 'n' && mtime == (uint32_t)now) {
487 /* See pure/parsers.py:pack_dirstate for why we do
487 /* See pure/parsers.py:pack_dirstate for why we do
488 * this. */
488 * this. */
489 mtime = -1;
489 mtime = -1;
490 mtime_unset = (PyObject *)make_dirstate_tuple(
490 mtime_unset = (PyObject *)make_dirstate_tuple(
491 state, mode, size, mtime);
491 state, mode, size, mtime);
492 if (!mtime_unset)
492 if (!mtime_unset)
493 goto bail;
493 goto bail;
494 if (PyDict_SetItem(map, k, mtime_unset) == -1)
494 if (PyDict_SetItem(map, k, mtime_unset) == -1)
495 goto bail;
495 goto bail;
496 Py_DECREF(mtime_unset);
496 Py_DECREF(mtime_unset);
497 mtime_unset = NULL;
497 mtime_unset = NULL;
498 }
498 }
499 *p++ = state;
499 *p++ = state;
500 putbe32(mode, p);
500 putbe32(mode, p);
501 putbe32(size, p + 4);
501 putbe32(size, p + 4);
502 putbe32(mtime, p + 8);
502 putbe32(mtime, p + 8);
503 t = p + 12;
503 t = p + 12;
504 p += 16;
504 p += 16;
505 len = PyString_GET_SIZE(k);
505 len = PyString_GET_SIZE(k);
506 memcpy(p, PyString_AS_STRING(k), len);
506 memcpy(p, PyString_AS_STRING(k), len);
507 p += len;
507 p += len;
508 o = PyDict_GetItem(copymap, k);
508 o = PyDict_GetItem(copymap, k);
509 if (o) {
509 if (o) {
510 *p++ = '\0';
510 *p++ = '\0';
511 l = PyString_GET_SIZE(o);
511 l = PyString_GET_SIZE(o);
512 memcpy(p, PyString_AS_STRING(o), l);
512 memcpy(p, PyString_AS_STRING(o), l);
513 p += l;
513 p += l;
514 len += l + 1;
514 len += l + 1;
515 }
515 }
516 putbe32((uint32_t)len, t);
516 putbe32((uint32_t)len, t);
517 }
517 }
518
518
519 pos = p - PyString_AS_STRING(packobj);
519 pos = p - PyString_AS_STRING(packobj);
520 if (pos != nbytes) {
520 if (pos != nbytes) {
521 PyErr_Format(PyExc_SystemError, "bad dirstate size: %ld != %ld",
521 PyErr_Format(PyExc_SystemError, "bad dirstate size: %ld != %ld",
522 (long)pos, (long)nbytes);
522 (long)pos, (long)nbytes);
523 goto bail;
523 goto bail;
524 }
524 }
525
525
526 return packobj;
526 return packobj;
527 bail:
527 bail:
528 Py_XDECREF(mtime_unset);
528 Py_XDECREF(mtime_unset);
529 Py_XDECREF(packobj);
529 Py_XDECREF(packobj);
530 Py_XDECREF(v);
530 Py_XDECREF(v);
531 return NULL;
531 return NULL;
532 }
532 }
533
533
534 /*
534 /*
535 * A base-16 trie for fast node->rev mapping.
535 * A base-16 trie for fast node->rev mapping.
536 *
536 *
537 * Positive value is index of the next node in the trie
537 * Positive value is index of the next node in the trie
538 * Negative value is a leaf: -(rev + 1)
538 * Negative value is a leaf: -(rev + 1)
539 * Zero is empty
539 * Zero is empty
540 */
540 */
541 typedef struct {
541 typedef struct {
542 int children[16];
542 int children[16];
543 } nodetree;
543 } nodetree;
544
544
545 /*
545 /*
546 * This class has two behaviours.
546 * This class has two behaviours.
547 *
547 *
548 * When used in a list-like way (with integer keys), we decode an
548 * When used in a list-like way (with integer keys), we decode an
549 * entry in a RevlogNG index file on demand. Our last entry is a
549 * entry in a RevlogNG index file on demand. Our last entry is a
550 * sentinel, always a nullid. We have limited support for
550 * sentinel, always a nullid. We have limited support for
551 * integer-keyed insert and delete, only at elements right before the
551 * integer-keyed insert and delete, only at elements right before the
552 * sentinel.
552 * sentinel.
553 *
553 *
554 * With string keys, we lazily perform a reverse mapping from node to
554 * With string keys, we lazily perform a reverse mapping from node to
555 * rev, using a base-16 trie.
555 * rev, using a base-16 trie.
556 */
556 */
557 typedef struct {
557 typedef struct {
558 PyObject_HEAD
558 PyObject_HEAD
559 /* Type-specific fields go here. */
559 /* Type-specific fields go here. */
560 PyObject *data; /* raw bytes of index */
560 PyObject *data; /* raw bytes of index */
561 PyObject **cache; /* cached tuples */
561 PyObject **cache; /* cached tuples */
562 const char **offsets; /* populated on demand */
562 const char **offsets; /* populated on demand */
563 Py_ssize_t raw_length; /* original number of elements */
563 Py_ssize_t raw_length; /* original number of elements */
564 Py_ssize_t length; /* current number of elements */
564 Py_ssize_t length; /* current number of elements */
565 PyObject *added; /* populated on demand */
565 PyObject *added; /* populated on demand */
566 PyObject *headrevs; /* cache, invalidated on changes */
566 PyObject *headrevs; /* cache, invalidated on changes */
567 PyObject *filteredrevs;/* filtered revs set */
567 PyObject *filteredrevs;/* filtered revs set */
568 nodetree *nt; /* base-16 trie */
568 nodetree *nt; /* base-16 trie */
569 int ntlength; /* # nodes in use */
569 int ntlength; /* # nodes in use */
570 int ntcapacity; /* # nodes allocated */
570 int ntcapacity; /* # nodes allocated */
571 int ntdepth; /* maximum depth of tree */
571 int ntdepth; /* maximum depth of tree */
572 int ntsplits; /* # splits performed */
572 int ntsplits; /* # splits performed */
573 int ntrev; /* last rev scanned */
573 int ntrev; /* last rev scanned */
574 int ntlookups; /* # lookups */
574 int ntlookups; /* # lookups */
575 int ntmisses; /* # lookups that miss the cache */
575 int ntmisses; /* # lookups that miss the cache */
576 int inlined;
576 int inlined;
577 } indexObject;
577 } indexObject;
578
578
579 static Py_ssize_t index_length(const indexObject *self)
579 static Py_ssize_t index_length(const indexObject *self)
580 {
580 {
581 if (self->added == NULL)
581 if (self->added == NULL)
582 return self->length;
582 return self->length;
583 return self->length + PyList_GET_SIZE(self->added);
583 return self->length + PyList_GET_SIZE(self->added);
584 }
584 }
585
585
586 static PyObject *nullentry;
586 static PyObject *nullentry;
587 static const char nullid[20];
587 static const char nullid[20];
588
588
589 static Py_ssize_t inline_scan(indexObject *self, const char **offsets);
589 static Py_ssize_t inline_scan(indexObject *self, const char **offsets);
590
590
591 #if LONG_MAX == 0x7fffffffL
591 #if LONG_MAX == 0x7fffffffL
592 static char *tuple_format = "Kiiiiiis#";
592 static char *tuple_format = "Kiiiiiis#";
593 #else
593 #else
594 static char *tuple_format = "kiiiiiis#";
594 static char *tuple_format = "kiiiiiis#";
595 #endif
595 #endif
596
596
597 /* A RevlogNG v1 index entry is 64 bytes long. */
597 /* A RevlogNG v1 index entry is 64 bytes long. */
598 static const long v1_hdrsize = 64;
598 static const long v1_hdrsize = 64;
599
599
600 /*
600 /*
601 * Return a pointer to the beginning of a RevlogNG record.
601 * Return a pointer to the beginning of a RevlogNG record.
602 */
602 */
603 static const char *index_deref(indexObject *self, Py_ssize_t pos)
603 static const char *index_deref(indexObject *self, Py_ssize_t pos)
604 {
604 {
605 if (self->inlined && pos > 0) {
605 if (self->inlined && pos > 0) {
606 if (self->offsets == NULL) {
606 if (self->offsets == NULL) {
607 self->offsets = malloc(self->raw_length *
607 self->offsets = malloc(self->raw_length *
608 sizeof(*self->offsets));
608 sizeof(*self->offsets));
609 if (self->offsets == NULL)
609 if (self->offsets == NULL)
610 return (const char *)PyErr_NoMemory();
610 return (const char *)PyErr_NoMemory();
611 inline_scan(self, self->offsets);
611 inline_scan(self, self->offsets);
612 }
612 }
613 return self->offsets[pos];
613 return self->offsets[pos];
614 }
614 }
615
615
616 return PyString_AS_STRING(self->data) + pos * v1_hdrsize;
616 return PyString_AS_STRING(self->data) + pos * v1_hdrsize;
617 }
617 }
618
618
619 /*
619 /*
620 * RevlogNG format (all in big endian, data may be inlined):
620 * RevlogNG format (all in big endian, data may be inlined):
621 * 6 bytes: offset
621 * 6 bytes: offset
622 * 2 bytes: flags
622 * 2 bytes: flags
623 * 4 bytes: compressed length
623 * 4 bytes: compressed length
624 * 4 bytes: uncompressed length
624 * 4 bytes: uncompressed length
625 * 4 bytes: base revision
625 * 4 bytes: base revision
626 * 4 bytes: link revision
626 * 4 bytes: link revision
627 * 4 bytes: parent 1 revision
627 * 4 bytes: parent 1 revision
628 * 4 bytes: parent 2 revision
628 * 4 bytes: parent 2 revision
629 * 32 bytes: nodeid (only 20 bytes used)
629 * 32 bytes: nodeid (only 20 bytes used)
630 */
630 */
631 static PyObject *index_get(indexObject *self, Py_ssize_t pos)
631 static PyObject *index_get(indexObject *self, Py_ssize_t pos)
632 {
632 {
633 uint64_t offset_flags;
633 uint64_t offset_flags;
634 int comp_len, uncomp_len, base_rev, link_rev, parent_1, parent_2;
634 int comp_len, uncomp_len, base_rev, link_rev, parent_1, parent_2;
635 const char *c_node_id;
635 const char *c_node_id;
636 const char *data;
636 const char *data;
637 Py_ssize_t length = index_length(self);
637 Py_ssize_t length = index_length(self);
638 PyObject *entry;
638 PyObject *entry;
639
639
640 if (pos < 0)
640 if (pos < 0)
641 pos += length;
641 pos += length;
642
642
643 if (pos < 0 || pos >= length) {
643 if (pos < 0 || pos >= length) {
644 PyErr_SetString(PyExc_IndexError, "revlog index out of range");
644 PyErr_SetString(PyExc_IndexError, "revlog index out of range");
645 return NULL;
645 return NULL;
646 }
646 }
647
647
648 if (pos == length - 1) {
648 if (pos == length - 1) {
649 Py_INCREF(nullentry);
649 Py_INCREF(nullentry);
650 return nullentry;
650 return nullentry;
651 }
651 }
652
652
653 if (pos >= self->length - 1) {
653 if (pos >= self->length - 1) {
654 PyObject *obj;
654 PyObject *obj;
655 obj = PyList_GET_ITEM(self->added, pos - self->length + 1);
655 obj = PyList_GET_ITEM(self->added, pos - self->length + 1);
656 Py_INCREF(obj);
656 Py_INCREF(obj);
657 return obj;
657 return obj;
658 }
658 }
659
659
660 if (self->cache) {
660 if (self->cache) {
661 if (self->cache[pos]) {
661 if (self->cache[pos]) {
662 Py_INCREF(self->cache[pos]);
662 Py_INCREF(self->cache[pos]);
663 return self->cache[pos];
663 return self->cache[pos];
664 }
664 }
665 } else {
665 } else {
666 self->cache = calloc(self->raw_length, sizeof(PyObject *));
666 self->cache = calloc(self->raw_length, sizeof(PyObject *));
667 if (self->cache == NULL)
667 if (self->cache == NULL)
668 return PyErr_NoMemory();
668 return PyErr_NoMemory();
669 }
669 }
670
670
671 data = index_deref(self, pos);
671 data = index_deref(self, pos);
672 if (data == NULL)
672 if (data == NULL)
673 return NULL;
673 return NULL;
674
674
675 offset_flags = getbe32(data + 4);
675 offset_flags = getbe32(data + 4);
676 if (pos == 0) /* mask out version number for the first entry */
676 if (pos == 0) /* mask out version number for the first entry */
677 offset_flags &= 0xFFFF;
677 offset_flags &= 0xFFFF;
678 else {
678 else {
679 uint32_t offset_high = getbe32(data);
679 uint32_t offset_high = getbe32(data);
680 offset_flags |= ((uint64_t)offset_high) << 32;
680 offset_flags |= ((uint64_t)offset_high) << 32;
681 }
681 }
682
682
683 comp_len = getbe32(data + 8);
683 comp_len = getbe32(data + 8);
684 uncomp_len = getbe32(data + 12);
684 uncomp_len = getbe32(data + 12);
685 base_rev = getbe32(data + 16);
685 base_rev = getbe32(data + 16);
686 link_rev = getbe32(data + 20);
686 link_rev = getbe32(data + 20);
687 parent_1 = getbe32(data + 24);
687 parent_1 = getbe32(data + 24);
688 parent_2 = getbe32(data + 28);
688 parent_2 = getbe32(data + 28);
689 c_node_id = data + 32;
689 c_node_id = data + 32;
690
690
691 entry = Py_BuildValue(tuple_format, offset_flags, comp_len,
691 entry = Py_BuildValue(tuple_format, offset_flags, comp_len,
692 uncomp_len, base_rev, link_rev,
692 uncomp_len, base_rev, link_rev,
693 parent_1, parent_2, c_node_id, 20);
693 parent_1, parent_2, c_node_id, 20);
694
694
695 if (entry) {
695 if (entry) {
696 PyObject_GC_UnTrack(entry);
696 PyObject_GC_UnTrack(entry);
697 Py_INCREF(entry);
697 Py_INCREF(entry);
698 }
698 }
699
699
700 self->cache[pos] = entry;
700 self->cache[pos] = entry;
701
701
702 return entry;
702 return entry;
703 }
703 }
704
704
705 /*
705 /*
706 * Return the 20-byte SHA of the node corresponding to the given rev.
706 * Return the 20-byte SHA of the node corresponding to the given rev.
707 */
707 */
708 static const char *index_node(indexObject *self, Py_ssize_t pos)
708 static const char *index_node(indexObject *self, Py_ssize_t pos)
709 {
709 {
710 Py_ssize_t length = index_length(self);
710 Py_ssize_t length = index_length(self);
711 const char *data;
711 const char *data;
712
712
713 if (pos == length - 1 || pos == INT_MAX)
713 if (pos == length - 1 || pos == INT_MAX)
714 return nullid;
714 return nullid;
715
715
716 if (pos >= length)
716 if (pos >= length)
717 return NULL;
717 return NULL;
718
718
719 if (pos >= self->length - 1) {
719 if (pos >= self->length - 1) {
720 PyObject *tuple, *str;
720 PyObject *tuple, *str;
721 tuple = PyList_GET_ITEM(self->added, pos - self->length + 1);
721 tuple = PyList_GET_ITEM(self->added, pos - self->length + 1);
722 str = PyTuple_GetItem(tuple, 7);
722 str = PyTuple_GetItem(tuple, 7);
723 return str ? PyString_AS_STRING(str) : NULL;
723 return str ? PyString_AS_STRING(str) : NULL;
724 }
724 }
725
725
726 data = index_deref(self, pos);
726 data = index_deref(self, pos);
727 return data ? data + 32 : NULL;
727 return data ? data + 32 : NULL;
728 }
728 }
729
729
730 static int nt_insert(indexObject *self, const char *node, int rev);
730 static int nt_insert(indexObject *self, const char *node, int rev);
731
731
732 static int node_check(PyObject *obj, char **node, Py_ssize_t *nodelen)
732 static int node_check(PyObject *obj, char **node, Py_ssize_t *nodelen)
733 {
733 {
734 if (PyString_AsStringAndSize(obj, node, nodelen) == -1)
734 if (PyString_AsStringAndSize(obj, node, nodelen) == -1)
735 return -1;
735 return -1;
736 if (*nodelen == 20)
736 if (*nodelen == 20)
737 return 0;
737 return 0;
738 PyErr_SetString(PyExc_ValueError, "20-byte hash required");
738 PyErr_SetString(PyExc_ValueError, "20-byte hash required");
739 return -1;
739 return -1;
740 }
740 }
741
741
742 static PyObject *index_insert(indexObject *self, PyObject *args)
742 static PyObject *index_insert(indexObject *self, PyObject *args)
743 {
743 {
744 PyObject *obj;
744 PyObject *obj;
745 char *node;
745 char *node;
746 int index;
746 int index;
747 Py_ssize_t len, nodelen;
747 Py_ssize_t len, nodelen;
748
748
749 if (!PyArg_ParseTuple(args, "iO", &index, &obj))
749 if (!PyArg_ParseTuple(args, "iO", &index, &obj))
750 return NULL;
750 return NULL;
751
751
752 if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 8) {
752 if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 8) {
753 PyErr_SetString(PyExc_TypeError, "8-tuple required");
753 PyErr_SetString(PyExc_TypeError, "8-tuple required");
754 return NULL;
754 return NULL;
755 }
755 }
756
756
757 if (node_check(PyTuple_GET_ITEM(obj, 7), &node, &nodelen) == -1)
757 if (node_check(PyTuple_GET_ITEM(obj, 7), &node, &nodelen) == -1)
758 return NULL;
758 return NULL;
759
759
760 len = index_length(self);
760 len = index_length(self);
761
761
762 if (index < 0)
762 if (index < 0)
763 index += len;
763 index += len;
764
764
765 if (index != len - 1) {
765 if (index != len - 1) {
766 PyErr_SetString(PyExc_IndexError,
766 PyErr_SetString(PyExc_IndexError,
767 "insert only supported at index -1");
767 "insert only supported at index -1");
768 return NULL;
768 return NULL;
769 }
769 }
770
770
771 if (self->added == NULL) {
771 if (self->added == NULL) {
772 self->added = PyList_New(0);
772 self->added = PyList_New(0);
773 if (self->added == NULL)
773 if (self->added == NULL)
774 return NULL;
774 return NULL;
775 }
775 }
776
776
777 if (PyList_Append(self->added, obj) == -1)
777 if (PyList_Append(self->added, obj) == -1)
778 return NULL;
778 return NULL;
779
779
780 if (self->nt)
780 if (self->nt)
781 nt_insert(self, node, index);
781 nt_insert(self, node, index);
782
782
783 Py_CLEAR(self->headrevs);
783 Py_CLEAR(self->headrevs);
784 Py_RETURN_NONE;
784 Py_RETURN_NONE;
785 }
785 }
786
786
787 static void _index_clearcaches(indexObject *self)
787 static void _index_clearcaches(indexObject *self)
788 {
788 {
789 if (self->cache) {
789 if (self->cache) {
790 Py_ssize_t i;
790 Py_ssize_t i;
791
791
792 for (i = 0; i < self->raw_length; i++)
792 for (i = 0; i < self->raw_length; i++)
793 Py_CLEAR(self->cache[i]);
793 Py_CLEAR(self->cache[i]);
794 free(self->cache);
794 free(self->cache);
795 self->cache = NULL;
795 self->cache = NULL;
796 }
796 }
797 if (self->offsets) {
797 if (self->offsets) {
798 free(self->offsets);
798 free(self->offsets);
799 self->offsets = NULL;
799 self->offsets = NULL;
800 }
800 }
801 if (self->nt) {
801 if (self->nt) {
802 free(self->nt);
802 free(self->nt);
803 self->nt = NULL;
803 self->nt = NULL;
804 }
804 }
805 Py_CLEAR(self->headrevs);
805 Py_CLEAR(self->headrevs);
806 }
806 }
807
807
808 static PyObject *index_clearcaches(indexObject *self)
808 static PyObject *index_clearcaches(indexObject *self)
809 {
809 {
810 _index_clearcaches(self);
810 _index_clearcaches(self);
811 self->ntlength = self->ntcapacity = 0;
811 self->ntlength = self->ntcapacity = 0;
812 self->ntdepth = self->ntsplits = 0;
812 self->ntdepth = self->ntsplits = 0;
813 self->ntrev = -1;
813 self->ntrev = -1;
814 self->ntlookups = self->ntmisses = 0;
814 self->ntlookups = self->ntmisses = 0;
815 Py_RETURN_NONE;
815 Py_RETURN_NONE;
816 }
816 }
817
817
818 static PyObject *index_stats(indexObject *self)
818 static PyObject *index_stats(indexObject *self)
819 {
819 {
820 PyObject *obj = PyDict_New();
820 PyObject *obj = PyDict_New();
821 PyObject *t = NULL;
821 PyObject *t = NULL;
822
822
823 if (obj == NULL)
823 if (obj == NULL)
824 return NULL;
824 return NULL;
825
825
826 #define istat(__n, __d) \
826 #define istat(__n, __d) \
827 t = PyInt_FromSsize_t(self->__n); \
827 t = PyInt_FromSsize_t(self->__n); \
828 if (!t) \
828 if (!t) \
829 goto bail; \
829 goto bail; \
830 if (PyDict_SetItemString(obj, __d, t) == -1) \
830 if (PyDict_SetItemString(obj, __d, t) == -1) \
831 goto bail; \
831 goto bail; \
832 Py_DECREF(t);
832 Py_DECREF(t);
833
833
834 if (self->added) {
834 if (self->added) {
835 Py_ssize_t len = PyList_GET_SIZE(self->added);
835 Py_ssize_t len = PyList_GET_SIZE(self->added);
836 t = PyInt_FromSsize_t(len);
836 t = PyInt_FromSsize_t(len);
837 if (!t)
837 if (!t)
838 goto bail;
838 goto bail;
839 if (PyDict_SetItemString(obj, "index entries added", t) == -1)
839 if (PyDict_SetItemString(obj, "index entries added", t) == -1)
840 goto bail;
840 goto bail;
841 Py_DECREF(t);
841 Py_DECREF(t);
842 }
842 }
843
843
844 if (self->raw_length != self->length - 1)
844 if (self->raw_length != self->length - 1)
845 istat(raw_length, "revs on disk");
845 istat(raw_length, "revs on disk");
846 istat(length, "revs in memory");
846 istat(length, "revs in memory");
847 istat(ntcapacity, "node trie capacity");
847 istat(ntcapacity, "node trie capacity");
848 istat(ntdepth, "node trie depth");
848 istat(ntdepth, "node trie depth");
849 istat(ntlength, "node trie count");
849 istat(ntlength, "node trie count");
850 istat(ntlookups, "node trie lookups");
850 istat(ntlookups, "node trie lookups");
851 istat(ntmisses, "node trie misses");
851 istat(ntmisses, "node trie misses");
852 istat(ntrev, "node trie last rev scanned");
852 istat(ntrev, "node trie last rev scanned");
853 istat(ntsplits, "node trie splits");
853 istat(ntsplits, "node trie splits");
854
854
855 #undef istat
855 #undef istat
856
856
857 return obj;
857 return obj;
858
858
859 bail:
859 bail:
860 Py_XDECREF(obj);
860 Py_XDECREF(obj);
861 Py_XDECREF(t);
861 Py_XDECREF(t);
862 return NULL;
862 return NULL;
863 }
863 }
864
864
865 /*
865 /*
866 * When we cache a list, we want to be sure the caller can't mutate
866 * When we cache a list, we want to be sure the caller can't mutate
867 * the cached copy.
867 * the cached copy.
868 */
868 */
869 static PyObject *list_copy(PyObject *list)
869 static PyObject *list_copy(PyObject *list)
870 {
870 {
871 Py_ssize_t len = PyList_GET_SIZE(list);
871 Py_ssize_t len = PyList_GET_SIZE(list);
872 PyObject *newlist = PyList_New(len);
872 PyObject *newlist = PyList_New(len);
873 Py_ssize_t i;
873 Py_ssize_t i;
874
874
875 if (newlist == NULL)
875 if (newlist == NULL)
876 return NULL;
876 return NULL;
877
877
878 for (i = 0; i < len; i++) {
878 for (i = 0; i < len; i++) {
879 PyObject *obj = PyList_GET_ITEM(list, i);
879 PyObject *obj = PyList_GET_ITEM(list, i);
880 Py_INCREF(obj);
880 Py_INCREF(obj);
881 PyList_SET_ITEM(newlist, i, obj);
881 PyList_SET_ITEM(newlist, i, obj);
882 }
882 }
883
883
884 return newlist;
884 return newlist;
885 }
885 }
886
886
887 /* arg should be Py_ssize_t but Python 2.4 do not support the n format */
887 /* arg should be Py_ssize_t but Python 2.4 do not support the n format */
888 static int check_filter(PyObject *filter, unsigned long arg) {
888 static int check_filter(PyObject *filter, unsigned long arg) {
889 if (filter) {
889 if (filter) {
890 PyObject *arglist, *result;
890 PyObject *arglist, *result;
891 int isfiltered;
891 int isfiltered;
892
892
893 arglist = Py_BuildValue("(k)", arg);
893 arglist = Py_BuildValue("(k)", arg);
894 if (!arglist) {
894 if (!arglist) {
895 return -1;
895 return -1;
896 }
896 }
897
897
898 result = PyEval_CallObject(filter, arglist);
898 result = PyEval_CallObject(filter, arglist);
899 Py_DECREF(arglist);
899 Py_DECREF(arglist);
900 if (!result) {
900 if (!result) {
901 return -1;
901 return -1;
902 }
902 }
903
903
904 /* PyObject_IsTrue returns 1 if true, 0 if false, -1 if error,
904 /* PyObject_IsTrue returns 1 if true, 0 if false, -1 if error,
905 * same as this function, so we can just return it directly.*/
905 * same as this function, so we can just return it directly.*/
906 isfiltered = PyObject_IsTrue(result);
906 isfiltered = PyObject_IsTrue(result);
907 Py_DECREF(result);
907 Py_DECREF(result);
908 return isfiltered;
908 return isfiltered;
909 } else {
909 } else {
910 return 0;
910 return 0;
911 }
911 }
912 }
912 }
913
913
914 static Py_ssize_t add_roots_get_min(indexObject *self, PyObject *list,
914 static Py_ssize_t add_roots_get_min(indexObject *self, PyObject *list,
915 int marker, char *phases)
915 Py_ssize_t marker, char *phases)
916 {
916 {
917 PyObject *iter = NULL;
917 PyObject *iter = NULL;
918 PyObject *iter_item = NULL;
918 PyObject *iter_item = NULL;
919 Py_ssize_t min_idx = index_length(self) + 1;
919 Py_ssize_t min_idx = index_length(self) + 1;
920 long iter_item_long;
920 long iter_item_long;
921
921
922 if (PyList_GET_SIZE(list) != 0) {
922 if (PyList_GET_SIZE(list) != 0) {
923 iter = PyObject_GetIter(list);
923 iter = PyObject_GetIter(list);
924 if (iter == NULL)
924 if (iter == NULL)
925 return -2;
925 return -2;
926 while ((iter_item = PyIter_Next(iter)))
926 while ((iter_item = PyIter_Next(iter)))
927 {
927 {
928 iter_item_long = PyInt_AS_LONG(iter_item);
928 iter_item_long = PyInt_AS_LONG(iter_item);
929 Py_DECREF(iter_item);
929 Py_DECREF(iter_item);
930 if (iter_item_long < min_idx)
930 if (iter_item_long < min_idx)
931 min_idx = iter_item_long;
931 min_idx = iter_item_long;
932 phases[iter_item_long] = marker;
932 phases[iter_item_long] = marker;
933 }
933 }
934 Py_DECREF(iter);
934 Py_DECREF(iter);
935 }
935 }
936
936
937 return min_idx;
937 return min_idx;
938 }
938 }
939
939
940 static inline void set_phase_from_parents(char *phases, int parent_1,
940 static inline void set_phase_from_parents(char *phases, int parent_1,
941 int parent_2, int i)
941 int parent_2, Py_ssize_t i)
942 {
942 {
943 if (parent_1 >= 0 && phases[parent_1] > phases[i])
943 if (parent_1 >= 0 && phases[parent_1] > phases[i])
944 phases[i] = phases[parent_1];
944 phases[i] = phases[parent_1];
945 if (parent_2 >= 0 && phases[parent_2] > phases[i])
945 if (parent_2 >= 0 && phases[parent_2] > phases[i])
946 phases[i] = phases[parent_2];
946 phases[i] = phases[parent_2];
947 }
947 }
948
948
949 static PyObject *compute_phases(indexObject *self, PyObject *args)
949 static PyObject *compute_phases(indexObject *self, PyObject *args)
950 {
950 {
951 PyObject *roots = Py_None;
951 PyObject *roots = Py_None;
952 PyObject *phaseslist = NULL;
952 PyObject *phaseslist = NULL;
953 PyObject *phaseroots = NULL;
953 PyObject *phaseroots = NULL;
954 PyObject *rev = NULL;
954 PyObject *rev = NULL;
955 PyObject *p1 = NULL;
955 PyObject *p1 = NULL;
956 PyObject *p2 = NULL;
956 PyObject *p2 = NULL;
957 Py_ssize_t addlen = self->added ? PyList_GET_SIZE(self->added) : 0;
957 Py_ssize_t addlen = self->added ? PyList_GET_SIZE(self->added) : 0;
958 Py_ssize_t len = index_length(self) - 1;
958 Py_ssize_t len = index_length(self) - 1;
959 Py_ssize_t numphase = 0;
959 Py_ssize_t numphase = 0;
960 Py_ssize_t minrevallphases = 0;
960 Py_ssize_t minrevallphases = 0;
961 Py_ssize_t minrevphase = 0;
961 Py_ssize_t minrevphase = 0;
962 Py_ssize_t i = 0;
962 Py_ssize_t i = 0;
963 long parent_1, parent_2;
963 int parent_1, parent_2;
964 char *phases = NULL;
964 char *phases = NULL;
965 const char *data;
965 const char *data;
966
966
967 if (!PyArg_ParseTuple(args, "O", &roots))
967 if (!PyArg_ParseTuple(args, "O", &roots))
968 goto release_none;
968 goto release_none;
969 if (roots == NULL || !PyList_Check(roots))
969 if (roots == NULL || !PyList_Check(roots))
970 goto release_none;
970 goto release_none;
971
971
972 phases = calloc(len, 1); /* phase per rev: {0: public, 1: draft, 2: secret} */
972 phases = calloc(len, 1); /* phase per rev: {0: public, 1: draft, 2: secret} */
973 if (phases == NULL)
973 if (phases == NULL)
974 goto release_none;
974 goto release_none;
975 /* Put the phase information of all the roots in phases */
975 /* Put the phase information of all the roots in phases */
976 numphase = PyList_GET_SIZE(roots)+1;
976 numphase = PyList_GET_SIZE(roots)+1;
977 minrevallphases = len + 1;
977 minrevallphases = len + 1;
978 for (i = 0; i < numphase-1; i++) {
978 for (i = 0; i < numphase-1; i++) {
979 phaseroots = PyList_GET_ITEM(roots, i);
979 phaseroots = PyList_GET_ITEM(roots, i);
980 if (!PyList_Check(phaseroots))
980 if (!PyList_Check(phaseroots))
981 goto release_phases;
981 goto release_phases;
982 minrevphase = add_roots_get_min(self, phaseroots, i+1, phases);
982 minrevphase = add_roots_get_min(self, phaseroots, i+1, phases);
983 if (minrevphase == -2) /* Error from add_roots_get_min */
983 if (minrevphase == -2) /* Error from add_roots_get_min */
984 goto release_phases;
984 goto release_phases;
985 minrevallphases = MIN(minrevallphases, minrevphase);
985 minrevallphases = MIN(minrevallphases, minrevphase);
986 }
986 }
987 /* Propagate the phase information from the roots to the revs */
987 /* Propagate the phase information from the roots to the revs */
988 if (minrevallphases != -1) {
988 if (minrevallphases != -1) {
989 for (i = minrevallphases; i < self->raw_length; i++) {
989 for (i = minrevallphases; i < self->raw_length; i++) {
990 data = index_deref(self, i);
990 data = index_deref(self, i);
991 set_phase_from_parents(phases, getbe32(data+24), getbe32(data+28), i);
991 set_phase_from_parents(phases, getbe32(data+24), getbe32(data+28), i);
992 }
992 }
993 for (i = 0; i < addlen; i++) {
993 for (i = 0; i < addlen; i++) {
994 rev = PyList_GET_ITEM(self->added, i);
994 rev = PyList_GET_ITEM(self->added, i);
995 p1 = PyTuple_GET_ITEM(rev, 5);
995 p1 = PyTuple_GET_ITEM(rev, 5);
996 p2 = PyTuple_GET_ITEM(rev, 6);
996 p2 = PyTuple_GET_ITEM(rev, 6);
997 if (!PyInt_Check(p1) || !PyInt_Check(p2)) {
997 if (!PyInt_Check(p1) || !PyInt_Check(p2)) {
998 PyErr_SetString(PyExc_TypeError, "revlog parents are invalid");
998 PyErr_SetString(PyExc_TypeError, "revlog parents are invalid");
999 goto release_phases;
999 goto release_phases;
1000 }
1000 }
1001 parent_1 = PyInt_AS_LONG(p1);
1001 parent_1 = (int)PyInt_AS_LONG(p1);
1002 parent_2 = PyInt_AS_LONG(p2);
1002 parent_2 = (int)PyInt_AS_LONG(p2);
1003 set_phase_from_parents(phases, parent_1, parent_2, i+self->raw_length);
1003 set_phase_from_parents(phases, parent_1, parent_2, i+self->raw_length);
1004 }
1004 }
1005 }
1005 }
1006 /* Transform phase list to a python list */
1006 /* Transform phase list to a python list */
1007 phaseslist = PyList_New(len);
1007 phaseslist = PyList_New(len);
1008 if (phaseslist == NULL)
1008 if (phaseslist == NULL)
1009 goto release_phases;
1009 goto release_phases;
1010 for (i = 0; i < len; i++)
1010 for (i = 0; i < len; i++)
1011 PyList_SET_ITEM(phaseslist, i, PyInt_FromLong(phases[i]));
1011 PyList_SET_ITEM(phaseslist, i, PyInt_FromLong(phases[i]));
1012
1012
1013 release_phases:
1013 release_phases:
1014 free(phases);
1014 free(phases);
1015 release_none:
1015 release_none:
1016 return phaseslist;
1016 return phaseslist;
1017 }
1017 }
1018
1018
1019 static PyObject *index_headrevs(indexObject *self, PyObject *args)
1019 static PyObject *index_headrevs(indexObject *self, PyObject *args)
1020 {
1020 {
1021 Py_ssize_t i, len, addlen;
1021 Py_ssize_t i, len, addlen;
1022 char *nothead = NULL;
1022 char *nothead = NULL;
1023 PyObject *heads = NULL;
1023 PyObject *heads = NULL;
1024 PyObject *filter = NULL;
1024 PyObject *filter = NULL;
1025 PyObject *filteredrevs = Py_None;
1025 PyObject *filteredrevs = Py_None;
1026
1026
1027 if (!PyArg_ParseTuple(args, "|O", &filteredrevs)) {
1027 if (!PyArg_ParseTuple(args, "|O", &filteredrevs)) {
1028 return NULL;
1028 return NULL;
1029 }
1029 }
1030
1030
1031 if (self->headrevs && filteredrevs == self->filteredrevs)
1031 if (self->headrevs && filteredrevs == self->filteredrevs)
1032 return list_copy(self->headrevs);
1032 return list_copy(self->headrevs);
1033
1033
1034 Py_DECREF(self->filteredrevs);
1034 Py_DECREF(self->filteredrevs);
1035 self->filteredrevs = filteredrevs;
1035 self->filteredrevs = filteredrevs;
1036 Py_INCREF(filteredrevs);
1036 Py_INCREF(filteredrevs);
1037
1037
1038 if (filteredrevs != Py_None) {
1038 if (filteredrevs != Py_None) {
1039 filter = PyObject_GetAttrString(filteredrevs, "__contains__");
1039 filter = PyObject_GetAttrString(filteredrevs, "__contains__");
1040 if (!filter) {
1040 if (!filter) {
1041 PyErr_SetString(PyExc_TypeError,
1041 PyErr_SetString(PyExc_TypeError,
1042 "filteredrevs has no attribute __contains__");
1042 "filteredrevs has no attribute __contains__");
1043 goto bail;
1043 goto bail;
1044 }
1044 }
1045 }
1045 }
1046
1046
1047 len = index_length(self) - 1;
1047 len = index_length(self) - 1;
1048 heads = PyList_New(0);
1048 heads = PyList_New(0);
1049 if (heads == NULL)
1049 if (heads == NULL)
1050 goto bail;
1050 goto bail;
1051 if (len == 0) {
1051 if (len == 0) {
1052 PyObject *nullid = PyInt_FromLong(-1);
1052 PyObject *nullid = PyInt_FromLong(-1);
1053 if (nullid == NULL || PyList_Append(heads, nullid) == -1) {
1053 if (nullid == NULL || PyList_Append(heads, nullid) == -1) {
1054 Py_XDECREF(nullid);
1054 Py_XDECREF(nullid);
1055 goto bail;
1055 goto bail;
1056 }
1056 }
1057 goto done;
1057 goto done;
1058 }
1058 }
1059
1059
1060 nothead = calloc(len, 1);
1060 nothead = calloc(len, 1);
1061 if (nothead == NULL)
1061 if (nothead == NULL)
1062 goto bail;
1062 goto bail;
1063
1063
1064 for (i = 0; i < self->raw_length; i++) {
1064 for (i = 0; i < self->raw_length; i++) {
1065 const char *data;
1065 const char *data;
1066 int parent_1, parent_2, isfiltered;
1066 int parent_1, parent_2, isfiltered;
1067
1067
1068 isfiltered = check_filter(filter, i);
1068 isfiltered = check_filter(filter, i);
1069 if (isfiltered == -1) {
1069 if (isfiltered == -1) {
1070 PyErr_SetString(PyExc_TypeError,
1070 PyErr_SetString(PyExc_TypeError,
1071 "unable to check filter");
1071 "unable to check filter");
1072 goto bail;
1072 goto bail;
1073 }
1073 }
1074
1074
1075 if (isfiltered) {
1075 if (isfiltered) {
1076 nothead[i] = 1;
1076 nothead[i] = 1;
1077 continue;
1077 continue;
1078 }
1078 }
1079
1079
1080 data = index_deref(self, i);
1080 data = index_deref(self, i);
1081 parent_1 = getbe32(data + 24);
1081 parent_1 = getbe32(data + 24);
1082 parent_2 = getbe32(data + 28);
1082 parent_2 = getbe32(data + 28);
1083
1083
1084 if (parent_1 >= 0)
1084 if (parent_1 >= 0)
1085 nothead[parent_1] = 1;
1085 nothead[parent_1] = 1;
1086 if (parent_2 >= 0)
1086 if (parent_2 >= 0)
1087 nothead[parent_2] = 1;
1087 nothead[parent_2] = 1;
1088 }
1088 }
1089
1089
1090 addlen = self->added ? PyList_GET_SIZE(self->added) : 0;
1090 addlen = self->added ? PyList_GET_SIZE(self->added) : 0;
1091
1091
1092 for (i = 0; i < addlen; i++) {
1092 for (i = 0; i < addlen; i++) {
1093 PyObject *rev = PyList_GET_ITEM(self->added, i);
1093 PyObject *rev = PyList_GET_ITEM(self->added, i);
1094 PyObject *p1 = PyTuple_GET_ITEM(rev, 5);
1094 PyObject *p1 = PyTuple_GET_ITEM(rev, 5);
1095 PyObject *p2 = PyTuple_GET_ITEM(rev, 6);
1095 PyObject *p2 = PyTuple_GET_ITEM(rev, 6);
1096 long parent_1, parent_2;
1096 long parent_1, parent_2;
1097 int isfiltered;
1097 int isfiltered;
1098
1098
1099 if (!PyInt_Check(p1) || !PyInt_Check(p2)) {
1099 if (!PyInt_Check(p1) || !PyInt_Check(p2)) {
1100 PyErr_SetString(PyExc_TypeError,
1100 PyErr_SetString(PyExc_TypeError,
1101 "revlog parents are invalid");
1101 "revlog parents are invalid");
1102 goto bail;
1102 goto bail;
1103 }
1103 }
1104
1104
1105 isfiltered = check_filter(filter, i);
1105 isfiltered = check_filter(filter, i);
1106 if (isfiltered == -1) {
1106 if (isfiltered == -1) {
1107 PyErr_SetString(PyExc_TypeError,
1107 PyErr_SetString(PyExc_TypeError,
1108 "unable to check filter");
1108 "unable to check filter");
1109 goto bail;
1109 goto bail;
1110 }
1110 }
1111
1111
1112 if (isfiltered) {
1112 if (isfiltered) {
1113 nothead[i] = 1;
1113 nothead[i] = 1;
1114 continue;
1114 continue;
1115 }
1115 }
1116
1116
1117 parent_1 = PyInt_AS_LONG(p1);
1117 parent_1 = PyInt_AS_LONG(p1);
1118 parent_2 = PyInt_AS_LONG(p2);
1118 parent_2 = PyInt_AS_LONG(p2);
1119 if (parent_1 >= 0)
1119 if (parent_1 >= 0)
1120 nothead[parent_1] = 1;
1120 nothead[parent_1] = 1;
1121 if (parent_2 >= 0)
1121 if (parent_2 >= 0)
1122 nothead[parent_2] = 1;
1122 nothead[parent_2] = 1;
1123 }
1123 }
1124
1124
1125 for (i = 0; i < len; i++) {
1125 for (i = 0; i < len; i++) {
1126 PyObject *head;
1126 PyObject *head;
1127
1127
1128 if (nothead[i])
1128 if (nothead[i])
1129 continue;
1129 continue;
1130 head = PyInt_FromSsize_t(i);
1130 head = PyInt_FromSsize_t(i);
1131 if (head == NULL || PyList_Append(heads, head) == -1) {
1131 if (head == NULL || PyList_Append(heads, head) == -1) {
1132 Py_XDECREF(head);
1132 Py_XDECREF(head);
1133 goto bail;
1133 goto bail;
1134 }
1134 }
1135 }
1135 }
1136
1136
1137 done:
1137 done:
1138 self->headrevs = heads;
1138 self->headrevs = heads;
1139 Py_XDECREF(filter);
1139 Py_XDECREF(filter);
1140 free(nothead);
1140 free(nothead);
1141 return list_copy(self->headrevs);
1141 return list_copy(self->headrevs);
1142 bail:
1142 bail:
1143 Py_XDECREF(filter);
1143 Py_XDECREF(filter);
1144 Py_XDECREF(heads);
1144 Py_XDECREF(heads);
1145 free(nothead);
1145 free(nothead);
1146 return NULL;
1146 return NULL;
1147 }
1147 }
1148
1148
1149 static inline int nt_level(const char *node, Py_ssize_t level)
1149 static inline int nt_level(const char *node, Py_ssize_t level)
1150 {
1150 {
1151 int v = node[level>>1];
1151 int v = node[level>>1];
1152 if (!(level & 1))
1152 if (!(level & 1))
1153 v >>= 4;
1153 v >>= 4;
1154 return v & 0xf;
1154 return v & 0xf;
1155 }
1155 }
1156
1156
1157 /*
1157 /*
1158 * Return values:
1158 * Return values:
1159 *
1159 *
1160 * -4: match is ambiguous (multiple candidates)
1160 * -4: match is ambiguous (multiple candidates)
1161 * -2: not found
1161 * -2: not found
1162 * rest: valid rev
1162 * rest: valid rev
1163 */
1163 */
1164 static int nt_find(indexObject *self, const char *node, Py_ssize_t nodelen,
1164 static int nt_find(indexObject *self, const char *node, Py_ssize_t nodelen,
1165 int hex)
1165 int hex)
1166 {
1166 {
1167 int (*getnybble)(const char *, Py_ssize_t) = hex ? hexdigit : nt_level;
1167 int (*getnybble)(const char *, Py_ssize_t) = hex ? hexdigit : nt_level;
1168 int level, maxlevel, off;
1168 int level, maxlevel, off;
1169
1169
1170 if (nodelen == 20 && node[0] == '\0' && memcmp(node, nullid, 20) == 0)
1170 if (nodelen == 20 && node[0] == '\0' && memcmp(node, nullid, 20) == 0)
1171 return -1;
1171 return -1;
1172
1172
1173 if (self->nt == NULL)
1173 if (self->nt == NULL)
1174 return -2;
1174 return -2;
1175
1175
1176 if (hex)
1176 if (hex)
1177 maxlevel = nodelen > 40 ? 40 : (int)nodelen;
1177 maxlevel = nodelen > 40 ? 40 : (int)nodelen;
1178 else
1178 else
1179 maxlevel = nodelen > 20 ? 40 : ((int)nodelen * 2);
1179 maxlevel = nodelen > 20 ? 40 : ((int)nodelen * 2);
1180
1180
1181 for (level = off = 0; level < maxlevel; level++) {
1181 for (level = off = 0; level < maxlevel; level++) {
1182 int k = getnybble(node, level);
1182 int k = getnybble(node, level);
1183 nodetree *n = &self->nt[off];
1183 nodetree *n = &self->nt[off];
1184 int v = n->children[k];
1184 int v = n->children[k];
1185
1185
1186 if (v < 0) {
1186 if (v < 0) {
1187 const char *n;
1187 const char *n;
1188 Py_ssize_t i;
1188 Py_ssize_t i;
1189
1189
1190 v = -v - 1;
1190 v = -v - 1;
1191 n = index_node(self, v);
1191 n = index_node(self, v);
1192 if (n == NULL)
1192 if (n == NULL)
1193 return -2;
1193 return -2;
1194 for (i = level; i < maxlevel; i++)
1194 for (i = level; i < maxlevel; i++)
1195 if (getnybble(node, i) != nt_level(n, i))
1195 if (getnybble(node, i) != nt_level(n, i))
1196 return -2;
1196 return -2;
1197 return v;
1197 return v;
1198 }
1198 }
1199 if (v == 0)
1199 if (v == 0)
1200 return -2;
1200 return -2;
1201 off = v;
1201 off = v;
1202 }
1202 }
1203 /* multiple matches against an ambiguous prefix */
1203 /* multiple matches against an ambiguous prefix */
1204 return -4;
1204 return -4;
1205 }
1205 }
1206
1206
1207 static int nt_new(indexObject *self)
1207 static int nt_new(indexObject *self)
1208 {
1208 {
1209 if (self->ntlength == self->ntcapacity) {
1209 if (self->ntlength == self->ntcapacity) {
1210 self->ntcapacity *= 2;
1210 self->ntcapacity *= 2;
1211 self->nt = realloc(self->nt,
1211 self->nt = realloc(self->nt,
1212 self->ntcapacity * sizeof(nodetree));
1212 self->ntcapacity * sizeof(nodetree));
1213 if (self->nt == NULL) {
1213 if (self->nt == NULL) {
1214 PyErr_SetString(PyExc_MemoryError, "out of memory");
1214 PyErr_SetString(PyExc_MemoryError, "out of memory");
1215 return -1;
1215 return -1;
1216 }
1216 }
1217 memset(&self->nt[self->ntlength], 0,
1217 memset(&self->nt[self->ntlength], 0,
1218 sizeof(nodetree) * (self->ntcapacity - self->ntlength));
1218 sizeof(nodetree) * (self->ntcapacity - self->ntlength));
1219 }
1219 }
1220 return self->ntlength++;
1220 return self->ntlength++;
1221 }
1221 }
1222
1222
1223 static int nt_insert(indexObject *self, const char *node, int rev)
1223 static int nt_insert(indexObject *self, const char *node, int rev)
1224 {
1224 {
1225 int level = 0;
1225 int level = 0;
1226 int off = 0;
1226 int off = 0;
1227
1227
1228 while (level < 40) {
1228 while (level < 40) {
1229 int k = nt_level(node, level);
1229 int k = nt_level(node, level);
1230 nodetree *n;
1230 nodetree *n;
1231 int v;
1231 int v;
1232
1232
1233 n = &self->nt[off];
1233 n = &self->nt[off];
1234 v = n->children[k];
1234 v = n->children[k];
1235
1235
1236 if (v == 0) {
1236 if (v == 0) {
1237 n->children[k] = -rev - 1;
1237 n->children[k] = -rev - 1;
1238 return 0;
1238 return 0;
1239 }
1239 }
1240 if (v < 0) {
1240 if (v < 0) {
1241 const char *oldnode = index_node(self, -v - 1);
1241 const char *oldnode = index_node(self, -v - 1);
1242 int noff;
1242 int noff;
1243
1243
1244 if (!oldnode || !memcmp(oldnode, node, 20)) {
1244 if (!oldnode || !memcmp(oldnode, node, 20)) {
1245 n->children[k] = -rev - 1;
1245 n->children[k] = -rev - 1;
1246 return 0;
1246 return 0;
1247 }
1247 }
1248 noff = nt_new(self);
1248 noff = nt_new(self);
1249 if (noff == -1)
1249 if (noff == -1)
1250 return -1;
1250 return -1;
1251 /* self->nt may have been changed by realloc */
1251 /* self->nt may have been changed by realloc */
1252 self->nt[off].children[k] = noff;
1252 self->nt[off].children[k] = noff;
1253 off = noff;
1253 off = noff;
1254 n = &self->nt[off];
1254 n = &self->nt[off];
1255 n->children[nt_level(oldnode, ++level)] = v;
1255 n->children[nt_level(oldnode, ++level)] = v;
1256 if (level > self->ntdepth)
1256 if (level > self->ntdepth)
1257 self->ntdepth = level;
1257 self->ntdepth = level;
1258 self->ntsplits += 1;
1258 self->ntsplits += 1;
1259 } else {
1259 } else {
1260 level += 1;
1260 level += 1;
1261 off = v;
1261 off = v;
1262 }
1262 }
1263 }
1263 }
1264
1264
1265 return -1;
1265 return -1;
1266 }
1266 }
1267
1267
1268 static int nt_init(indexObject *self)
1268 static int nt_init(indexObject *self)
1269 {
1269 {
1270 if (self->nt == NULL) {
1270 if (self->nt == NULL) {
1271 if (self->raw_length > INT_MAX) {
1271 if (self->raw_length > INT_MAX) {
1272 PyErr_SetString(PyExc_ValueError, "overflow in nt_init");
1272 PyErr_SetString(PyExc_ValueError, "overflow in nt_init");
1273 return -1;
1273 return -1;
1274 }
1274 }
1275 self->ntcapacity = self->raw_length < 4
1275 self->ntcapacity = self->raw_length < 4
1276 ? 4 : (int)self->raw_length / 2;
1276 ? 4 : (int)self->raw_length / 2;
1277
1277
1278 self->nt = calloc(self->ntcapacity, sizeof(nodetree));
1278 self->nt = calloc(self->ntcapacity, sizeof(nodetree));
1279 if (self->nt == NULL) {
1279 if (self->nt == NULL) {
1280 PyErr_NoMemory();
1280 PyErr_NoMemory();
1281 return -1;
1281 return -1;
1282 }
1282 }
1283 self->ntlength = 1;
1283 self->ntlength = 1;
1284 self->ntrev = (int)index_length(self) - 1;
1284 self->ntrev = (int)index_length(self) - 1;
1285 self->ntlookups = 1;
1285 self->ntlookups = 1;
1286 self->ntmisses = 0;
1286 self->ntmisses = 0;
1287 if (nt_insert(self, nullid, INT_MAX) == -1)
1287 if (nt_insert(self, nullid, INT_MAX) == -1)
1288 return -1;
1288 return -1;
1289 }
1289 }
1290 return 0;
1290 return 0;
1291 }
1291 }
1292
1292
1293 /*
1293 /*
1294 * Return values:
1294 * Return values:
1295 *
1295 *
1296 * -3: error (exception set)
1296 * -3: error (exception set)
1297 * -2: not found (no exception set)
1297 * -2: not found (no exception set)
1298 * rest: valid rev
1298 * rest: valid rev
1299 */
1299 */
1300 static int index_find_node(indexObject *self,
1300 static int index_find_node(indexObject *self,
1301 const char *node, Py_ssize_t nodelen)
1301 const char *node, Py_ssize_t nodelen)
1302 {
1302 {
1303 int rev;
1303 int rev;
1304
1304
1305 self->ntlookups++;
1305 self->ntlookups++;
1306 rev = nt_find(self, node, nodelen, 0);
1306 rev = nt_find(self, node, nodelen, 0);
1307 if (rev >= -1)
1307 if (rev >= -1)
1308 return rev;
1308 return rev;
1309
1309
1310 if (nt_init(self) == -1)
1310 if (nt_init(self) == -1)
1311 return -3;
1311 return -3;
1312
1312
1313 /*
1313 /*
1314 * For the first handful of lookups, we scan the entire index,
1314 * For the first handful of lookups, we scan the entire index,
1315 * and cache only the matching nodes. This optimizes for cases
1315 * and cache only the matching nodes. This optimizes for cases
1316 * like "hg tip", where only a few nodes are accessed.
1316 * like "hg tip", where only a few nodes are accessed.
1317 *
1317 *
1318 * After that, we cache every node we visit, using a single
1318 * After that, we cache every node we visit, using a single
1319 * scan amortized over multiple lookups. This gives the best
1319 * scan amortized over multiple lookups. This gives the best
1320 * bulk performance, e.g. for "hg log".
1320 * bulk performance, e.g. for "hg log".
1321 */
1321 */
1322 if (self->ntmisses++ < 4) {
1322 if (self->ntmisses++ < 4) {
1323 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1323 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1324 const char *n = index_node(self, rev);
1324 const char *n = index_node(self, rev);
1325 if (n == NULL)
1325 if (n == NULL)
1326 return -2;
1326 return -2;
1327 if (memcmp(node, n, nodelen > 20 ? 20 : nodelen) == 0) {
1327 if (memcmp(node, n, nodelen > 20 ? 20 : nodelen) == 0) {
1328 if (nt_insert(self, n, rev) == -1)
1328 if (nt_insert(self, n, rev) == -1)
1329 return -3;
1329 return -3;
1330 break;
1330 break;
1331 }
1331 }
1332 }
1332 }
1333 } else {
1333 } else {
1334 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1334 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1335 const char *n = index_node(self, rev);
1335 const char *n = index_node(self, rev);
1336 if (n == NULL) {
1336 if (n == NULL) {
1337 self->ntrev = rev + 1;
1337 self->ntrev = rev + 1;
1338 return -2;
1338 return -2;
1339 }
1339 }
1340 if (nt_insert(self, n, rev) == -1) {
1340 if (nt_insert(self, n, rev) == -1) {
1341 self->ntrev = rev + 1;
1341 self->ntrev = rev + 1;
1342 return -3;
1342 return -3;
1343 }
1343 }
1344 if (memcmp(node, n, nodelen > 20 ? 20 : nodelen) == 0) {
1344 if (memcmp(node, n, nodelen > 20 ? 20 : nodelen) == 0) {
1345 break;
1345 break;
1346 }
1346 }
1347 }
1347 }
1348 self->ntrev = rev;
1348 self->ntrev = rev;
1349 }
1349 }
1350
1350
1351 if (rev >= 0)
1351 if (rev >= 0)
1352 return rev;
1352 return rev;
1353 return -2;
1353 return -2;
1354 }
1354 }
1355
1355
1356 static PyObject *raise_revlog_error(void)
1356 static PyObject *raise_revlog_error(void)
1357 {
1357 {
1358 static PyObject *errclass;
1358 static PyObject *errclass;
1359 PyObject *mod = NULL, *errobj;
1359 PyObject *mod = NULL, *errobj;
1360
1360
1361 if (errclass == NULL) {
1361 if (errclass == NULL) {
1362 PyObject *dict;
1362 PyObject *dict;
1363
1363
1364 mod = PyImport_ImportModule("mercurial.error");
1364 mod = PyImport_ImportModule("mercurial.error");
1365 if (mod == NULL)
1365 if (mod == NULL)
1366 goto classfail;
1366 goto classfail;
1367
1367
1368 dict = PyModule_GetDict(mod);
1368 dict = PyModule_GetDict(mod);
1369 if (dict == NULL)
1369 if (dict == NULL)
1370 goto classfail;
1370 goto classfail;
1371
1371
1372 errclass = PyDict_GetItemString(dict, "RevlogError");
1372 errclass = PyDict_GetItemString(dict, "RevlogError");
1373 if (errclass == NULL) {
1373 if (errclass == NULL) {
1374 PyErr_SetString(PyExc_SystemError,
1374 PyErr_SetString(PyExc_SystemError,
1375 "could not find RevlogError");
1375 "could not find RevlogError");
1376 goto classfail;
1376 goto classfail;
1377 }
1377 }
1378 Py_INCREF(errclass);
1378 Py_INCREF(errclass);
1379 Py_DECREF(mod);
1379 Py_DECREF(mod);
1380 }
1380 }
1381
1381
1382 errobj = PyObject_CallFunction(errclass, NULL);
1382 errobj = PyObject_CallFunction(errclass, NULL);
1383 if (errobj == NULL)
1383 if (errobj == NULL)
1384 return NULL;
1384 return NULL;
1385 PyErr_SetObject(errclass, errobj);
1385 PyErr_SetObject(errclass, errobj);
1386 return errobj;
1386 return errobj;
1387
1387
1388 classfail:
1388 classfail:
1389 Py_XDECREF(mod);
1389 Py_XDECREF(mod);
1390 return NULL;
1390 return NULL;
1391 }
1391 }
1392
1392
1393 static PyObject *index_getitem(indexObject *self, PyObject *value)
1393 static PyObject *index_getitem(indexObject *self, PyObject *value)
1394 {
1394 {
1395 char *node;
1395 char *node;
1396 Py_ssize_t nodelen;
1396 Py_ssize_t nodelen;
1397 int rev;
1397 int rev;
1398
1398
1399 if (PyInt_Check(value))
1399 if (PyInt_Check(value))
1400 return index_get(self, PyInt_AS_LONG(value));
1400 return index_get(self, PyInt_AS_LONG(value));
1401
1401
1402 if (node_check(value, &node, &nodelen) == -1)
1402 if (node_check(value, &node, &nodelen) == -1)
1403 return NULL;
1403 return NULL;
1404 rev = index_find_node(self, node, nodelen);
1404 rev = index_find_node(self, node, nodelen);
1405 if (rev >= -1)
1405 if (rev >= -1)
1406 return PyInt_FromLong(rev);
1406 return PyInt_FromLong(rev);
1407 if (rev == -2)
1407 if (rev == -2)
1408 raise_revlog_error();
1408 raise_revlog_error();
1409 return NULL;
1409 return NULL;
1410 }
1410 }
1411
1411
1412 static int nt_partialmatch(indexObject *self, const char *node,
1412 static int nt_partialmatch(indexObject *self, const char *node,
1413 Py_ssize_t nodelen)
1413 Py_ssize_t nodelen)
1414 {
1414 {
1415 int rev;
1415 int rev;
1416
1416
1417 if (nt_init(self) == -1)
1417 if (nt_init(self) == -1)
1418 return -3;
1418 return -3;
1419
1419
1420 if (self->ntrev > 0) {
1420 if (self->ntrev > 0) {
1421 /* ensure that the radix tree is fully populated */
1421 /* ensure that the radix tree is fully populated */
1422 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1422 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1423 const char *n = index_node(self, rev);
1423 const char *n = index_node(self, rev);
1424 if (n == NULL)
1424 if (n == NULL)
1425 return -2;
1425 return -2;
1426 if (nt_insert(self, n, rev) == -1)
1426 if (nt_insert(self, n, rev) == -1)
1427 return -3;
1427 return -3;
1428 }
1428 }
1429 self->ntrev = rev;
1429 self->ntrev = rev;
1430 }
1430 }
1431
1431
1432 return nt_find(self, node, nodelen, 1);
1432 return nt_find(self, node, nodelen, 1);
1433 }
1433 }
1434
1434
1435 static PyObject *index_partialmatch(indexObject *self, PyObject *args)
1435 static PyObject *index_partialmatch(indexObject *self, PyObject *args)
1436 {
1436 {
1437 const char *fullnode;
1437 const char *fullnode;
1438 int nodelen;
1438 int nodelen;
1439 char *node;
1439 char *node;
1440 int rev, i;
1440 int rev, i;
1441
1441
1442 if (!PyArg_ParseTuple(args, "s#", &node, &nodelen))
1442 if (!PyArg_ParseTuple(args, "s#", &node, &nodelen))
1443 return NULL;
1443 return NULL;
1444
1444
1445 if (nodelen < 4) {
1445 if (nodelen < 4) {
1446 PyErr_SetString(PyExc_ValueError, "key too short");
1446 PyErr_SetString(PyExc_ValueError, "key too short");
1447 return NULL;
1447 return NULL;
1448 }
1448 }
1449
1449
1450 if (nodelen > 40) {
1450 if (nodelen > 40) {
1451 PyErr_SetString(PyExc_ValueError, "key too long");
1451 PyErr_SetString(PyExc_ValueError, "key too long");
1452 return NULL;
1452 return NULL;
1453 }
1453 }
1454
1454
1455 for (i = 0; i < nodelen; i++)
1455 for (i = 0; i < nodelen; i++)
1456 hexdigit(node, i);
1456 hexdigit(node, i);
1457 if (PyErr_Occurred()) {
1457 if (PyErr_Occurred()) {
1458 /* input contains non-hex characters */
1458 /* input contains non-hex characters */
1459 PyErr_Clear();
1459 PyErr_Clear();
1460 Py_RETURN_NONE;
1460 Py_RETURN_NONE;
1461 }
1461 }
1462
1462
1463 rev = nt_partialmatch(self, node, nodelen);
1463 rev = nt_partialmatch(self, node, nodelen);
1464
1464
1465 switch (rev) {
1465 switch (rev) {
1466 case -4:
1466 case -4:
1467 raise_revlog_error();
1467 raise_revlog_error();
1468 case -3:
1468 case -3:
1469 return NULL;
1469 return NULL;
1470 case -2:
1470 case -2:
1471 Py_RETURN_NONE;
1471 Py_RETURN_NONE;
1472 case -1:
1472 case -1:
1473 return PyString_FromStringAndSize(nullid, 20);
1473 return PyString_FromStringAndSize(nullid, 20);
1474 }
1474 }
1475
1475
1476 fullnode = index_node(self, rev);
1476 fullnode = index_node(self, rev);
1477 if (fullnode == NULL) {
1477 if (fullnode == NULL) {
1478 PyErr_Format(PyExc_IndexError,
1478 PyErr_Format(PyExc_IndexError,
1479 "could not access rev %d", rev);
1479 "could not access rev %d", rev);
1480 return NULL;
1480 return NULL;
1481 }
1481 }
1482 return PyString_FromStringAndSize(fullnode, 20);
1482 return PyString_FromStringAndSize(fullnode, 20);
1483 }
1483 }
1484
1484
1485 static PyObject *index_m_get(indexObject *self, PyObject *args)
1485 static PyObject *index_m_get(indexObject *self, PyObject *args)
1486 {
1486 {
1487 Py_ssize_t nodelen;
1487 Py_ssize_t nodelen;
1488 PyObject *val;
1488 PyObject *val;
1489 char *node;
1489 char *node;
1490 int rev;
1490 int rev;
1491
1491
1492 if (!PyArg_ParseTuple(args, "O", &val))
1492 if (!PyArg_ParseTuple(args, "O", &val))
1493 return NULL;
1493 return NULL;
1494 if (node_check(val, &node, &nodelen) == -1)
1494 if (node_check(val, &node, &nodelen) == -1)
1495 return NULL;
1495 return NULL;
1496 rev = index_find_node(self, node, nodelen);
1496 rev = index_find_node(self, node, nodelen);
1497 if (rev == -3)
1497 if (rev == -3)
1498 return NULL;
1498 return NULL;
1499 if (rev == -2)
1499 if (rev == -2)
1500 Py_RETURN_NONE;
1500 Py_RETURN_NONE;
1501 return PyInt_FromLong(rev);
1501 return PyInt_FromLong(rev);
1502 }
1502 }
1503
1503
1504 static int index_contains(indexObject *self, PyObject *value)
1504 static int index_contains(indexObject *self, PyObject *value)
1505 {
1505 {
1506 char *node;
1506 char *node;
1507 Py_ssize_t nodelen;
1507 Py_ssize_t nodelen;
1508
1508
1509 if (PyInt_Check(value)) {
1509 if (PyInt_Check(value)) {
1510 long rev = PyInt_AS_LONG(value);
1510 long rev = PyInt_AS_LONG(value);
1511 return rev >= -1 && rev < index_length(self);
1511 return rev >= -1 && rev < index_length(self);
1512 }
1512 }
1513
1513
1514 if (node_check(value, &node, &nodelen) == -1)
1514 if (node_check(value, &node, &nodelen) == -1)
1515 return -1;
1515 return -1;
1516
1516
1517 switch (index_find_node(self, node, nodelen)) {
1517 switch (index_find_node(self, node, nodelen)) {
1518 case -3:
1518 case -3:
1519 return -1;
1519 return -1;
1520 case -2:
1520 case -2:
1521 return 0;
1521 return 0;
1522 default:
1522 default:
1523 return 1;
1523 return 1;
1524 }
1524 }
1525 }
1525 }
1526
1526
1527 static inline void index_get_parents(indexObject *self, int rev, int *ps)
1527 static inline void index_get_parents(indexObject *self, int rev, int *ps)
1528 {
1528 {
1529 if (rev >= self->length - 1) {
1529 if (rev >= self->length - 1) {
1530 PyObject *tuple = PyList_GET_ITEM(self->added,
1530 PyObject *tuple = PyList_GET_ITEM(self->added,
1531 rev - self->length + 1);
1531 rev - self->length + 1);
1532 ps[0] = (int)PyInt_AS_LONG(PyTuple_GET_ITEM(tuple, 5));
1532 ps[0] = (int)PyInt_AS_LONG(PyTuple_GET_ITEM(tuple, 5));
1533 ps[1] = (int)PyInt_AS_LONG(PyTuple_GET_ITEM(tuple, 6));
1533 ps[1] = (int)PyInt_AS_LONG(PyTuple_GET_ITEM(tuple, 6));
1534 } else {
1534 } else {
1535 const char *data = index_deref(self, rev);
1535 const char *data = index_deref(self, rev);
1536 ps[0] = getbe32(data + 24);
1536 ps[0] = getbe32(data + 24);
1537 ps[1] = getbe32(data + 28);
1537 ps[1] = getbe32(data + 28);
1538 }
1538 }
1539 }
1539 }
1540
1540
1541 typedef uint64_t bitmask;
1541 typedef uint64_t bitmask;
1542
1542
1543 /*
1543 /*
1544 * Given a disjoint set of revs, return all candidates for the
1544 * Given a disjoint set of revs, return all candidates for the
1545 * greatest common ancestor. In revset notation, this is the set
1545 * greatest common ancestor. In revset notation, this is the set
1546 * "heads(::a and ::b and ...)"
1546 * "heads(::a and ::b and ...)"
1547 */
1547 */
1548 static PyObject *find_gca_candidates(indexObject *self, const int *revs,
1548 static PyObject *find_gca_candidates(indexObject *self, const int *revs,
1549 int revcount)
1549 int revcount)
1550 {
1550 {
1551 const bitmask allseen = (1ull << revcount) - 1;
1551 const bitmask allseen = (1ull << revcount) - 1;
1552 const bitmask poison = 1ull << revcount;
1552 const bitmask poison = 1ull << revcount;
1553 PyObject *gca = PyList_New(0);
1553 PyObject *gca = PyList_New(0);
1554 int i, v, interesting;
1554 int i, v, interesting;
1555 int maxrev = -1;
1555 int maxrev = -1;
1556 bitmask sp;
1556 bitmask sp;
1557 bitmask *seen;
1557 bitmask *seen;
1558
1558
1559 if (gca == NULL)
1559 if (gca == NULL)
1560 return PyErr_NoMemory();
1560 return PyErr_NoMemory();
1561
1561
1562 for (i = 0; i < revcount; i++) {
1562 for (i = 0; i < revcount; i++) {
1563 if (revs[i] > maxrev)
1563 if (revs[i] > maxrev)
1564 maxrev = revs[i];
1564 maxrev = revs[i];
1565 }
1565 }
1566
1566
1567 seen = calloc(sizeof(*seen), maxrev + 1);
1567 seen = calloc(sizeof(*seen), maxrev + 1);
1568 if (seen == NULL) {
1568 if (seen == NULL) {
1569 Py_DECREF(gca);
1569 Py_DECREF(gca);
1570 return PyErr_NoMemory();
1570 return PyErr_NoMemory();
1571 }
1571 }
1572
1572
1573 for (i = 0; i < revcount; i++)
1573 for (i = 0; i < revcount; i++)
1574 seen[revs[i]] = 1ull << i;
1574 seen[revs[i]] = 1ull << i;
1575
1575
1576 interesting = revcount;
1576 interesting = revcount;
1577
1577
1578 for (v = maxrev; v >= 0 && interesting; v--) {
1578 for (v = maxrev; v >= 0 && interesting; v--) {
1579 bitmask sv = seen[v];
1579 bitmask sv = seen[v];
1580 int parents[2];
1580 int parents[2];
1581
1581
1582 if (!sv)
1582 if (!sv)
1583 continue;
1583 continue;
1584
1584
1585 if (sv < poison) {
1585 if (sv < poison) {
1586 interesting -= 1;
1586 interesting -= 1;
1587 if (sv == allseen) {
1587 if (sv == allseen) {
1588 PyObject *obj = PyInt_FromLong(v);
1588 PyObject *obj = PyInt_FromLong(v);
1589 if (obj == NULL)
1589 if (obj == NULL)
1590 goto bail;
1590 goto bail;
1591 if (PyList_Append(gca, obj) == -1) {
1591 if (PyList_Append(gca, obj) == -1) {
1592 Py_DECREF(obj);
1592 Py_DECREF(obj);
1593 goto bail;
1593 goto bail;
1594 }
1594 }
1595 sv |= poison;
1595 sv |= poison;
1596 for (i = 0; i < revcount; i++) {
1596 for (i = 0; i < revcount; i++) {
1597 if (revs[i] == v)
1597 if (revs[i] == v)
1598 goto done;
1598 goto done;
1599 }
1599 }
1600 }
1600 }
1601 }
1601 }
1602 index_get_parents(self, v, parents);
1602 index_get_parents(self, v, parents);
1603
1603
1604 for (i = 0; i < 2; i++) {
1604 for (i = 0; i < 2; i++) {
1605 int p = parents[i];
1605 int p = parents[i];
1606 if (p == -1)
1606 if (p == -1)
1607 continue;
1607 continue;
1608 sp = seen[p];
1608 sp = seen[p];
1609 if (sv < poison) {
1609 if (sv < poison) {
1610 if (sp == 0) {
1610 if (sp == 0) {
1611 seen[p] = sv;
1611 seen[p] = sv;
1612 interesting++;
1612 interesting++;
1613 }
1613 }
1614 else if (sp != sv)
1614 else if (sp != sv)
1615 seen[p] |= sv;
1615 seen[p] |= sv;
1616 } else {
1616 } else {
1617 if (sp && sp < poison)
1617 if (sp && sp < poison)
1618 interesting--;
1618 interesting--;
1619 seen[p] = sv;
1619 seen[p] = sv;
1620 }
1620 }
1621 }
1621 }
1622 }
1622 }
1623
1623
1624 done:
1624 done:
1625 free(seen);
1625 free(seen);
1626 return gca;
1626 return gca;
1627 bail:
1627 bail:
1628 free(seen);
1628 free(seen);
1629 Py_XDECREF(gca);
1629 Py_XDECREF(gca);
1630 return NULL;
1630 return NULL;
1631 }
1631 }
1632
1632
1633 /*
1633 /*
1634 * Given a disjoint set of revs, return the subset with the longest
1634 * Given a disjoint set of revs, return the subset with the longest
1635 * path to the root.
1635 * path to the root.
1636 */
1636 */
1637 static PyObject *find_deepest(indexObject *self, PyObject *revs)
1637 static PyObject *find_deepest(indexObject *self, PyObject *revs)
1638 {
1638 {
1639 const Py_ssize_t revcount = PyList_GET_SIZE(revs);
1639 const Py_ssize_t revcount = PyList_GET_SIZE(revs);
1640 static const Py_ssize_t capacity = 24;
1640 static const Py_ssize_t capacity = 24;
1641 int *depth, *interesting = NULL;
1641 int *depth, *interesting = NULL;
1642 int i, j, v, ninteresting;
1642 int i, j, v, ninteresting;
1643 PyObject *dict = NULL, *keys = NULL;
1643 PyObject *dict = NULL, *keys = NULL;
1644 long *seen = NULL;
1644 long *seen = NULL;
1645 int maxrev = -1;
1645 int maxrev = -1;
1646 long final;
1646 long final;
1647
1647
1648 if (revcount > capacity) {
1648 if (revcount > capacity) {
1649 PyErr_Format(PyExc_OverflowError,
1649 PyErr_Format(PyExc_OverflowError,
1650 "bitset size (%ld) > capacity (%ld)",
1650 "bitset size (%ld) > capacity (%ld)",
1651 (long)revcount, (long)capacity);
1651 (long)revcount, (long)capacity);
1652 return NULL;
1652 return NULL;
1653 }
1653 }
1654
1654
1655 for (i = 0; i < revcount; i++) {
1655 for (i = 0; i < revcount; i++) {
1656 int n = (int)PyInt_AsLong(PyList_GET_ITEM(revs, i));
1656 int n = (int)PyInt_AsLong(PyList_GET_ITEM(revs, i));
1657 if (n > maxrev)
1657 if (n > maxrev)
1658 maxrev = n;
1658 maxrev = n;
1659 }
1659 }
1660
1660
1661 depth = calloc(sizeof(*depth), maxrev + 1);
1661 depth = calloc(sizeof(*depth), maxrev + 1);
1662 if (depth == NULL)
1662 if (depth == NULL)
1663 return PyErr_NoMemory();
1663 return PyErr_NoMemory();
1664
1664
1665 seen = calloc(sizeof(*seen), maxrev + 1);
1665 seen = calloc(sizeof(*seen), maxrev + 1);
1666 if (seen == NULL) {
1666 if (seen == NULL) {
1667 PyErr_NoMemory();
1667 PyErr_NoMemory();
1668 goto bail;
1668 goto bail;
1669 }
1669 }
1670
1670
1671 interesting = calloc(sizeof(*interesting), 2 << revcount);
1671 interesting = calloc(sizeof(*interesting), 2 << revcount);
1672 if (interesting == NULL) {
1672 if (interesting == NULL) {
1673 PyErr_NoMemory();
1673 PyErr_NoMemory();
1674 goto bail;
1674 goto bail;
1675 }
1675 }
1676
1676
1677 if (PyList_Sort(revs) == -1)
1677 if (PyList_Sort(revs) == -1)
1678 goto bail;
1678 goto bail;
1679
1679
1680 for (i = 0; i < revcount; i++) {
1680 for (i = 0; i < revcount; i++) {
1681 int n = (int)PyInt_AsLong(PyList_GET_ITEM(revs, i));
1681 int n = (int)PyInt_AsLong(PyList_GET_ITEM(revs, i));
1682 long b = 1l << i;
1682 long b = 1l << i;
1683 depth[n] = 1;
1683 depth[n] = 1;
1684 seen[n] = b;
1684 seen[n] = b;
1685 interesting[b] = 1;
1685 interesting[b] = 1;
1686 }
1686 }
1687
1687
1688 ninteresting = (int)revcount;
1688 ninteresting = (int)revcount;
1689
1689
1690 for (v = maxrev; v >= 0 && ninteresting > 1; v--) {
1690 for (v = maxrev; v >= 0 && ninteresting > 1; v--) {
1691 int dv = depth[v];
1691 int dv = depth[v];
1692 int parents[2];
1692 int parents[2];
1693 long sv;
1693 long sv;
1694
1694
1695 if (dv == 0)
1695 if (dv == 0)
1696 continue;
1696 continue;
1697
1697
1698 sv = seen[v];
1698 sv = seen[v];
1699 index_get_parents(self, v, parents);
1699 index_get_parents(self, v, parents);
1700
1700
1701 for (i = 0; i < 2; i++) {
1701 for (i = 0; i < 2; i++) {
1702 int p = parents[i];
1702 int p = parents[i];
1703 long nsp, sp;
1703 long nsp, sp;
1704 int dp;
1704 int dp;
1705
1705
1706 if (p == -1)
1706 if (p == -1)
1707 continue;
1707 continue;
1708
1708
1709 dp = depth[p];
1709 dp = depth[p];
1710 nsp = sp = seen[p];
1710 nsp = sp = seen[p];
1711 if (dp <= dv) {
1711 if (dp <= dv) {
1712 depth[p] = dv + 1;
1712 depth[p] = dv + 1;
1713 if (sp != sv) {
1713 if (sp != sv) {
1714 interesting[sv] += 1;
1714 interesting[sv] += 1;
1715 nsp = seen[p] = sv;
1715 nsp = seen[p] = sv;
1716 if (sp) {
1716 if (sp) {
1717 interesting[sp] -= 1;
1717 interesting[sp] -= 1;
1718 if (interesting[sp] == 0)
1718 if (interesting[sp] == 0)
1719 ninteresting -= 1;
1719 ninteresting -= 1;
1720 }
1720 }
1721 }
1721 }
1722 }
1722 }
1723 else if (dv == dp - 1) {
1723 else if (dv == dp - 1) {
1724 nsp = sp | sv;
1724 nsp = sp | sv;
1725 if (nsp == sp)
1725 if (nsp == sp)
1726 continue;
1726 continue;
1727 seen[p] = nsp;
1727 seen[p] = nsp;
1728 interesting[sp] -= 1;
1728 interesting[sp] -= 1;
1729 if (interesting[sp] == 0 && interesting[nsp] > 0)
1729 if (interesting[sp] == 0 && interesting[nsp] > 0)
1730 ninteresting -= 1;
1730 ninteresting -= 1;
1731 interesting[nsp] += 1;
1731 interesting[nsp] += 1;
1732 }
1732 }
1733 }
1733 }
1734 interesting[sv] -= 1;
1734 interesting[sv] -= 1;
1735 if (interesting[sv] == 0)
1735 if (interesting[sv] == 0)
1736 ninteresting -= 1;
1736 ninteresting -= 1;
1737 }
1737 }
1738
1738
1739 final = 0;
1739 final = 0;
1740 j = ninteresting;
1740 j = ninteresting;
1741 for (i = 0; i < (int)(2 << revcount) && j > 0; i++) {
1741 for (i = 0; i < (int)(2 << revcount) && j > 0; i++) {
1742 if (interesting[i] == 0)
1742 if (interesting[i] == 0)
1743 continue;
1743 continue;
1744 final |= i;
1744 final |= i;
1745 j -= 1;
1745 j -= 1;
1746 }
1746 }
1747 if (final == 0) {
1747 if (final == 0) {
1748 keys = PyList_New(0);
1748 keys = PyList_New(0);
1749 goto bail;
1749 goto bail;
1750 }
1750 }
1751
1751
1752 dict = PyDict_New();
1752 dict = PyDict_New();
1753 if (dict == NULL)
1753 if (dict == NULL)
1754 goto bail;
1754 goto bail;
1755
1755
1756 for (i = 0; i < revcount; i++) {
1756 for (i = 0; i < revcount; i++) {
1757 PyObject *key;
1757 PyObject *key;
1758
1758
1759 if ((final & (1 << i)) == 0)
1759 if ((final & (1 << i)) == 0)
1760 continue;
1760 continue;
1761
1761
1762 key = PyList_GET_ITEM(revs, i);
1762 key = PyList_GET_ITEM(revs, i);
1763 Py_INCREF(key);
1763 Py_INCREF(key);
1764 Py_INCREF(Py_None);
1764 Py_INCREF(Py_None);
1765 if (PyDict_SetItem(dict, key, Py_None) == -1) {
1765 if (PyDict_SetItem(dict, key, Py_None) == -1) {
1766 Py_DECREF(key);
1766 Py_DECREF(key);
1767 Py_DECREF(Py_None);
1767 Py_DECREF(Py_None);
1768 goto bail;
1768 goto bail;
1769 }
1769 }
1770 }
1770 }
1771
1771
1772 keys = PyDict_Keys(dict);
1772 keys = PyDict_Keys(dict);
1773
1773
1774 bail:
1774 bail:
1775 free(depth);
1775 free(depth);
1776 free(seen);
1776 free(seen);
1777 free(interesting);
1777 free(interesting);
1778 Py_XDECREF(dict);
1778 Py_XDECREF(dict);
1779
1779
1780 return keys;
1780 return keys;
1781 }
1781 }
1782
1782
1783 /*
1783 /*
1784 * Given a (possibly overlapping) set of revs, return all the
1784 * Given a (possibly overlapping) set of revs, return all the
1785 * common ancestors heads: heads(::args[0] and ::a[1] and ...)
1785 * common ancestors heads: heads(::args[0] and ::a[1] and ...)
1786 */
1786 */
1787 static PyObject *index_commonancestorsheads(indexObject *self, PyObject *args)
1787 static PyObject *index_commonancestorsheads(indexObject *self, PyObject *args)
1788 {
1788 {
1789 PyObject *ret = NULL;
1789 PyObject *ret = NULL;
1790 Py_ssize_t argcount, i, len;
1790 Py_ssize_t argcount, i, len;
1791 bitmask repeat = 0;
1791 bitmask repeat = 0;
1792 int revcount = 0;
1792 int revcount = 0;
1793 int *revs;
1793 int *revs;
1794
1794
1795 argcount = PySequence_Length(args);
1795 argcount = PySequence_Length(args);
1796 revs = malloc(argcount * sizeof(*revs));
1796 revs = malloc(argcount * sizeof(*revs));
1797 if (argcount > 0 && revs == NULL)
1797 if (argcount > 0 && revs == NULL)
1798 return PyErr_NoMemory();
1798 return PyErr_NoMemory();
1799 len = index_length(self) - 1;
1799 len = index_length(self) - 1;
1800
1800
1801 for (i = 0; i < argcount; i++) {
1801 for (i = 0; i < argcount; i++) {
1802 static const int capacity = 24;
1802 static const int capacity = 24;
1803 PyObject *obj = PySequence_GetItem(args, i);
1803 PyObject *obj = PySequence_GetItem(args, i);
1804 bitmask x;
1804 bitmask x;
1805 long val;
1805 long val;
1806
1806
1807 if (!PyInt_Check(obj)) {
1807 if (!PyInt_Check(obj)) {
1808 PyErr_SetString(PyExc_TypeError,
1808 PyErr_SetString(PyExc_TypeError,
1809 "arguments must all be ints");
1809 "arguments must all be ints");
1810 Py_DECREF(obj);
1810 Py_DECREF(obj);
1811 goto bail;
1811 goto bail;
1812 }
1812 }
1813 val = PyInt_AsLong(obj);
1813 val = PyInt_AsLong(obj);
1814 Py_DECREF(obj);
1814 Py_DECREF(obj);
1815 if (val == -1) {
1815 if (val == -1) {
1816 ret = PyList_New(0);
1816 ret = PyList_New(0);
1817 goto done;
1817 goto done;
1818 }
1818 }
1819 if (val < 0 || val >= len) {
1819 if (val < 0 || val >= len) {
1820 PyErr_SetString(PyExc_IndexError,
1820 PyErr_SetString(PyExc_IndexError,
1821 "index out of range");
1821 "index out of range");
1822 goto bail;
1822 goto bail;
1823 }
1823 }
1824 /* this cheesy bloom filter lets us avoid some more
1824 /* this cheesy bloom filter lets us avoid some more
1825 * expensive duplicate checks in the common set-is-disjoint
1825 * expensive duplicate checks in the common set-is-disjoint
1826 * case */
1826 * case */
1827 x = 1ull << (val & 0x3f);
1827 x = 1ull << (val & 0x3f);
1828 if (repeat & x) {
1828 if (repeat & x) {
1829 int k;
1829 int k;
1830 for (k = 0; k < revcount; k++) {
1830 for (k = 0; k < revcount; k++) {
1831 if (val == revs[k])
1831 if (val == revs[k])
1832 goto duplicate;
1832 goto duplicate;
1833 }
1833 }
1834 }
1834 }
1835 else repeat |= x;
1835 else repeat |= x;
1836 if (revcount >= capacity) {
1836 if (revcount >= capacity) {
1837 PyErr_Format(PyExc_OverflowError,
1837 PyErr_Format(PyExc_OverflowError,
1838 "bitset size (%d) > capacity (%d)",
1838 "bitset size (%d) > capacity (%d)",
1839 revcount, capacity);
1839 revcount, capacity);
1840 goto bail;
1840 goto bail;
1841 }
1841 }
1842 revs[revcount++] = (int)val;
1842 revs[revcount++] = (int)val;
1843 duplicate:;
1843 duplicate:;
1844 }
1844 }
1845
1845
1846 if (revcount == 0) {
1846 if (revcount == 0) {
1847 ret = PyList_New(0);
1847 ret = PyList_New(0);
1848 goto done;
1848 goto done;
1849 }
1849 }
1850 if (revcount == 1) {
1850 if (revcount == 1) {
1851 PyObject *obj;
1851 PyObject *obj;
1852 ret = PyList_New(1);
1852 ret = PyList_New(1);
1853 if (ret == NULL)
1853 if (ret == NULL)
1854 goto bail;
1854 goto bail;
1855 obj = PyInt_FromLong(revs[0]);
1855 obj = PyInt_FromLong(revs[0]);
1856 if (obj == NULL)
1856 if (obj == NULL)
1857 goto bail;
1857 goto bail;
1858 PyList_SET_ITEM(ret, 0, obj);
1858 PyList_SET_ITEM(ret, 0, obj);
1859 goto done;
1859 goto done;
1860 }
1860 }
1861
1861
1862 ret = find_gca_candidates(self, revs, revcount);
1862 ret = find_gca_candidates(self, revs, revcount);
1863 if (ret == NULL)
1863 if (ret == NULL)
1864 goto bail;
1864 goto bail;
1865
1865
1866 done:
1866 done:
1867 free(revs);
1867 free(revs);
1868 return ret;
1868 return ret;
1869
1869
1870 bail:
1870 bail:
1871 free(revs);
1871 free(revs);
1872 Py_XDECREF(ret);
1872 Py_XDECREF(ret);
1873 return NULL;
1873 return NULL;
1874 }
1874 }
1875
1875
1876 /*
1876 /*
1877 * Given a (possibly overlapping) set of revs, return the greatest
1877 * Given a (possibly overlapping) set of revs, return the greatest
1878 * common ancestors: those with the longest path to the root.
1878 * common ancestors: those with the longest path to the root.
1879 */
1879 */
1880 static PyObject *index_ancestors(indexObject *self, PyObject *args)
1880 static PyObject *index_ancestors(indexObject *self, PyObject *args)
1881 {
1881 {
1882 PyObject *gca = index_commonancestorsheads(self, args);
1882 PyObject *gca = index_commonancestorsheads(self, args);
1883 if (gca == NULL)
1883 if (gca == NULL)
1884 return NULL;
1884 return NULL;
1885
1885
1886 if (PyList_GET_SIZE(gca) <= 1) {
1886 if (PyList_GET_SIZE(gca) <= 1) {
1887 Py_INCREF(gca);
1887 Py_INCREF(gca);
1888 return gca;
1888 return gca;
1889 }
1889 }
1890
1890
1891 return find_deepest(self, gca);
1891 return find_deepest(self, gca);
1892 }
1892 }
1893
1893
1894 /*
1894 /*
1895 * Invalidate any trie entries introduced by added revs.
1895 * Invalidate any trie entries introduced by added revs.
1896 */
1896 */
1897 static void nt_invalidate_added(indexObject *self, Py_ssize_t start)
1897 static void nt_invalidate_added(indexObject *self, Py_ssize_t start)
1898 {
1898 {
1899 Py_ssize_t i, len = PyList_GET_SIZE(self->added);
1899 Py_ssize_t i, len = PyList_GET_SIZE(self->added);
1900
1900
1901 for (i = start; i < len; i++) {
1901 for (i = start; i < len; i++) {
1902 PyObject *tuple = PyList_GET_ITEM(self->added, i);
1902 PyObject *tuple = PyList_GET_ITEM(self->added, i);
1903 PyObject *node = PyTuple_GET_ITEM(tuple, 7);
1903 PyObject *node = PyTuple_GET_ITEM(tuple, 7);
1904
1904
1905 nt_insert(self, PyString_AS_STRING(node), -1);
1905 nt_insert(self, PyString_AS_STRING(node), -1);
1906 }
1906 }
1907
1907
1908 if (start == 0)
1908 if (start == 0)
1909 Py_CLEAR(self->added);
1909 Py_CLEAR(self->added);
1910 }
1910 }
1911
1911
1912 /*
1912 /*
1913 * Delete a numeric range of revs, which must be at the end of the
1913 * Delete a numeric range of revs, which must be at the end of the
1914 * range, but exclude the sentinel nullid entry.
1914 * range, but exclude the sentinel nullid entry.
1915 */
1915 */
1916 static int index_slice_del(indexObject *self, PyObject *item)
1916 static int index_slice_del(indexObject *self, PyObject *item)
1917 {
1917 {
1918 Py_ssize_t start, stop, step, slicelength;
1918 Py_ssize_t start, stop, step, slicelength;
1919 Py_ssize_t length = index_length(self);
1919 Py_ssize_t length = index_length(self);
1920 int ret = 0;
1920 int ret = 0;
1921
1921
1922 if (PySlice_GetIndicesEx((PySliceObject*)item, length,
1922 if (PySlice_GetIndicesEx((PySliceObject*)item, length,
1923 &start, &stop, &step, &slicelength) < 0)
1923 &start, &stop, &step, &slicelength) < 0)
1924 return -1;
1924 return -1;
1925
1925
1926 if (slicelength <= 0)
1926 if (slicelength <= 0)
1927 return 0;
1927 return 0;
1928
1928
1929 if ((step < 0 && start < stop) || (step > 0 && start > stop))
1929 if ((step < 0 && start < stop) || (step > 0 && start > stop))
1930 stop = start;
1930 stop = start;
1931
1931
1932 if (step < 0) {
1932 if (step < 0) {
1933 stop = start + 1;
1933 stop = start + 1;
1934 start = stop + step*(slicelength - 1) - 1;
1934 start = stop + step*(slicelength - 1) - 1;
1935 step = -step;
1935 step = -step;
1936 }
1936 }
1937
1937
1938 if (step != 1) {
1938 if (step != 1) {
1939 PyErr_SetString(PyExc_ValueError,
1939 PyErr_SetString(PyExc_ValueError,
1940 "revlog index delete requires step size of 1");
1940 "revlog index delete requires step size of 1");
1941 return -1;
1941 return -1;
1942 }
1942 }
1943
1943
1944 if (stop != length - 1) {
1944 if (stop != length - 1) {
1945 PyErr_SetString(PyExc_IndexError,
1945 PyErr_SetString(PyExc_IndexError,
1946 "revlog index deletion indices are invalid");
1946 "revlog index deletion indices are invalid");
1947 return -1;
1947 return -1;
1948 }
1948 }
1949
1949
1950 if (start < self->length - 1) {
1950 if (start < self->length - 1) {
1951 if (self->nt) {
1951 if (self->nt) {
1952 Py_ssize_t i;
1952 Py_ssize_t i;
1953
1953
1954 for (i = start + 1; i < self->length - 1; i++) {
1954 for (i = start + 1; i < self->length - 1; i++) {
1955 const char *node = index_node(self, i);
1955 const char *node = index_node(self, i);
1956
1956
1957 if (node)
1957 if (node)
1958 nt_insert(self, node, -1);
1958 nt_insert(self, node, -1);
1959 }
1959 }
1960 if (self->added)
1960 if (self->added)
1961 nt_invalidate_added(self, 0);
1961 nt_invalidate_added(self, 0);
1962 if (self->ntrev > start)
1962 if (self->ntrev > start)
1963 self->ntrev = (int)start;
1963 self->ntrev = (int)start;
1964 }
1964 }
1965 self->length = start + 1;
1965 self->length = start + 1;
1966 if (start < self->raw_length) {
1966 if (start < self->raw_length) {
1967 if (self->cache) {
1967 if (self->cache) {
1968 Py_ssize_t i;
1968 Py_ssize_t i;
1969 for (i = start; i < self->raw_length; i++)
1969 for (i = start; i < self->raw_length; i++)
1970 Py_CLEAR(self->cache[i]);
1970 Py_CLEAR(self->cache[i]);
1971 }
1971 }
1972 self->raw_length = start;
1972 self->raw_length = start;
1973 }
1973 }
1974 goto done;
1974 goto done;
1975 }
1975 }
1976
1976
1977 if (self->nt) {
1977 if (self->nt) {
1978 nt_invalidate_added(self, start - self->length + 1);
1978 nt_invalidate_added(self, start - self->length + 1);
1979 if (self->ntrev > start)
1979 if (self->ntrev > start)
1980 self->ntrev = (int)start;
1980 self->ntrev = (int)start;
1981 }
1981 }
1982 if (self->added)
1982 if (self->added)
1983 ret = PyList_SetSlice(self->added, start - self->length + 1,
1983 ret = PyList_SetSlice(self->added, start - self->length + 1,
1984 PyList_GET_SIZE(self->added), NULL);
1984 PyList_GET_SIZE(self->added), NULL);
1985 done:
1985 done:
1986 Py_CLEAR(self->headrevs);
1986 Py_CLEAR(self->headrevs);
1987 return ret;
1987 return ret;
1988 }
1988 }
1989
1989
1990 /*
1990 /*
1991 * Supported ops:
1991 * Supported ops:
1992 *
1992 *
1993 * slice deletion
1993 * slice deletion
1994 * string assignment (extend node->rev mapping)
1994 * string assignment (extend node->rev mapping)
1995 * string deletion (shrink node->rev mapping)
1995 * string deletion (shrink node->rev mapping)
1996 */
1996 */
1997 static int index_assign_subscript(indexObject *self, PyObject *item,
1997 static int index_assign_subscript(indexObject *self, PyObject *item,
1998 PyObject *value)
1998 PyObject *value)
1999 {
1999 {
2000 char *node;
2000 char *node;
2001 Py_ssize_t nodelen;
2001 Py_ssize_t nodelen;
2002 long rev;
2002 long rev;
2003
2003
2004 if (PySlice_Check(item) && value == NULL)
2004 if (PySlice_Check(item) && value == NULL)
2005 return index_slice_del(self, item);
2005 return index_slice_del(self, item);
2006
2006
2007 if (node_check(item, &node, &nodelen) == -1)
2007 if (node_check(item, &node, &nodelen) == -1)
2008 return -1;
2008 return -1;
2009
2009
2010 if (value == NULL)
2010 if (value == NULL)
2011 return self->nt ? nt_insert(self, node, -1) : 0;
2011 return self->nt ? nt_insert(self, node, -1) : 0;
2012 rev = PyInt_AsLong(value);
2012 rev = PyInt_AsLong(value);
2013 if (rev > INT_MAX || rev < 0) {
2013 if (rev > INT_MAX || rev < 0) {
2014 if (!PyErr_Occurred())
2014 if (!PyErr_Occurred())
2015 PyErr_SetString(PyExc_ValueError, "rev out of range");
2015 PyErr_SetString(PyExc_ValueError, "rev out of range");
2016 return -1;
2016 return -1;
2017 }
2017 }
2018
2018
2019 if (nt_init(self) == -1)
2019 if (nt_init(self) == -1)
2020 return -1;
2020 return -1;
2021 return nt_insert(self, node, (int)rev);
2021 return nt_insert(self, node, (int)rev);
2022 }
2022 }
2023
2023
2024 /*
2024 /*
2025 * Find all RevlogNG entries in an index that has inline data. Update
2025 * Find all RevlogNG entries in an index that has inline data. Update
2026 * the optional "offsets" table with those entries.
2026 * the optional "offsets" table with those entries.
2027 */
2027 */
2028 static Py_ssize_t inline_scan(indexObject *self, const char **offsets)
2028 static Py_ssize_t inline_scan(indexObject *self, const char **offsets)
2029 {
2029 {
2030 const char *data = PyString_AS_STRING(self->data);
2030 const char *data = PyString_AS_STRING(self->data);
2031 Py_ssize_t pos = 0;
2031 Py_ssize_t pos = 0;
2032 Py_ssize_t end = PyString_GET_SIZE(self->data);
2032 Py_ssize_t end = PyString_GET_SIZE(self->data);
2033 long incr = v1_hdrsize;
2033 long incr = v1_hdrsize;
2034 Py_ssize_t len = 0;
2034 Py_ssize_t len = 0;
2035
2035
2036 while (pos + v1_hdrsize <= end && pos >= 0) {
2036 while (pos + v1_hdrsize <= end && pos >= 0) {
2037 uint32_t comp_len;
2037 uint32_t comp_len;
2038 /* 3rd element of header is length of compressed inline data */
2038 /* 3rd element of header is length of compressed inline data */
2039 comp_len = getbe32(data + pos + 8);
2039 comp_len = getbe32(data + pos + 8);
2040 incr = v1_hdrsize + comp_len;
2040 incr = v1_hdrsize + comp_len;
2041 if (offsets)
2041 if (offsets)
2042 offsets[len] = data + pos;
2042 offsets[len] = data + pos;
2043 len++;
2043 len++;
2044 pos += incr;
2044 pos += incr;
2045 }
2045 }
2046
2046
2047 if (pos != end) {
2047 if (pos != end) {
2048 if (!PyErr_Occurred())
2048 if (!PyErr_Occurred())
2049 PyErr_SetString(PyExc_ValueError, "corrupt index file");
2049 PyErr_SetString(PyExc_ValueError, "corrupt index file");
2050 return -1;
2050 return -1;
2051 }
2051 }
2052
2052
2053 return len;
2053 return len;
2054 }
2054 }
2055
2055
2056 static int index_init(indexObject *self, PyObject *args)
2056 static int index_init(indexObject *self, PyObject *args)
2057 {
2057 {
2058 PyObject *data_obj, *inlined_obj;
2058 PyObject *data_obj, *inlined_obj;
2059 Py_ssize_t size;
2059 Py_ssize_t size;
2060
2060
2061 /* Initialize before argument-checking to avoid index_dealloc() crash. */
2061 /* Initialize before argument-checking to avoid index_dealloc() crash. */
2062 self->raw_length = 0;
2062 self->raw_length = 0;
2063 self->added = NULL;
2063 self->added = NULL;
2064 self->cache = NULL;
2064 self->cache = NULL;
2065 self->data = NULL;
2065 self->data = NULL;
2066 self->headrevs = NULL;
2066 self->headrevs = NULL;
2067 self->filteredrevs = Py_None;
2067 self->filteredrevs = Py_None;
2068 Py_INCREF(Py_None);
2068 Py_INCREF(Py_None);
2069 self->nt = NULL;
2069 self->nt = NULL;
2070 self->offsets = NULL;
2070 self->offsets = NULL;
2071
2071
2072 if (!PyArg_ParseTuple(args, "OO", &data_obj, &inlined_obj))
2072 if (!PyArg_ParseTuple(args, "OO", &data_obj, &inlined_obj))
2073 return -1;
2073 return -1;
2074 if (!PyString_Check(data_obj)) {
2074 if (!PyString_Check(data_obj)) {
2075 PyErr_SetString(PyExc_TypeError, "data is not a string");
2075 PyErr_SetString(PyExc_TypeError, "data is not a string");
2076 return -1;
2076 return -1;
2077 }
2077 }
2078 size = PyString_GET_SIZE(data_obj);
2078 size = PyString_GET_SIZE(data_obj);
2079
2079
2080 self->inlined = inlined_obj && PyObject_IsTrue(inlined_obj);
2080 self->inlined = inlined_obj && PyObject_IsTrue(inlined_obj);
2081 self->data = data_obj;
2081 self->data = data_obj;
2082
2082
2083 self->ntlength = self->ntcapacity = 0;
2083 self->ntlength = self->ntcapacity = 0;
2084 self->ntdepth = self->ntsplits = 0;
2084 self->ntdepth = self->ntsplits = 0;
2085 self->ntlookups = self->ntmisses = 0;
2085 self->ntlookups = self->ntmisses = 0;
2086 self->ntrev = -1;
2086 self->ntrev = -1;
2087 Py_INCREF(self->data);
2087 Py_INCREF(self->data);
2088
2088
2089 if (self->inlined) {
2089 if (self->inlined) {
2090 Py_ssize_t len = inline_scan(self, NULL);
2090 Py_ssize_t len = inline_scan(self, NULL);
2091 if (len == -1)
2091 if (len == -1)
2092 goto bail;
2092 goto bail;
2093 self->raw_length = len;
2093 self->raw_length = len;
2094 self->length = len + 1;
2094 self->length = len + 1;
2095 } else {
2095 } else {
2096 if (size % v1_hdrsize) {
2096 if (size % v1_hdrsize) {
2097 PyErr_SetString(PyExc_ValueError, "corrupt index file");
2097 PyErr_SetString(PyExc_ValueError, "corrupt index file");
2098 goto bail;
2098 goto bail;
2099 }
2099 }
2100 self->raw_length = size / v1_hdrsize;
2100 self->raw_length = size / v1_hdrsize;
2101 self->length = self->raw_length + 1;
2101 self->length = self->raw_length + 1;
2102 }
2102 }
2103
2103
2104 return 0;
2104 return 0;
2105 bail:
2105 bail:
2106 return -1;
2106 return -1;
2107 }
2107 }
2108
2108
2109 static PyObject *index_nodemap(indexObject *self)
2109 static PyObject *index_nodemap(indexObject *self)
2110 {
2110 {
2111 Py_INCREF(self);
2111 Py_INCREF(self);
2112 return (PyObject *)self;
2112 return (PyObject *)self;
2113 }
2113 }
2114
2114
2115 static void index_dealloc(indexObject *self)
2115 static void index_dealloc(indexObject *self)
2116 {
2116 {
2117 _index_clearcaches(self);
2117 _index_clearcaches(self);
2118 Py_XDECREF(self->filteredrevs);
2118 Py_XDECREF(self->filteredrevs);
2119 Py_XDECREF(self->data);
2119 Py_XDECREF(self->data);
2120 Py_XDECREF(self->added);
2120 Py_XDECREF(self->added);
2121 PyObject_Del(self);
2121 PyObject_Del(self);
2122 }
2122 }
2123
2123
2124 static PySequenceMethods index_sequence_methods = {
2124 static PySequenceMethods index_sequence_methods = {
2125 (lenfunc)index_length, /* sq_length */
2125 (lenfunc)index_length, /* sq_length */
2126 0, /* sq_concat */
2126 0, /* sq_concat */
2127 0, /* sq_repeat */
2127 0, /* sq_repeat */
2128 (ssizeargfunc)index_get, /* sq_item */
2128 (ssizeargfunc)index_get, /* sq_item */
2129 0, /* sq_slice */
2129 0, /* sq_slice */
2130 0, /* sq_ass_item */
2130 0, /* sq_ass_item */
2131 0, /* sq_ass_slice */
2131 0, /* sq_ass_slice */
2132 (objobjproc)index_contains, /* sq_contains */
2132 (objobjproc)index_contains, /* sq_contains */
2133 };
2133 };
2134
2134
2135 static PyMappingMethods index_mapping_methods = {
2135 static PyMappingMethods index_mapping_methods = {
2136 (lenfunc)index_length, /* mp_length */
2136 (lenfunc)index_length, /* mp_length */
2137 (binaryfunc)index_getitem, /* mp_subscript */
2137 (binaryfunc)index_getitem, /* mp_subscript */
2138 (objobjargproc)index_assign_subscript, /* mp_ass_subscript */
2138 (objobjargproc)index_assign_subscript, /* mp_ass_subscript */
2139 };
2139 };
2140
2140
2141 static PyMethodDef index_methods[] = {
2141 static PyMethodDef index_methods[] = {
2142 {"ancestors", (PyCFunction)index_ancestors, METH_VARARGS,
2142 {"ancestors", (PyCFunction)index_ancestors, METH_VARARGS,
2143 "return the gca set of the given revs"},
2143 "return the gca set of the given revs"},
2144 {"commonancestorsheads", (PyCFunction)index_commonancestorsheads,
2144 {"commonancestorsheads", (PyCFunction)index_commonancestorsheads,
2145 METH_VARARGS,
2145 METH_VARARGS,
2146 "return the heads of the common ancestors of the given revs"},
2146 "return the heads of the common ancestors of the given revs"},
2147 {"clearcaches", (PyCFunction)index_clearcaches, METH_NOARGS,
2147 {"clearcaches", (PyCFunction)index_clearcaches, METH_NOARGS,
2148 "clear the index caches"},
2148 "clear the index caches"},
2149 {"get", (PyCFunction)index_m_get, METH_VARARGS,
2149 {"get", (PyCFunction)index_m_get, METH_VARARGS,
2150 "get an index entry"},
2150 "get an index entry"},
2151 {"computephases", (PyCFunction)compute_phases, METH_VARARGS,
2151 {"computephases", (PyCFunction)compute_phases, METH_VARARGS,
2152 "compute phases"},
2152 "compute phases"},
2153 {"headrevs", (PyCFunction)index_headrevs, METH_VARARGS,
2153 {"headrevs", (PyCFunction)index_headrevs, METH_VARARGS,
2154 "get head revisions"}, /* Can do filtering since 3.2 */
2154 "get head revisions"}, /* Can do filtering since 3.2 */
2155 {"headrevsfiltered", (PyCFunction)index_headrevs, METH_VARARGS,
2155 {"headrevsfiltered", (PyCFunction)index_headrevs, METH_VARARGS,
2156 "get filtered head revisions"}, /* Can always do filtering */
2156 "get filtered head revisions"}, /* Can always do filtering */
2157 {"insert", (PyCFunction)index_insert, METH_VARARGS,
2157 {"insert", (PyCFunction)index_insert, METH_VARARGS,
2158 "insert an index entry"},
2158 "insert an index entry"},
2159 {"partialmatch", (PyCFunction)index_partialmatch, METH_VARARGS,
2159 {"partialmatch", (PyCFunction)index_partialmatch, METH_VARARGS,
2160 "match a potentially ambiguous node ID"},
2160 "match a potentially ambiguous node ID"},
2161 {"stats", (PyCFunction)index_stats, METH_NOARGS,
2161 {"stats", (PyCFunction)index_stats, METH_NOARGS,
2162 "stats for the index"},
2162 "stats for the index"},
2163 {NULL} /* Sentinel */
2163 {NULL} /* Sentinel */
2164 };
2164 };
2165
2165
2166 static PyGetSetDef index_getset[] = {
2166 static PyGetSetDef index_getset[] = {
2167 {"nodemap", (getter)index_nodemap, NULL, "nodemap", NULL},
2167 {"nodemap", (getter)index_nodemap, NULL, "nodemap", NULL},
2168 {NULL} /* Sentinel */
2168 {NULL} /* Sentinel */
2169 };
2169 };
2170
2170
2171 static PyTypeObject indexType = {
2171 static PyTypeObject indexType = {
2172 PyObject_HEAD_INIT(NULL)
2172 PyObject_HEAD_INIT(NULL)
2173 0, /* ob_size */
2173 0, /* ob_size */
2174 "parsers.index", /* tp_name */
2174 "parsers.index", /* tp_name */
2175 sizeof(indexObject), /* tp_basicsize */
2175 sizeof(indexObject), /* tp_basicsize */
2176 0, /* tp_itemsize */
2176 0, /* tp_itemsize */
2177 (destructor)index_dealloc, /* tp_dealloc */
2177 (destructor)index_dealloc, /* tp_dealloc */
2178 0, /* tp_print */
2178 0, /* tp_print */
2179 0, /* tp_getattr */
2179 0, /* tp_getattr */
2180 0, /* tp_setattr */
2180 0, /* tp_setattr */
2181 0, /* tp_compare */
2181 0, /* tp_compare */
2182 0, /* tp_repr */
2182 0, /* tp_repr */
2183 0, /* tp_as_number */
2183 0, /* tp_as_number */
2184 &index_sequence_methods, /* tp_as_sequence */
2184 &index_sequence_methods, /* tp_as_sequence */
2185 &index_mapping_methods, /* tp_as_mapping */
2185 &index_mapping_methods, /* tp_as_mapping */
2186 0, /* tp_hash */
2186 0, /* tp_hash */
2187 0, /* tp_call */
2187 0, /* tp_call */
2188 0, /* tp_str */
2188 0, /* tp_str */
2189 0, /* tp_getattro */
2189 0, /* tp_getattro */
2190 0, /* tp_setattro */
2190 0, /* tp_setattro */
2191 0, /* tp_as_buffer */
2191 0, /* tp_as_buffer */
2192 Py_TPFLAGS_DEFAULT, /* tp_flags */
2192 Py_TPFLAGS_DEFAULT, /* tp_flags */
2193 "revlog index", /* tp_doc */
2193 "revlog index", /* tp_doc */
2194 0, /* tp_traverse */
2194 0, /* tp_traverse */
2195 0, /* tp_clear */
2195 0, /* tp_clear */
2196 0, /* tp_richcompare */
2196 0, /* tp_richcompare */
2197 0, /* tp_weaklistoffset */
2197 0, /* tp_weaklistoffset */
2198 0, /* tp_iter */
2198 0, /* tp_iter */
2199 0, /* tp_iternext */
2199 0, /* tp_iternext */
2200 index_methods, /* tp_methods */
2200 index_methods, /* tp_methods */
2201 0, /* tp_members */
2201 0, /* tp_members */
2202 index_getset, /* tp_getset */
2202 index_getset, /* tp_getset */
2203 0, /* tp_base */
2203 0, /* tp_base */
2204 0, /* tp_dict */
2204 0, /* tp_dict */
2205 0, /* tp_descr_get */
2205 0, /* tp_descr_get */
2206 0, /* tp_descr_set */
2206 0, /* tp_descr_set */
2207 0, /* tp_dictoffset */
2207 0, /* tp_dictoffset */
2208 (initproc)index_init, /* tp_init */
2208 (initproc)index_init, /* tp_init */
2209 0, /* tp_alloc */
2209 0, /* tp_alloc */
2210 };
2210 };
2211
2211
2212 /*
2212 /*
2213 * returns a tuple of the form (index, index, cache) with elements as
2213 * returns a tuple of the form (index, index, cache) with elements as
2214 * follows:
2214 * follows:
2215 *
2215 *
2216 * index: an index object that lazily parses RevlogNG records
2216 * index: an index object that lazily parses RevlogNG records
2217 * cache: if data is inlined, a tuple (index_file_content, 0), else None
2217 * cache: if data is inlined, a tuple (index_file_content, 0), else None
2218 *
2218 *
2219 * added complications are for backwards compatibility
2219 * added complications are for backwards compatibility
2220 */
2220 */
2221 static PyObject *parse_index2(PyObject *self, PyObject *args)
2221 static PyObject *parse_index2(PyObject *self, PyObject *args)
2222 {
2222 {
2223 PyObject *tuple = NULL, *cache = NULL;
2223 PyObject *tuple = NULL, *cache = NULL;
2224 indexObject *idx;
2224 indexObject *idx;
2225 int ret;
2225 int ret;
2226
2226
2227 idx = PyObject_New(indexObject, &indexType);
2227 idx = PyObject_New(indexObject, &indexType);
2228 if (idx == NULL)
2228 if (idx == NULL)
2229 goto bail;
2229 goto bail;
2230
2230
2231 ret = index_init(idx, args);
2231 ret = index_init(idx, args);
2232 if (ret == -1)
2232 if (ret == -1)
2233 goto bail;
2233 goto bail;
2234
2234
2235 if (idx->inlined) {
2235 if (idx->inlined) {
2236 cache = Py_BuildValue("iO", 0, idx->data);
2236 cache = Py_BuildValue("iO", 0, idx->data);
2237 if (cache == NULL)
2237 if (cache == NULL)
2238 goto bail;
2238 goto bail;
2239 } else {
2239 } else {
2240 cache = Py_None;
2240 cache = Py_None;
2241 Py_INCREF(cache);
2241 Py_INCREF(cache);
2242 }
2242 }
2243
2243
2244 tuple = Py_BuildValue("NN", idx, cache);
2244 tuple = Py_BuildValue("NN", idx, cache);
2245 if (!tuple)
2245 if (!tuple)
2246 goto bail;
2246 goto bail;
2247 return tuple;
2247 return tuple;
2248
2248
2249 bail:
2249 bail:
2250 Py_XDECREF(idx);
2250 Py_XDECREF(idx);
2251 Py_XDECREF(cache);
2251 Py_XDECREF(cache);
2252 Py_XDECREF(tuple);
2252 Py_XDECREF(tuple);
2253 return NULL;
2253 return NULL;
2254 }
2254 }
2255
2255
2256 #define BUMPED_FIX 1
2256 #define BUMPED_FIX 1
2257 #define USING_SHA_256 2
2257 #define USING_SHA_256 2
2258
2258
2259 static PyObject *readshas(
2259 static PyObject *readshas(
2260 const char *source, unsigned char num, Py_ssize_t hashwidth)
2260 const char *source, unsigned char num, Py_ssize_t hashwidth)
2261 {
2261 {
2262 int i;
2262 int i;
2263 PyObject *list = PyTuple_New(num);
2263 PyObject *list = PyTuple_New(num);
2264 if (list == NULL) {
2264 if (list == NULL) {
2265 return NULL;
2265 return NULL;
2266 }
2266 }
2267 for (i = 0; i < num; i++) {
2267 for (i = 0; i < num; i++) {
2268 PyObject *hash = PyString_FromStringAndSize(source, hashwidth);
2268 PyObject *hash = PyString_FromStringAndSize(source, hashwidth);
2269 if (hash == NULL) {
2269 if (hash == NULL) {
2270 Py_DECREF(list);
2270 Py_DECREF(list);
2271 return NULL;
2271 return NULL;
2272 }
2272 }
2273 PyTuple_SetItem(list, i, hash);
2273 PyTuple_SetItem(list, i, hash);
2274 source += hashwidth;
2274 source += hashwidth;
2275 }
2275 }
2276 return list;
2276 return list;
2277 }
2277 }
2278
2278
2279 static PyObject *fm1readmarker(const char *data, uint32_t *msize)
2279 static PyObject *fm1readmarker(const char *data, uint32_t *msize)
2280 {
2280 {
2281 const char *meta;
2281 const char *meta;
2282
2282
2283 double mtime;
2283 double mtime;
2284 int16_t tz;
2284 int16_t tz;
2285 uint16_t flags;
2285 uint16_t flags;
2286 unsigned char nsuccs, nparents, nmetadata;
2286 unsigned char nsuccs, nparents, nmetadata;
2287 Py_ssize_t hashwidth = 20;
2287 Py_ssize_t hashwidth = 20;
2288
2288
2289 PyObject *prec = NULL, *parents = NULL, *succs = NULL;
2289 PyObject *prec = NULL, *parents = NULL, *succs = NULL;
2290 PyObject *metadata = NULL, *ret = NULL;
2290 PyObject *metadata = NULL, *ret = NULL;
2291 int i;
2291 int i;
2292
2292
2293 *msize = getbe32(data);
2293 *msize = getbe32(data);
2294 data += 4;
2294 data += 4;
2295 mtime = getbefloat64(data);
2295 mtime = getbefloat64(data);
2296 data += 8;
2296 data += 8;
2297 tz = getbeint16(data);
2297 tz = getbeint16(data);
2298 data += 2;
2298 data += 2;
2299 flags = getbeuint16(data);
2299 flags = getbeuint16(data);
2300 data += 2;
2300 data += 2;
2301
2301
2302 if (flags & USING_SHA_256) {
2302 if (flags & USING_SHA_256) {
2303 hashwidth = 32;
2303 hashwidth = 32;
2304 }
2304 }
2305
2305
2306 nsuccs = (unsigned char)(*data++);
2306 nsuccs = (unsigned char)(*data++);
2307 nparents = (unsigned char)(*data++);
2307 nparents = (unsigned char)(*data++);
2308 nmetadata = (unsigned char)(*data++);
2308 nmetadata = (unsigned char)(*data++);
2309
2309
2310 prec = PyString_FromStringAndSize(data, hashwidth);
2310 prec = PyString_FromStringAndSize(data, hashwidth);
2311 data += hashwidth;
2311 data += hashwidth;
2312 if (prec == NULL) {
2312 if (prec == NULL) {
2313 goto bail;
2313 goto bail;
2314 }
2314 }
2315
2315
2316 succs = readshas(data, nsuccs, hashwidth);
2316 succs = readshas(data, nsuccs, hashwidth);
2317 if (succs == NULL) {
2317 if (succs == NULL) {
2318 goto bail;
2318 goto bail;
2319 }
2319 }
2320 data += nsuccs * hashwidth;
2320 data += nsuccs * hashwidth;
2321
2321
2322 if (nparents == 1 || nparents == 2) {
2322 if (nparents == 1 || nparents == 2) {
2323 parents = readshas(data, nparents, hashwidth);
2323 parents = readshas(data, nparents, hashwidth);
2324 if (parents == NULL) {
2324 if (parents == NULL) {
2325 goto bail;
2325 goto bail;
2326 }
2326 }
2327 data += nparents * hashwidth;
2327 data += nparents * hashwidth;
2328 } else {
2328 } else {
2329 parents = Py_None;
2329 parents = Py_None;
2330 }
2330 }
2331
2331
2332 meta = data + (2 * nmetadata);
2332 meta = data + (2 * nmetadata);
2333 metadata = PyTuple_New(nmetadata);
2333 metadata = PyTuple_New(nmetadata);
2334 if (metadata == NULL) {
2334 if (metadata == NULL) {
2335 goto bail;
2335 goto bail;
2336 }
2336 }
2337 for (i = 0; i < nmetadata; i++) {
2337 for (i = 0; i < nmetadata; i++) {
2338 PyObject *tmp, *left = NULL, *right = NULL;
2338 PyObject *tmp, *left = NULL, *right = NULL;
2339 Py_ssize_t metasize = (unsigned char)(*data++);
2339 Py_ssize_t metasize = (unsigned char)(*data++);
2340 left = PyString_FromStringAndSize(meta, metasize);
2340 left = PyString_FromStringAndSize(meta, metasize);
2341 meta += metasize;
2341 meta += metasize;
2342 metasize = (unsigned char)(*data++);
2342 metasize = (unsigned char)(*data++);
2343 right = PyString_FromStringAndSize(meta, metasize);
2343 right = PyString_FromStringAndSize(meta, metasize);
2344 meta += metasize;
2344 meta += metasize;
2345 if (!left || !right) {
2345 if (!left || !right) {
2346 Py_XDECREF(left);
2346 Py_XDECREF(left);
2347 Py_XDECREF(right);
2347 Py_XDECREF(right);
2348 goto bail;
2348 goto bail;
2349 }
2349 }
2350 tmp = PyTuple_Pack(2, left, right);
2350 tmp = PyTuple_Pack(2, left, right);
2351 Py_DECREF(left);
2351 Py_DECREF(left);
2352 Py_DECREF(right);
2352 Py_DECREF(right);
2353 if (!tmp) {
2353 if (!tmp) {
2354 goto bail;
2354 goto bail;
2355 }
2355 }
2356 PyTuple_SetItem(metadata, i, tmp);
2356 PyTuple_SetItem(metadata, i, tmp);
2357 }
2357 }
2358 ret = Py_BuildValue("(OOHO(di)O)", prec, succs, flags,
2358 ret = Py_BuildValue("(OOHO(di)O)", prec, succs, flags,
2359 metadata, mtime, (int)tz * 60, parents);
2359 metadata, mtime, (int)tz * 60, parents);
2360 bail:
2360 bail:
2361 Py_XDECREF(prec);
2361 Py_XDECREF(prec);
2362 Py_XDECREF(succs);
2362 Py_XDECREF(succs);
2363 Py_XDECREF(metadata);
2363 Py_XDECREF(metadata);
2364 if (parents != Py_None)
2364 if (parents != Py_None)
2365 Py_XDECREF(parents);
2365 Py_XDECREF(parents);
2366 return ret;
2366 return ret;
2367 }
2367 }
2368
2368
2369
2369
2370 static PyObject *fm1readmarkers(PyObject *self, PyObject *args) {
2370 static PyObject *fm1readmarkers(PyObject *self, PyObject *args) {
2371 const char *data;
2371 const char *data;
2372 Py_ssize_t datalen;
2372 Py_ssize_t datalen;
2373 /* only unsigned long because python 2.4, should be Py_ssize_t */
2373 /* only unsigned long because python 2.4, should be Py_ssize_t */
2374 unsigned long offset, stop;
2374 unsigned long offset, stop;
2375 PyObject *markers = NULL;
2375 PyObject *markers = NULL;
2376
2376
2377 /* replace kk with nn when we drop Python 2.4 */
2377 /* replace kk with nn when we drop Python 2.4 */
2378 if (!PyArg_ParseTuple(args, "s#kk", &data, &datalen, &offset, &stop)) {
2378 if (!PyArg_ParseTuple(args, "s#kk", &data, &datalen, &offset, &stop)) {
2379 return NULL;
2379 return NULL;
2380 }
2380 }
2381 data += offset;
2381 data += offset;
2382 markers = PyList_New(0);
2382 markers = PyList_New(0);
2383 if (!markers) {
2383 if (!markers) {
2384 return NULL;
2384 return NULL;
2385 }
2385 }
2386 while (offset < stop) {
2386 while (offset < stop) {
2387 uint32_t msize;
2387 uint32_t msize;
2388 int error;
2388 int error;
2389 PyObject *record = fm1readmarker(data, &msize);
2389 PyObject *record = fm1readmarker(data, &msize);
2390 if (!record) {
2390 if (!record) {
2391 goto bail;
2391 goto bail;
2392 }
2392 }
2393 error = PyList_Append(markers, record);
2393 error = PyList_Append(markers, record);
2394 Py_DECREF(record);
2394 Py_DECREF(record);
2395 if (error) {
2395 if (error) {
2396 goto bail;
2396 goto bail;
2397 }
2397 }
2398 data += msize;
2398 data += msize;
2399 offset += msize;
2399 offset += msize;
2400 }
2400 }
2401 return markers;
2401 return markers;
2402 bail:
2402 bail:
2403 Py_DECREF(markers);
2403 Py_DECREF(markers);
2404 return NULL;
2404 return NULL;
2405 }
2405 }
2406
2406
2407 static char parsers_doc[] = "Efficient content parsing.";
2407 static char parsers_doc[] = "Efficient content parsing.";
2408
2408
2409 PyObject *encodedir(PyObject *self, PyObject *args);
2409 PyObject *encodedir(PyObject *self, PyObject *args);
2410 PyObject *pathencode(PyObject *self, PyObject *args);
2410 PyObject *pathencode(PyObject *self, PyObject *args);
2411 PyObject *lowerencode(PyObject *self, PyObject *args);
2411 PyObject *lowerencode(PyObject *self, PyObject *args);
2412
2412
2413 static PyMethodDef methods[] = {
2413 static PyMethodDef methods[] = {
2414 {"pack_dirstate", pack_dirstate, METH_VARARGS, "pack a dirstate\n"},
2414 {"pack_dirstate", pack_dirstate, METH_VARARGS, "pack a dirstate\n"},
2415 {"parse_manifest", parse_manifest, METH_VARARGS, "parse a manifest\n"},
2415 {"parse_manifest", parse_manifest, METH_VARARGS, "parse a manifest\n"},
2416 {"parse_dirstate", parse_dirstate, METH_VARARGS, "parse a dirstate\n"},
2416 {"parse_dirstate", parse_dirstate, METH_VARARGS, "parse a dirstate\n"},
2417 {"parse_index2", parse_index2, METH_VARARGS, "parse a revlog index\n"},
2417 {"parse_index2", parse_index2, METH_VARARGS, "parse a revlog index\n"},
2418 {"asciilower", asciilower, METH_VARARGS, "lowercase an ASCII string\n"},
2418 {"asciilower", asciilower, METH_VARARGS, "lowercase an ASCII string\n"},
2419 {"encodedir", encodedir, METH_VARARGS, "encodedir a path\n"},
2419 {"encodedir", encodedir, METH_VARARGS, "encodedir a path\n"},
2420 {"pathencode", pathencode, METH_VARARGS, "fncache-encode a path\n"},
2420 {"pathencode", pathencode, METH_VARARGS, "fncache-encode a path\n"},
2421 {"lowerencode", lowerencode, METH_VARARGS, "lower-encode a path\n"},
2421 {"lowerencode", lowerencode, METH_VARARGS, "lower-encode a path\n"},
2422 {"fm1readmarkers", fm1readmarkers, METH_VARARGS,
2422 {"fm1readmarkers", fm1readmarkers, METH_VARARGS,
2423 "parse v1 obsolete markers\n"},
2423 "parse v1 obsolete markers\n"},
2424 {NULL, NULL}
2424 {NULL, NULL}
2425 };
2425 };
2426
2426
2427 void dirs_module_init(PyObject *mod);
2427 void dirs_module_init(PyObject *mod);
2428 void manifest_module_init(PyObject *mod);
2428 void manifest_module_init(PyObject *mod);
2429
2429
2430 static void module_init(PyObject *mod)
2430 static void module_init(PyObject *mod)
2431 {
2431 {
2432 /* This module constant has two purposes. First, it lets us unit test
2432 /* This module constant has two purposes. First, it lets us unit test
2433 * the ImportError raised without hard-coding any error text. This
2433 * the ImportError raised without hard-coding any error text. This
2434 * means we can change the text in the future without breaking tests,
2434 * means we can change the text in the future without breaking tests,
2435 * even across changesets without a recompile. Second, its presence
2435 * even across changesets without a recompile. Second, its presence
2436 * can be used to determine whether the version-checking logic is
2436 * can be used to determine whether the version-checking logic is
2437 * present, which also helps in testing across changesets without a
2437 * present, which also helps in testing across changesets without a
2438 * recompile. Note that this means the pure-Python version of parsers
2438 * recompile. Note that this means the pure-Python version of parsers
2439 * should not have this module constant. */
2439 * should not have this module constant. */
2440 PyModule_AddStringConstant(mod, "versionerrortext", versionerrortext);
2440 PyModule_AddStringConstant(mod, "versionerrortext", versionerrortext);
2441
2441
2442 dirs_module_init(mod);
2442 dirs_module_init(mod);
2443 manifest_module_init(mod);
2443 manifest_module_init(mod);
2444
2444
2445 indexType.tp_new = PyType_GenericNew;
2445 indexType.tp_new = PyType_GenericNew;
2446 if (PyType_Ready(&indexType) < 0 ||
2446 if (PyType_Ready(&indexType) < 0 ||
2447 PyType_Ready(&dirstateTupleType) < 0)
2447 PyType_Ready(&dirstateTupleType) < 0)
2448 return;
2448 return;
2449 Py_INCREF(&indexType);
2449 Py_INCREF(&indexType);
2450 PyModule_AddObject(mod, "index", (PyObject *)&indexType);
2450 PyModule_AddObject(mod, "index", (PyObject *)&indexType);
2451 Py_INCREF(&dirstateTupleType);
2451 Py_INCREF(&dirstateTupleType);
2452 PyModule_AddObject(mod, "dirstatetuple",
2452 PyModule_AddObject(mod, "dirstatetuple",
2453 (PyObject *)&dirstateTupleType);
2453 (PyObject *)&dirstateTupleType);
2454
2454
2455 nullentry = Py_BuildValue("iiiiiiis#", 0, 0, 0,
2455 nullentry = Py_BuildValue("iiiiiiis#", 0, 0, 0,
2456 -1, -1, -1, -1, nullid, 20);
2456 -1, -1, -1, -1, nullid, 20);
2457 if (nullentry)
2457 if (nullentry)
2458 PyObject_GC_UnTrack(nullentry);
2458 PyObject_GC_UnTrack(nullentry);
2459 }
2459 }
2460
2460
2461 static int check_python_version(void)
2461 static int check_python_version(void)
2462 {
2462 {
2463 PyObject *sys = PyImport_ImportModule("sys"), *ver;
2463 PyObject *sys = PyImport_ImportModule("sys"), *ver;
2464 long hexversion;
2464 long hexversion;
2465 if (!sys)
2465 if (!sys)
2466 return -1;
2466 return -1;
2467 ver = PyObject_GetAttrString(sys, "hexversion");
2467 ver = PyObject_GetAttrString(sys, "hexversion");
2468 Py_DECREF(sys);
2468 Py_DECREF(sys);
2469 if (!ver)
2469 if (!ver)
2470 return -1;
2470 return -1;
2471 hexversion = PyInt_AsLong(ver);
2471 hexversion = PyInt_AsLong(ver);
2472 Py_DECREF(ver);
2472 Py_DECREF(ver);
2473 /* sys.hexversion is a 32-bit number by default, so the -1 case
2473 /* sys.hexversion is a 32-bit number by default, so the -1 case
2474 * should only occur in unusual circumstances (e.g. if sys.hexversion
2474 * should only occur in unusual circumstances (e.g. if sys.hexversion
2475 * is manually set to an invalid value). */
2475 * is manually set to an invalid value). */
2476 if ((hexversion == -1) || (hexversion >> 16 != PY_VERSION_HEX >> 16)) {
2476 if ((hexversion == -1) || (hexversion >> 16 != PY_VERSION_HEX >> 16)) {
2477 PyErr_Format(PyExc_ImportError, "%s: The Mercurial extension "
2477 PyErr_Format(PyExc_ImportError, "%s: The Mercurial extension "
2478 "modules were compiled with Python " PY_VERSION ", but "
2478 "modules were compiled with Python " PY_VERSION ", but "
2479 "Mercurial is currently using Python with sys.hexversion=%ld: "
2479 "Mercurial is currently using Python with sys.hexversion=%ld: "
2480 "Python %s\n at: %s", versionerrortext, hexversion,
2480 "Python %s\n at: %s", versionerrortext, hexversion,
2481 Py_GetVersion(), Py_GetProgramFullPath());
2481 Py_GetVersion(), Py_GetProgramFullPath());
2482 return -1;
2482 return -1;
2483 }
2483 }
2484 return 0;
2484 return 0;
2485 }
2485 }
2486
2486
2487 #ifdef IS_PY3K
2487 #ifdef IS_PY3K
2488 static struct PyModuleDef parsers_module = {
2488 static struct PyModuleDef parsers_module = {
2489 PyModuleDef_HEAD_INIT,
2489 PyModuleDef_HEAD_INIT,
2490 "parsers",
2490 "parsers",
2491 parsers_doc,
2491 parsers_doc,
2492 -1,
2492 -1,
2493 methods
2493 methods
2494 };
2494 };
2495
2495
2496 PyMODINIT_FUNC PyInit_parsers(void)
2496 PyMODINIT_FUNC PyInit_parsers(void)
2497 {
2497 {
2498 PyObject *mod;
2498 PyObject *mod;
2499
2499
2500 if (check_python_version() == -1)
2500 if (check_python_version() == -1)
2501 return;
2501 return;
2502 mod = PyModule_Create(&parsers_module);
2502 mod = PyModule_Create(&parsers_module);
2503 module_init(mod);
2503 module_init(mod);
2504 return mod;
2504 return mod;
2505 }
2505 }
2506 #else
2506 #else
2507 PyMODINIT_FUNC initparsers(void)
2507 PyMODINIT_FUNC initparsers(void)
2508 {
2508 {
2509 PyObject *mod;
2509 PyObject *mod;
2510
2510
2511 if (check_python_version() == -1)
2511 if (check_python_version() == -1)
2512 return;
2512 return;
2513 mod = Py_InitModule3("parsers", methods, parsers_doc);
2513 mod = Py_InitModule3("parsers", methods, parsers_doc);
2514 module_init(mod);
2514 module_init(mod);
2515 }
2515 }
2516 #endif
2516 #endif
General Comments 0
You need to be logged in to leave comments. Login now