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