blob: 1ee3612745c9260a2377f843692b8301b5d0a74e [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
Thomas Wouters0e3f5912006-08-11 14:57:12 +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
Thomas Wouters0e3f5912006-08-11 14:57:12 +000025 * on both ends, algorithms for left and right operations become
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000026 * symmetrical which simplifies the design.
Thomas Wouters0e3f5912006-08-11 14:57:12 +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 *
Thomas Wouters0e3f5912006-08-11 14:57:12 +000040 * Whenever d.leftblock == d.rightblock,
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000041 * d.leftindex + d.len - 1 == d.rightindex.
Thomas Wouters0e3f5912006-08-11 14:57:12 +000042 *
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000043 * However, when d.leftblock != d.rightblock, d.leftindex and d.rightindex
Thomas Wouters0e3f5912006-08-11 14:57:12 +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
Tim Peters6f853562004-10-01 01:04:50 +000054static block *
Raymond Hettingerc5fa9922004-10-06 17:51:54 +000055newblock(block *leftlink, block *rightlink, int len) {
56 block *b;
57 /* To prevent len from overflowing INT_MAX on 64-bit machines, we
58 * refuse to allocate new blocks if the current len is dangerously
59 * close. There is some extra margin to prevent spurious arithmetic
60 * overflows at various places. The following check ensures that
61 * the blocks allocated to the deque, in the worst case, can only
62 * have INT_MAX-2 entries in total.
63 */
64 if (len >= INT_MAX - 2*BLOCKLEN) {
65 PyErr_SetString(PyExc_OverflowError,
66 "cannot add more blocks to the deque");
67 return NULL;
68 }
69 b = PyMem_Malloc(sizeof(block));
Raymond Hettinger756b3f32004-01-29 06:37:52 +000070 if (b == NULL) {
71 PyErr_NoMemory();
72 return NULL;
73 }
74 b->leftlink = leftlink;
75 b->rightlink = rightlink;
76 return b;
77}
78
79typedef struct {
80 PyObject_HEAD
81 block *leftblock;
82 block *rightblock;
Tim Petersd8768d32004-10-01 01:32:53 +000083 int leftindex; /* in range(BLOCKLEN) */
84 int rightindex; /* in range(BLOCKLEN) */
Raymond Hettinger756b3f32004-01-29 06:37:52 +000085 int len;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +000086 long state; /* incremented whenever the indices move */
Raymond Hettinger691d8052004-05-30 07:26:47 +000087 PyObject *weakreflist; /* List of weak references */
Raymond Hettinger756b3f32004-01-29 06:37:52 +000088} dequeobject;
89
Neal Norwitz87f10132004-02-29 15:40:53 +000090static PyTypeObject deque_type;
Raymond Hettinger738ec902004-02-29 02:15:56 +000091
Raymond Hettinger756b3f32004-01-29 06:37:52 +000092static PyObject *
93deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
94{
95 dequeobject *deque;
96 block *b;
97
Thomas Woutersb2137042007-02-01 18:02:27 +000098 if (type == &deque_type && !_PyArg_NoKeywords("deque()", kwds))
Georg Brandl02c42872005-08-26 06:42:30 +000099 return NULL;
100
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000101 /* create dequeobject structure */
102 deque = (dequeobject *)type->tp_alloc(type, 0);
103 if (deque == NULL)
104 return NULL;
Tim Peters1065f752004-10-01 01:03:29 +0000105
Raymond Hettingerc5fa9922004-10-06 17:51:54 +0000106 b = newblock(NULL, NULL, 0);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000107 if (b == NULL) {
108 Py_DECREF(deque);
109 return NULL;
110 }
111
Raymond Hettinger61f05fb2004-10-01 06:24:12 +0000112 assert(BLOCKLEN >= 2);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000113 deque->leftblock = b;
114 deque->rightblock = b;
Raymond Hettinger61f05fb2004-10-01 06:24:12 +0000115 deque->leftindex = CENTER + 1;
116 deque->rightindex = CENTER;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000117 deque->len = 0;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000118 deque->state = 0;
Raymond Hettinger691d8052004-05-30 07:26:47 +0000119 deque->weakreflist = NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000120
121 return (PyObject *)deque;
122}
123
124static PyObject *
125deque_append(dequeobject *deque, PyObject *item)
126{
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000127 deque->state++;
Armin Rigo974d7572004-10-02 13:59:34 +0000128 if (deque->rightindex == BLOCKLEN-1) {
Raymond Hettingerc5fa9922004-10-06 17:51:54 +0000129 block *b = newblock(deque->rightblock, NULL, deque->len);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000130 if (b == NULL)
131 return NULL;
132 assert(deque->rightblock->rightlink == NULL);
133 deque->rightblock->rightlink = b;
134 deque->rightblock = b;
Armin Rigo974d7572004-10-02 13:59:34 +0000135 deque->rightindex = -1;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000136 }
137 Py_INCREF(item);
Armin Rigo974d7572004-10-02 13:59:34 +0000138 deque->len++;
139 deque->rightindex++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000140 deque->rightblock->data[deque->rightindex] = item;
141 Py_RETURN_NONE;
142}
143
144PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
145
146static PyObject *
147deque_appendleft(dequeobject *deque, PyObject *item)
148{
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000149 deque->state++;
Armin Rigo974d7572004-10-02 13:59:34 +0000150 if (deque->leftindex == 0) {
Raymond Hettingerc5fa9922004-10-06 17:51:54 +0000151 block *b = newblock(NULL, deque->leftblock, deque->len);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000152 if (b == NULL)
153 return NULL;
154 assert(deque->leftblock->leftlink == NULL);
155 deque->leftblock->leftlink = b;
156 deque->leftblock = b;
Armin Rigo974d7572004-10-02 13:59:34 +0000157 deque->leftindex = BLOCKLEN;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000158 }
159 Py_INCREF(item);
Armin Rigo974d7572004-10-02 13:59:34 +0000160 deque->len++;
161 deque->leftindex--;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000162 deque->leftblock->data[deque->leftindex] = item;
163 Py_RETURN_NONE;
164}
165
166PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
167
168static PyObject *
169deque_pop(dequeobject *deque, PyObject *unused)
170{
171 PyObject *item;
172 block *prevblock;
173
174 if (deque->len == 0) {
Raymond Hettinger738ec902004-02-29 02:15:56 +0000175 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000176 return NULL;
177 }
178 item = deque->rightblock->data[deque->rightindex];
179 deque->rightindex--;
180 deque->len--;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000181 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000182
183 if (deque->rightindex == -1) {
184 if (deque->len == 0) {
185 assert(deque->leftblock == deque->rightblock);
186 assert(deque->leftindex == deque->rightindex+1);
187 /* re-center instead of freeing a block */
Raymond Hettinger61f05fb2004-10-01 06:24:12 +0000188 deque->leftindex = CENTER + 1;
189 deque->rightindex = CENTER;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000190 } else {
191 prevblock = deque->rightblock->leftlink;
192 assert(deque->leftblock != deque->rightblock);
193 PyMem_Free(deque->rightblock);
194 prevblock->rightlink = NULL;
195 deque->rightblock = prevblock;
196 deque->rightindex = BLOCKLEN - 1;
197 }
198 }
199 return item;
200}
201
202PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
203
204static PyObject *
205deque_popleft(dequeobject *deque, PyObject *unused)
206{
207 PyObject *item;
208 block *prevblock;
209
210 if (deque->len == 0) {
Raymond Hettinger738ec902004-02-29 02:15:56 +0000211 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000212 return NULL;
213 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000214 assert(deque->leftblock != NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000215 item = deque->leftblock->data[deque->leftindex];
216 deque->leftindex++;
217 deque->len--;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000218 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000219
220 if (deque->leftindex == BLOCKLEN) {
221 if (deque->len == 0) {
222 assert(deque->leftblock == deque->rightblock);
223 assert(deque->leftindex == deque->rightindex+1);
224 /* re-center instead of freeing a block */
Raymond Hettinger61f05fb2004-10-01 06:24:12 +0000225 deque->leftindex = CENTER + 1;
226 deque->rightindex = CENTER;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000227 } else {
228 assert(deque->leftblock != deque->rightblock);
229 prevblock = deque->leftblock->rightlink;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000230 PyMem_Free(deque->leftblock);
231 assert(prevblock != NULL);
232 prevblock->leftlink = NULL;
233 deque->leftblock = prevblock;
234 deque->leftindex = 0;
235 }
236 }
237 return item;
238}
239
240PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
241
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000242static PyObject *
243deque_extend(dequeobject *deque, PyObject *iterable)
244{
245 PyObject *it, *item;
246
247 it = PyObject_GetIter(iterable);
248 if (it == NULL)
249 return NULL;
250
251 while ((item = PyIter_Next(it)) != NULL) {
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000252 deque->state++;
Armin Rigo974d7572004-10-02 13:59:34 +0000253 if (deque->rightindex == BLOCKLEN-1) {
Raymond Hettingerc5fa9922004-10-06 17:51:54 +0000254 block *b = newblock(deque->rightblock, NULL,
255 deque->len);
Raymond Hettingerc058fd12004-02-07 02:45:22 +0000256 if (b == NULL) {
257 Py_DECREF(item);
258 Py_DECREF(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000259 return NULL;
Raymond Hettingerc058fd12004-02-07 02:45:22 +0000260 }
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000261 assert(deque->rightblock->rightlink == NULL);
262 deque->rightblock->rightlink = b;
263 deque->rightblock = b;
Armin Rigo974d7572004-10-02 13:59:34 +0000264 deque->rightindex = -1;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000265 }
Armin Rigo974d7572004-10-02 13:59:34 +0000266 deque->len++;
267 deque->rightindex++;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000268 deque->rightblock->data[deque->rightindex] = item;
269 }
270 Py_DECREF(it);
Tim Peters1065f752004-10-01 01:03:29 +0000271 if (PyErr_Occurred())
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000272 return NULL;
273 Py_RETURN_NONE;
274}
275
Tim Peters1065f752004-10-01 01:03:29 +0000276PyDoc_STRVAR(extend_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000277"Extend the right side of the deque with elements from the iterable");
278
279static PyObject *
280deque_extendleft(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->leftindex == 0) {
Raymond Hettingerc5fa9922004-10-06 17:51:54 +0000291 block *b = newblock(NULL, deque->leftblock,
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->leftblock->leftlink == NULL);
299 deque->leftblock->leftlink = b;
300 deque->leftblock = b;
Armin Rigo974d7572004-10-02 13:59:34 +0000301 deque->leftindex = BLOCKLEN;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000302 }
Armin Rigo974d7572004-10-02 13:59:34 +0000303 deque->len++;
304 deque->leftindex--;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000305 deque->leftblock->data[deque->leftindex] = item;
306 }
307 Py_DECREF(it);
Raymond Hettingera435c532004-07-09 04:10:20 +0000308 if (PyErr_Occurred())
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000309 return NULL;
310 Py_RETURN_NONE;
311}
312
Tim Peters1065f752004-10-01 01:03:29 +0000313PyDoc_STRVAR(extendleft_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000314"Extend the left side of the deque with elements from the iterable");
315
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000316static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000317_deque_rotate(dequeobject *deque, Py_ssize_t n)
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000318{
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000319 int i, len=deque->len, halflen=(len+1)>>1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000320 PyObject *item, *rv;
321
Raymond Hettingeree33b272004-02-08 04:05:26 +0000322 if (len == 0)
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000323 return 0;
Raymond Hettingeree33b272004-02-08 04:05:26 +0000324 if (n > halflen || n < -halflen) {
325 n %= len;
326 if (n > halflen)
327 n -= len;
328 else if (n < -halflen)
329 n += len;
330 }
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000331
332 for (i=0 ; i<n ; i++) {
333 item = deque_pop(deque, NULL);
Raymond Hettingera435c532004-07-09 04:10:20 +0000334 assert (item != NULL);
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000335 rv = deque_appendleft(deque, item);
336 Py_DECREF(item);
337 if (rv == NULL)
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000338 return -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000339 Py_DECREF(rv);
340 }
341 for (i=0 ; i>n ; i--) {
342 item = deque_popleft(deque, NULL);
Raymond Hettingera435c532004-07-09 04:10:20 +0000343 assert (item != NULL);
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000344 rv = deque_append(deque, item);
345 Py_DECREF(item);
346 if (rv == NULL)
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000347 return -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000348 Py_DECREF(rv);
349 }
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000350 return 0;
351}
352
353static PyObject *
354deque_rotate(dequeobject *deque, PyObject *args)
355{
356 int n=1;
357
358 if (!PyArg_ParseTuple(args, "|i:rotate", &n))
359 return NULL;
360 if (_deque_rotate(deque, n) == 0)
361 Py_RETURN_NONE;
362 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000363}
364
Tim Peters1065f752004-10-01 01:03:29 +0000365PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000366"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000367
Martin v. Löwis18e16552006-02-15 17:27:45 +0000368static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000369deque_len(dequeobject *deque)
370{
371 return deque->len;
372}
373
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000374static PyObject *
375deque_remove(dequeobject *deque, PyObject *value)
376{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000377 Py_ssize_t i, n=deque->len;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000378
379 for (i=0 ; i<n ; i++) {
380 PyObject *item = deque->leftblock->data[deque->leftindex];
381 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000382
383 if (deque->len != n) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000384 PyErr_SetString(PyExc_IndexError,
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000385 "deque mutated during remove().");
386 return NULL;
387 }
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000388 if (cmp > 0) {
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000389 PyObject *tgt = deque_popleft(deque, NULL);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000390 assert (tgt != NULL);
391 Py_DECREF(tgt);
392 if (_deque_rotate(deque, i) == -1)
393 return NULL;
394 Py_RETURN_NONE;
395 }
396 else if (cmp < 0) {
397 _deque_rotate(deque, i);
398 return NULL;
399 }
400 _deque_rotate(deque, -1);
401 }
402 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
403 return NULL;
404}
405
406PyDoc_STRVAR(remove_doc,
407"D.remove(value) -- remove first occurrence of value.");
408
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000409static int
410deque_clear(dequeobject *deque)
411{
412 PyObject *item;
413
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000414 while (deque->len) {
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000415 item = deque_pop(deque, NULL);
Raymond Hettingera435c532004-07-09 04:10:20 +0000416 assert (item != NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000417 Py_DECREF(item);
418 }
419 assert(deque->leftblock == deque->rightblock &&
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000420 deque->leftindex - 1 == deque->rightindex &&
421 deque->len == 0);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000422 return 0;
423}
424
425static PyObject *
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000426deque_item(dequeobject *deque, int i)
427{
428 block *b;
429 PyObject *item;
Armin Rigo974d7572004-10-02 13:59:34 +0000430 int n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000431
432 if (i < 0 || i >= deque->len) {
433 PyErr_SetString(PyExc_IndexError,
434 "deque index out of range");
435 return NULL;
436 }
437
Raymond Hettinger6c79a512004-03-04 08:00:54 +0000438 if (i == 0) {
439 i = deque->leftindex;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000440 b = deque->leftblock;
Raymond Hettinger6c79a512004-03-04 08:00:54 +0000441 } else if (i == deque->len - 1) {
442 i = deque->rightindex;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000443 b = deque->rightblock;
Raymond Hettinger6c79a512004-03-04 08:00:54 +0000444 } else {
445 i += deque->leftindex;
446 n = i / BLOCKLEN;
447 i %= BLOCKLEN;
Armin Rigo974d7572004-10-02 13:59:34 +0000448 if (index < (deque->len >> 1)) {
Raymond Hettinger6c79a512004-03-04 08:00:54 +0000449 b = deque->leftblock;
450 while (n--)
451 b = b->rightlink;
452 } else {
453 n = (deque->leftindex + deque->len - 1) / BLOCKLEN - n;
454 b = deque->rightblock;
455 while (n--)
456 b = b->leftlink;
457 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000458 }
459 item = b->data[i];
460 Py_INCREF(item);
461 return item;
462}
463
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000464/* delitem() implemented in terms of rotate for simplicity and reasonable
465 performance near the end points. If for some reason this method becomes
Tim Peters1065f752004-10-01 01:03:29 +0000466 popular, it is not hard to re-implement this using direct data movement
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000467 (similar to code in list slice assignment) and achieve a two or threefold
468 performance boost.
469*/
470
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000471static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000472deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000473{
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000474 PyObject *item;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000475
Tim Peters1065f752004-10-01 01:03:29 +0000476 assert (i >= 0 && i < deque->len);
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000477 if (_deque_rotate(deque, -i) == -1)
478 return -1;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000479
480 item = deque_popleft(deque, NULL);
Raymond Hettingera435c532004-07-09 04:10:20 +0000481 assert (item != NULL);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000482 Py_DECREF(item);
483
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000484 return _deque_rotate(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000485}
486
487static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000488deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000489{
490 PyObject *old_value;
491 block *b;
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000492 Py_ssize_t n, len=deque->len, halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000493
Raymond Hettingera435c532004-07-09 04:10:20 +0000494 if (i < 0 || i >= len) {
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000495 PyErr_SetString(PyExc_IndexError,
496 "deque index out of range");
497 return -1;
498 }
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000499 if (v == NULL)
500 return deque_del_item(deque, i);
501
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000502 i += deque->leftindex;
503 n = i / BLOCKLEN;
504 i %= BLOCKLEN;
Raymond Hettingera435c532004-07-09 04:10:20 +0000505 if (index <= halflen) {
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000506 b = deque->leftblock;
507 while (n--)
508 b = b->rightlink;
509 } else {
Raymond Hettingera435c532004-07-09 04:10:20 +0000510 n = (deque->leftindex + len - 1) / BLOCKLEN - n;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000511 b = deque->rightblock;
512 while (n--)
513 b = b->leftlink;
514 }
515 Py_INCREF(v);
516 old_value = b->data[i];
517 b->data[i] = v;
518 Py_DECREF(old_value);
519 return 0;
520}
521
522static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000523deque_clearmethod(dequeobject *deque)
524{
Raymond Hettingera435c532004-07-09 04:10:20 +0000525 int rv;
526
527 rv = deque_clear(deque);
528 assert (rv != -1);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000529 Py_RETURN_NONE;
530}
531
532PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
533
534static void
535deque_dealloc(dequeobject *deque)
536{
537 PyObject_GC_UnTrack(deque);
Raymond Hettinger691d8052004-05-30 07:26:47 +0000538 if (deque->weakreflist != NULL)
539 PyObject_ClearWeakRefs((PyObject *) deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000540 if (deque->leftblock != NULL) {
Raymond Hettingere9c89e82004-07-19 00:10:24 +0000541 deque_clear(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000542 assert(deque->leftblock != NULL);
543 PyMem_Free(deque->leftblock);
544 }
545 deque->leftblock = NULL;
546 deque->rightblock = NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000547 Py_Type(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000548}
549
550static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000551deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000552{
Tim Peters10c7e862004-10-01 02:01:04 +0000553 block *b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000554 PyObject *item;
Tim Peters10c7e862004-10-01 02:01:04 +0000555 int index;
556 int indexlo = deque->leftindex;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000557
Tim Peters10c7e862004-10-01 02:01:04 +0000558 for (b = deque->leftblock; b != NULL; b = b->rightlink) {
559 const int indexhi = b == deque->rightblock ?
560 deque->rightindex :
561 BLOCKLEN - 1;
562
563 for (index = indexlo; index <= indexhi; ++index) {
564 item = b->data[index];
565 Py_VISIT(item);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000566 }
Tim Peters10c7e862004-10-01 02:01:04 +0000567 indexlo = 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000568 }
569 return 0;
570}
571
572static long
573deque_nohash(PyObject *self)
574{
575 PyErr_SetString(PyExc_TypeError, "deque objects are unhashable");
576 return -1;
577}
578
579static PyObject *
580deque_copy(PyObject *deque)
581{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000582 return PyObject_CallFunctionObjArgs((PyObject *)(Py_Type(deque)),
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000583 deque, NULL);
584}
585
586PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
587
588static PyObject *
589deque_reduce(dequeobject *deque)
590{
Raymond Hettinger952f8802004-11-09 07:27:35 +0000591 PyObject *dict, *result, *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000592
Raymond Hettinger952f8802004-11-09 07:27:35 +0000593 dict = PyObject_GetAttrString((PyObject *)deque, "__dict__");
594 if (dict == NULL) {
595 PyErr_Clear();
596 dict = Py_None;
597 Py_INCREF(dict);
598 }
599 it = PyObject_GetIter((PyObject *)deque);
600 if (it == NULL) {
601 Py_DECREF(dict);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000602 return NULL;
603 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000604 result = Py_BuildValue("O()ON", Py_Type(deque), dict, it);
Raymond Hettinger952f8802004-11-09 07:27:35 +0000605 Py_DECREF(dict);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000606 return result;
607}
608
609PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
610
611static PyObject *
612deque_repr(PyObject *deque)
613{
Walter Dörwald1ab83302007-05-18 17:15:44 +0000614 PyObject *aslist, *result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000615 int i;
616
617 i = Py_ReprEnter(deque);
618 if (i != 0) {
619 if (i < 0)
620 return NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +0000621 return PyUnicode_FromString("[...]");
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000622 }
623
624 aslist = PySequence_List(deque);
625 if (aslist == NULL) {
626 Py_ReprLeave(deque);
627 return NULL;
628 }
629
Walter Dörwald7569dfe2007-05-19 21:49:49 +0000630 result = PyUnicode_FromFormat("deque(%R)", aslist);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000631 Py_DECREF(aslist);
632 Py_ReprLeave(deque);
633 return result;
634}
635
636static int
637deque_tp_print(PyObject *deque, FILE *fp, int flags)
638{
639 PyObject *it, *item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000640 char *emit = ""; /* No separator emitted on first pass */
641 char *separator = ", ";
642 int i;
643
644 i = Py_ReprEnter(deque);
645 if (i != 0) {
646 if (i < 0)
647 return i;
648 fputs("[...]", fp);
649 return 0;
650 }
651
652 it = PyObject_GetIter(deque);
653 if (it == NULL)
654 return -1;
655
656 fputs("deque([", fp);
657 while ((item = PyIter_Next(it)) != NULL) {
658 fputs(emit, fp);
659 emit = separator;
660 if (PyObject_Print(item, fp, 0) != 0) {
661 Py_DECREF(item);
662 Py_DECREF(it);
663 Py_ReprLeave(deque);
664 return -1;
665 }
666 Py_DECREF(item);
667 }
668 Py_ReprLeave(deque);
669 Py_DECREF(it);
Tim Peters1065f752004-10-01 01:03:29 +0000670 if (PyErr_Occurred())
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000671 return -1;
672 fputs("])", fp);
673 return 0;
674}
675
Raymond Hettinger738ec902004-02-29 02:15:56 +0000676static PyObject *
677deque_richcompare(PyObject *v, PyObject *w, int op)
678{
679 PyObject *it1=NULL, *it2=NULL, *x, *y;
Armin Rigo974d7572004-10-02 13:59:34 +0000680 int b, vs, ws, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000681
Tim Peters1065f752004-10-01 01:03:29 +0000682 if (!PyObject_TypeCheck(v, &deque_type) ||
Raymond Hettinger285cfcc2004-05-18 18:15:03 +0000683 !PyObject_TypeCheck(w, &deque_type)) {
Raymond Hettinger738ec902004-02-29 02:15:56 +0000684 Py_INCREF(Py_NotImplemented);
685 return Py_NotImplemented;
686 }
687
688 /* Shortcuts */
689 vs = ((dequeobject *)v)->len;
690 ws = ((dequeobject *)w)->len;
691 if (op == Py_EQ) {
692 if (v == w)
693 Py_RETURN_TRUE;
694 if (vs != ws)
695 Py_RETURN_FALSE;
696 }
697 if (op == Py_NE) {
698 if (v == w)
699 Py_RETURN_FALSE;
700 if (vs != ws)
701 Py_RETURN_TRUE;
702 }
703
704 /* Search for the first index where items are different */
705 it1 = PyObject_GetIter(v);
706 if (it1 == NULL)
707 goto done;
708 it2 = PyObject_GetIter(w);
709 if (it2 == NULL)
710 goto done;
Armin Rigo974d7572004-10-02 13:59:34 +0000711 for (;;) {
Raymond Hettinger738ec902004-02-29 02:15:56 +0000712 x = PyIter_Next(it1);
Armin Rigo974d7572004-10-02 13:59:34 +0000713 if (x == NULL && PyErr_Occurred())
Raymond Hettinger738ec902004-02-29 02:15:56 +0000714 goto done;
715 y = PyIter_Next(it2);
Armin Rigo974d7572004-10-02 13:59:34 +0000716 if (x == NULL || y == NULL)
717 break;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000718 b = PyObject_RichCompareBool(x, y, Py_EQ);
719 if (b == 0) {
720 cmp = PyObject_RichCompareBool(x, y, op);
721 Py_DECREF(x);
722 Py_DECREF(y);
723 goto done;
724 }
725 Py_DECREF(x);
726 Py_DECREF(y);
727 if (b == -1)
728 goto done;
729 }
Armin Rigo974d7572004-10-02 13:59:34 +0000730 /* We reached the end of one deque or both */
731 Py_XDECREF(x);
732 Py_XDECREF(y);
733 if (PyErr_Occurred())
734 goto done;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000735 switch (op) {
Armin Rigo974d7572004-10-02 13:59:34 +0000736 case Py_LT: cmp = y != NULL; break; /* if w was longer */
737 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
738 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
739 case Py_NE: cmp = x != y; break; /* if one deque continues */
740 case Py_GT: cmp = x != NULL; break; /* if v was longer */
741 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
Raymond Hettinger738ec902004-02-29 02:15:56 +0000742 }
Tim Peters1065f752004-10-01 01:03:29 +0000743
Raymond Hettinger738ec902004-02-29 02:15:56 +0000744done:
745 Py_XDECREF(it1);
746 Py_XDECREF(it2);
747 if (cmp == 1)
748 Py_RETURN_TRUE;
749 if (cmp == 0)
750 Py_RETURN_FALSE;
751 return NULL;
752}
753
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000754static int
755deque_init(dequeobject *deque, PyObject *args, PyObject *kwds)
756{
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000757 PyObject *iterable = NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000758
759 if (!PyArg_UnpackTuple(args, "deque", 0, 1, &iterable))
760 return -1;
761
762 if (iterable != NULL) {
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000763 PyObject *rv = deque_extend(deque, iterable);
764 if (rv == NULL)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000765 return -1;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000766 Py_DECREF(rv);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000767 }
768 return 0;
769}
770
771static PySequenceMethods deque_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000772 (lenfunc)deque_len, /* sq_length */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000773 0, /* sq_concat */
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000774 0, /* sq_repeat */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000775 (ssizeargfunc)deque_item, /* sq_item */
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000776 0, /* sq_slice */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000777 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000778};
779
780/* deque object ********************************************************/
781
782static PyObject *deque_iter(dequeobject *deque);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000783static PyObject *deque_reviter(dequeobject *deque);
Tim Peters1065f752004-10-01 01:03:29 +0000784PyDoc_STRVAR(reversed_doc,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000785 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000786
787static PyMethodDef deque_methods[] = {
Tim Peters1065f752004-10-01 01:03:29 +0000788 {"append", (PyCFunction)deque_append,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000789 METH_O, append_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000790 {"appendleft", (PyCFunction)deque_appendleft,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000791 METH_O, appendleft_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000792 {"clear", (PyCFunction)deque_clearmethod,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000793 METH_NOARGS, clear_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000794 {"__copy__", (PyCFunction)deque_copy,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000795 METH_NOARGS, copy_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000796 {"extend", (PyCFunction)deque_extend,
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000797 METH_O, extend_doc},
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000798 {"extendleft", (PyCFunction)deque_extendleft,
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000799 METH_O, extendleft_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000800 {"pop", (PyCFunction)deque_pop,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000801 METH_NOARGS, pop_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000802 {"popleft", (PyCFunction)deque_popleft,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000803 METH_NOARGS, popleft_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000804 {"__reduce__", (PyCFunction)deque_reduce,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000805 METH_NOARGS, reduce_doc},
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000806 {"remove", (PyCFunction)deque_remove,
807 METH_O, remove_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000808 {"__reversed__", (PyCFunction)deque_reviter,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000809 METH_NOARGS, reversed_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000810 {"rotate", (PyCFunction)deque_rotate,
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000811 METH_VARARGS, rotate_doc},
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000812 {NULL, NULL} /* sentinel */
813};
814
815PyDoc_STRVAR(deque_doc,
816"deque(iterable) --> deque object\n\
817\n\
818Build an ordered collection accessible from endpoints only.");
819
Neal Norwitz87f10132004-02-29 15:40:53 +0000820static PyTypeObject deque_type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000821 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000822 "collections.deque", /* tp_name */
823 sizeof(dequeobject), /* tp_basicsize */
824 0, /* tp_itemsize */
825 /* methods */
826 (destructor)deque_dealloc, /* tp_dealloc */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000827 deque_tp_print, /* tp_print */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000828 0, /* tp_getattr */
829 0, /* tp_setattr */
830 0, /* tp_compare */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000831 deque_repr, /* tp_repr */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000832 0, /* tp_as_number */
833 &deque_as_sequence, /* tp_as_sequence */
834 0, /* tp_as_mapping */
835 deque_nohash, /* tp_hash */
836 0, /* tp_call */
837 0, /* tp_str */
838 PyObject_GenericGetAttr, /* tp_getattro */
839 0, /* tp_setattro */
840 0, /* tp_as_buffer */
Guido van Rossumd8faa362007-04-27 19:54:29 +0000841 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
842 /* tp_flags */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000843 deque_doc, /* tp_doc */
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000844 (traverseproc)deque_traverse, /* tp_traverse */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000845 (inquiry)deque_clear, /* tp_clear */
Raymond Hettinger738ec902004-02-29 02:15:56 +0000846 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Raymond Hettinger691d8052004-05-30 07:26:47 +0000847 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000848 (getiterfunc)deque_iter, /* tp_iter */
849 0, /* tp_iternext */
850 deque_methods, /* tp_methods */
851 0, /* tp_members */
852 0, /* tp_getset */
853 0, /* tp_base */
854 0, /* tp_dict */
855 0, /* tp_descr_get */
856 0, /* tp_descr_set */
857 0, /* tp_dictoffset */
858 (initproc)deque_init, /* tp_init */
859 PyType_GenericAlloc, /* tp_alloc */
860 deque_new, /* tp_new */
861 PyObject_GC_Del, /* tp_free */
862};
863
864/*********************** Deque Iterator **************************/
865
866typedef struct {
867 PyObject_HEAD
868 int index;
869 block *b;
870 dequeobject *deque;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000871 long state; /* state when the iterator is created */
872 int counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000873} dequeiterobject;
874
875PyTypeObject dequeiter_type;
876
877static PyObject *
878deque_iter(dequeobject *deque)
879{
880 dequeiterobject *it;
881
882 it = PyObject_New(dequeiterobject, &dequeiter_type);
883 if (it == NULL)
884 return NULL;
885 it->b = deque->leftblock;
886 it->index = deque->leftindex;
887 Py_INCREF(deque);
888 it->deque = deque;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000889 it->state = deque->state;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000890 it->counter = deque->len;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000891 return (PyObject *)it;
892}
893
894static void
895dequeiter_dealloc(dequeiterobject *dio)
896{
897 Py_XDECREF(dio->deque);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000898 Py_Type(dio)->tp_free(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000899}
900
901static PyObject *
902dequeiter_next(dequeiterobject *it)
903{
904 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000905
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000906 if (it->deque->state != it->state) {
Raymond Hettinger7892b1c2004-04-12 18:10:01 +0000907 it->counter = 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000908 PyErr_SetString(PyExc_RuntimeError,
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000909 "deque mutated during iteration");
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000910 return NULL;
911 }
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000912 if (it->counter == 0)
913 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000914 assert (!(it->b == it->deque->rightblock &&
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000915 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000916
917 item = it->b->data[it->index];
918 it->index++;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000919 it->counter--;
920 if (it->index == BLOCKLEN && it->counter > 0) {
921 assert (it->b->rightlink != NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000922 it->b = it->b->rightlink;
923 it->index = 0;
924 }
925 Py_INCREF(item);
926 return item;
927}
928
Raymond Hettinger6b27cda2005-09-24 21:23:05 +0000929static PyObject *
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000930dequeiter_len(dequeiterobject *it)
931{
Raymond Hettinger6b27cda2005-09-24 21:23:05 +0000932 return PyInt_FromLong(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000933}
934
Armin Rigof5b3e362006-02-11 21:32:43 +0000935PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +0000936
937static PyMethodDef dequeiter_methods[] = {
Armin Rigof5b3e362006-02-11 21:32:43 +0000938 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Raymond Hettinger6b27cda2005-09-24 21:23:05 +0000939 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000940};
941
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000942PyTypeObject dequeiter_type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000943 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000944 "deque_iterator", /* tp_name */
945 sizeof(dequeiterobject), /* tp_basicsize */
946 0, /* tp_itemsize */
947 /* methods */
948 (destructor)dequeiter_dealloc, /* tp_dealloc */
949 0, /* tp_print */
950 0, /* tp_getattr */
951 0, /* tp_setattr */
952 0, /* tp_compare */
953 0, /* tp_repr */
954 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +0000955 0, /* tp_as_sequence */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000956 0, /* tp_as_mapping */
957 0, /* tp_hash */
958 0, /* tp_call */
959 0, /* tp_str */
960 PyObject_GenericGetAttr, /* tp_getattro */
961 0, /* tp_setattro */
962 0, /* tp_as_buffer */
963 Py_TPFLAGS_DEFAULT, /* tp_flags */
964 0, /* tp_doc */
965 0, /* tp_traverse */
966 0, /* tp_clear */
967 0, /* tp_richcompare */
968 0, /* tp_weaklistoffset */
969 PyObject_SelfIter, /* tp_iter */
970 (iternextfunc)dequeiter_next, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +0000971 dequeiter_methods, /* tp_methods */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000972 0,
973};
974
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000975/*********************** Deque Reverse Iterator **************************/
976
977PyTypeObject dequereviter_type;
978
979static PyObject *
980deque_reviter(dequeobject *deque)
981{
982 dequeiterobject *it;
983
984 it = PyObject_New(dequeiterobject, &dequereviter_type);
985 if (it == NULL)
986 return NULL;
987 it->b = deque->rightblock;
988 it->index = deque->rightindex;
989 Py_INCREF(deque);
990 it->deque = deque;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000991 it->state = deque->state;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000992 it->counter = deque->len;
993 return (PyObject *)it;
994}
995
996static PyObject *
997dequereviter_next(dequeiterobject *it)
998{
999 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001000 if (it->counter == 0)
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001001 return NULL;
1002
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001003 if (it->deque->state != it->state) {
Raymond Hettinger7892b1c2004-04-12 18:10:01 +00001004 it->counter = 0;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001005 PyErr_SetString(PyExc_RuntimeError,
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001006 "deque mutated during iteration");
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001007 return NULL;
1008 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001009 assert (!(it->b == it->deque->leftblock &&
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001010 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001011
1012 item = it->b->data[it->index];
1013 it->index--;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001014 it->counter--;
1015 if (it->index == -1 && it->counter > 0) {
1016 assert (it->b->leftlink != NULL);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001017 it->b = it->b->leftlink;
1018 it->index = BLOCKLEN - 1;
1019 }
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001020 Py_INCREF(item);
1021 return item;
1022}
1023
1024PyTypeObject dequereviter_type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001025 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001026 "deque_reverse_iterator", /* tp_name */
1027 sizeof(dequeiterobject), /* tp_basicsize */
1028 0, /* tp_itemsize */
1029 /* methods */
1030 (destructor)dequeiter_dealloc, /* tp_dealloc */
1031 0, /* tp_print */
1032 0, /* tp_getattr */
1033 0, /* tp_setattr */
1034 0, /* tp_compare */
1035 0, /* tp_repr */
1036 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001037 0, /* tp_as_sequence */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001038 0, /* tp_as_mapping */
1039 0, /* tp_hash */
1040 0, /* tp_call */
1041 0, /* tp_str */
1042 PyObject_GenericGetAttr, /* tp_getattro */
1043 0, /* tp_setattro */
1044 0, /* tp_as_buffer */
1045 Py_TPFLAGS_DEFAULT, /* tp_flags */
1046 0, /* tp_doc */
1047 0, /* tp_traverse */
1048 0, /* tp_clear */
1049 0, /* tp_richcompare */
1050 0, /* tp_weaklistoffset */
1051 PyObject_SelfIter, /* tp_iter */
1052 (iternextfunc)dequereviter_next, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001053 dequeiter_methods, /* tp_methods */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001054 0,
1055};
1056
Guido van Rossum1968ad32006-02-25 22:38:04 +00001057/* defaultdict type *********************************************************/
1058
1059typedef struct {
1060 PyDictObject dict;
1061 PyObject *default_factory;
1062} defdictobject;
1063
1064static PyTypeObject defdict_type; /* Forward */
1065
1066PyDoc_STRVAR(defdict_missing_doc,
1067"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001068 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001069 self[key] = value = self.default_factory()\n\
1070 return value\n\
1071");
1072
1073static PyObject *
1074defdict_missing(defdictobject *dd, PyObject *key)
1075{
1076 PyObject *factory = dd->default_factory;
1077 PyObject *value;
1078 if (factory == NULL || factory == Py_None) {
1079 /* XXX Call dict.__missing__(key) */
Guido van Rossumd8faa362007-04-27 19:54:29 +00001080 PyObject *tup;
1081 tup = PyTuple_Pack(1, key);
1082 if (!tup) return NULL;
1083 PyErr_SetObject(PyExc_KeyError, tup);
1084 Py_DECREF(tup);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001085 return NULL;
1086 }
1087 value = PyEval_CallObject(factory, NULL);
1088 if (value == NULL)
1089 return value;
1090 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1091 Py_DECREF(value);
1092 return NULL;
1093 }
1094 return value;
1095}
1096
1097PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1098
1099static PyObject *
1100defdict_copy(defdictobject *dd)
1101{
1102 /* This calls the object's class. That only works for subclasses
1103 whose class constructor has the same signature. Subclasses that
1104 define a different constructor signature must override copy().
1105 */
Guido van Rossum2f2fffb2007-07-25 16:47:51 +00001106 return PyObject_CallFunctionObjArgs((PyObject *)Py_Type(dd),
Guido van Rossum1968ad32006-02-25 22:38:04 +00001107 dd->default_factory, dd, NULL);
1108}
1109
1110static PyObject *
1111defdict_reduce(defdictobject *dd)
1112{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001113 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001114
1115 - factory function
1116 - tuple of args for the factory function
1117 - additional state (here None)
1118 - sequence iterator (here None)
1119 - dictionary iterator (yielding successive (key, value) pairs
1120
1121 This API is used by pickle.py and copy.py.
1122
1123 For this to be useful with pickle.py, the default_factory
1124 must be picklable; e.g., None, a built-in, or a global
1125 function in a module or package.
1126
1127 Both shallow and deep copying are supported, but for deep
1128 copying, the default_factory must be deep-copyable; e.g. None,
1129 or a built-in (functions are not copyable at this time).
1130
1131 This only works for subclasses as long as their constructor
1132 signature is compatible; the first argument must be the
1133 optional default_factory, defaulting to None.
1134 */
1135 PyObject *args;
1136 PyObject *items;
1137 PyObject *result;
1138 if (dd->default_factory == NULL || dd->default_factory == Py_None)
1139 args = PyTuple_New(0);
1140 else
1141 args = PyTuple_Pack(1, dd->default_factory);
1142 if (args == NULL)
1143 return NULL;
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001144 items = PyObject_CallMethod((PyObject *)dd, "items", "()");
Guido van Rossum1968ad32006-02-25 22:38:04 +00001145 if (items == NULL) {
1146 Py_DECREF(args);
1147 return NULL;
1148 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001149 result = PyTuple_Pack(5, Py_Type(dd), args,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001150 Py_None, Py_None, items);
1151 Py_DECREF(items);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001152 Py_DECREF(args);
1153 return result;
1154}
1155
1156static PyMethodDef defdict_methods[] = {
1157 {"__missing__", (PyCFunction)defdict_missing, METH_O,
1158 defdict_missing_doc},
1159 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
1160 defdict_copy_doc},
1161 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
1162 defdict_copy_doc},
1163 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
1164 reduce_doc},
1165 {NULL}
1166};
1167
1168static PyMemberDef defdict_members[] = {
1169 {"default_factory", T_OBJECT,
1170 offsetof(defdictobject, default_factory), 0,
1171 PyDoc_STR("Factory for default value called by __missing__().")},
1172 {NULL}
1173};
1174
1175static void
1176defdict_dealloc(defdictobject *dd)
1177{
1178 Py_CLEAR(dd->default_factory);
1179 PyDict_Type.tp_dealloc((PyObject *)dd);
1180}
1181
1182static int
1183defdict_print(defdictobject *dd, FILE *fp, int flags)
1184{
1185 int sts;
1186 fprintf(fp, "defaultdict(");
1187 if (dd->default_factory == NULL)
1188 fprintf(fp, "None");
1189 else {
1190 PyObject_Print(dd->default_factory, fp, 0);
1191 }
1192 fprintf(fp, ", ");
1193 sts = PyDict_Type.tp_print((PyObject *)dd, fp, 0);
1194 fprintf(fp, ")");
1195 return sts;
1196}
1197
1198static PyObject *
1199defdict_repr(defdictobject *dd)
1200{
Guido van Rossum1968ad32006-02-25 22:38:04 +00001201 PyObject *baserepr;
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001202 PyObject *def;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001203 PyObject *result;
1204 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
1205 if (baserepr == NULL)
1206 return NULL;
1207 if (dd->default_factory == NULL)
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001208 def = Py_None;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001209 else
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001210 def = dd->default_factory;
1211 result = PyUnicode_FromFormat("defaultdict(%R, %U)", def, baserepr);
1212 Py_DECREF(baserepr);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001213 return result;
1214}
1215
1216static int
1217defdict_traverse(PyObject *self, visitproc visit, void *arg)
1218{
1219 Py_VISIT(((defdictobject *)self)->default_factory);
1220 return PyDict_Type.tp_traverse(self, visit, arg);
1221}
1222
1223static int
1224defdict_tp_clear(defdictobject *dd)
1225{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001226 Py_CLEAR(dd->default_factory);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001227 return PyDict_Type.tp_clear((PyObject *)dd);
1228}
1229
1230static int
1231defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
1232{
1233 defdictobject *dd = (defdictobject *)self;
1234 PyObject *olddefault = dd->default_factory;
1235 PyObject *newdefault = NULL;
1236 PyObject *newargs;
1237 int result;
1238 if (args == NULL || !PyTuple_Check(args))
1239 newargs = PyTuple_New(0);
1240 else {
1241 Py_ssize_t n = PyTuple_GET_SIZE(args);
Thomas Wouterscf297e42007-02-23 15:07:44 +00001242 if (n > 0) {
Guido van Rossum1968ad32006-02-25 22:38:04 +00001243 newdefault = PyTuple_GET_ITEM(args, 0);
Thomas Wouterscf297e42007-02-23 15:07:44 +00001244 if (!PyCallable_Check(newdefault)) {
1245 PyErr_SetString(PyExc_TypeError,
1246 "first argument must be callable");
1247 return -1;
1248 }
1249 }
Guido van Rossum1968ad32006-02-25 22:38:04 +00001250 newargs = PySequence_GetSlice(args, 1, n);
1251 }
1252 if (newargs == NULL)
1253 return -1;
1254 Py_XINCREF(newdefault);
1255 dd->default_factory = newdefault;
1256 result = PyDict_Type.tp_init(self, newargs, kwds);
1257 Py_DECREF(newargs);
1258 Py_XDECREF(olddefault);
1259 return result;
1260}
1261
1262PyDoc_STRVAR(defdict_doc,
1263"defaultdict(default_factory) --> dict with default factory\n\
1264\n\
1265The default factory is called without arguments to produce\n\
1266a new value when a key is not present, in __getitem__ only.\n\
1267A defaultdict compares equal to a dict with the same items.\n\
1268");
1269
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001270/* See comment in xxsubtype.c */
1271#define DEFERRED_ADDRESS(ADDR) 0
1272
Guido van Rossum1968ad32006-02-25 22:38:04 +00001273static PyTypeObject defdict_type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001274 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
Guido van Rossum1968ad32006-02-25 22:38:04 +00001275 "collections.defaultdict", /* tp_name */
1276 sizeof(defdictobject), /* tp_basicsize */
1277 0, /* tp_itemsize */
1278 /* methods */
1279 (destructor)defdict_dealloc, /* tp_dealloc */
1280 (printfunc)defdict_print, /* tp_print */
1281 0, /* tp_getattr */
1282 0, /* tp_setattr */
1283 0, /* tp_compare */
1284 (reprfunc)defdict_repr, /* tp_repr */
1285 0, /* tp_as_number */
1286 0, /* tp_as_sequence */
1287 0, /* tp_as_mapping */
1288 0, /* tp_hash */
1289 0, /* tp_call */
1290 0, /* tp_str */
1291 PyObject_GenericGetAttr, /* tp_getattro */
1292 0, /* tp_setattro */
1293 0, /* tp_as_buffer */
Guido van Rossumd8faa362007-04-27 19:54:29 +00001294 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1295 /* tp_flags */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001296 defdict_doc, /* tp_doc */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001297 defdict_traverse, /* tp_traverse */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001298 (inquiry)defdict_tp_clear, /* tp_clear */
1299 0, /* tp_richcompare */
1300 0, /* tp_weaklistoffset*/
1301 0, /* tp_iter */
1302 0, /* tp_iternext */
1303 defdict_methods, /* tp_methods */
1304 defdict_members, /* tp_members */
1305 0, /* tp_getset */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001306 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001307 0, /* tp_dict */
1308 0, /* tp_descr_get */
1309 0, /* tp_descr_set */
1310 0, /* tp_dictoffset */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001311 defdict_init, /* tp_init */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001312 PyType_GenericAlloc, /* tp_alloc */
1313 0, /* tp_new */
1314 PyObject_GC_Del, /* tp_free */
1315};
1316
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001317/* module level code ********************************************************/
1318
1319PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00001320"High performance data structures.\n\
1321- deque: ordered collection accessible from endpoints only\n\
1322- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001323");
1324
1325PyMODINIT_FUNC
Guido van Rossumd8faa362007-04-27 19:54:29 +00001326init_collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001327{
1328 PyObject *m;
1329
Guido van Rossumd8faa362007-04-27 19:54:29 +00001330 m = Py_InitModule3("_collections", NULL, module_doc);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00001331 if (m == NULL)
1332 return;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001333
1334 if (PyType_Ready(&deque_type) < 0)
1335 return;
1336 Py_INCREF(&deque_type);
1337 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
1338
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001339 defdict_type.tp_base = &PyDict_Type;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001340 if (PyType_Ready(&defdict_type) < 0)
1341 return;
1342 Py_INCREF(&defdict_type);
1343 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
1344
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001345 if (PyType_Ready(&dequeiter_type) < 0)
Tim Peters1065f752004-10-01 01:03:29 +00001346 return;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001347
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001348 if (PyType_Ready(&dequereviter_type) < 0)
1349 return;
1350
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001351 return;
1352}