##// END OF EJS Templates
reachableroots: reduce nesting level by jumping to next iteration by continue...
Yuya Nishihara -
r26041:8da628be default
parent child Browse files
Show More
@@ -1,2800 +1,2801
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)
1188 if (val == NULL)
1189 goto bail;
1189 goto bail;
1190 if (PySet_Contains(roots, val) == 1) {
1190 if (PySet_Contains(roots, val) == 1) {
1191 PySet_Add(reachable, val);
1191 PySet_Add(reachable, val);
1192 if (includepath == 0) {
1192 if (includepath == 0) {
1193 Py_DECREF(val);
1193 Py_DECREF(val);
1194 continue;
1194 continue;
1195 }
1195 }
1196 }
1196 }
1197 Py_DECREF(val);
1197 Py_DECREF(val);
1198
1198
1199 /* Add its parents to the list of nodes to visit */
1199 /* Add its parents to the list of nodes to visit */
1200 if (revnum != -1) {
1200 if (revnum == -1)
1201 continue;
1201 r = index_get_parents(self, revnum, parents, (int)len - 1);
1202 r = index_get_parents(self, revnum, parents, (int)len - 1);
1202 if (r < 0)
1203 if (r < 0)
1203 goto bail;
1204 goto bail;
1204
1205 for (i = 0; i < 2; i++) {
1205 for (i = 0; i < 2; i++) {
1206 if (seen[parents[i] + 1] == 0 && parents[i] >= minroot) {
1206 if (seen[parents[i] + 1] == 0
1207 && parents[i] >= minroot) {
1207 tovisit[lentovisit++] = parents[i];
1208 tovisit[lentovisit++] = parents[i];
1208 seen[parents[i] + 1] = 1;
1209 seen[parents[i] + 1] = 1;
1209 }
1210 }
1210 }
1211 }
1211 }
1212 }
1212 }
1213
1213
1214 /* 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
1215 * and add them to the reachable set */
1215 * and add them to the reachable set */
1216 if (includepath == 1) {
1216 if (includepath == 1) {
1217 minidx = minroot;
1217 minidx = minroot;
1218 if (minidx < 0)
1218 if (minidx < 0)
1219 minidx = 0;
1219 minidx = 0;
1220 for (i = minidx; i < len; i++) {
1220 for (i = minidx; i < len; i++) {
1221 if (seen[i + 1] == 1) {
1221 if (seen[i + 1] != 1)
1222 continue;
1222 r = index_get_parents(self, i, parents, (int)len - 1);
1223 r = index_get_parents(self, i, parents, (int)len - 1);
1223 /* Corrupted index file, error is set from index_get_parents */
1224 /* Corrupted index file, error is set from
1225 * index_get_parents */
1224 if (r < 0)
1226 if (r < 0)
1225 goto bail;
1227 goto bail;
1226 for (k = 0; k < 2; k++) {
1228 for (k = 0; k < 2; k++) {
1227 PyObject *p = PyInt_FromLong(parents[k]);
1229 PyObject *p = PyInt_FromLong(parents[k]);
1228 if (p == NULL)
1230 if (p == NULL)
1229 goto bail;
1231 goto bail;
1230 if (PySet_Contains(reachable, p) == 1) {
1232 if (PySet_Contains(reachable, p) == 1) {
1231 val = PyInt_FromLong(i);
1233 val = PyInt_FromLong(i);
1232 if (val == NULL)
1234 if (val == NULL)
1233 goto bail;
1235 goto bail;
1234 PySet_Add(reachable, val);
1236 PySet_Add(reachable, val);
1235 Py_DECREF(val);
1237 Py_DECREF(val);
1236 }
1238 }
1237 Py_DECREF(p);
1239 Py_DECREF(p);
1238 }
1240 }
1239 }
1241 }
1240 }
1242 }
1241 }
1242
1243
1243 free(seen);
1244 free(seen);
1244 free(tovisit);
1245 free(tovisit);
1245 return reachable;
1246 return reachable;
1246 bail:
1247 bail:
1247 Py_XDECREF(reachable);
1248 Py_XDECREF(reachable);
1248 free(seen);
1249 free(seen);
1249 free(tovisit);
1250 free(tovisit);
1250 return NULL;
1251 return NULL;
1251 }
1252 }
1252
1253
1253 static PyObject *compute_phases_map_sets(indexObject *self, PyObject *args)
1254 static PyObject *compute_phases_map_sets(indexObject *self, PyObject *args)
1254 {
1255 {
1255 PyObject *roots = Py_None;
1256 PyObject *roots = Py_None;
1256 PyObject *ret = NULL;
1257 PyObject *ret = NULL;
1257 PyObject *phaseslist = NULL;
1258 PyObject *phaseslist = NULL;
1258 PyObject *phaseroots = NULL;
1259 PyObject *phaseroots = NULL;
1259 PyObject *phaseset = NULL;
1260 PyObject *phaseset = NULL;
1260 PyObject *phasessetlist = NULL;
1261 PyObject *phasessetlist = NULL;
1261 PyObject *rev = NULL;
1262 PyObject *rev = NULL;
1262 Py_ssize_t len = index_length(self) - 1;
1263 Py_ssize_t len = index_length(self) - 1;
1263 Py_ssize_t numphase = 0;
1264 Py_ssize_t numphase = 0;
1264 Py_ssize_t minrevallphases = 0;
1265 Py_ssize_t minrevallphases = 0;
1265 Py_ssize_t minrevphase = 0;
1266 Py_ssize_t minrevphase = 0;
1266 Py_ssize_t i = 0;
1267 Py_ssize_t i = 0;
1267 char *phases = NULL;
1268 char *phases = NULL;
1268 long phase;
1269 long phase;
1269
1270
1270 if (!PyArg_ParseTuple(args, "O", &roots))
1271 if (!PyArg_ParseTuple(args, "O", &roots))
1271 goto release_none;
1272 goto release_none;
1272 if (roots == NULL || !PyList_Check(roots))
1273 if (roots == NULL || !PyList_Check(roots))
1273 goto release_none;
1274 goto release_none;
1274
1275
1275 phases = calloc(len, 1); /* phase per rev: {0: public, 1: draft, 2: secret} */
1276 phases = calloc(len, 1); /* phase per rev: {0: public, 1: draft, 2: secret} */
1276 if (phases == NULL)
1277 if (phases == NULL)
1277 goto release_none;
1278 goto release_none;
1278 /* Put the phase information of all the roots in phases */
1279 /* Put the phase information of all the roots in phases */
1279 numphase = PyList_GET_SIZE(roots)+1;
1280 numphase = PyList_GET_SIZE(roots)+1;
1280 minrevallphases = len + 1;
1281 minrevallphases = len + 1;
1281 phasessetlist = PyList_New(numphase);
1282 phasessetlist = PyList_New(numphase);
1282 if (phasessetlist == NULL)
1283 if (phasessetlist == NULL)
1283 goto release_none;
1284 goto release_none;
1284
1285
1285 PyList_SET_ITEM(phasessetlist, 0, Py_None);
1286 PyList_SET_ITEM(phasessetlist, 0, Py_None);
1286 Py_INCREF(Py_None);
1287 Py_INCREF(Py_None);
1287
1288
1288 for (i = 0; i < numphase-1; i++) {
1289 for (i = 0; i < numphase-1; i++) {
1289 phaseroots = PyList_GET_ITEM(roots, i);
1290 phaseroots = PyList_GET_ITEM(roots, i);
1290 phaseset = PySet_New(NULL);
1291 phaseset = PySet_New(NULL);
1291 if (phaseset == NULL)
1292 if (phaseset == NULL)
1292 goto release_phasesetlist;
1293 goto release_phasesetlist;
1293 PyList_SET_ITEM(phasessetlist, i+1, phaseset);
1294 PyList_SET_ITEM(phasessetlist, i+1, phaseset);
1294 if (!PyList_Check(phaseroots))
1295 if (!PyList_Check(phaseroots))
1295 goto release_phasesetlist;
1296 goto release_phasesetlist;
1296 minrevphase = add_roots_get_min(self, phaseroots, i+1, phases);
1297 minrevphase = add_roots_get_min(self, phaseroots, i+1, phases);
1297 if (minrevphase == -2) /* Error from add_roots_get_min */
1298 if (minrevphase == -2) /* Error from add_roots_get_min */
1298 goto release_phasesetlist;
1299 goto release_phasesetlist;
1299 minrevallphases = MIN(minrevallphases, minrevphase);
1300 minrevallphases = MIN(minrevallphases, minrevphase);
1300 }
1301 }
1301 /* Propagate the phase information from the roots to the revs */
1302 /* Propagate the phase information from the roots to the revs */
1302 if (minrevallphases != -1) {
1303 if (minrevallphases != -1) {
1303 int parents[2];
1304 int parents[2];
1304 for (i = minrevallphases; i < len; i++) {
1305 for (i = minrevallphases; i < len; i++) {
1305 if (index_get_parents(self, i, parents,
1306 if (index_get_parents(self, i, parents,
1306 (int)len - 1) < 0)
1307 (int)len - 1) < 0)
1307 goto release_phasesetlist;
1308 goto release_phasesetlist;
1308 set_phase_from_parents(phases, parents[0], parents[1], i);
1309 set_phase_from_parents(phases, parents[0], parents[1], i);
1309 }
1310 }
1310 }
1311 }
1311 /* Transform phase list to a python list */
1312 /* Transform phase list to a python list */
1312 phaseslist = PyList_New(len);
1313 phaseslist = PyList_New(len);
1313 if (phaseslist == NULL)
1314 if (phaseslist == NULL)
1314 goto release_phasesetlist;
1315 goto release_phasesetlist;
1315 for (i = 0; i < len; i++) {
1316 for (i = 0; i < len; i++) {
1316 phase = phases[i];
1317 phase = phases[i];
1317 /* We only store the sets of phase for non public phase, the public phase
1318 /* We only store the sets of phase for non public phase, the public phase
1318 * is computed as a difference */
1319 * is computed as a difference */
1319 if (phase != 0) {
1320 if (phase != 0) {
1320 phaseset = PyList_GET_ITEM(phasessetlist, phase);
1321 phaseset = PyList_GET_ITEM(phasessetlist, phase);
1321 rev = PyInt_FromLong(i);
1322 rev = PyInt_FromLong(i);
1322 PySet_Add(phaseset, rev);
1323 PySet_Add(phaseset, rev);
1323 Py_XDECREF(rev);
1324 Py_XDECREF(rev);
1324 }
1325 }
1325 PyList_SET_ITEM(phaseslist, i, PyInt_FromLong(phase));
1326 PyList_SET_ITEM(phaseslist, i, PyInt_FromLong(phase));
1326 }
1327 }
1327 ret = PyList_New(2);
1328 ret = PyList_New(2);
1328 if (ret == NULL)
1329 if (ret == NULL)
1329 goto release_phaseslist;
1330 goto release_phaseslist;
1330
1331
1331 PyList_SET_ITEM(ret, 0, phaseslist);
1332 PyList_SET_ITEM(ret, 0, phaseslist);
1332 PyList_SET_ITEM(ret, 1, phasessetlist);
1333 PyList_SET_ITEM(ret, 1, phasessetlist);
1333 /* We don't release phaseslist and phasessetlist as we return them to
1334 /* We don't release phaseslist and phasessetlist as we return them to
1334 * python */
1335 * python */
1335 goto release_phases;
1336 goto release_phases;
1336
1337
1337 release_phaseslist:
1338 release_phaseslist:
1338 Py_XDECREF(phaseslist);
1339 Py_XDECREF(phaseslist);
1339 release_phasesetlist:
1340 release_phasesetlist:
1340 Py_XDECREF(phasessetlist);
1341 Py_XDECREF(phasessetlist);
1341 release_phases:
1342 release_phases:
1342 free(phases);
1343 free(phases);
1343 release_none:
1344 release_none:
1344 return ret;
1345 return ret;
1345 }
1346 }
1346
1347
1347 static PyObject *index_headrevs(indexObject *self, PyObject *args)
1348 static PyObject *index_headrevs(indexObject *self, PyObject *args)
1348 {
1349 {
1349 Py_ssize_t i, j, len;
1350 Py_ssize_t i, j, len;
1350 char *nothead = NULL;
1351 char *nothead = NULL;
1351 PyObject *heads = NULL;
1352 PyObject *heads = NULL;
1352 PyObject *filter = NULL;
1353 PyObject *filter = NULL;
1353 PyObject *filteredrevs = Py_None;
1354 PyObject *filteredrevs = Py_None;
1354
1355
1355 if (!PyArg_ParseTuple(args, "|O", &filteredrevs)) {
1356 if (!PyArg_ParseTuple(args, "|O", &filteredrevs)) {
1356 return NULL;
1357 return NULL;
1357 }
1358 }
1358
1359
1359 if (self->headrevs && filteredrevs == self->filteredrevs)
1360 if (self->headrevs && filteredrevs == self->filteredrevs)
1360 return list_copy(self->headrevs);
1361 return list_copy(self->headrevs);
1361
1362
1362 Py_DECREF(self->filteredrevs);
1363 Py_DECREF(self->filteredrevs);
1363 self->filteredrevs = filteredrevs;
1364 self->filteredrevs = filteredrevs;
1364 Py_INCREF(filteredrevs);
1365 Py_INCREF(filteredrevs);
1365
1366
1366 if (filteredrevs != Py_None) {
1367 if (filteredrevs != Py_None) {
1367 filter = PyObject_GetAttrString(filteredrevs, "__contains__");
1368 filter = PyObject_GetAttrString(filteredrevs, "__contains__");
1368 if (!filter) {
1369 if (!filter) {
1369 PyErr_SetString(PyExc_TypeError,
1370 PyErr_SetString(PyExc_TypeError,
1370 "filteredrevs has no attribute __contains__");
1371 "filteredrevs has no attribute __contains__");
1371 goto bail;
1372 goto bail;
1372 }
1373 }
1373 }
1374 }
1374
1375
1375 len = index_length(self) - 1;
1376 len = index_length(self) - 1;
1376 heads = PyList_New(0);
1377 heads = PyList_New(0);
1377 if (heads == NULL)
1378 if (heads == NULL)
1378 goto bail;
1379 goto bail;
1379 if (len == 0) {
1380 if (len == 0) {
1380 PyObject *nullid = PyInt_FromLong(-1);
1381 PyObject *nullid = PyInt_FromLong(-1);
1381 if (nullid == NULL || PyList_Append(heads, nullid) == -1) {
1382 if (nullid == NULL || PyList_Append(heads, nullid) == -1) {
1382 Py_XDECREF(nullid);
1383 Py_XDECREF(nullid);
1383 goto bail;
1384 goto bail;
1384 }
1385 }
1385 goto done;
1386 goto done;
1386 }
1387 }
1387
1388
1388 nothead = calloc(len, 1);
1389 nothead = calloc(len, 1);
1389 if (nothead == NULL)
1390 if (nothead == NULL)
1390 goto bail;
1391 goto bail;
1391
1392
1392 for (i = 0; i < len; i++) {
1393 for (i = 0; i < len; i++) {
1393 int isfiltered;
1394 int isfiltered;
1394 int parents[2];
1395 int parents[2];
1395
1396
1396 isfiltered = check_filter(filter, i);
1397 isfiltered = check_filter(filter, i);
1397 if (isfiltered == -1) {
1398 if (isfiltered == -1) {
1398 PyErr_SetString(PyExc_TypeError,
1399 PyErr_SetString(PyExc_TypeError,
1399 "unable to check filter");
1400 "unable to check filter");
1400 goto bail;
1401 goto bail;
1401 }
1402 }
1402
1403
1403 if (isfiltered) {
1404 if (isfiltered) {
1404 nothead[i] = 1;
1405 nothead[i] = 1;
1405 continue;
1406 continue;
1406 }
1407 }
1407
1408
1408 if (index_get_parents(self, i, parents, (int)len - 1) < 0)
1409 if (index_get_parents(self, i, parents, (int)len - 1) < 0)
1409 goto bail;
1410 goto bail;
1410 for (j = 0; j < 2; j++) {
1411 for (j = 0; j < 2; j++) {
1411 if (parents[j] >= 0)
1412 if (parents[j] >= 0)
1412 nothead[parents[j]] = 1;
1413 nothead[parents[j]] = 1;
1413 }
1414 }
1414 }
1415 }
1415
1416
1416 for (i = 0; i < len; i++) {
1417 for (i = 0; i < len; i++) {
1417 PyObject *head;
1418 PyObject *head;
1418
1419
1419 if (nothead[i])
1420 if (nothead[i])
1420 continue;
1421 continue;
1421 head = PyInt_FromSsize_t(i);
1422 head = PyInt_FromSsize_t(i);
1422 if (head == NULL || PyList_Append(heads, head) == -1) {
1423 if (head == NULL || PyList_Append(heads, head) == -1) {
1423 Py_XDECREF(head);
1424 Py_XDECREF(head);
1424 goto bail;
1425 goto bail;
1425 }
1426 }
1426 }
1427 }
1427
1428
1428 done:
1429 done:
1429 self->headrevs = heads;
1430 self->headrevs = heads;
1430 Py_XDECREF(filter);
1431 Py_XDECREF(filter);
1431 free(nothead);
1432 free(nothead);
1432 return list_copy(self->headrevs);
1433 return list_copy(self->headrevs);
1433 bail:
1434 bail:
1434 Py_XDECREF(filter);
1435 Py_XDECREF(filter);
1435 Py_XDECREF(heads);
1436 Py_XDECREF(heads);
1436 free(nothead);
1437 free(nothead);
1437 return NULL;
1438 return NULL;
1438 }
1439 }
1439
1440
1440 static inline int nt_level(const char *node, Py_ssize_t level)
1441 static inline int nt_level(const char *node, Py_ssize_t level)
1441 {
1442 {
1442 int v = node[level>>1];
1443 int v = node[level>>1];
1443 if (!(level & 1))
1444 if (!(level & 1))
1444 v >>= 4;
1445 v >>= 4;
1445 return v & 0xf;
1446 return v & 0xf;
1446 }
1447 }
1447
1448
1448 /*
1449 /*
1449 * Return values:
1450 * Return values:
1450 *
1451 *
1451 * -4: match is ambiguous (multiple candidates)
1452 * -4: match is ambiguous (multiple candidates)
1452 * -2: not found
1453 * -2: not found
1453 * rest: valid rev
1454 * rest: valid rev
1454 */
1455 */
1455 static int nt_find(indexObject *self, const char *node, Py_ssize_t nodelen,
1456 static int nt_find(indexObject *self, const char *node, Py_ssize_t nodelen,
1456 int hex)
1457 int hex)
1457 {
1458 {
1458 int (*getnybble)(const char *, Py_ssize_t) = hex ? hexdigit : nt_level;
1459 int (*getnybble)(const char *, Py_ssize_t) = hex ? hexdigit : nt_level;
1459 int level, maxlevel, off;
1460 int level, maxlevel, off;
1460
1461
1461 if (nodelen == 20 && node[0] == '\0' && memcmp(node, nullid, 20) == 0)
1462 if (nodelen == 20 && node[0] == '\0' && memcmp(node, nullid, 20) == 0)
1462 return -1;
1463 return -1;
1463
1464
1464 if (self->nt == NULL)
1465 if (self->nt == NULL)
1465 return -2;
1466 return -2;
1466
1467
1467 if (hex)
1468 if (hex)
1468 maxlevel = nodelen > 40 ? 40 : (int)nodelen;
1469 maxlevel = nodelen > 40 ? 40 : (int)nodelen;
1469 else
1470 else
1470 maxlevel = nodelen > 20 ? 40 : ((int)nodelen * 2);
1471 maxlevel = nodelen > 20 ? 40 : ((int)nodelen * 2);
1471
1472
1472 for (level = off = 0; level < maxlevel; level++) {
1473 for (level = off = 0; level < maxlevel; level++) {
1473 int k = getnybble(node, level);
1474 int k = getnybble(node, level);
1474 nodetree *n = &self->nt[off];
1475 nodetree *n = &self->nt[off];
1475 int v = n->children[k];
1476 int v = n->children[k];
1476
1477
1477 if (v < 0) {
1478 if (v < 0) {
1478 const char *n;
1479 const char *n;
1479 Py_ssize_t i;
1480 Py_ssize_t i;
1480
1481
1481 v = -(v + 1);
1482 v = -(v + 1);
1482 n = index_node(self, v);
1483 n = index_node(self, v);
1483 if (n == NULL)
1484 if (n == NULL)
1484 return -2;
1485 return -2;
1485 for (i = level; i < maxlevel; i++)
1486 for (i = level; i < maxlevel; i++)
1486 if (getnybble(node, i) != nt_level(n, i))
1487 if (getnybble(node, i) != nt_level(n, i))
1487 return -2;
1488 return -2;
1488 return v;
1489 return v;
1489 }
1490 }
1490 if (v == 0)
1491 if (v == 0)
1491 return -2;
1492 return -2;
1492 off = v;
1493 off = v;
1493 }
1494 }
1494 /* multiple matches against an ambiguous prefix */
1495 /* multiple matches against an ambiguous prefix */
1495 return -4;
1496 return -4;
1496 }
1497 }
1497
1498
1498 static int nt_new(indexObject *self)
1499 static int nt_new(indexObject *self)
1499 {
1500 {
1500 if (self->ntlength == self->ntcapacity) {
1501 if (self->ntlength == self->ntcapacity) {
1501 if (self->ntcapacity >= INT_MAX / (sizeof(nodetree) * 2)) {
1502 if (self->ntcapacity >= INT_MAX / (sizeof(nodetree) * 2)) {
1502 PyErr_SetString(PyExc_MemoryError,
1503 PyErr_SetString(PyExc_MemoryError,
1503 "overflow in nt_new");
1504 "overflow in nt_new");
1504 return -1;
1505 return -1;
1505 }
1506 }
1506 self->ntcapacity *= 2;
1507 self->ntcapacity *= 2;
1507 self->nt = realloc(self->nt,
1508 self->nt = realloc(self->nt,
1508 self->ntcapacity * sizeof(nodetree));
1509 self->ntcapacity * sizeof(nodetree));
1509 if (self->nt == NULL) {
1510 if (self->nt == NULL) {
1510 PyErr_SetString(PyExc_MemoryError, "out of memory");
1511 PyErr_SetString(PyExc_MemoryError, "out of memory");
1511 return -1;
1512 return -1;
1512 }
1513 }
1513 memset(&self->nt[self->ntlength], 0,
1514 memset(&self->nt[self->ntlength], 0,
1514 sizeof(nodetree) * (self->ntcapacity - self->ntlength));
1515 sizeof(nodetree) * (self->ntcapacity - self->ntlength));
1515 }
1516 }
1516 return self->ntlength++;
1517 return self->ntlength++;
1517 }
1518 }
1518
1519
1519 static int nt_insert(indexObject *self, const char *node, int rev)
1520 static int nt_insert(indexObject *self, const char *node, int rev)
1520 {
1521 {
1521 int level = 0;
1522 int level = 0;
1522 int off = 0;
1523 int off = 0;
1523
1524
1524 while (level < 40) {
1525 while (level < 40) {
1525 int k = nt_level(node, level);
1526 int k = nt_level(node, level);
1526 nodetree *n;
1527 nodetree *n;
1527 int v;
1528 int v;
1528
1529
1529 n = &self->nt[off];
1530 n = &self->nt[off];
1530 v = n->children[k];
1531 v = n->children[k];
1531
1532
1532 if (v == 0) {
1533 if (v == 0) {
1533 n->children[k] = -rev - 1;
1534 n->children[k] = -rev - 1;
1534 return 0;
1535 return 0;
1535 }
1536 }
1536 if (v < 0) {
1537 if (v < 0) {
1537 const char *oldnode = index_node(self, -(v + 1));
1538 const char *oldnode = index_node(self, -(v + 1));
1538 int noff;
1539 int noff;
1539
1540
1540 if (!oldnode || !memcmp(oldnode, node, 20)) {
1541 if (!oldnode || !memcmp(oldnode, node, 20)) {
1541 n->children[k] = -rev - 1;
1542 n->children[k] = -rev - 1;
1542 return 0;
1543 return 0;
1543 }
1544 }
1544 noff = nt_new(self);
1545 noff = nt_new(self);
1545 if (noff == -1)
1546 if (noff == -1)
1546 return -1;
1547 return -1;
1547 /* self->nt may have been changed by realloc */
1548 /* self->nt may have been changed by realloc */
1548 self->nt[off].children[k] = noff;
1549 self->nt[off].children[k] = noff;
1549 off = noff;
1550 off = noff;
1550 n = &self->nt[off];
1551 n = &self->nt[off];
1551 n->children[nt_level(oldnode, ++level)] = v;
1552 n->children[nt_level(oldnode, ++level)] = v;
1552 if (level > self->ntdepth)
1553 if (level > self->ntdepth)
1553 self->ntdepth = level;
1554 self->ntdepth = level;
1554 self->ntsplits += 1;
1555 self->ntsplits += 1;
1555 } else {
1556 } else {
1556 level += 1;
1557 level += 1;
1557 off = v;
1558 off = v;
1558 }
1559 }
1559 }
1560 }
1560
1561
1561 return -1;
1562 return -1;
1562 }
1563 }
1563
1564
1564 static int nt_init(indexObject *self)
1565 static int nt_init(indexObject *self)
1565 {
1566 {
1566 if (self->nt == NULL) {
1567 if (self->nt == NULL) {
1567 if (self->raw_length > INT_MAX / sizeof(nodetree)) {
1568 if (self->raw_length > INT_MAX / sizeof(nodetree)) {
1568 PyErr_SetString(PyExc_ValueError, "overflow in nt_init");
1569 PyErr_SetString(PyExc_ValueError, "overflow in nt_init");
1569 return -1;
1570 return -1;
1570 }
1571 }
1571 self->ntcapacity = self->raw_length < 4
1572 self->ntcapacity = self->raw_length < 4
1572 ? 4 : (int)self->raw_length / 2;
1573 ? 4 : (int)self->raw_length / 2;
1573
1574
1574 self->nt = calloc(self->ntcapacity, sizeof(nodetree));
1575 self->nt = calloc(self->ntcapacity, sizeof(nodetree));
1575 if (self->nt == NULL) {
1576 if (self->nt == NULL) {
1576 PyErr_NoMemory();
1577 PyErr_NoMemory();
1577 return -1;
1578 return -1;
1578 }
1579 }
1579 self->ntlength = 1;
1580 self->ntlength = 1;
1580 self->ntrev = (int)index_length(self) - 1;
1581 self->ntrev = (int)index_length(self) - 1;
1581 self->ntlookups = 1;
1582 self->ntlookups = 1;
1582 self->ntmisses = 0;
1583 self->ntmisses = 0;
1583 if (nt_insert(self, nullid, INT_MAX) == -1)
1584 if (nt_insert(self, nullid, INT_MAX) == -1)
1584 return -1;
1585 return -1;
1585 }
1586 }
1586 return 0;
1587 return 0;
1587 }
1588 }
1588
1589
1589 /*
1590 /*
1590 * Return values:
1591 * Return values:
1591 *
1592 *
1592 * -3: error (exception set)
1593 * -3: error (exception set)
1593 * -2: not found (no exception set)
1594 * -2: not found (no exception set)
1594 * rest: valid rev
1595 * rest: valid rev
1595 */
1596 */
1596 static int index_find_node(indexObject *self,
1597 static int index_find_node(indexObject *self,
1597 const char *node, Py_ssize_t nodelen)
1598 const char *node, Py_ssize_t nodelen)
1598 {
1599 {
1599 int rev;
1600 int rev;
1600
1601
1601 self->ntlookups++;
1602 self->ntlookups++;
1602 rev = nt_find(self, node, nodelen, 0);
1603 rev = nt_find(self, node, nodelen, 0);
1603 if (rev >= -1)
1604 if (rev >= -1)
1604 return rev;
1605 return rev;
1605
1606
1606 if (nt_init(self) == -1)
1607 if (nt_init(self) == -1)
1607 return -3;
1608 return -3;
1608
1609
1609 /*
1610 /*
1610 * For the first handful of lookups, we scan the entire index,
1611 * For the first handful of lookups, we scan the entire index,
1611 * and cache only the matching nodes. This optimizes for cases
1612 * and cache only the matching nodes. This optimizes for cases
1612 * like "hg tip", where only a few nodes are accessed.
1613 * like "hg tip", where only a few nodes are accessed.
1613 *
1614 *
1614 * After that, we cache every node we visit, using a single
1615 * After that, we cache every node we visit, using a single
1615 * scan amortized over multiple lookups. This gives the best
1616 * scan amortized over multiple lookups. This gives the best
1616 * bulk performance, e.g. for "hg log".
1617 * bulk performance, e.g. for "hg log".
1617 */
1618 */
1618 if (self->ntmisses++ < 4) {
1619 if (self->ntmisses++ < 4) {
1619 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1620 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1620 const char *n = index_node(self, rev);
1621 const char *n = index_node(self, rev);
1621 if (n == NULL)
1622 if (n == NULL)
1622 return -2;
1623 return -2;
1623 if (memcmp(node, n, nodelen > 20 ? 20 : nodelen) == 0) {
1624 if (memcmp(node, n, nodelen > 20 ? 20 : nodelen) == 0) {
1624 if (nt_insert(self, n, rev) == -1)
1625 if (nt_insert(self, n, rev) == -1)
1625 return -3;
1626 return -3;
1626 break;
1627 break;
1627 }
1628 }
1628 }
1629 }
1629 } else {
1630 } else {
1630 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1631 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1631 const char *n = index_node(self, rev);
1632 const char *n = index_node(self, rev);
1632 if (n == NULL) {
1633 if (n == NULL) {
1633 self->ntrev = rev + 1;
1634 self->ntrev = rev + 1;
1634 return -2;
1635 return -2;
1635 }
1636 }
1636 if (nt_insert(self, n, rev) == -1) {
1637 if (nt_insert(self, n, rev) == -1) {
1637 self->ntrev = rev + 1;
1638 self->ntrev = rev + 1;
1638 return -3;
1639 return -3;
1639 }
1640 }
1640 if (memcmp(node, n, nodelen > 20 ? 20 : nodelen) == 0) {
1641 if (memcmp(node, n, nodelen > 20 ? 20 : nodelen) == 0) {
1641 break;
1642 break;
1642 }
1643 }
1643 }
1644 }
1644 self->ntrev = rev;
1645 self->ntrev = rev;
1645 }
1646 }
1646
1647
1647 if (rev >= 0)
1648 if (rev >= 0)
1648 return rev;
1649 return rev;
1649 return -2;
1650 return -2;
1650 }
1651 }
1651
1652
1652 static void raise_revlog_error(void)
1653 static void raise_revlog_error(void)
1653 {
1654 {
1654 PyObject *mod = NULL, *dict = NULL, *errclass = NULL;
1655 PyObject *mod = NULL, *dict = NULL, *errclass = NULL;
1655
1656
1656 mod = PyImport_ImportModule("mercurial.error");
1657 mod = PyImport_ImportModule("mercurial.error");
1657 if (mod == NULL) {
1658 if (mod == NULL) {
1658 goto cleanup;
1659 goto cleanup;
1659 }
1660 }
1660
1661
1661 dict = PyModule_GetDict(mod);
1662 dict = PyModule_GetDict(mod);
1662 if (dict == NULL) {
1663 if (dict == NULL) {
1663 goto cleanup;
1664 goto cleanup;
1664 }
1665 }
1665 Py_INCREF(dict);
1666 Py_INCREF(dict);
1666
1667
1667 errclass = PyDict_GetItemString(dict, "RevlogError");
1668 errclass = PyDict_GetItemString(dict, "RevlogError");
1668 if (errclass == NULL) {
1669 if (errclass == NULL) {
1669 PyErr_SetString(PyExc_SystemError,
1670 PyErr_SetString(PyExc_SystemError,
1670 "could not find RevlogError");
1671 "could not find RevlogError");
1671 goto cleanup;
1672 goto cleanup;
1672 }
1673 }
1673
1674
1674 /* value of exception is ignored by callers */
1675 /* value of exception is ignored by callers */
1675 PyErr_SetString(errclass, "RevlogError");
1676 PyErr_SetString(errclass, "RevlogError");
1676
1677
1677 cleanup:
1678 cleanup:
1678 Py_XDECREF(dict);
1679 Py_XDECREF(dict);
1679 Py_XDECREF(mod);
1680 Py_XDECREF(mod);
1680 }
1681 }
1681
1682
1682 static PyObject *index_getitem(indexObject *self, PyObject *value)
1683 static PyObject *index_getitem(indexObject *self, PyObject *value)
1683 {
1684 {
1684 char *node;
1685 char *node;
1685 Py_ssize_t nodelen;
1686 Py_ssize_t nodelen;
1686 int rev;
1687 int rev;
1687
1688
1688 if (PyInt_Check(value))
1689 if (PyInt_Check(value))
1689 return index_get(self, PyInt_AS_LONG(value));
1690 return index_get(self, PyInt_AS_LONG(value));
1690
1691
1691 if (node_check(value, &node, &nodelen) == -1)
1692 if (node_check(value, &node, &nodelen) == -1)
1692 return NULL;
1693 return NULL;
1693 rev = index_find_node(self, node, nodelen);
1694 rev = index_find_node(self, node, nodelen);
1694 if (rev >= -1)
1695 if (rev >= -1)
1695 return PyInt_FromLong(rev);
1696 return PyInt_FromLong(rev);
1696 if (rev == -2)
1697 if (rev == -2)
1697 raise_revlog_error();
1698 raise_revlog_error();
1698 return NULL;
1699 return NULL;
1699 }
1700 }
1700
1701
1701 static int nt_partialmatch(indexObject *self, const char *node,
1702 static int nt_partialmatch(indexObject *self, const char *node,
1702 Py_ssize_t nodelen)
1703 Py_ssize_t nodelen)
1703 {
1704 {
1704 int rev;
1705 int rev;
1705
1706
1706 if (nt_init(self) == -1)
1707 if (nt_init(self) == -1)
1707 return -3;
1708 return -3;
1708
1709
1709 if (self->ntrev > 0) {
1710 if (self->ntrev > 0) {
1710 /* ensure that the radix tree is fully populated */
1711 /* ensure that the radix tree is fully populated */
1711 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1712 for (rev = self->ntrev - 1; rev >= 0; rev--) {
1712 const char *n = index_node(self, rev);
1713 const char *n = index_node(self, rev);
1713 if (n == NULL)
1714 if (n == NULL)
1714 return -2;
1715 return -2;
1715 if (nt_insert(self, n, rev) == -1)
1716 if (nt_insert(self, n, rev) == -1)
1716 return -3;
1717 return -3;
1717 }
1718 }
1718 self->ntrev = rev;
1719 self->ntrev = rev;
1719 }
1720 }
1720
1721
1721 return nt_find(self, node, nodelen, 1);
1722 return nt_find(self, node, nodelen, 1);
1722 }
1723 }
1723
1724
1724 static PyObject *index_partialmatch(indexObject *self, PyObject *args)
1725 static PyObject *index_partialmatch(indexObject *self, PyObject *args)
1725 {
1726 {
1726 const char *fullnode;
1727 const char *fullnode;
1727 int nodelen;
1728 int nodelen;
1728 char *node;
1729 char *node;
1729 int rev, i;
1730 int rev, i;
1730
1731
1731 if (!PyArg_ParseTuple(args, "s#", &node, &nodelen))
1732 if (!PyArg_ParseTuple(args, "s#", &node, &nodelen))
1732 return NULL;
1733 return NULL;
1733
1734
1734 if (nodelen < 4) {
1735 if (nodelen < 4) {
1735 PyErr_SetString(PyExc_ValueError, "key too short");
1736 PyErr_SetString(PyExc_ValueError, "key too short");
1736 return NULL;
1737 return NULL;
1737 }
1738 }
1738
1739
1739 if (nodelen > 40) {
1740 if (nodelen > 40) {
1740 PyErr_SetString(PyExc_ValueError, "key too long");
1741 PyErr_SetString(PyExc_ValueError, "key too long");
1741 return NULL;
1742 return NULL;
1742 }
1743 }
1743
1744
1744 for (i = 0; i < nodelen; i++)
1745 for (i = 0; i < nodelen; i++)
1745 hexdigit(node, i);
1746 hexdigit(node, i);
1746 if (PyErr_Occurred()) {
1747 if (PyErr_Occurred()) {
1747 /* input contains non-hex characters */
1748 /* input contains non-hex characters */
1748 PyErr_Clear();
1749 PyErr_Clear();
1749 Py_RETURN_NONE;
1750 Py_RETURN_NONE;
1750 }
1751 }
1751
1752
1752 rev = nt_partialmatch(self, node, nodelen);
1753 rev = nt_partialmatch(self, node, nodelen);
1753
1754
1754 switch (rev) {
1755 switch (rev) {
1755 case -4:
1756 case -4:
1756 raise_revlog_error();
1757 raise_revlog_error();
1757 case -3:
1758 case -3:
1758 return NULL;
1759 return NULL;
1759 case -2:
1760 case -2:
1760 Py_RETURN_NONE;
1761 Py_RETURN_NONE;
1761 case -1:
1762 case -1:
1762 return PyString_FromStringAndSize(nullid, 20);
1763 return PyString_FromStringAndSize(nullid, 20);
1763 }
1764 }
1764
1765
1765 fullnode = index_node(self, rev);
1766 fullnode = index_node(self, rev);
1766 if (fullnode == NULL) {
1767 if (fullnode == NULL) {
1767 PyErr_Format(PyExc_IndexError,
1768 PyErr_Format(PyExc_IndexError,
1768 "could not access rev %d", rev);
1769 "could not access rev %d", rev);
1769 return NULL;
1770 return NULL;
1770 }
1771 }
1771 return PyString_FromStringAndSize(fullnode, 20);
1772 return PyString_FromStringAndSize(fullnode, 20);
1772 }
1773 }
1773
1774
1774 static PyObject *index_m_get(indexObject *self, PyObject *args)
1775 static PyObject *index_m_get(indexObject *self, PyObject *args)
1775 {
1776 {
1776 Py_ssize_t nodelen;
1777 Py_ssize_t nodelen;
1777 PyObject *val;
1778 PyObject *val;
1778 char *node;
1779 char *node;
1779 int rev;
1780 int rev;
1780
1781
1781 if (!PyArg_ParseTuple(args, "O", &val))
1782 if (!PyArg_ParseTuple(args, "O", &val))
1782 return NULL;
1783 return NULL;
1783 if (node_check(val, &node, &nodelen) == -1)
1784 if (node_check(val, &node, &nodelen) == -1)
1784 return NULL;
1785 return NULL;
1785 rev = index_find_node(self, node, nodelen);
1786 rev = index_find_node(self, node, nodelen);
1786 if (rev == -3)
1787 if (rev == -3)
1787 return NULL;
1788 return NULL;
1788 if (rev == -2)
1789 if (rev == -2)
1789 Py_RETURN_NONE;
1790 Py_RETURN_NONE;
1790 return PyInt_FromLong(rev);
1791 return PyInt_FromLong(rev);
1791 }
1792 }
1792
1793
1793 static int index_contains(indexObject *self, PyObject *value)
1794 static int index_contains(indexObject *self, PyObject *value)
1794 {
1795 {
1795 char *node;
1796 char *node;
1796 Py_ssize_t nodelen;
1797 Py_ssize_t nodelen;
1797
1798
1798 if (PyInt_Check(value)) {
1799 if (PyInt_Check(value)) {
1799 long rev = PyInt_AS_LONG(value);
1800 long rev = PyInt_AS_LONG(value);
1800 return rev >= -1 && rev < index_length(self);
1801 return rev >= -1 && rev < index_length(self);
1801 }
1802 }
1802
1803
1803 if (node_check(value, &node, &nodelen) == -1)
1804 if (node_check(value, &node, &nodelen) == -1)
1804 return -1;
1805 return -1;
1805
1806
1806 switch (index_find_node(self, node, nodelen)) {
1807 switch (index_find_node(self, node, nodelen)) {
1807 case -3:
1808 case -3:
1808 return -1;
1809 return -1;
1809 case -2:
1810 case -2:
1810 return 0;
1811 return 0;
1811 default:
1812 default:
1812 return 1;
1813 return 1;
1813 }
1814 }
1814 }
1815 }
1815
1816
1816 typedef uint64_t bitmask;
1817 typedef uint64_t bitmask;
1817
1818
1818 /*
1819 /*
1819 * Given a disjoint set of revs, return all candidates for the
1820 * Given a disjoint set of revs, return all candidates for the
1820 * greatest common ancestor. In revset notation, this is the set
1821 * greatest common ancestor. In revset notation, this is the set
1821 * "heads(::a and ::b and ...)"
1822 * "heads(::a and ::b and ...)"
1822 */
1823 */
1823 static PyObject *find_gca_candidates(indexObject *self, const int *revs,
1824 static PyObject *find_gca_candidates(indexObject *self, const int *revs,
1824 int revcount)
1825 int revcount)
1825 {
1826 {
1826 const bitmask allseen = (1ull << revcount) - 1;
1827 const bitmask allseen = (1ull << revcount) - 1;
1827 const bitmask poison = 1ull << revcount;
1828 const bitmask poison = 1ull << revcount;
1828 PyObject *gca = PyList_New(0);
1829 PyObject *gca = PyList_New(0);
1829 int i, v, interesting;
1830 int i, v, interesting;
1830 int maxrev = -1;
1831 int maxrev = -1;
1831 bitmask sp;
1832 bitmask sp;
1832 bitmask *seen;
1833 bitmask *seen;
1833
1834
1834 if (gca == NULL)
1835 if (gca == NULL)
1835 return PyErr_NoMemory();
1836 return PyErr_NoMemory();
1836
1837
1837 for (i = 0; i < revcount; i++) {
1838 for (i = 0; i < revcount; i++) {
1838 if (revs[i] > maxrev)
1839 if (revs[i] > maxrev)
1839 maxrev = revs[i];
1840 maxrev = revs[i];
1840 }
1841 }
1841
1842
1842 seen = calloc(sizeof(*seen), maxrev + 1);
1843 seen = calloc(sizeof(*seen), maxrev + 1);
1843 if (seen == NULL) {
1844 if (seen == NULL) {
1844 Py_DECREF(gca);
1845 Py_DECREF(gca);
1845 return PyErr_NoMemory();
1846 return PyErr_NoMemory();
1846 }
1847 }
1847
1848
1848 for (i = 0; i < revcount; i++)
1849 for (i = 0; i < revcount; i++)
1849 seen[revs[i]] = 1ull << i;
1850 seen[revs[i]] = 1ull << i;
1850
1851
1851 interesting = revcount;
1852 interesting = revcount;
1852
1853
1853 for (v = maxrev; v >= 0 && interesting; v--) {
1854 for (v = maxrev; v >= 0 && interesting; v--) {
1854 bitmask sv = seen[v];
1855 bitmask sv = seen[v];
1855 int parents[2];
1856 int parents[2];
1856
1857
1857 if (!sv)
1858 if (!sv)
1858 continue;
1859 continue;
1859
1860
1860 if (sv < poison) {
1861 if (sv < poison) {
1861 interesting -= 1;
1862 interesting -= 1;
1862 if (sv == allseen) {
1863 if (sv == allseen) {
1863 PyObject *obj = PyInt_FromLong(v);
1864 PyObject *obj = PyInt_FromLong(v);
1864 if (obj == NULL)
1865 if (obj == NULL)
1865 goto bail;
1866 goto bail;
1866 if (PyList_Append(gca, obj) == -1) {
1867 if (PyList_Append(gca, obj) == -1) {
1867 Py_DECREF(obj);
1868 Py_DECREF(obj);
1868 goto bail;
1869 goto bail;
1869 }
1870 }
1870 sv |= poison;
1871 sv |= poison;
1871 for (i = 0; i < revcount; i++) {
1872 for (i = 0; i < revcount; i++) {
1872 if (revs[i] == v)
1873 if (revs[i] == v)
1873 goto done;
1874 goto done;
1874 }
1875 }
1875 }
1876 }
1876 }
1877 }
1877 if (index_get_parents(self, v, parents, maxrev) < 0)
1878 if (index_get_parents(self, v, parents, maxrev) < 0)
1878 goto bail;
1879 goto bail;
1879
1880
1880 for (i = 0; i < 2; i++) {
1881 for (i = 0; i < 2; i++) {
1881 int p = parents[i];
1882 int p = parents[i];
1882 if (p == -1)
1883 if (p == -1)
1883 continue;
1884 continue;
1884 sp = seen[p];
1885 sp = seen[p];
1885 if (sv < poison) {
1886 if (sv < poison) {
1886 if (sp == 0) {
1887 if (sp == 0) {
1887 seen[p] = sv;
1888 seen[p] = sv;
1888 interesting++;
1889 interesting++;
1889 }
1890 }
1890 else if (sp != sv)
1891 else if (sp != sv)
1891 seen[p] |= sv;
1892 seen[p] |= sv;
1892 } else {
1893 } else {
1893 if (sp && sp < poison)
1894 if (sp && sp < poison)
1894 interesting--;
1895 interesting--;
1895 seen[p] = sv;
1896 seen[p] = sv;
1896 }
1897 }
1897 }
1898 }
1898 }
1899 }
1899
1900
1900 done:
1901 done:
1901 free(seen);
1902 free(seen);
1902 return gca;
1903 return gca;
1903 bail:
1904 bail:
1904 free(seen);
1905 free(seen);
1905 Py_XDECREF(gca);
1906 Py_XDECREF(gca);
1906 return NULL;
1907 return NULL;
1907 }
1908 }
1908
1909
1909 /*
1910 /*
1910 * Given a disjoint set of revs, return the subset with the longest
1911 * Given a disjoint set of revs, return the subset with the longest
1911 * path to the root.
1912 * path to the root.
1912 */
1913 */
1913 static PyObject *find_deepest(indexObject *self, PyObject *revs)
1914 static PyObject *find_deepest(indexObject *self, PyObject *revs)
1914 {
1915 {
1915 const Py_ssize_t revcount = PyList_GET_SIZE(revs);
1916 const Py_ssize_t revcount = PyList_GET_SIZE(revs);
1916 static const Py_ssize_t capacity = 24;
1917 static const Py_ssize_t capacity = 24;
1917 int *depth, *interesting = NULL;
1918 int *depth, *interesting = NULL;
1918 int i, j, v, ninteresting;
1919 int i, j, v, ninteresting;
1919 PyObject *dict = NULL, *keys = NULL;
1920 PyObject *dict = NULL, *keys = NULL;
1920 long *seen = NULL;
1921 long *seen = NULL;
1921 int maxrev = -1;
1922 int maxrev = -1;
1922 long final;
1923 long final;
1923
1924
1924 if (revcount > capacity) {
1925 if (revcount > capacity) {
1925 PyErr_Format(PyExc_OverflowError,
1926 PyErr_Format(PyExc_OverflowError,
1926 "bitset size (%ld) > capacity (%ld)",
1927 "bitset size (%ld) > capacity (%ld)",
1927 (long)revcount, (long)capacity);
1928 (long)revcount, (long)capacity);
1928 return NULL;
1929 return NULL;
1929 }
1930 }
1930
1931
1931 for (i = 0; i < revcount; i++) {
1932 for (i = 0; i < revcount; i++) {
1932 int n = (int)PyInt_AsLong(PyList_GET_ITEM(revs, i));
1933 int n = (int)PyInt_AsLong(PyList_GET_ITEM(revs, i));
1933 if (n > maxrev)
1934 if (n > maxrev)
1934 maxrev = n;
1935 maxrev = n;
1935 }
1936 }
1936
1937
1937 depth = calloc(sizeof(*depth), maxrev + 1);
1938 depth = calloc(sizeof(*depth), maxrev + 1);
1938 if (depth == NULL)
1939 if (depth == NULL)
1939 return PyErr_NoMemory();
1940 return PyErr_NoMemory();
1940
1941
1941 seen = calloc(sizeof(*seen), maxrev + 1);
1942 seen = calloc(sizeof(*seen), maxrev + 1);
1942 if (seen == NULL) {
1943 if (seen == NULL) {
1943 PyErr_NoMemory();
1944 PyErr_NoMemory();
1944 goto bail;
1945 goto bail;
1945 }
1946 }
1946
1947
1947 interesting = calloc(sizeof(*interesting), 2 << revcount);
1948 interesting = calloc(sizeof(*interesting), 2 << revcount);
1948 if (interesting == NULL) {
1949 if (interesting == NULL) {
1949 PyErr_NoMemory();
1950 PyErr_NoMemory();
1950 goto bail;
1951 goto bail;
1951 }
1952 }
1952
1953
1953 if (PyList_Sort(revs) == -1)
1954 if (PyList_Sort(revs) == -1)
1954 goto bail;
1955 goto bail;
1955
1956
1956 for (i = 0; i < revcount; i++) {
1957 for (i = 0; i < revcount; i++) {
1957 int n = (int)PyInt_AsLong(PyList_GET_ITEM(revs, i));
1958 int n = (int)PyInt_AsLong(PyList_GET_ITEM(revs, i));
1958 long b = 1l << i;
1959 long b = 1l << i;
1959 depth[n] = 1;
1960 depth[n] = 1;
1960 seen[n] = b;
1961 seen[n] = b;
1961 interesting[b] = 1;
1962 interesting[b] = 1;
1962 }
1963 }
1963
1964
1964 ninteresting = (int)revcount;
1965 ninteresting = (int)revcount;
1965
1966
1966 for (v = maxrev; v >= 0 && ninteresting > 1; v--) {
1967 for (v = maxrev; v >= 0 && ninteresting > 1; v--) {
1967 int dv = depth[v];
1968 int dv = depth[v];
1968 int parents[2];
1969 int parents[2];
1969 long sv;
1970 long sv;
1970
1971
1971 if (dv == 0)
1972 if (dv == 0)
1972 continue;
1973 continue;
1973
1974
1974 sv = seen[v];
1975 sv = seen[v];
1975 if (index_get_parents(self, v, parents, maxrev) < 0)
1976 if (index_get_parents(self, v, parents, maxrev) < 0)
1976 goto bail;
1977 goto bail;
1977
1978
1978 for (i = 0; i < 2; i++) {
1979 for (i = 0; i < 2; i++) {
1979 int p = parents[i];
1980 int p = parents[i];
1980 long nsp, sp;
1981 long nsp, sp;
1981 int dp;
1982 int dp;
1982
1983
1983 if (p == -1)
1984 if (p == -1)
1984 continue;
1985 continue;
1985
1986
1986 dp = depth[p];
1987 dp = depth[p];
1987 nsp = sp = seen[p];
1988 nsp = sp = seen[p];
1988 if (dp <= dv) {
1989 if (dp <= dv) {
1989 depth[p] = dv + 1;
1990 depth[p] = dv + 1;
1990 if (sp != sv) {
1991 if (sp != sv) {
1991 interesting[sv] += 1;
1992 interesting[sv] += 1;
1992 nsp = seen[p] = sv;
1993 nsp = seen[p] = sv;
1993 if (sp) {
1994 if (sp) {
1994 interesting[sp] -= 1;
1995 interesting[sp] -= 1;
1995 if (interesting[sp] == 0)
1996 if (interesting[sp] == 0)
1996 ninteresting -= 1;
1997 ninteresting -= 1;
1997 }
1998 }
1998 }
1999 }
1999 }
2000 }
2000 else if (dv == dp - 1) {
2001 else if (dv == dp - 1) {
2001 nsp = sp | sv;
2002 nsp = sp | sv;
2002 if (nsp == sp)
2003 if (nsp == sp)
2003 continue;
2004 continue;
2004 seen[p] = nsp;
2005 seen[p] = nsp;
2005 interesting[sp] -= 1;
2006 interesting[sp] -= 1;
2006 if (interesting[sp] == 0 && interesting[nsp] > 0)
2007 if (interesting[sp] == 0 && interesting[nsp] > 0)
2007 ninteresting -= 1;
2008 ninteresting -= 1;
2008 interesting[nsp] += 1;
2009 interesting[nsp] += 1;
2009 }
2010 }
2010 }
2011 }
2011 interesting[sv] -= 1;
2012 interesting[sv] -= 1;
2012 if (interesting[sv] == 0)
2013 if (interesting[sv] == 0)
2013 ninteresting -= 1;
2014 ninteresting -= 1;
2014 }
2015 }
2015
2016
2016 final = 0;
2017 final = 0;
2017 j = ninteresting;
2018 j = ninteresting;
2018 for (i = 0; i < (int)(2 << revcount) && j > 0; i++) {
2019 for (i = 0; i < (int)(2 << revcount) && j > 0; i++) {
2019 if (interesting[i] == 0)
2020 if (interesting[i] == 0)
2020 continue;
2021 continue;
2021 final |= i;
2022 final |= i;
2022 j -= 1;
2023 j -= 1;
2023 }
2024 }
2024 if (final == 0) {
2025 if (final == 0) {
2025 keys = PyList_New(0);
2026 keys = PyList_New(0);
2026 goto bail;
2027 goto bail;
2027 }
2028 }
2028
2029
2029 dict = PyDict_New();
2030 dict = PyDict_New();
2030 if (dict == NULL)
2031 if (dict == NULL)
2031 goto bail;
2032 goto bail;
2032
2033
2033 for (i = 0; i < revcount; i++) {
2034 for (i = 0; i < revcount; i++) {
2034 PyObject *key;
2035 PyObject *key;
2035
2036
2036 if ((final & (1 << i)) == 0)
2037 if ((final & (1 << i)) == 0)
2037 continue;
2038 continue;
2038
2039
2039 key = PyList_GET_ITEM(revs, i);
2040 key = PyList_GET_ITEM(revs, i);
2040 Py_INCREF(key);
2041 Py_INCREF(key);
2041 Py_INCREF(Py_None);
2042 Py_INCREF(Py_None);
2042 if (PyDict_SetItem(dict, key, Py_None) == -1) {
2043 if (PyDict_SetItem(dict, key, Py_None) == -1) {
2043 Py_DECREF(key);
2044 Py_DECREF(key);
2044 Py_DECREF(Py_None);
2045 Py_DECREF(Py_None);
2045 goto bail;
2046 goto bail;
2046 }
2047 }
2047 }
2048 }
2048
2049
2049 keys = PyDict_Keys(dict);
2050 keys = PyDict_Keys(dict);
2050
2051
2051 bail:
2052 bail:
2052 free(depth);
2053 free(depth);
2053 free(seen);
2054 free(seen);
2054 free(interesting);
2055 free(interesting);
2055 Py_XDECREF(dict);
2056 Py_XDECREF(dict);
2056
2057
2057 return keys;
2058 return keys;
2058 }
2059 }
2059
2060
2060 /*
2061 /*
2061 * Given a (possibly overlapping) set of revs, return all the
2062 * Given a (possibly overlapping) set of revs, return all the
2062 * common ancestors heads: heads(::args[0] and ::a[1] and ...)
2063 * common ancestors heads: heads(::args[0] and ::a[1] and ...)
2063 */
2064 */
2064 static PyObject *index_commonancestorsheads(indexObject *self, PyObject *args)
2065 static PyObject *index_commonancestorsheads(indexObject *self, PyObject *args)
2065 {
2066 {
2066 PyObject *ret = NULL;
2067 PyObject *ret = NULL;
2067 Py_ssize_t argcount, i, len;
2068 Py_ssize_t argcount, i, len;
2068 bitmask repeat = 0;
2069 bitmask repeat = 0;
2069 int revcount = 0;
2070 int revcount = 0;
2070 int *revs;
2071 int *revs;
2071
2072
2072 argcount = PySequence_Length(args);
2073 argcount = PySequence_Length(args);
2073 revs = malloc(argcount * sizeof(*revs));
2074 revs = malloc(argcount * sizeof(*revs));
2074 if (argcount > 0 && revs == NULL)
2075 if (argcount > 0 && revs == NULL)
2075 return PyErr_NoMemory();
2076 return PyErr_NoMemory();
2076 len = index_length(self) - 1;
2077 len = index_length(self) - 1;
2077
2078
2078 for (i = 0; i < argcount; i++) {
2079 for (i = 0; i < argcount; i++) {
2079 static const int capacity = 24;
2080 static const int capacity = 24;
2080 PyObject *obj = PySequence_GetItem(args, i);
2081 PyObject *obj = PySequence_GetItem(args, i);
2081 bitmask x;
2082 bitmask x;
2082 long val;
2083 long val;
2083
2084
2084 if (!PyInt_Check(obj)) {
2085 if (!PyInt_Check(obj)) {
2085 PyErr_SetString(PyExc_TypeError,
2086 PyErr_SetString(PyExc_TypeError,
2086 "arguments must all be ints");
2087 "arguments must all be ints");
2087 Py_DECREF(obj);
2088 Py_DECREF(obj);
2088 goto bail;
2089 goto bail;
2089 }
2090 }
2090 val = PyInt_AsLong(obj);
2091 val = PyInt_AsLong(obj);
2091 Py_DECREF(obj);
2092 Py_DECREF(obj);
2092 if (val == -1) {
2093 if (val == -1) {
2093 ret = PyList_New(0);
2094 ret = PyList_New(0);
2094 goto done;
2095 goto done;
2095 }
2096 }
2096 if (val < 0 || val >= len) {
2097 if (val < 0 || val >= len) {
2097 PyErr_SetString(PyExc_IndexError,
2098 PyErr_SetString(PyExc_IndexError,
2098 "index out of range");
2099 "index out of range");
2099 goto bail;
2100 goto bail;
2100 }
2101 }
2101 /* this cheesy bloom filter lets us avoid some more
2102 /* this cheesy bloom filter lets us avoid some more
2102 * expensive duplicate checks in the common set-is-disjoint
2103 * expensive duplicate checks in the common set-is-disjoint
2103 * case */
2104 * case */
2104 x = 1ull << (val & 0x3f);
2105 x = 1ull << (val & 0x3f);
2105 if (repeat & x) {
2106 if (repeat & x) {
2106 int k;
2107 int k;
2107 for (k = 0; k < revcount; k++) {
2108 for (k = 0; k < revcount; k++) {
2108 if (val == revs[k])
2109 if (val == revs[k])
2109 goto duplicate;
2110 goto duplicate;
2110 }
2111 }
2111 }
2112 }
2112 else repeat |= x;
2113 else repeat |= x;
2113 if (revcount >= capacity) {
2114 if (revcount >= capacity) {
2114 PyErr_Format(PyExc_OverflowError,
2115 PyErr_Format(PyExc_OverflowError,
2115 "bitset size (%d) > capacity (%d)",
2116 "bitset size (%d) > capacity (%d)",
2116 revcount, capacity);
2117 revcount, capacity);
2117 goto bail;
2118 goto bail;
2118 }
2119 }
2119 revs[revcount++] = (int)val;
2120 revs[revcount++] = (int)val;
2120 duplicate:;
2121 duplicate:;
2121 }
2122 }
2122
2123
2123 if (revcount == 0) {
2124 if (revcount == 0) {
2124 ret = PyList_New(0);
2125 ret = PyList_New(0);
2125 goto done;
2126 goto done;
2126 }
2127 }
2127 if (revcount == 1) {
2128 if (revcount == 1) {
2128 PyObject *obj;
2129 PyObject *obj;
2129 ret = PyList_New(1);
2130 ret = PyList_New(1);
2130 if (ret == NULL)
2131 if (ret == NULL)
2131 goto bail;
2132 goto bail;
2132 obj = PyInt_FromLong(revs[0]);
2133 obj = PyInt_FromLong(revs[0]);
2133 if (obj == NULL)
2134 if (obj == NULL)
2134 goto bail;
2135 goto bail;
2135 PyList_SET_ITEM(ret, 0, obj);
2136 PyList_SET_ITEM(ret, 0, obj);
2136 goto done;
2137 goto done;
2137 }
2138 }
2138
2139
2139 ret = find_gca_candidates(self, revs, revcount);
2140 ret = find_gca_candidates(self, revs, revcount);
2140 if (ret == NULL)
2141 if (ret == NULL)
2141 goto bail;
2142 goto bail;
2142
2143
2143 done:
2144 done:
2144 free(revs);
2145 free(revs);
2145 return ret;
2146 return ret;
2146
2147
2147 bail:
2148 bail:
2148 free(revs);
2149 free(revs);
2149 Py_XDECREF(ret);
2150 Py_XDECREF(ret);
2150 return NULL;
2151 return NULL;
2151 }
2152 }
2152
2153
2153 /*
2154 /*
2154 * Given a (possibly overlapping) set of revs, return the greatest
2155 * Given a (possibly overlapping) set of revs, return the greatest
2155 * common ancestors: those with the longest path to the root.
2156 * common ancestors: those with the longest path to the root.
2156 */
2157 */
2157 static PyObject *index_ancestors(indexObject *self, PyObject *args)
2158 static PyObject *index_ancestors(indexObject *self, PyObject *args)
2158 {
2159 {
2159 PyObject *gca = index_commonancestorsheads(self, args);
2160 PyObject *gca = index_commonancestorsheads(self, args);
2160 if (gca == NULL)
2161 if (gca == NULL)
2161 return NULL;
2162 return NULL;
2162
2163
2163 if (PyList_GET_SIZE(gca) <= 1) {
2164 if (PyList_GET_SIZE(gca) <= 1) {
2164 Py_INCREF(gca);
2165 Py_INCREF(gca);
2165 return gca;
2166 return gca;
2166 }
2167 }
2167
2168
2168 return find_deepest(self, gca);
2169 return find_deepest(self, gca);
2169 }
2170 }
2170
2171
2171 /*
2172 /*
2172 * Invalidate any trie entries introduced by added revs.
2173 * Invalidate any trie entries introduced by added revs.
2173 */
2174 */
2174 static void nt_invalidate_added(indexObject *self, Py_ssize_t start)
2175 static void nt_invalidate_added(indexObject *self, Py_ssize_t start)
2175 {
2176 {
2176 Py_ssize_t i, len = PyList_GET_SIZE(self->added);
2177 Py_ssize_t i, len = PyList_GET_SIZE(self->added);
2177
2178
2178 for (i = start; i < len; i++) {
2179 for (i = start; i < len; i++) {
2179 PyObject *tuple = PyList_GET_ITEM(self->added, i);
2180 PyObject *tuple = PyList_GET_ITEM(self->added, i);
2180 PyObject *node = PyTuple_GET_ITEM(tuple, 7);
2181 PyObject *node = PyTuple_GET_ITEM(tuple, 7);
2181
2182
2182 nt_insert(self, PyString_AS_STRING(node), -1);
2183 nt_insert(self, PyString_AS_STRING(node), -1);
2183 }
2184 }
2184
2185
2185 if (start == 0)
2186 if (start == 0)
2186 Py_CLEAR(self->added);
2187 Py_CLEAR(self->added);
2187 }
2188 }
2188
2189
2189 /*
2190 /*
2190 * Delete a numeric range of revs, which must be at the end of the
2191 * Delete a numeric range of revs, which must be at the end of the
2191 * range, but exclude the sentinel nullid entry.
2192 * range, but exclude the sentinel nullid entry.
2192 */
2193 */
2193 static int index_slice_del(indexObject *self, PyObject *item)
2194 static int index_slice_del(indexObject *self, PyObject *item)
2194 {
2195 {
2195 Py_ssize_t start, stop, step, slicelength;
2196 Py_ssize_t start, stop, step, slicelength;
2196 Py_ssize_t length = index_length(self);
2197 Py_ssize_t length = index_length(self);
2197 int ret = 0;
2198 int ret = 0;
2198
2199
2199 if (PySlice_GetIndicesEx((PySliceObject*)item, length,
2200 if (PySlice_GetIndicesEx((PySliceObject*)item, length,
2200 &start, &stop, &step, &slicelength) < 0)
2201 &start, &stop, &step, &slicelength) < 0)
2201 return -1;
2202 return -1;
2202
2203
2203 if (slicelength <= 0)
2204 if (slicelength <= 0)
2204 return 0;
2205 return 0;
2205
2206
2206 if ((step < 0 && start < stop) || (step > 0 && start > stop))
2207 if ((step < 0 && start < stop) || (step > 0 && start > stop))
2207 stop = start;
2208 stop = start;
2208
2209
2209 if (step < 0) {
2210 if (step < 0) {
2210 stop = start + 1;
2211 stop = start + 1;
2211 start = stop + step*(slicelength - 1) - 1;
2212 start = stop + step*(slicelength - 1) - 1;
2212 step = -step;
2213 step = -step;
2213 }
2214 }
2214
2215
2215 if (step != 1) {
2216 if (step != 1) {
2216 PyErr_SetString(PyExc_ValueError,
2217 PyErr_SetString(PyExc_ValueError,
2217 "revlog index delete requires step size of 1");
2218 "revlog index delete requires step size of 1");
2218 return -1;
2219 return -1;
2219 }
2220 }
2220
2221
2221 if (stop != length - 1) {
2222 if (stop != length - 1) {
2222 PyErr_SetString(PyExc_IndexError,
2223 PyErr_SetString(PyExc_IndexError,
2223 "revlog index deletion indices are invalid");
2224 "revlog index deletion indices are invalid");
2224 return -1;
2225 return -1;
2225 }
2226 }
2226
2227
2227 if (start < self->length - 1) {
2228 if (start < self->length - 1) {
2228 if (self->nt) {
2229 if (self->nt) {
2229 Py_ssize_t i;
2230 Py_ssize_t i;
2230
2231
2231 for (i = start + 1; i < self->length - 1; i++) {
2232 for (i = start + 1; i < self->length - 1; i++) {
2232 const char *node = index_node(self, i);
2233 const char *node = index_node(self, i);
2233
2234
2234 if (node)
2235 if (node)
2235 nt_insert(self, node, -1);
2236 nt_insert(self, node, -1);
2236 }
2237 }
2237 if (self->added)
2238 if (self->added)
2238 nt_invalidate_added(self, 0);
2239 nt_invalidate_added(self, 0);
2239 if (self->ntrev > start)
2240 if (self->ntrev > start)
2240 self->ntrev = (int)start;
2241 self->ntrev = (int)start;
2241 }
2242 }
2242 self->length = start + 1;
2243 self->length = start + 1;
2243 if (start < self->raw_length) {
2244 if (start < self->raw_length) {
2244 if (self->cache) {
2245 if (self->cache) {
2245 Py_ssize_t i;
2246 Py_ssize_t i;
2246 for (i = start; i < self->raw_length; i++)
2247 for (i = start; i < self->raw_length; i++)
2247 Py_CLEAR(self->cache[i]);
2248 Py_CLEAR(self->cache[i]);
2248 }
2249 }
2249 self->raw_length = start;
2250 self->raw_length = start;
2250 }
2251 }
2251 goto done;
2252 goto done;
2252 }
2253 }
2253
2254
2254 if (self->nt) {
2255 if (self->nt) {
2255 nt_invalidate_added(self, start - self->length + 1);
2256 nt_invalidate_added(self, start - self->length + 1);
2256 if (self->ntrev > start)
2257 if (self->ntrev > start)
2257 self->ntrev = (int)start;
2258 self->ntrev = (int)start;
2258 }
2259 }
2259 if (self->added)
2260 if (self->added)
2260 ret = PyList_SetSlice(self->added, start - self->length + 1,
2261 ret = PyList_SetSlice(self->added, start - self->length + 1,
2261 PyList_GET_SIZE(self->added), NULL);
2262 PyList_GET_SIZE(self->added), NULL);
2262 done:
2263 done:
2263 Py_CLEAR(self->headrevs);
2264 Py_CLEAR(self->headrevs);
2264 return ret;
2265 return ret;
2265 }
2266 }
2266
2267
2267 /*
2268 /*
2268 * Supported ops:
2269 * Supported ops:
2269 *
2270 *
2270 * slice deletion
2271 * slice deletion
2271 * string assignment (extend node->rev mapping)
2272 * string assignment (extend node->rev mapping)
2272 * string deletion (shrink node->rev mapping)
2273 * string deletion (shrink node->rev mapping)
2273 */
2274 */
2274 static int index_assign_subscript(indexObject *self, PyObject *item,
2275 static int index_assign_subscript(indexObject *self, PyObject *item,
2275 PyObject *value)
2276 PyObject *value)
2276 {
2277 {
2277 char *node;
2278 char *node;
2278 Py_ssize_t nodelen;
2279 Py_ssize_t nodelen;
2279 long rev;
2280 long rev;
2280
2281
2281 if (PySlice_Check(item) && value == NULL)
2282 if (PySlice_Check(item) && value == NULL)
2282 return index_slice_del(self, item);
2283 return index_slice_del(self, item);
2283
2284
2284 if (node_check(item, &node, &nodelen) == -1)
2285 if (node_check(item, &node, &nodelen) == -1)
2285 return -1;
2286 return -1;
2286
2287
2287 if (value == NULL)
2288 if (value == NULL)
2288 return self->nt ? nt_insert(self, node, -1) : 0;
2289 return self->nt ? nt_insert(self, node, -1) : 0;
2289 rev = PyInt_AsLong(value);
2290 rev = PyInt_AsLong(value);
2290 if (rev > INT_MAX || rev < 0) {
2291 if (rev > INT_MAX || rev < 0) {
2291 if (!PyErr_Occurred())
2292 if (!PyErr_Occurred())
2292 PyErr_SetString(PyExc_ValueError, "rev out of range");
2293 PyErr_SetString(PyExc_ValueError, "rev out of range");
2293 return -1;
2294 return -1;
2294 }
2295 }
2295
2296
2296 if (nt_init(self) == -1)
2297 if (nt_init(self) == -1)
2297 return -1;
2298 return -1;
2298 return nt_insert(self, node, (int)rev);
2299 return nt_insert(self, node, (int)rev);
2299 }
2300 }
2300
2301
2301 /*
2302 /*
2302 * Find all RevlogNG entries in an index that has inline data. Update
2303 * Find all RevlogNG entries in an index that has inline data. Update
2303 * the optional "offsets" table with those entries.
2304 * the optional "offsets" table with those entries.
2304 */
2305 */
2305 static Py_ssize_t inline_scan(indexObject *self, const char **offsets)
2306 static Py_ssize_t inline_scan(indexObject *self, const char **offsets)
2306 {
2307 {
2307 const char *data = PyString_AS_STRING(self->data);
2308 const char *data = PyString_AS_STRING(self->data);
2308 Py_ssize_t pos = 0;
2309 Py_ssize_t pos = 0;
2309 Py_ssize_t end = PyString_GET_SIZE(self->data);
2310 Py_ssize_t end = PyString_GET_SIZE(self->data);
2310 long incr = v1_hdrsize;
2311 long incr = v1_hdrsize;
2311 Py_ssize_t len = 0;
2312 Py_ssize_t len = 0;
2312
2313
2313 while (pos + v1_hdrsize <= end && pos >= 0) {
2314 while (pos + v1_hdrsize <= end && pos >= 0) {
2314 uint32_t comp_len;
2315 uint32_t comp_len;
2315 /* 3rd element of header is length of compressed inline data */
2316 /* 3rd element of header is length of compressed inline data */
2316 comp_len = getbe32(data + pos + 8);
2317 comp_len = getbe32(data + pos + 8);
2317 incr = v1_hdrsize + comp_len;
2318 incr = v1_hdrsize + comp_len;
2318 if (offsets)
2319 if (offsets)
2319 offsets[len] = data + pos;
2320 offsets[len] = data + pos;
2320 len++;
2321 len++;
2321 pos += incr;
2322 pos += incr;
2322 }
2323 }
2323
2324
2324 if (pos != end) {
2325 if (pos != end) {
2325 if (!PyErr_Occurred())
2326 if (!PyErr_Occurred())
2326 PyErr_SetString(PyExc_ValueError, "corrupt index file");
2327 PyErr_SetString(PyExc_ValueError, "corrupt index file");
2327 return -1;
2328 return -1;
2328 }
2329 }
2329
2330
2330 return len;
2331 return len;
2331 }
2332 }
2332
2333
2333 static int index_init(indexObject *self, PyObject *args)
2334 static int index_init(indexObject *self, PyObject *args)
2334 {
2335 {
2335 PyObject *data_obj, *inlined_obj;
2336 PyObject *data_obj, *inlined_obj;
2336 Py_ssize_t size;
2337 Py_ssize_t size;
2337
2338
2338 /* Initialize before argument-checking to avoid index_dealloc() crash. */
2339 /* Initialize before argument-checking to avoid index_dealloc() crash. */
2339 self->raw_length = 0;
2340 self->raw_length = 0;
2340 self->added = NULL;
2341 self->added = NULL;
2341 self->cache = NULL;
2342 self->cache = NULL;
2342 self->data = NULL;
2343 self->data = NULL;
2343 self->headrevs = NULL;
2344 self->headrevs = NULL;
2344 self->filteredrevs = Py_None;
2345 self->filteredrevs = Py_None;
2345 Py_INCREF(Py_None);
2346 Py_INCREF(Py_None);
2346 self->nt = NULL;
2347 self->nt = NULL;
2347 self->offsets = NULL;
2348 self->offsets = NULL;
2348
2349
2349 if (!PyArg_ParseTuple(args, "OO", &data_obj, &inlined_obj))
2350 if (!PyArg_ParseTuple(args, "OO", &data_obj, &inlined_obj))
2350 return -1;
2351 return -1;
2351 if (!PyString_Check(data_obj)) {
2352 if (!PyString_Check(data_obj)) {
2352 PyErr_SetString(PyExc_TypeError, "data is not a string");
2353 PyErr_SetString(PyExc_TypeError, "data is not a string");
2353 return -1;
2354 return -1;
2354 }
2355 }
2355 size = PyString_GET_SIZE(data_obj);
2356 size = PyString_GET_SIZE(data_obj);
2356
2357
2357 self->inlined = inlined_obj && PyObject_IsTrue(inlined_obj);
2358 self->inlined = inlined_obj && PyObject_IsTrue(inlined_obj);
2358 self->data = data_obj;
2359 self->data = data_obj;
2359
2360
2360 self->ntlength = self->ntcapacity = 0;
2361 self->ntlength = self->ntcapacity = 0;
2361 self->ntdepth = self->ntsplits = 0;
2362 self->ntdepth = self->ntsplits = 0;
2362 self->ntlookups = self->ntmisses = 0;
2363 self->ntlookups = self->ntmisses = 0;
2363 self->ntrev = -1;
2364 self->ntrev = -1;
2364 Py_INCREF(self->data);
2365 Py_INCREF(self->data);
2365
2366
2366 if (self->inlined) {
2367 if (self->inlined) {
2367 Py_ssize_t len = inline_scan(self, NULL);
2368 Py_ssize_t len = inline_scan(self, NULL);
2368 if (len == -1)
2369 if (len == -1)
2369 goto bail;
2370 goto bail;
2370 self->raw_length = len;
2371 self->raw_length = len;
2371 self->length = len + 1;
2372 self->length = len + 1;
2372 } else {
2373 } else {
2373 if (size % v1_hdrsize) {
2374 if (size % v1_hdrsize) {
2374 PyErr_SetString(PyExc_ValueError, "corrupt index file");
2375 PyErr_SetString(PyExc_ValueError, "corrupt index file");
2375 goto bail;
2376 goto bail;
2376 }
2377 }
2377 self->raw_length = size / v1_hdrsize;
2378 self->raw_length = size / v1_hdrsize;
2378 self->length = self->raw_length + 1;
2379 self->length = self->raw_length + 1;
2379 }
2380 }
2380
2381
2381 return 0;
2382 return 0;
2382 bail:
2383 bail:
2383 return -1;
2384 return -1;
2384 }
2385 }
2385
2386
2386 static PyObject *index_nodemap(indexObject *self)
2387 static PyObject *index_nodemap(indexObject *self)
2387 {
2388 {
2388 Py_INCREF(self);
2389 Py_INCREF(self);
2389 return (PyObject *)self;
2390 return (PyObject *)self;
2390 }
2391 }
2391
2392
2392 static void index_dealloc(indexObject *self)
2393 static void index_dealloc(indexObject *self)
2393 {
2394 {
2394 _index_clearcaches(self);
2395 _index_clearcaches(self);
2395 Py_XDECREF(self->filteredrevs);
2396 Py_XDECREF(self->filteredrevs);
2396 Py_XDECREF(self->data);
2397 Py_XDECREF(self->data);
2397 Py_XDECREF(self->added);
2398 Py_XDECREF(self->added);
2398 PyObject_Del(self);
2399 PyObject_Del(self);
2399 }
2400 }
2400
2401
2401 static PySequenceMethods index_sequence_methods = {
2402 static PySequenceMethods index_sequence_methods = {
2402 (lenfunc)index_length, /* sq_length */
2403 (lenfunc)index_length, /* sq_length */
2403 0, /* sq_concat */
2404 0, /* sq_concat */
2404 0, /* sq_repeat */
2405 0, /* sq_repeat */
2405 (ssizeargfunc)index_get, /* sq_item */
2406 (ssizeargfunc)index_get, /* sq_item */
2406 0, /* sq_slice */
2407 0, /* sq_slice */
2407 0, /* sq_ass_item */
2408 0, /* sq_ass_item */
2408 0, /* sq_ass_slice */
2409 0, /* sq_ass_slice */
2409 (objobjproc)index_contains, /* sq_contains */
2410 (objobjproc)index_contains, /* sq_contains */
2410 };
2411 };
2411
2412
2412 static PyMappingMethods index_mapping_methods = {
2413 static PyMappingMethods index_mapping_methods = {
2413 (lenfunc)index_length, /* mp_length */
2414 (lenfunc)index_length, /* mp_length */
2414 (binaryfunc)index_getitem, /* mp_subscript */
2415 (binaryfunc)index_getitem, /* mp_subscript */
2415 (objobjargproc)index_assign_subscript, /* mp_ass_subscript */
2416 (objobjargproc)index_assign_subscript, /* mp_ass_subscript */
2416 };
2417 };
2417
2418
2418 static PyMethodDef index_methods[] = {
2419 static PyMethodDef index_methods[] = {
2419 {"ancestors", (PyCFunction)index_ancestors, METH_VARARGS,
2420 {"ancestors", (PyCFunction)index_ancestors, METH_VARARGS,
2420 "return the gca set of the given revs"},
2421 "return the gca set of the given revs"},
2421 {"commonancestorsheads", (PyCFunction)index_commonancestorsheads,
2422 {"commonancestorsheads", (PyCFunction)index_commonancestorsheads,
2422 METH_VARARGS,
2423 METH_VARARGS,
2423 "return the heads of the common ancestors of the given revs"},
2424 "return the heads of the common ancestors of the given revs"},
2424 {"clearcaches", (PyCFunction)index_clearcaches, METH_NOARGS,
2425 {"clearcaches", (PyCFunction)index_clearcaches, METH_NOARGS,
2425 "clear the index caches"},
2426 "clear the index caches"},
2426 {"get", (PyCFunction)index_m_get, METH_VARARGS,
2427 {"get", (PyCFunction)index_m_get, METH_VARARGS,
2427 "get an index entry"},
2428 "get an index entry"},
2428 {"computephasesmapsets", (PyCFunction)compute_phases_map_sets,
2429 {"computephasesmapsets", (PyCFunction)compute_phases_map_sets,
2429 METH_VARARGS, "compute phases"},
2430 METH_VARARGS, "compute phases"},
2430 {"reachableroots", (PyCFunction)reachableroots, METH_VARARGS,
2431 {"reachableroots", (PyCFunction)reachableroots, METH_VARARGS,
2431 "reachableroots"},
2432 "reachableroots"},
2432 {"headrevs", (PyCFunction)index_headrevs, METH_VARARGS,
2433 {"headrevs", (PyCFunction)index_headrevs, METH_VARARGS,
2433 "get head revisions"}, /* Can do filtering since 3.2 */
2434 "get head revisions"}, /* Can do filtering since 3.2 */
2434 {"headrevsfiltered", (PyCFunction)index_headrevs, METH_VARARGS,
2435 {"headrevsfiltered", (PyCFunction)index_headrevs, METH_VARARGS,
2435 "get filtered head revisions"}, /* Can always do filtering */
2436 "get filtered head revisions"}, /* Can always do filtering */
2436 {"insert", (PyCFunction)index_insert, METH_VARARGS,
2437 {"insert", (PyCFunction)index_insert, METH_VARARGS,
2437 "insert an index entry"},
2438 "insert an index entry"},
2438 {"partialmatch", (PyCFunction)index_partialmatch, METH_VARARGS,
2439 {"partialmatch", (PyCFunction)index_partialmatch, METH_VARARGS,
2439 "match a potentially ambiguous node ID"},
2440 "match a potentially ambiguous node ID"},
2440 {"stats", (PyCFunction)index_stats, METH_NOARGS,
2441 {"stats", (PyCFunction)index_stats, METH_NOARGS,
2441 "stats for the index"},
2442 "stats for the index"},
2442 {NULL} /* Sentinel */
2443 {NULL} /* Sentinel */
2443 };
2444 };
2444
2445
2445 static PyGetSetDef index_getset[] = {
2446 static PyGetSetDef index_getset[] = {
2446 {"nodemap", (getter)index_nodemap, NULL, "nodemap", NULL},
2447 {"nodemap", (getter)index_nodemap, NULL, "nodemap", NULL},
2447 {NULL} /* Sentinel */
2448 {NULL} /* Sentinel */
2448 };
2449 };
2449
2450
2450 static PyTypeObject indexType = {
2451 static PyTypeObject indexType = {
2451 PyObject_HEAD_INIT(NULL)
2452 PyObject_HEAD_INIT(NULL)
2452 0, /* ob_size */
2453 0, /* ob_size */
2453 "parsers.index", /* tp_name */
2454 "parsers.index", /* tp_name */
2454 sizeof(indexObject), /* tp_basicsize */
2455 sizeof(indexObject), /* tp_basicsize */
2455 0, /* tp_itemsize */
2456 0, /* tp_itemsize */
2456 (destructor)index_dealloc, /* tp_dealloc */
2457 (destructor)index_dealloc, /* tp_dealloc */
2457 0, /* tp_print */
2458 0, /* tp_print */
2458 0, /* tp_getattr */
2459 0, /* tp_getattr */
2459 0, /* tp_setattr */
2460 0, /* tp_setattr */
2460 0, /* tp_compare */
2461 0, /* tp_compare */
2461 0, /* tp_repr */
2462 0, /* tp_repr */
2462 0, /* tp_as_number */
2463 0, /* tp_as_number */
2463 &index_sequence_methods, /* tp_as_sequence */
2464 &index_sequence_methods, /* tp_as_sequence */
2464 &index_mapping_methods, /* tp_as_mapping */
2465 &index_mapping_methods, /* tp_as_mapping */
2465 0, /* tp_hash */
2466 0, /* tp_hash */
2466 0, /* tp_call */
2467 0, /* tp_call */
2467 0, /* tp_str */
2468 0, /* tp_str */
2468 0, /* tp_getattro */
2469 0, /* tp_getattro */
2469 0, /* tp_setattro */
2470 0, /* tp_setattro */
2470 0, /* tp_as_buffer */
2471 0, /* tp_as_buffer */
2471 Py_TPFLAGS_DEFAULT, /* tp_flags */
2472 Py_TPFLAGS_DEFAULT, /* tp_flags */
2472 "revlog index", /* tp_doc */
2473 "revlog index", /* tp_doc */
2473 0, /* tp_traverse */
2474 0, /* tp_traverse */
2474 0, /* tp_clear */
2475 0, /* tp_clear */
2475 0, /* tp_richcompare */
2476 0, /* tp_richcompare */
2476 0, /* tp_weaklistoffset */
2477 0, /* tp_weaklistoffset */
2477 0, /* tp_iter */
2478 0, /* tp_iter */
2478 0, /* tp_iternext */
2479 0, /* tp_iternext */
2479 index_methods, /* tp_methods */
2480 index_methods, /* tp_methods */
2480 0, /* tp_members */
2481 0, /* tp_members */
2481 index_getset, /* tp_getset */
2482 index_getset, /* tp_getset */
2482 0, /* tp_base */
2483 0, /* tp_base */
2483 0, /* tp_dict */
2484 0, /* tp_dict */
2484 0, /* tp_descr_get */
2485 0, /* tp_descr_get */
2485 0, /* tp_descr_set */
2486 0, /* tp_descr_set */
2486 0, /* tp_dictoffset */
2487 0, /* tp_dictoffset */
2487 (initproc)index_init, /* tp_init */
2488 (initproc)index_init, /* tp_init */
2488 0, /* tp_alloc */
2489 0, /* tp_alloc */
2489 };
2490 };
2490
2491
2491 /*
2492 /*
2492 * returns a tuple of the form (index, index, cache) with elements as
2493 * returns a tuple of the form (index, index, cache) with elements as
2493 * follows:
2494 * follows:
2494 *
2495 *
2495 * index: an index object that lazily parses RevlogNG records
2496 * index: an index object that lazily parses RevlogNG records
2496 * cache: if data is inlined, a tuple (index_file_content, 0), else None
2497 * cache: if data is inlined, a tuple (index_file_content, 0), else None
2497 *
2498 *
2498 * added complications are for backwards compatibility
2499 * added complications are for backwards compatibility
2499 */
2500 */
2500 static PyObject *parse_index2(PyObject *self, PyObject *args)
2501 static PyObject *parse_index2(PyObject *self, PyObject *args)
2501 {
2502 {
2502 PyObject *tuple = NULL, *cache = NULL;
2503 PyObject *tuple = NULL, *cache = NULL;
2503 indexObject *idx;
2504 indexObject *idx;
2504 int ret;
2505 int ret;
2505
2506
2506 idx = PyObject_New(indexObject, &indexType);
2507 idx = PyObject_New(indexObject, &indexType);
2507 if (idx == NULL)
2508 if (idx == NULL)
2508 goto bail;
2509 goto bail;
2509
2510
2510 ret = index_init(idx, args);
2511 ret = index_init(idx, args);
2511 if (ret == -1)
2512 if (ret == -1)
2512 goto bail;
2513 goto bail;
2513
2514
2514 if (idx->inlined) {
2515 if (idx->inlined) {
2515 cache = Py_BuildValue("iO", 0, idx->data);
2516 cache = Py_BuildValue("iO", 0, idx->data);
2516 if (cache == NULL)
2517 if (cache == NULL)
2517 goto bail;
2518 goto bail;
2518 } else {
2519 } else {
2519 cache = Py_None;
2520 cache = Py_None;
2520 Py_INCREF(cache);
2521 Py_INCREF(cache);
2521 }
2522 }
2522
2523
2523 tuple = Py_BuildValue("NN", idx, cache);
2524 tuple = Py_BuildValue("NN", idx, cache);
2524 if (!tuple)
2525 if (!tuple)
2525 goto bail;
2526 goto bail;
2526 return tuple;
2527 return tuple;
2527
2528
2528 bail:
2529 bail:
2529 Py_XDECREF(idx);
2530 Py_XDECREF(idx);
2530 Py_XDECREF(cache);
2531 Py_XDECREF(cache);
2531 Py_XDECREF(tuple);
2532 Py_XDECREF(tuple);
2532 return NULL;
2533 return NULL;
2533 }
2534 }
2534
2535
2535 #define BUMPED_FIX 1
2536 #define BUMPED_FIX 1
2536 #define USING_SHA_256 2
2537 #define USING_SHA_256 2
2537
2538
2538 static PyObject *readshas(
2539 static PyObject *readshas(
2539 const char *source, unsigned char num, Py_ssize_t hashwidth)
2540 const char *source, unsigned char num, Py_ssize_t hashwidth)
2540 {
2541 {
2541 int i;
2542 int i;
2542 PyObject *list = PyTuple_New(num);
2543 PyObject *list = PyTuple_New(num);
2543 if (list == NULL) {
2544 if (list == NULL) {
2544 return NULL;
2545 return NULL;
2545 }
2546 }
2546 for (i = 0; i < num; i++) {
2547 for (i = 0; i < num; i++) {
2547 PyObject *hash = PyString_FromStringAndSize(source, hashwidth);
2548 PyObject *hash = PyString_FromStringAndSize(source, hashwidth);
2548 if (hash == NULL) {
2549 if (hash == NULL) {
2549 Py_DECREF(list);
2550 Py_DECREF(list);
2550 return NULL;
2551 return NULL;
2551 }
2552 }
2552 PyTuple_SetItem(list, i, hash);
2553 PyTuple_SetItem(list, i, hash);
2553 source += hashwidth;
2554 source += hashwidth;
2554 }
2555 }
2555 return list;
2556 return list;
2556 }
2557 }
2557
2558
2558 static PyObject *fm1readmarker(const char *data, uint32_t *msize)
2559 static PyObject *fm1readmarker(const char *data, uint32_t *msize)
2559 {
2560 {
2560 const char *meta;
2561 const char *meta;
2561
2562
2562 double mtime;
2563 double mtime;
2563 int16_t tz;
2564 int16_t tz;
2564 uint16_t flags;
2565 uint16_t flags;
2565 unsigned char nsuccs, nparents, nmetadata;
2566 unsigned char nsuccs, nparents, nmetadata;
2566 Py_ssize_t hashwidth = 20;
2567 Py_ssize_t hashwidth = 20;
2567
2568
2568 PyObject *prec = NULL, *parents = NULL, *succs = NULL;
2569 PyObject *prec = NULL, *parents = NULL, *succs = NULL;
2569 PyObject *metadata = NULL, *ret = NULL;
2570 PyObject *metadata = NULL, *ret = NULL;
2570 int i;
2571 int i;
2571
2572
2572 *msize = getbe32(data);
2573 *msize = getbe32(data);
2573 data += 4;
2574 data += 4;
2574 mtime = getbefloat64(data);
2575 mtime = getbefloat64(data);
2575 data += 8;
2576 data += 8;
2576 tz = getbeint16(data);
2577 tz = getbeint16(data);
2577 data += 2;
2578 data += 2;
2578 flags = getbeuint16(data);
2579 flags = getbeuint16(data);
2579 data += 2;
2580 data += 2;
2580
2581
2581 if (flags & USING_SHA_256) {
2582 if (flags & USING_SHA_256) {
2582 hashwidth = 32;
2583 hashwidth = 32;
2583 }
2584 }
2584
2585
2585 nsuccs = (unsigned char)(*data++);
2586 nsuccs = (unsigned char)(*data++);
2586 nparents = (unsigned char)(*data++);
2587 nparents = (unsigned char)(*data++);
2587 nmetadata = (unsigned char)(*data++);
2588 nmetadata = (unsigned char)(*data++);
2588
2589
2589 prec = PyString_FromStringAndSize(data, hashwidth);
2590 prec = PyString_FromStringAndSize(data, hashwidth);
2590 data += hashwidth;
2591 data += hashwidth;
2591 if (prec == NULL) {
2592 if (prec == NULL) {
2592 goto bail;
2593 goto bail;
2593 }
2594 }
2594
2595
2595 succs = readshas(data, nsuccs, hashwidth);
2596 succs = readshas(data, nsuccs, hashwidth);
2596 if (succs == NULL) {
2597 if (succs == NULL) {
2597 goto bail;
2598 goto bail;
2598 }
2599 }
2599 data += nsuccs * hashwidth;
2600 data += nsuccs * hashwidth;
2600
2601
2601 if (nparents == 1 || nparents == 2) {
2602 if (nparents == 1 || nparents == 2) {
2602 parents = readshas(data, nparents, hashwidth);
2603 parents = readshas(data, nparents, hashwidth);
2603 if (parents == NULL) {
2604 if (parents == NULL) {
2604 goto bail;
2605 goto bail;
2605 }
2606 }
2606 data += nparents * hashwidth;
2607 data += nparents * hashwidth;
2607 } else {
2608 } else {
2608 parents = Py_None;
2609 parents = Py_None;
2609 }
2610 }
2610
2611
2611 meta = data + (2 * nmetadata);
2612 meta = data + (2 * nmetadata);
2612 metadata = PyTuple_New(nmetadata);
2613 metadata = PyTuple_New(nmetadata);
2613 if (metadata == NULL) {
2614 if (metadata == NULL) {
2614 goto bail;
2615 goto bail;
2615 }
2616 }
2616 for (i = 0; i < nmetadata; i++) {
2617 for (i = 0; i < nmetadata; i++) {
2617 PyObject *tmp, *left = NULL, *right = NULL;
2618 PyObject *tmp, *left = NULL, *right = NULL;
2618 Py_ssize_t metasize = (unsigned char)(*data++);
2619 Py_ssize_t metasize = (unsigned char)(*data++);
2619 left = PyString_FromStringAndSize(meta, metasize);
2620 left = PyString_FromStringAndSize(meta, metasize);
2620 meta += metasize;
2621 meta += metasize;
2621 metasize = (unsigned char)(*data++);
2622 metasize = (unsigned char)(*data++);
2622 right = PyString_FromStringAndSize(meta, metasize);
2623 right = PyString_FromStringAndSize(meta, metasize);
2623 meta += metasize;
2624 meta += metasize;
2624 if (!left || !right) {
2625 if (!left || !right) {
2625 Py_XDECREF(left);
2626 Py_XDECREF(left);
2626 Py_XDECREF(right);
2627 Py_XDECREF(right);
2627 goto bail;
2628 goto bail;
2628 }
2629 }
2629 tmp = PyTuple_Pack(2, left, right);
2630 tmp = PyTuple_Pack(2, left, right);
2630 Py_DECREF(left);
2631 Py_DECREF(left);
2631 Py_DECREF(right);
2632 Py_DECREF(right);
2632 if (!tmp) {
2633 if (!tmp) {
2633 goto bail;
2634 goto bail;
2634 }
2635 }
2635 PyTuple_SetItem(metadata, i, tmp);
2636 PyTuple_SetItem(metadata, i, tmp);
2636 }
2637 }
2637 ret = Py_BuildValue("(OOHO(di)O)", prec, succs, flags,
2638 ret = Py_BuildValue("(OOHO(di)O)", prec, succs, flags,
2638 metadata, mtime, (int)tz * 60, parents);
2639 metadata, mtime, (int)tz * 60, parents);
2639 bail:
2640 bail:
2640 Py_XDECREF(prec);
2641 Py_XDECREF(prec);
2641 Py_XDECREF(succs);
2642 Py_XDECREF(succs);
2642 Py_XDECREF(metadata);
2643 Py_XDECREF(metadata);
2643 if (parents != Py_None)
2644 if (parents != Py_None)
2644 Py_XDECREF(parents);
2645 Py_XDECREF(parents);
2645 return ret;
2646 return ret;
2646 }
2647 }
2647
2648
2648
2649
2649 static PyObject *fm1readmarkers(PyObject *self, PyObject *args) {
2650 static PyObject *fm1readmarkers(PyObject *self, PyObject *args) {
2650 const char *data;
2651 const char *data;
2651 Py_ssize_t datalen;
2652 Py_ssize_t datalen;
2652 /* only unsigned long because python 2.4, should be Py_ssize_t */
2653 /* only unsigned long because python 2.4, should be Py_ssize_t */
2653 unsigned long offset, stop;
2654 unsigned long offset, stop;
2654 PyObject *markers = NULL;
2655 PyObject *markers = NULL;
2655
2656
2656 /* replace kk with nn when we drop Python 2.4 */
2657 /* replace kk with nn when we drop Python 2.4 */
2657 if (!PyArg_ParseTuple(args, "s#kk", &data, &datalen, &offset, &stop)) {
2658 if (!PyArg_ParseTuple(args, "s#kk", &data, &datalen, &offset, &stop)) {
2658 return NULL;
2659 return NULL;
2659 }
2660 }
2660 data += offset;
2661 data += offset;
2661 markers = PyList_New(0);
2662 markers = PyList_New(0);
2662 if (!markers) {
2663 if (!markers) {
2663 return NULL;
2664 return NULL;
2664 }
2665 }
2665 while (offset < stop) {
2666 while (offset < stop) {
2666 uint32_t msize;
2667 uint32_t msize;
2667 int error;
2668 int error;
2668 PyObject *record = fm1readmarker(data, &msize);
2669 PyObject *record = fm1readmarker(data, &msize);
2669 if (!record) {
2670 if (!record) {
2670 goto bail;
2671 goto bail;
2671 }
2672 }
2672 error = PyList_Append(markers, record);
2673 error = PyList_Append(markers, record);
2673 Py_DECREF(record);
2674 Py_DECREF(record);
2674 if (error) {
2675 if (error) {
2675 goto bail;
2676 goto bail;
2676 }
2677 }
2677 data += msize;
2678 data += msize;
2678 offset += msize;
2679 offset += msize;
2679 }
2680 }
2680 return markers;
2681 return markers;
2681 bail:
2682 bail:
2682 Py_DECREF(markers);
2683 Py_DECREF(markers);
2683 return NULL;
2684 return NULL;
2684 }
2685 }
2685
2686
2686 static char parsers_doc[] = "Efficient content parsing.";
2687 static char parsers_doc[] = "Efficient content parsing.";
2687
2688
2688 PyObject *encodedir(PyObject *self, PyObject *args);
2689 PyObject *encodedir(PyObject *self, PyObject *args);
2689 PyObject *pathencode(PyObject *self, PyObject *args);
2690 PyObject *pathencode(PyObject *self, PyObject *args);
2690 PyObject *lowerencode(PyObject *self, PyObject *args);
2691 PyObject *lowerencode(PyObject *self, PyObject *args);
2691
2692
2692 static PyMethodDef methods[] = {
2693 static PyMethodDef methods[] = {
2693 {"pack_dirstate", pack_dirstate, METH_VARARGS, "pack a dirstate\n"},
2694 {"pack_dirstate", pack_dirstate, METH_VARARGS, "pack a dirstate\n"},
2694 {"parse_manifest", parse_manifest, METH_VARARGS, "parse a manifest\n"},
2695 {"parse_manifest", parse_manifest, METH_VARARGS, "parse a manifest\n"},
2695 {"parse_dirstate", parse_dirstate, METH_VARARGS, "parse a dirstate\n"},
2696 {"parse_dirstate", parse_dirstate, METH_VARARGS, "parse a dirstate\n"},
2696 {"parse_index2", parse_index2, METH_VARARGS, "parse a revlog index\n"},
2697 {"parse_index2", parse_index2, METH_VARARGS, "parse a revlog index\n"},
2697 {"asciilower", asciilower, METH_VARARGS, "lowercase an ASCII string\n"},
2698 {"asciilower", asciilower, METH_VARARGS, "lowercase an ASCII string\n"},
2698 {"asciiupper", asciiupper, METH_VARARGS, "uppercase an ASCII string\n"},
2699 {"asciiupper", asciiupper, METH_VARARGS, "uppercase an ASCII string\n"},
2699 {"dict_new_presized", dict_new_presized, METH_VARARGS,
2700 {"dict_new_presized", dict_new_presized, METH_VARARGS,
2700 "construct a dict with an expected size\n"},
2701 "construct a dict with an expected size\n"},
2701 {"make_file_foldmap", make_file_foldmap, METH_VARARGS,
2702 {"make_file_foldmap", make_file_foldmap, METH_VARARGS,
2702 "make file foldmap\n"},
2703 "make file foldmap\n"},
2703 {"encodedir", encodedir, METH_VARARGS, "encodedir a path\n"},
2704 {"encodedir", encodedir, METH_VARARGS, "encodedir a path\n"},
2704 {"pathencode", pathencode, METH_VARARGS, "fncache-encode a path\n"},
2705 {"pathencode", pathencode, METH_VARARGS, "fncache-encode a path\n"},
2705 {"lowerencode", lowerencode, METH_VARARGS, "lower-encode a path\n"},
2706 {"lowerencode", lowerencode, METH_VARARGS, "lower-encode a path\n"},
2706 {"fm1readmarkers", fm1readmarkers, METH_VARARGS,
2707 {"fm1readmarkers", fm1readmarkers, METH_VARARGS,
2707 "parse v1 obsolete markers\n"},
2708 "parse v1 obsolete markers\n"},
2708 {NULL, NULL}
2709 {NULL, NULL}
2709 };
2710 };
2710
2711
2711 void dirs_module_init(PyObject *mod);
2712 void dirs_module_init(PyObject *mod);
2712 void manifest_module_init(PyObject *mod);
2713 void manifest_module_init(PyObject *mod);
2713
2714
2714 static void module_init(PyObject *mod)
2715 static void module_init(PyObject *mod)
2715 {
2716 {
2716 /* This module constant has two purposes. First, it lets us unit test
2717 /* This module constant has two purposes. First, it lets us unit test
2717 * the ImportError raised without hard-coding any error text. This
2718 * the ImportError raised without hard-coding any error text. This
2718 * means we can change the text in the future without breaking tests,
2719 * means we can change the text in the future without breaking tests,
2719 * even across changesets without a recompile. Second, its presence
2720 * even across changesets without a recompile. Second, its presence
2720 * can be used to determine whether the version-checking logic is
2721 * can be used to determine whether the version-checking logic is
2721 * present, which also helps in testing across changesets without a
2722 * present, which also helps in testing across changesets without a
2722 * recompile. Note that this means the pure-Python version of parsers
2723 * recompile. Note that this means the pure-Python version of parsers
2723 * should not have this module constant. */
2724 * should not have this module constant. */
2724 PyModule_AddStringConstant(mod, "versionerrortext", versionerrortext);
2725 PyModule_AddStringConstant(mod, "versionerrortext", versionerrortext);
2725
2726
2726 dirs_module_init(mod);
2727 dirs_module_init(mod);
2727 manifest_module_init(mod);
2728 manifest_module_init(mod);
2728
2729
2729 indexType.tp_new = PyType_GenericNew;
2730 indexType.tp_new = PyType_GenericNew;
2730 if (PyType_Ready(&indexType) < 0 ||
2731 if (PyType_Ready(&indexType) < 0 ||
2731 PyType_Ready(&dirstateTupleType) < 0)
2732 PyType_Ready(&dirstateTupleType) < 0)
2732 return;
2733 return;
2733 Py_INCREF(&indexType);
2734 Py_INCREF(&indexType);
2734 PyModule_AddObject(mod, "index", (PyObject *)&indexType);
2735 PyModule_AddObject(mod, "index", (PyObject *)&indexType);
2735 Py_INCREF(&dirstateTupleType);
2736 Py_INCREF(&dirstateTupleType);
2736 PyModule_AddObject(mod, "dirstatetuple",
2737 PyModule_AddObject(mod, "dirstatetuple",
2737 (PyObject *)&dirstateTupleType);
2738 (PyObject *)&dirstateTupleType);
2738
2739
2739 nullentry = Py_BuildValue("iiiiiiis#", 0, 0, 0,
2740 nullentry = Py_BuildValue("iiiiiiis#", 0, 0, 0,
2740 -1, -1, -1, -1, nullid, 20);
2741 -1, -1, -1, -1, nullid, 20);
2741 if (nullentry)
2742 if (nullentry)
2742 PyObject_GC_UnTrack(nullentry);
2743 PyObject_GC_UnTrack(nullentry);
2743 }
2744 }
2744
2745
2745 static int check_python_version(void)
2746 static int check_python_version(void)
2746 {
2747 {
2747 PyObject *sys = PyImport_ImportModule("sys"), *ver;
2748 PyObject *sys = PyImport_ImportModule("sys"), *ver;
2748 long hexversion;
2749 long hexversion;
2749 if (!sys)
2750 if (!sys)
2750 return -1;
2751 return -1;
2751 ver = PyObject_GetAttrString(sys, "hexversion");
2752 ver = PyObject_GetAttrString(sys, "hexversion");
2752 Py_DECREF(sys);
2753 Py_DECREF(sys);
2753 if (!ver)
2754 if (!ver)
2754 return -1;
2755 return -1;
2755 hexversion = PyInt_AsLong(ver);
2756 hexversion = PyInt_AsLong(ver);
2756 Py_DECREF(ver);
2757 Py_DECREF(ver);
2757 /* sys.hexversion is a 32-bit number by default, so the -1 case
2758 /* sys.hexversion is a 32-bit number by default, so the -1 case
2758 * should only occur in unusual circumstances (e.g. if sys.hexversion
2759 * should only occur in unusual circumstances (e.g. if sys.hexversion
2759 * is manually set to an invalid value). */
2760 * is manually set to an invalid value). */
2760 if ((hexversion == -1) || (hexversion >> 16 != PY_VERSION_HEX >> 16)) {
2761 if ((hexversion == -1) || (hexversion >> 16 != PY_VERSION_HEX >> 16)) {
2761 PyErr_Format(PyExc_ImportError, "%s: The Mercurial extension "
2762 PyErr_Format(PyExc_ImportError, "%s: The Mercurial extension "
2762 "modules were compiled with Python " PY_VERSION ", but "
2763 "modules were compiled with Python " PY_VERSION ", but "
2763 "Mercurial is currently using Python with sys.hexversion=%ld: "
2764 "Mercurial is currently using Python with sys.hexversion=%ld: "
2764 "Python %s\n at: %s", versionerrortext, hexversion,
2765 "Python %s\n at: %s", versionerrortext, hexversion,
2765 Py_GetVersion(), Py_GetProgramFullPath());
2766 Py_GetVersion(), Py_GetProgramFullPath());
2766 return -1;
2767 return -1;
2767 }
2768 }
2768 return 0;
2769 return 0;
2769 }
2770 }
2770
2771
2771 #ifdef IS_PY3K
2772 #ifdef IS_PY3K
2772 static struct PyModuleDef parsers_module = {
2773 static struct PyModuleDef parsers_module = {
2773 PyModuleDef_HEAD_INIT,
2774 PyModuleDef_HEAD_INIT,
2774 "parsers",
2775 "parsers",
2775 parsers_doc,
2776 parsers_doc,
2776 -1,
2777 -1,
2777 methods
2778 methods
2778 };
2779 };
2779
2780
2780 PyMODINIT_FUNC PyInit_parsers(void)
2781 PyMODINIT_FUNC PyInit_parsers(void)
2781 {
2782 {
2782 PyObject *mod;
2783 PyObject *mod;
2783
2784
2784 if (check_python_version() == -1)
2785 if (check_python_version() == -1)
2785 return;
2786 return;
2786 mod = PyModule_Create(&parsers_module);
2787 mod = PyModule_Create(&parsers_module);
2787 module_init(mod);
2788 module_init(mod);
2788 return mod;
2789 return mod;
2789 }
2790 }
2790 #else
2791 #else
2791 PyMODINIT_FUNC initparsers(void)
2792 PyMODINIT_FUNC initparsers(void)
2792 {
2793 {
2793 PyObject *mod;
2794 PyObject *mod;
2794
2795
2795 if (check_python_version() == -1)
2796 if (check_python_version() == -1)
2796 return;
2797 return;
2797 mod = Py_InitModule3("parsers", methods, parsers_doc);
2798 mod = Py_InitModule3("parsers", methods, parsers_doc);
2798 module_init(mod);
2799 module_init(mod);
2799 }
2800 }
2800 #endif
2801 #endif
General Comments 0
You need to be logged in to leave comments. Login now