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