blob: 67700de72858f80225b145be00c2b76668b41d10 [file] [log] [blame]
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001#include "Python.h"
Raymond Hettinger691d8052004-05-30 07:26:47 +00002#include "structmember.h"
Raymond Hettinger756b3f32004-01-29 06:37:52 +00003
4/* collections module implementation of a deque() datatype
5 Written and maintained by Raymond D. Hettinger <python@rcn.com>
6 Copyright (c) 2004 Python Software Foundation.
7 All rights reserved.
8*/
9
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000010/* The block length may be set to any number over 1. Larger numbers
11 * reduce the number of calls to the memory allocator but take more
12 * memory. Ideally, BLOCKLEN should be set with an eye to the
Tim Peters5566e962006-07-28 00:23:15 +000013 * length of a cache line.
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000014 */
15
Raymond Hettinger7d112df2004-11-02 02:11:35 +000016#define BLOCKLEN 62
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000017#define CENTER ((BLOCKLEN - 1) / 2)
Raymond Hettinger756b3f32004-01-29 06:37:52 +000018
Tim Petersd8768d32004-10-01 01:32:53 +000019/* A `dequeobject` is composed of a doubly-linked list of `block` nodes.
20 * This list is not circular (the leftmost block has leftlink==NULL,
21 * and the rightmost block has rightlink==NULL). A deque d's first
22 * element is at d.leftblock[leftindex] and its last element is at
23 * d.rightblock[rightindex]; note that, unlike as for Python slice
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000024 * indices, these indices are inclusive on both ends. By being inclusive
Tim Peters5566e962006-07-28 00:23:15 +000025 * on both ends, algorithms for left and right operations become
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000026 * symmetrical which simplifies the design.
Tim Peters5566e962006-07-28 00:23:15 +000027 *
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000028 * The list of blocks is never empty, so d.leftblock and d.rightblock
29 * are never equal to NULL.
30 *
31 * The indices, d.leftindex and d.rightindex are always in the range
32 * 0 <= index < BLOCKLEN.
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000033 * Their exact relationship is:
34 * (d.leftindex + d.len - 1) % BLOCKLEN == d.rightindex.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000035 *
36 * Empty deques have d.len == 0; d.leftblock==d.rightblock;
37 * d.leftindex == CENTER+1; and d.rightindex == CENTER.
38 * Checking for d.len == 0 is the intended way to see whether d is empty.
39 *
Tim Peters5566e962006-07-28 00:23:15 +000040 * Whenever d.leftblock == d.rightblock,
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000041 * d.leftindex + d.len - 1 == d.rightindex.
Tim Peters5566e962006-07-28 00:23:15 +000042 *
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000043 * However, when d.leftblock != d.rightblock, d.leftindex and d.rightindex
Tim Peters5566e962006-07-28 00:23:15 +000044 * become indices into distinct blocks and either may be larger than the
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000045 * other.
Tim Petersd8768d32004-10-01 01:32:53 +000046 */
47
Raymond Hettinger756b3f32004-01-29 06:37:52 +000048typedef struct BLOCK {
49 struct BLOCK *leftlink;
50 struct BLOCK *rightlink;
51 PyObject *data[BLOCKLEN];
52} block;
53
Raymond Hettingerd3ffd342007-11-10 01:54:03 +000054#define MAXFREEBLOCKS 10
55static int numfreeblocks = 0;
56static block *freeblocks[MAXFREEBLOCKS];
57
Tim Peters6f853562004-10-01 01:04:50 +000058static block *
Raymond Hettingerc5fa9922004-10-06 17:51:54 +000059newblock(block *leftlink, block *rightlink, int len) {
60 block *b;
61 /* To prevent len from overflowing INT_MAX on 64-bit machines, we
62 * refuse to allocate new blocks if the current len is dangerously
63 * close. There is some extra margin to prevent spurious arithmetic
64 * overflows at various places. The following check ensures that
65 * the blocks allocated to the deque, in the worst case, can only
66 * have INT_MAX-2 entries in total.
67 */
68 if (len >= INT_MAX - 2*BLOCKLEN) {
69 PyErr_SetString(PyExc_OverflowError,
70 "cannot add more blocks to the deque");
71 return NULL;
72 }
Raymond Hettingerd3ffd342007-11-10 01:54:03 +000073 if (numfreeblocks) {
74 numfreeblocks -= 1;
75 b = freeblocks[numfreeblocks];
76 } else {
77 b = PyMem_Malloc(sizeof(block));
78 if (b == NULL) {
79 PyErr_NoMemory();
80 return NULL;
81 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +000082 }
83 b->leftlink = leftlink;
84 b->rightlink = rightlink;
85 return b;
86}
87
Raymond Hettingerd3ffd342007-11-10 01:54:03 +000088void
89freeblock(block *b)
90{
91 if (numfreeblocks < MAXFREEBLOCKS) {
92 freeblocks[numfreeblocks] = b;
93 numfreeblocks++;
94 } else {
95 PyMem_Free(b);
96 }
97}
98
Raymond Hettinger756b3f32004-01-29 06:37:52 +000099typedef struct {
100 PyObject_HEAD
101 block *leftblock;
102 block *rightblock;
Tim Petersd8768d32004-10-01 01:32:53 +0000103 int leftindex; /* in range(BLOCKLEN) */
104 int rightindex; /* in range(BLOCKLEN) */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000105 int len;
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000106 int maxlen;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000107 long state; /* incremented whenever the indices move */
Raymond Hettinger691d8052004-05-30 07:26:47 +0000108 PyObject *weakreflist; /* List of weak references */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000109} dequeobject;
110
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000111/* The deque's size limit is d.maxlen. The limit can be zero or positive.
112 * If there is no limit, then d.maxlen == -1.
113 *
114 * After an item is added to a deque, we check to see if the size has grown past
115 * the limit. If it has, we get the size back down to the limit by popping an
116 * item off of the opposite end. The methods that can trigger this are append(),
117 * appendleft(), extend(), and extendleft().
118 */
119
120#define TRIM(d, popfunction) \
121 if (d->maxlen != -1 && d->len > d->maxlen) { \
122 PyObject *rv = popfunction(d, NULL); \
123 assert(rv != NULL && d->len <= d->maxlen); \
124 Py_DECREF(rv); \
125 }
126
Neal Norwitz87f10132004-02-29 15:40:53 +0000127static PyTypeObject deque_type;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000128
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000129static PyObject *
130deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
131{
132 dequeobject *deque;
133 block *b;
134
135 /* create dequeobject structure */
136 deque = (dequeobject *)type->tp_alloc(type, 0);
137 if (deque == NULL)
138 return NULL;
Tim Peters1065f752004-10-01 01:03:29 +0000139
Raymond Hettingerc5fa9922004-10-06 17:51:54 +0000140 b = newblock(NULL, NULL, 0);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000141 if (b == NULL) {
142 Py_DECREF(deque);
143 return NULL;
144 }
145
Raymond Hettinger61f05fb2004-10-01 06:24:12 +0000146 assert(BLOCKLEN >= 2);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000147 deque->leftblock = b;
148 deque->rightblock = b;
Raymond Hettinger61f05fb2004-10-01 06:24:12 +0000149 deque->leftindex = CENTER + 1;
150 deque->rightindex = CENTER;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000151 deque->len = 0;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000152 deque->state = 0;
Raymond Hettinger691d8052004-05-30 07:26:47 +0000153 deque->weakreflist = NULL;
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000154 deque->maxlen = -1;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000155
156 return (PyObject *)deque;
157}
158
159static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000160deque_pop(dequeobject *deque, PyObject *unused)
161{
162 PyObject *item;
163 block *prevblock;
164
165 if (deque->len == 0) {
Raymond Hettinger738ec902004-02-29 02:15:56 +0000166 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000167 return NULL;
168 }
169 item = deque->rightblock->data[deque->rightindex];
170 deque->rightindex--;
171 deque->len--;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000172 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000173
174 if (deque->rightindex == -1) {
175 if (deque->len == 0) {
176 assert(deque->leftblock == deque->rightblock);
177 assert(deque->leftindex == deque->rightindex+1);
178 /* re-center instead of freeing a block */
Raymond Hettinger61f05fb2004-10-01 06:24:12 +0000179 deque->leftindex = CENTER + 1;
180 deque->rightindex = CENTER;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000181 } else {
182 prevblock = deque->rightblock->leftlink;
183 assert(deque->leftblock != deque->rightblock);
Raymond Hettingerd3ffd342007-11-10 01:54:03 +0000184 freeblock(deque->rightblock);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000185 prevblock->rightlink = NULL;
186 deque->rightblock = prevblock;
187 deque->rightindex = BLOCKLEN - 1;
188 }
189 }
190 return item;
191}
192
193PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
194
195static PyObject *
196deque_popleft(dequeobject *deque, PyObject *unused)
197{
198 PyObject *item;
199 block *prevblock;
200
201 if (deque->len == 0) {
Raymond Hettinger738ec902004-02-29 02:15:56 +0000202 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000203 return NULL;
204 }
Neal Norwitzccc56c72006-08-13 18:13:02 +0000205 assert(deque->leftblock != NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000206 item = deque->leftblock->data[deque->leftindex];
207 deque->leftindex++;
208 deque->len--;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000209 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000210
211 if (deque->leftindex == BLOCKLEN) {
212 if (deque->len == 0) {
213 assert(deque->leftblock == deque->rightblock);
214 assert(deque->leftindex == deque->rightindex+1);
215 /* re-center instead of freeing a block */
Raymond Hettinger61f05fb2004-10-01 06:24:12 +0000216 deque->leftindex = CENTER + 1;
217 deque->rightindex = CENTER;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000218 } else {
219 assert(deque->leftblock != deque->rightblock);
220 prevblock = deque->leftblock->rightlink;
Raymond Hettingerd3ffd342007-11-10 01:54:03 +0000221 freeblock(deque->leftblock);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000222 assert(prevblock != NULL);
223 prevblock->leftlink = NULL;
224 deque->leftblock = prevblock;
225 deque->leftindex = 0;
226 }
227 }
228 return item;
229}
230
231PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
232
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000233static PyObject *
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000234deque_append(dequeobject *deque, PyObject *item)
235{
236 deque->state++;
237 if (deque->rightindex == BLOCKLEN-1) {
238 block *b = newblock(deque->rightblock, NULL, deque->len);
239 if (b == NULL)
240 return NULL;
241 assert(deque->rightblock->rightlink == NULL);
242 deque->rightblock->rightlink = b;
243 deque->rightblock = b;
244 deque->rightindex = -1;
245 }
246 Py_INCREF(item);
247 deque->len++;
248 deque->rightindex++;
249 deque->rightblock->data[deque->rightindex] = item;
250 TRIM(deque, deque_popleft);
251 Py_RETURN_NONE;
252}
253
254PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
255
256static PyObject *
257deque_appendleft(dequeobject *deque, PyObject *item)
258{
259 deque->state++;
260 if (deque->leftindex == 0) {
261 block *b = newblock(NULL, deque->leftblock, deque->len);
262 if (b == NULL)
263 return NULL;
264 assert(deque->leftblock->leftlink == NULL);
265 deque->leftblock->leftlink = b;
266 deque->leftblock = b;
267 deque->leftindex = BLOCKLEN;
268 }
269 Py_INCREF(item);
270 deque->len++;
271 deque->leftindex--;
272 deque->leftblock->data[deque->leftindex] = item;
273 TRIM(deque, deque_pop);
274 Py_RETURN_NONE;
275}
276
277PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
278
279static PyObject *
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000280deque_extend(dequeobject *deque, PyObject *iterable)
281{
282 PyObject *it, *item;
283
284 it = PyObject_GetIter(iterable);
285 if (it == NULL)
286 return NULL;
287
288 while ((item = PyIter_Next(it)) != NULL) {
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000289 deque->state++;
Armin Rigo974d7572004-10-02 13:59:34 +0000290 if (deque->rightindex == BLOCKLEN-1) {
Raymond Hettingerc5fa9922004-10-06 17:51:54 +0000291 block *b = newblock(deque->rightblock, NULL,
292 deque->len);
Raymond Hettingerc058fd12004-02-07 02:45:22 +0000293 if (b == NULL) {
294 Py_DECREF(item);
295 Py_DECREF(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000296 return NULL;
Raymond Hettingerc058fd12004-02-07 02:45:22 +0000297 }
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000298 assert(deque->rightblock->rightlink == NULL);
299 deque->rightblock->rightlink = b;
300 deque->rightblock = b;
Armin Rigo974d7572004-10-02 13:59:34 +0000301 deque->rightindex = -1;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000302 }
Armin Rigo974d7572004-10-02 13:59:34 +0000303 deque->len++;
304 deque->rightindex++;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000305 deque->rightblock->data[deque->rightindex] = item;
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000306 TRIM(deque, deque_popleft);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000307 }
308 Py_DECREF(it);
Tim Peters1065f752004-10-01 01:03:29 +0000309 if (PyErr_Occurred())
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000310 return NULL;
311 Py_RETURN_NONE;
312}
313
Tim Peters1065f752004-10-01 01:03:29 +0000314PyDoc_STRVAR(extend_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000315"Extend the right side of the deque with elements from the iterable");
316
317static PyObject *
318deque_extendleft(dequeobject *deque, PyObject *iterable)
319{
320 PyObject *it, *item;
321
322 it = PyObject_GetIter(iterable);
323 if (it == NULL)
324 return NULL;
325
326 while ((item = PyIter_Next(it)) != NULL) {
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000327 deque->state++;
Armin Rigo974d7572004-10-02 13:59:34 +0000328 if (deque->leftindex == 0) {
Raymond Hettingerc5fa9922004-10-06 17:51:54 +0000329 block *b = newblock(NULL, deque->leftblock,
330 deque->len);
Raymond Hettingerc058fd12004-02-07 02:45:22 +0000331 if (b == NULL) {
332 Py_DECREF(item);
333 Py_DECREF(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000334 return NULL;
Raymond Hettingerc058fd12004-02-07 02:45:22 +0000335 }
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000336 assert(deque->leftblock->leftlink == NULL);
337 deque->leftblock->leftlink = b;
338 deque->leftblock = b;
Armin Rigo974d7572004-10-02 13:59:34 +0000339 deque->leftindex = BLOCKLEN;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000340 }
Armin Rigo974d7572004-10-02 13:59:34 +0000341 deque->len++;
342 deque->leftindex--;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000343 deque->leftblock->data[deque->leftindex] = item;
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000344 TRIM(deque, deque_pop);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000345 }
346 Py_DECREF(it);
Raymond Hettingera435c532004-07-09 04:10:20 +0000347 if (PyErr_Occurred())
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000348 return NULL;
349 Py_RETURN_NONE;
350}
351
Tim Peters1065f752004-10-01 01:03:29 +0000352PyDoc_STRVAR(extendleft_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000353"Extend the left side of the deque with elements from the iterable");
354
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000355static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000356_deque_rotate(dequeobject *deque, Py_ssize_t n)
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000357{
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000358 int i, len=deque->len, halflen=(len+1)>>1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000359 PyObject *item, *rv;
360
Raymond Hettingeree33b272004-02-08 04:05:26 +0000361 if (len == 0)
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000362 return 0;
Raymond Hettingeree33b272004-02-08 04:05:26 +0000363 if (n > halflen || n < -halflen) {
364 n %= len;
365 if (n > halflen)
366 n -= len;
367 else if (n < -halflen)
368 n += len;
369 }
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000370
371 for (i=0 ; i<n ; i++) {
372 item = deque_pop(deque, NULL);
Raymond Hettingera435c532004-07-09 04:10:20 +0000373 assert (item != NULL);
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000374 rv = deque_appendleft(deque, item);
375 Py_DECREF(item);
376 if (rv == NULL)
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000377 return -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000378 Py_DECREF(rv);
379 }
380 for (i=0 ; i>n ; i--) {
381 item = deque_popleft(deque, NULL);
Raymond Hettingera435c532004-07-09 04:10:20 +0000382 assert (item != NULL);
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000383 rv = deque_append(deque, item);
384 Py_DECREF(item);
385 if (rv == NULL)
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000386 return -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000387 Py_DECREF(rv);
388 }
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000389 return 0;
390}
391
392static PyObject *
393deque_rotate(dequeobject *deque, PyObject *args)
394{
395 int n=1;
396
397 if (!PyArg_ParseTuple(args, "|i:rotate", &n))
398 return NULL;
399 if (_deque_rotate(deque, n) == 0)
400 Py_RETURN_NONE;
401 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000402}
403
Tim Peters1065f752004-10-01 01:03:29 +0000404PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000405"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000406
Martin v. Löwis18e16552006-02-15 17:27:45 +0000407static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000408deque_len(dequeobject *deque)
409{
410 return deque->len;
411}
412
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000413static PyObject *
414deque_remove(dequeobject *deque, PyObject *value)
415{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000416 Py_ssize_t i, n=deque->len;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000417
418 for (i=0 ; i<n ; i++) {
419 PyObject *item = deque->leftblock->data[deque->leftindex];
420 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000421
422 if (deque->len != n) {
Tim Peters5566e962006-07-28 00:23:15 +0000423 PyErr_SetString(PyExc_IndexError,
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000424 "deque mutated during remove().");
425 return NULL;
426 }
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000427 if (cmp > 0) {
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000428 PyObject *tgt = deque_popleft(deque, NULL);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000429 assert (tgt != NULL);
430 Py_DECREF(tgt);
431 if (_deque_rotate(deque, i) == -1)
432 return NULL;
433 Py_RETURN_NONE;
434 }
435 else if (cmp < 0) {
436 _deque_rotate(deque, i);
437 return NULL;
438 }
439 _deque_rotate(deque, -1);
440 }
441 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
442 return NULL;
443}
444
445PyDoc_STRVAR(remove_doc,
446"D.remove(value) -- remove first occurrence of value.");
447
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000448static int
449deque_clear(dequeobject *deque)
450{
451 PyObject *item;
452
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000453 while (deque->len) {
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000454 item = deque_pop(deque, NULL);
Raymond Hettingera435c532004-07-09 04:10:20 +0000455 assert (item != NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000456 Py_DECREF(item);
457 }
458 assert(deque->leftblock == deque->rightblock &&
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000459 deque->leftindex - 1 == deque->rightindex &&
460 deque->len == 0);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000461 return 0;
462}
463
464static PyObject *
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000465deque_item(dequeobject *deque, int i)
466{
467 block *b;
468 PyObject *item;
Armin Rigo974d7572004-10-02 13:59:34 +0000469 int n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000470
471 if (i < 0 || i >= deque->len) {
472 PyErr_SetString(PyExc_IndexError,
473 "deque index out of range");
474 return NULL;
475 }
476
Raymond Hettinger6c79a512004-03-04 08:00:54 +0000477 if (i == 0) {
478 i = deque->leftindex;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000479 b = deque->leftblock;
Raymond Hettinger6c79a512004-03-04 08:00:54 +0000480 } else if (i == deque->len - 1) {
481 i = deque->rightindex;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000482 b = deque->rightblock;
Raymond Hettinger6c79a512004-03-04 08:00:54 +0000483 } else {
484 i += deque->leftindex;
485 n = i / BLOCKLEN;
486 i %= BLOCKLEN;
Armin Rigo974d7572004-10-02 13:59:34 +0000487 if (index < (deque->len >> 1)) {
Raymond Hettinger6c79a512004-03-04 08:00:54 +0000488 b = deque->leftblock;
489 while (n--)
490 b = b->rightlink;
491 } else {
492 n = (deque->leftindex + deque->len - 1) / BLOCKLEN - n;
493 b = deque->rightblock;
494 while (n--)
495 b = b->leftlink;
496 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000497 }
498 item = b->data[i];
499 Py_INCREF(item);
500 return item;
501}
502
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000503/* delitem() implemented in terms of rotate for simplicity and reasonable
504 performance near the end points. If for some reason this method becomes
Tim Peters1065f752004-10-01 01:03:29 +0000505 popular, it is not hard to re-implement this using direct data movement
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000506 (similar to code in list slice assignment) and achieve a two or threefold
507 performance boost.
508*/
509
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000510static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000511deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000512{
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000513 PyObject *item;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000514
Tim Peters1065f752004-10-01 01:03:29 +0000515 assert (i >= 0 && i < deque->len);
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000516 if (_deque_rotate(deque, -i) == -1)
517 return -1;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000518
519 item = deque_popleft(deque, NULL);
Raymond Hettingera435c532004-07-09 04:10:20 +0000520 assert (item != NULL);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000521 Py_DECREF(item);
522
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000523 return _deque_rotate(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000524}
525
526static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000527deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000528{
529 PyObject *old_value;
530 block *b;
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000531 Py_ssize_t n, len=deque->len, halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000532
Raymond Hettingera435c532004-07-09 04:10:20 +0000533 if (i < 0 || i >= len) {
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000534 PyErr_SetString(PyExc_IndexError,
535 "deque index out of range");
536 return -1;
537 }
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000538 if (v == NULL)
539 return deque_del_item(deque, i);
540
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000541 i += deque->leftindex;
542 n = i / BLOCKLEN;
543 i %= BLOCKLEN;
Raymond Hettingera435c532004-07-09 04:10:20 +0000544 if (index <= halflen) {
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000545 b = deque->leftblock;
546 while (n--)
547 b = b->rightlink;
548 } else {
Raymond Hettingera435c532004-07-09 04:10:20 +0000549 n = (deque->leftindex + len - 1) / BLOCKLEN - n;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000550 b = deque->rightblock;
551 while (n--)
552 b = b->leftlink;
553 }
554 Py_INCREF(v);
555 old_value = b->data[i];
556 b->data[i] = v;
557 Py_DECREF(old_value);
558 return 0;
559}
560
561static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000562deque_clearmethod(dequeobject *deque)
563{
Raymond Hettingera435c532004-07-09 04:10:20 +0000564 int rv;
565
566 rv = deque_clear(deque);
567 assert (rv != -1);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000568 Py_RETURN_NONE;
569}
570
571PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
572
573static void
574deque_dealloc(dequeobject *deque)
575{
576 PyObject_GC_UnTrack(deque);
Raymond Hettinger691d8052004-05-30 07:26:47 +0000577 if (deque->weakreflist != NULL)
578 PyObject_ClearWeakRefs((PyObject *) deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000579 if (deque->leftblock != NULL) {
Raymond Hettingere9c89e82004-07-19 00:10:24 +0000580 deque_clear(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000581 assert(deque->leftblock != NULL);
Raymond Hettingerd3ffd342007-11-10 01:54:03 +0000582 freeblock(deque->leftblock);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000583 }
584 deque->leftblock = NULL;
585 deque->rightblock = NULL;
Christian Heimese93237d2007-12-19 02:37:44 +0000586 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000587}
588
589static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000590deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000591{
Tim Peters10c7e862004-10-01 02:01:04 +0000592 block *b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000593 PyObject *item;
Tim Peters10c7e862004-10-01 02:01:04 +0000594 int index;
595 int indexlo = deque->leftindex;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000596
Tim Peters10c7e862004-10-01 02:01:04 +0000597 for (b = deque->leftblock; b != NULL; b = b->rightlink) {
598 const int indexhi = b == deque->rightblock ?
599 deque->rightindex :
600 BLOCKLEN - 1;
601
602 for (index = indexlo; index <= indexhi; ++index) {
603 item = b->data[index];
604 Py_VISIT(item);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000605 }
Tim Peters10c7e862004-10-01 02:01:04 +0000606 indexlo = 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000607 }
608 return 0;
609}
610
611static long
612deque_nohash(PyObject *self)
613{
614 PyErr_SetString(PyExc_TypeError, "deque objects are unhashable");
615 return -1;
616}
617
618static PyObject *
619deque_copy(PyObject *deque)
620{
Raymond Hettinger68995862007-10-10 00:26:46 +0000621 if (((dequeobject *)deque)->maxlen == -1)
Christian Heimese93237d2007-12-19 02:37:44 +0000622 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
Raymond Hettinger68995862007-10-10 00:26:46 +0000623 else
Christian Heimese93237d2007-12-19 02:37:44 +0000624 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
Raymond Hettinger68995862007-10-10 00:26:46 +0000625 deque, ((dequeobject *)deque)->maxlen, NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000626}
627
628PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
629
630static PyObject *
631deque_reduce(dequeobject *deque)
632{
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000633 PyObject *dict, *result, *aslist;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000634
Raymond Hettinger952f8802004-11-09 07:27:35 +0000635 dict = PyObject_GetAttrString((PyObject *)deque, "__dict__");
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000636 if (dict == NULL)
Raymond Hettinger952f8802004-11-09 07:27:35 +0000637 PyErr_Clear();
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000638 aslist = PySequence_List((PyObject *)deque);
639 if (aslist == NULL) {
Neal Norwitzc47cf7d2007-10-05 03:39:17 +0000640 Py_XDECREF(dict);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000641 return NULL;
642 }
Raymond Hettinger68995862007-10-10 00:26:46 +0000643 if (dict == NULL) {
644 if (deque->maxlen == -1)
Christian Heimese93237d2007-12-19 02:37:44 +0000645 result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
Raymond Hettinger68995862007-10-10 00:26:46 +0000646 else
Christian Heimese93237d2007-12-19 02:37:44 +0000647 result = Py_BuildValue("O(Oi)", Py_TYPE(deque), aslist, deque->maxlen);
Raymond Hettinger68995862007-10-10 00:26:46 +0000648 } else {
649 if (deque->maxlen == -1)
Christian Heimese93237d2007-12-19 02:37:44 +0000650 result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
Raymond Hettinger68995862007-10-10 00:26:46 +0000651 else
Christian Heimese93237d2007-12-19 02:37:44 +0000652 result = Py_BuildValue("O(Oi)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
Raymond Hettinger68995862007-10-10 00:26:46 +0000653 }
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000654 Py_XDECREF(dict);
655 Py_DECREF(aslist);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000656 return result;
657}
658
659PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
660
661static PyObject *
662deque_repr(PyObject *deque)
663{
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000664 PyObject *aslist, *result, *fmt;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000665 int i;
666
667 i = Py_ReprEnter(deque);
668 if (i != 0) {
669 if (i < 0)
670 return NULL;
671 return PyString_FromString("[...]");
672 }
673
674 aslist = PySequence_List(deque);
675 if (aslist == NULL) {
676 Py_ReprLeave(deque);
677 return NULL;
678 }
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000679 if (((dequeobject *)deque)->maxlen != -1)
680 fmt = PyString_FromFormat("deque(%%r, maxlen=%i)",
681 ((dequeobject *)deque)->maxlen);
682 else
683 fmt = PyString_FromString("deque(%r)");
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000684 if (fmt == NULL) {
685 Py_DECREF(aslist);
686 Py_ReprLeave(deque);
687 return NULL;
688 }
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000689 result = PyString_Format(fmt, aslist);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000690 Py_DECREF(fmt);
691 Py_DECREF(aslist);
692 Py_ReprLeave(deque);
693 return result;
694}
695
696static int
697deque_tp_print(PyObject *deque, FILE *fp, int flags)
698{
699 PyObject *it, *item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000700 char *emit = ""; /* No separator emitted on first pass */
701 char *separator = ", ";
702 int i;
703
704 i = Py_ReprEnter(deque);
705 if (i != 0) {
706 if (i < 0)
707 return i;
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000708 Py_BEGIN_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000709 fputs("[...]", fp);
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000710 Py_END_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000711 return 0;
712 }
713
714 it = PyObject_GetIter(deque);
715 if (it == NULL)
716 return -1;
717
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000718 Py_BEGIN_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000719 fputs("deque([", fp);
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000720 Py_END_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000721 while ((item = PyIter_Next(it)) != NULL) {
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000722 Py_BEGIN_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000723 fputs(emit, fp);
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000724 Py_END_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000725 emit = separator;
726 if (PyObject_Print(item, fp, 0) != 0) {
727 Py_DECREF(item);
728 Py_DECREF(it);
729 Py_ReprLeave(deque);
730 return -1;
731 }
732 Py_DECREF(item);
733 }
734 Py_ReprLeave(deque);
735 Py_DECREF(it);
Tim Peters1065f752004-10-01 01:03:29 +0000736 if (PyErr_Occurred())
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000737 return -1;
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000738
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000739 Py_BEGIN_ALLOW_THREADS
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000740 if (((dequeobject *)deque)->maxlen == -1)
741 fputs("])", fp);
742 else
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000743 fprintf(fp, "], maxlen=%d)", ((dequeobject *)deque)->maxlen);
744 Py_END_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000745 return 0;
746}
747
Raymond Hettinger738ec902004-02-29 02:15:56 +0000748static PyObject *
749deque_richcompare(PyObject *v, PyObject *w, int op)
750{
751 PyObject *it1=NULL, *it2=NULL, *x, *y;
Armin Rigo974d7572004-10-02 13:59:34 +0000752 int b, vs, ws, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000753
Tim Peters1065f752004-10-01 01:03:29 +0000754 if (!PyObject_TypeCheck(v, &deque_type) ||
Raymond Hettinger285cfcc2004-05-18 18:15:03 +0000755 !PyObject_TypeCheck(w, &deque_type)) {
Raymond Hettinger738ec902004-02-29 02:15:56 +0000756 Py_INCREF(Py_NotImplemented);
757 return Py_NotImplemented;
758 }
759
760 /* Shortcuts */
761 vs = ((dequeobject *)v)->len;
762 ws = ((dequeobject *)w)->len;
763 if (op == Py_EQ) {
764 if (v == w)
765 Py_RETURN_TRUE;
766 if (vs != ws)
767 Py_RETURN_FALSE;
768 }
769 if (op == Py_NE) {
770 if (v == w)
771 Py_RETURN_FALSE;
772 if (vs != ws)
773 Py_RETURN_TRUE;
774 }
775
776 /* Search for the first index where items are different */
777 it1 = PyObject_GetIter(v);
778 if (it1 == NULL)
779 goto done;
780 it2 = PyObject_GetIter(w);
781 if (it2 == NULL)
782 goto done;
Armin Rigo974d7572004-10-02 13:59:34 +0000783 for (;;) {
Raymond Hettinger738ec902004-02-29 02:15:56 +0000784 x = PyIter_Next(it1);
Armin Rigo974d7572004-10-02 13:59:34 +0000785 if (x == NULL && PyErr_Occurred())
Raymond Hettinger738ec902004-02-29 02:15:56 +0000786 goto done;
787 y = PyIter_Next(it2);
Armin Rigo974d7572004-10-02 13:59:34 +0000788 if (x == NULL || y == NULL)
789 break;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000790 b = PyObject_RichCompareBool(x, y, Py_EQ);
791 if (b == 0) {
792 cmp = PyObject_RichCompareBool(x, y, op);
793 Py_DECREF(x);
794 Py_DECREF(y);
795 goto done;
796 }
797 Py_DECREF(x);
798 Py_DECREF(y);
799 if (b == -1)
800 goto done;
801 }
Armin Rigo974d7572004-10-02 13:59:34 +0000802 /* We reached the end of one deque or both */
803 Py_XDECREF(x);
804 Py_XDECREF(y);
805 if (PyErr_Occurred())
806 goto done;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000807 switch (op) {
Armin Rigo974d7572004-10-02 13:59:34 +0000808 case Py_LT: cmp = y != NULL; break; /* if w was longer */
809 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
810 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
811 case Py_NE: cmp = x != y; break; /* if one deque continues */
812 case Py_GT: cmp = x != NULL; break; /* if v was longer */
813 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
Raymond Hettinger738ec902004-02-29 02:15:56 +0000814 }
Tim Peters1065f752004-10-01 01:03:29 +0000815
Raymond Hettinger738ec902004-02-29 02:15:56 +0000816done:
817 Py_XDECREF(it1);
818 Py_XDECREF(it2);
819 if (cmp == 1)
820 Py_RETURN_TRUE;
821 if (cmp == 0)
822 Py_RETURN_FALSE;
823 return NULL;
824}
825
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000826static int
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000827deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000828{
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000829 PyObject *iterable = NULL;
Raymond Hettinger68995862007-10-10 00:26:46 +0000830 PyObject *maxlenobj = NULL;
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000831 int maxlen = -1;
832 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000833
Raymond Hettinger68995862007-10-10 00:26:46 +0000834 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj))
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000835 return -1;
Raymond Hettinger68995862007-10-10 00:26:46 +0000836 if (maxlenobj != NULL && maxlenobj != Py_None) {
837 maxlen = PyInt_AsLong(maxlenobj);
838 if (maxlen == -1 && PyErr_Occurred())
839 return -1;
840 if (maxlen < 0) {
841 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
842 return -1;
843 }
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000844 }
845 deque->maxlen = maxlen;
Raymond Hettingeradf9ffd2007-12-13 00:08:37 +0000846 deque_clear(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000847 if (iterable != NULL) {
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000848 PyObject *rv = deque_extend(deque, iterable);
849 if (rv == NULL)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000850 return -1;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000851 Py_DECREF(rv);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000852 }
853 return 0;
854}
855
856static PySequenceMethods deque_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000857 (lenfunc)deque_len, /* sq_length */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000858 0, /* sq_concat */
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000859 0, /* sq_repeat */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000860 (ssizeargfunc)deque_item, /* sq_item */
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000861 0, /* sq_slice */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000862 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000863};
864
865/* deque object ********************************************************/
866
867static PyObject *deque_iter(dequeobject *deque);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000868static PyObject *deque_reviter(dequeobject *deque);
Tim Peters1065f752004-10-01 01:03:29 +0000869PyDoc_STRVAR(reversed_doc,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000870 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000871
872static PyMethodDef deque_methods[] = {
Tim Peters1065f752004-10-01 01:03:29 +0000873 {"append", (PyCFunction)deque_append,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000874 METH_O, append_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000875 {"appendleft", (PyCFunction)deque_appendleft,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000876 METH_O, appendleft_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000877 {"clear", (PyCFunction)deque_clearmethod,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000878 METH_NOARGS, clear_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000879 {"__copy__", (PyCFunction)deque_copy,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000880 METH_NOARGS, copy_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000881 {"extend", (PyCFunction)deque_extend,
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000882 METH_O, extend_doc},
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000883 {"extendleft", (PyCFunction)deque_extendleft,
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000884 METH_O, extendleft_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000885 {"pop", (PyCFunction)deque_pop,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000886 METH_NOARGS, pop_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000887 {"popleft", (PyCFunction)deque_popleft,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000888 METH_NOARGS, popleft_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000889 {"__reduce__", (PyCFunction)deque_reduce,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000890 METH_NOARGS, reduce_doc},
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000891 {"remove", (PyCFunction)deque_remove,
892 METH_O, remove_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000893 {"__reversed__", (PyCFunction)deque_reviter,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000894 METH_NOARGS, reversed_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000895 {"rotate", (PyCFunction)deque_rotate,
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000896 METH_VARARGS, rotate_doc},
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000897 {NULL, NULL} /* sentinel */
898};
899
900PyDoc_STRVAR(deque_doc,
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000901"deque(iterable[, maxlen]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000902\n\
903Build an ordered collection accessible from endpoints only.");
904
Neal Norwitz87f10132004-02-29 15:40:53 +0000905static PyTypeObject deque_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +0000906 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000907 "collections.deque", /* tp_name */
908 sizeof(dequeobject), /* tp_basicsize */
909 0, /* tp_itemsize */
910 /* methods */
911 (destructor)deque_dealloc, /* tp_dealloc */
Georg Brandld37ac692006-03-30 11:58:57 +0000912 deque_tp_print, /* tp_print */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000913 0, /* tp_getattr */
914 0, /* tp_setattr */
915 0, /* tp_compare */
Georg Brandld37ac692006-03-30 11:58:57 +0000916 deque_repr, /* tp_repr */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000917 0, /* tp_as_number */
918 &deque_as_sequence, /* tp_as_sequence */
919 0, /* tp_as_mapping */
920 deque_nohash, /* tp_hash */
921 0, /* tp_call */
922 0, /* tp_str */
923 PyObject_GenericGetAttr, /* tp_getattro */
924 0, /* tp_setattro */
925 0, /* tp_as_buffer */
Raymond Hettinger691d8052004-05-30 07:26:47 +0000926 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
927 Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000928 deque_doc, /* tp_doc */
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000929 (traverseproc)deque_traverse, /* tp_traverse */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000930 (inquiry)deque_clear, /* tp_clear */
Raymond Hettinger738ec902004-02-29 02:15:56 +0000931 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Raymond Hettinger691d8052004-05-30 07:26:47 +0000932 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000933 (getiterfunc)deque_iter, /* tp_iter */
934 0, /* tp_iternext */
935 deque_methods, /* tp_methods */
936 0, /* tp_members */
937 0, /* tp_getset */
938 0, /* tp_base */
939 0, /* tp_dict */
940 0, /* tp_descr_get */
941 0, /* tp_descr_set */
942 0, /* tp_dictoffset */
943 (initproc)deque_init, /* tp_init */
944 PyType_GenericAlloc, /* tp_alloc */
945 deque_new, /* tp_new */
946 PyObject_GC_Del, /* tp_free */
947};
948
949/*********************** Deque Iterator **************************/
950
951typedef struct {
952 PyObject_HEAD
953 int index;
954 block *b;
955 dequeobject *deque;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000956 long state; /* state when the iterator is created */
957 int counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000958} dequeiterobject;
959
960PyTypeObject dequeiter_type;
961
962static PyObject *
963deque_iter(dequeobject *deque)
964{
965 dequeiterobject *it;
966
967 it = PyObject_New(dequeiterobject, &dequeiter_type);
968 if (it == NULL)
969 return NULL;
970 it->b = deque->leftblock;
971 it->index = deque->leftindex;
972 Py_INCREF(deque);
973 it->deque = deque;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000974 it->state = deque->state;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000975 it->counter = deque->len;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000976 return (PyObject *)it;
977}
978
979static void
980dequeiter_dealloc(dequeiterobject *dio)
981{
982 Py_XDECREF(dio->deque);
Christian Heimese93237d2007-12-19 02:37:44 +0000983 Py_TYPE(dio)->tp_free(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000984}
985
986static PyObject *
987dequeiter_next(dequeiterobject *it)
988{
989 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000990
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000991 if (it->deque->state != it->state) {
Raymond Hettinger7892b1c2004-04-12 18:10:01 +0000992 it->counter = 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000993 PyErr_SetString(PyExc_RuntimeError,
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000994 "deque mutated during iteration");
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000995 return NULL;
996 }
Raymond Hettinger51c2f6c2007-01-08 18:09:20 +0000997 if (it->counter == 0)
998 return NULL;
Tim Peters5566e962006-07-28 00:23:15 +0000999 assert (!(it->b == it->deque->rightblock &&
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001000 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001001
1002 item = it->b->data[it->index];
1003 it->index++;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001004 it->counter--;
1005 if (it->index == BLOCKLEN && it->counter > 0) {
1006 assert (it->b->rightlink != NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001007 it->b = it->b->rightlink;
1008 it->index = 0;
1009 }
1010 Py_INCREF(item);
1011 return item;
1012}
1013
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001014static PyObject *
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001015dequeiter_len(dequeiterobject *it)
1016{
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001017 return PyInt_FromLong(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001018}
1019
Armin Rigof5b3e362006-02-11 21:32:43 +00001020PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001021
1022static PyMethodDef dequeiter_methods[] = {
Armin Rigof5b3e362006-02-11 21:32:43 +00001023 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001024 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001025};
1026
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001027PyTypeObject dequeiter_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001028 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001029 "deque_iterator", /* tp_name */
1030 sizeof(dequeiterobject), /* tp_basicsize */
1031 0, /* tp_itemsize */
1032 /* methods */
1033 (destructor)dequeiter_dealloc, /* tp_dealloc */
1034 0, /* tp_print */
1035 0, /* tp_getattr */
1036 0, /* tp_setattr */
1037 0, /* tp_compare */
1038 0, /* tp_repr */
1039 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001040 0, /* tp_as_sequence */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001041 0, /* tp_as_mapping */
1042 0, /* tp_hash */
1043 0, /* tp_call */
1044 0, /* tp_str */
1045 PyObject_GenericGetAttr, /* tp_getattro */
1046 0, /* tp_setattro */
1047 0, /* tp_as_buffer */
1048 Py_TPFLAGS_DEFAULT, /* tp_flags */
1049 0, /* tp_doc */
1050 0, /* tp_traverse */
1051 0, /* tp_clear */
1052 0, /* tp_richcompare */
1053 0, /* tp_weaklistoffset */
1054 PyObject_SelfIter, /* tp_iter */
1055 (iternextfunc)dequeiter_next, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001056 dequeiter_methods, /* tp_methods */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001057 0,
1058};
1059
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001060/*********************** Deque Reverse Iterator **************************/
1061
1062PyTypeObject dequereviter_type;
1063
1064static PyObject *
1065deque_reviter(dequeobject *deque)
1066{
1067 dequeiterobject *it;
1068
1069 it = PyObject_New(dequeiterobject, &dequereviter_type);
1070 if (it == NULL)
1071 return NULL;
1072 it->b = deque->rightblock;
1073 it->index = deque->rightindex;
1074 Py_INCREF(deque);
1075 it->deque = deque;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001076 it->state = deque->state;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001077 it->counter = deque->len;
1078 return (PyObject *)it;
1079}
1080
1081static PyObject *
1082dequereviter_next(dequeiterobject *it)
1083{
1084 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001085 if (it->counter == 0)
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001086 return NULL;
1087
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001088 if (it->deque->state != it->state) {
Raymond Hettinger7892b1c2004-04-12 18:10:01 +00001089 it->counter = 0;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001090 PyErr_SetString(PyExc_RuntimeError,
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001091 "deque mutated during iteration");
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001092 return NULL;
1093 }
Tim Peters5566e962006-07-28 00:23:15 +00001094 assert (!(it->b == it->deque->leftblock &&
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001095 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001096
1097 item = it->b->data[it->index];
1098 it->index--;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001099 it->counter--;
1100 if (it->index == -1 && it->counter > 0) {
1101 assert (it->b->leftlink != NULL);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001102 it->b = it->b->leftlink;
1103 it->index = BLOCKLEN - 1;
1104 }
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001105 Py_INCREF(item);
1106 return item;
1107}
1108
1109PyTypeObject dequereviter_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001110 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001111 "deque_reverse_iterator", /* tp_name */
1112 sizeof(dequeiterobject), /* tp_basicsize */
1113 0, /* tp_itemsize */
1114 /* methods */
1115 (destructor)dequeiter_dealloc, /* tp_dealloc */
1116 0, /* tp_print */
1117 0, /* tp_getattr */
1118 0, /* tp_setattr */
1119 0, /* tp_compare */
1120 0, /* tp_repr */
1121 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001122 0, /* tp_as_sequence */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001123 0, /* tp_as_mapping */
1124 0, /* tp_hash */
1125 0, /* tp_call */
1126 0, /* tp_str */
1127 PyObject_GenericGetAttr, /* tp_getattro */
1128 0, /* tp_setattro */
1129 0, /* tp_as_buffer */
1130 Py_TPFLAGS_DEFAULT, /* tp_flags */
1131 0, /* tp_doc */
1132 0, /* tp_traverse */
1133 0, /* tp_clear */
1134 0, /* tp_richcompare */
1135 0, /* tp_weaklistoffset */
1136 PyObject_SelfIter, /* tp_iter */
1137 (iternextfunc)dequereviter_next, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001138 dequeiter_methods, /* tp_methods */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001139 0,
1140};
1141
Guido van Rossum1968ad32006-02-25 22:38:04 +00001142/* defaultdict type *********************************************************/
1143
1144typedef struct {
1145 PyDictObject dict;
1146 PyObject *default_factory;
1147} defdictobject;
1148
1149static PyTypeObject defdict_type; /* Forward */
1150
1151PyDoc_STRVAR(defdict_missing_doc,
1152"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Georg Brandlb51a57e2007-03-06 13:32:52 +00001153 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001154 self[key] = value = self.default_factory()\n\
1155 return value\n\
1156");
1157
1158static PyObject *
1159defdict_missing(defdictobject *dd, PyObject *key)
1160{
1161 PyObject *factory = dd->default_factory;
1162 PyObject *value;
1163 if (factory == NULL || factory == Py_None) {
1164 /* XXX Call dict.__missing__(key) */
Georg Brandlb51a57e2007-03-06 13:32:52 +00001165 PyObject *tup;
1166 tup = PyTuple_Pack(1, key);
1167 if (!tup) return NULL;
1168 PyErr_SetObject(PyExc_KeyError, tup);
1169 Py_DECREF(tup);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001170 return NULL;
1171 }
1172 value = PyEval_CallObject(factory, NULL);
1173 if (value == NULL)
1174 return value;
1175 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1176 Py_DECREF(value);
1177 return NULL;
1178 }
1179 return value;
1180}
1181
1182PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1183
1184static PyObject *
1185defdict_copy(defdictobject *dd)
1186{
1187 /* This calls the object's class. That only works for subclasses
1188 whose class constructor has the same signature. Subclasses that
Raymond Hettingera37430a2008-02-12 19:05:36 +00001189 define a different constructor signature must override copy().
Guido van Rossum1968ad32006-02-25 22:38:04 +00001190 */
Christian Heimese93237d2007-12-19 02:37:44 +00001191 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
Guido van Rossum1968ad32006-02-25 22:38:04 +00001192 dd->default_factory, dd, NULL);
1193}
1194
1195static PyObject *
1196defdict_reduce(defdictobject *dd)
1197{
Tim Peters5566e962006-07-28 00:23:15 +00001198 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001199
1200 - factory function
1201 - tuple of args for the factory function
1202 - additional state (here None)
1203 - sequence iterator (here None)
1204 - dictionary iterator (yielding successive (key, value) pairs
1205
1206 This API is used by pickle.py and copy.py.
1207
1208 For this to be useful with pickle.py, the default_factory
1209 must be picklable; e.g., None, a built-in, or a global
1210 function in a module or package.
1211
1212 Both shallow and deep copying are supported, but for deep
1213 copying, the default_factory must be deep-copyable; e.g. None,
1214 or a built-in (functions are not copyable at this time).
1215
1216 This only works for subclasses as long as their constructor
1217 signature is compatible; the first argument must be the
1218 optional default_factory, defaulting to None.
1219 */
1220 PyObject *args;
1221 PyObject *items;
1222 PyObject *result;
1223 if (dd->default_factory == NULL || dd->default_factory == Py_None)
1224 args = PyTuple_New(0);
1225 else
1226 args = PyTuple_Pack(1, dd->default_factory);
1227 if (args == NULL)
1228 return NULL;
1229 items = PyObject_CallMethod((PyObject *)dd, "iteritems", "()");
1230 if (items == NULL) {
1231 Py_DECREF(args);
1232 return NULL;
1233 }
Christian Heimese93237d2007-12-19 02:37:44 +00001234 result = PyTuple_Pack(5, Py_TYPE(dd), args,
Guido van Rossum1968ad32006-02-25 22:38:04 +00001235 Py_None, Py_None, items);
Tim Peters5566e962006-07-28 00:23:15 +00001236 Py_DECREF(items);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001237 Py_DECREF(args);
1238 return result;
1239}
1240
1241static PyMethodDef defdict_methods[] = {
1242 {"__missing__", (PyCFunction)defdict_missing, METH_O,
1243 defdict_missing_doc},
Raymond Hettingera37430a2008-02-12 19:05:36 +00001244 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
Guido van Rossum1968ad32006-02-25 22:38:04 +00001245 defdict_copy_doc},
1246 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
1247 defdict_copy_doc},
1248 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
1249 reduce_doc},
1250 {NULL}
1251};
1252
1253static PyMemberDef defdict_members[] = {
1254 {"default_factory", T_OBJECT,
1255 offsetof(defdictobject, default_factory), 0,
1256 PyDoc_STR("Factory for default value called by __missing__().")},
1257 {NULL}
1258};
1259
1260static void
1261defdict_dealloc(defdictobject *dd)
1262{
1263 Py_CLEAR(dd->default_factory);
1264 PyDict_Type.tp_dealloc((PyObject *)dd);
1265}
1266
1267static int
1268defdict_print(defdictobject *dd, FILE *fp, int flags)
1269{
1270 int sts;
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001271 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1968ad32006-02-25 22:38:04 +00001272 fprintf(fp, "defaultdict(");
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001273 Py_END_ALLOW_THREADS
1274 if (dd->default_factory == NULL) {
1275 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1968ad32006-02-25 22:38:04 +00001276 fprintf(fp, "None");
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001277 Py_END_ALLOW_THREADS
1278 } else {
Guido van Rossum1968ad32006-02-25 22:38:04 +00001279 PyObject_Print(dd->default_factory, fp, 0);
1280 }
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001281 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1968ad32006-02-25 22:38:04 +00001282 fprintf(fp, ", ");
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001283 Py_END_ALLOW_THREADS
Guido van Rossum1968ad32006-02-25 22:38:04 +00001284 sts = PyDict_Type.tp_print((PyObject *)dd, fp, 0);
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001285 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1968ad32006-02-25 22:38:04 +00001286 fprintf(fp, ")");
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001287 Py_END_ALLOW_THREADS
Guido van Rossum1968ad32006-02-25 22:38:04 +00001288 return sts;
1289}
1290
1291static PyObject *
1292defdict_repr(defdictobject *dd)
1293{
1294 PyObject *defrepr;
1295 PyObject *baserepr;
1296 PyObject *result;
1297 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
1298 if (baserepr == NULL)
1299 return NULL;
1300 if (dd->default_factory == NULL)
1301 defrepr = PyString_FromString("None");
1302 else
Amaury Forgeot d'Arcb01aa432008-02-08 00:56:02 +00001303 {
1304 int status = Py_ReprEnter(dd->default_factory);
1305 if (status != 0) {
1306 if (status < 0)
1307 return NULL;
1308 defrepr = PyString_FromString("...");
1309 }
1310 else
1311 defrepr = PyObject_Repr(dd->default_factory);
1312 Py_ReprLeave(dd->default_factory);
1313 }
Guido van Rossum1968ad32006-02-25 22:38:04 +00001314 if (defrepr == NULL) {
1315 Py_DECREF(baserepr);
1316 return NULL;
1317 }
1318 result = PyString_FromFormat("defaultdict(%s, %s)",
1319 PyString_AS_STRING(defrepr),
1320 PyString_AS_STRING(baserepr));
1321 Py_DECREF(defrepr);
1322 Py_DECREF(baserepr);
1323 return result;
1324}
1325
1326static int
1327defdict_traverse(PyObject *self, visitproc visit, void *arg)
1328{
1329 Py_VISIT(((defdictobject *)self)->default_factory);
1330 return PyDict_Type.tp_traverse(self, visit, arg);
1331}
1332
1333static int
1334defdict_tp_clear(defdictobject *dd)
1335{
Thomas Woutersedf17d82006-04-15 17:28:34 +00001336 Py_CLEAR(dd->default_factory);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001337 return PyDict_Type.tp_clear((PyObject *)dd);
1338}
1339
1340static int
1341defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
1342{
1343 defdictobject *dd = (defdictobject *)self;
1344 PyObject *olddefault = dd->default_factory;
1345 PyObject *newdefault = NULL;
1346 PyObject *newargs;
1347 int result;
1348 if (args == NULL || !PyTuple_Check(args))
1349 newargs = PyTuple_New(0);
1350 else {
1351 Py_ssize_t n = PyTuple_GET_SIZE(args);
Raymond Hettinger5a0217e2007-02-07 21:42:17 +00001352 if (n > 0) {
Guido van Rossum1968ad32006-02-25 22:38:04 +00001353 newdefault = PyTuple_GET_ITEM(args, 0);
Raymond Hettinger5a0217e2007-02-07 21:42:17 +00001354 if (!PyCallable_Check(newdefault)) {
1355 PyErr_SetString(PyExc_TypeError,
1356 "first argument must be callable");
1357 return -1;
1358 }
1359 }
Guido van Rossum1968ad32006-02-25 22:38:04 +00001360 newargs = PySequence_GetSlice(args, 1, n);
1361 }
1362 if (newargs == NULL)
1363 return -1;
1364 Py_XINCREF(newdefault);
1365 dd->default_factory = newdefault;
1366 result = PyDict_Type.tp_init(self, newargs, kwds);
1367 Py_DECREF(newargs);
1368 Py_XDECREF(olddefault);
1369 return result;
1370}
1371
1372PyDoc_STRVAR(defdict_doc,
1373"defaultdict(default_factory) --> dict with default factory\n\
1374\n\
1375The default factory is called without arguments to produce\n\
1376a new value when a key is not present, in __getitem__ only.\n\
1377A defaultdict compares equal to a dict with the same items.\n\
1378");
1379
Anthony Baxter3b8ff312006-04-04 15:05:23 +00001380/* See comment in xxsubtype.c */
1381#define DEFERRED_ADDRESS(ADDR) 0
1382
Guido van Rossum1968ad32006-02-25 22:38:04 +00001383static PyTypeObject defdict_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001384 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
Guido van Rossum1968ad32006-02-25 22:38:04 +00001385 "collections.defaultdict", /* tp_name */
1386 sizeof(defdictobject), /* tp_basicsize */
1387 0, /* tp_itemsize */
1388 /* methods */
1389 (destructor)defdict_dealloc, /* tp_dealloc */
1390 (printfunc)defdict_print, /* tp_print */
1391 0, /* tp_getattr */
1392 0, /* tp_setattr */
1393 0, /* tp_compare */
1394 (reprfunc)defdict_repr, /* tp_repr */
1395 0, /* tp_as_number */
1396 0, /* tp_as_sequence */
1397 0, /* tp_as_mapping */
1398 0, /* tp_hash */
1399 0, /* tp_call */
1400 0, /* tp_str */
1401 PyObject_GenericGetAttr, /* tp_getattro */
1402 0, /* tp_setattro */
1403 0, /* tp_as_buffer */
1404 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
1405 Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
1406 defdict_doc, /* tp_doc */
Georg Brandld37ac692006-03-30 11:58:57 +00001407 defdict_traverse, /* tp_traverse */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001408 (inquiry)defdict_tp_clear, /* tp_clear */
1409 0, /* tp_richcompare */
1410 0, /* tp_weaklistoffset*/
1411 0, /* tp_iter */
1412 0, /* tp_iternext */
1413 defdict_methods, /* tp_methods */
1414 defdict_members, /* tp_members */
1415 0, /* tp_getset */
Anthony Baxter3b8ff312006-04-04 15:05:23 +00001416 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001417 0, /* tp_dict */
1418 0, /* tp_descr_get */
1419 0, /* tp_descr_set */
1420 0, /* tp_dictoffset */
Georg Brandld37ac692006-03-30 11:58:57 +00001421 defdict_init, /* tp_init */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001422 PyType_GenericAlloc, /* tp_alloc */
1423 0, /* tp_new */
1424 PyObject_GC_Del, /* tp_free */
1425};
1426
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001427/* module level code ********************************************************/
1428
1429PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00001430"High performance data structures.\n\
1431- deque: ordered collection accessible from endpoints only\n\
1432- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001433");
1434
1435PyMODINIT_FUNC
Raymond Hettingereb979882007-02-28 18:37:52 +00001436init_collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001437{
1438 PyObject *m;
1439
Raymond Hettingereb979882007-02-28 18:37:52 +00001440 m = Py_InitModule3("_collections", NULL, module_doc);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00001441 if (m == NULL)
1442 return;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001443
1444 if (PyType_Ready(&deque_type) < 0)
1445 return;
1446 Py_INCREF(&deque_type);
1447 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
1448
Anthony Baxter3b8ff312006-04-04 15:05:23 +00001449 defdict_type.tp_base = &PyDict_Type;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001450 if (PyType_Ready(&defdict_type) < 0)
1451 return;
1452 Py_INCREF(&defdict_type);
1453 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
1454
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001455 if (PyType_Ready(&dequeiter_type) < 0)
Tim Peters1065f752004-10-01 01:03:29 +00001456 return;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001457
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001458 if (PyType_Ready(&dequereviter_type) < 0)
1459 return;
1460
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001461 return;
1462}