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