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