Debian Codegraph @

cpython27/Modules/itertoolsmodule.c

raw symbols SCIP
1
2 #include "Python.h"
3 #include "structmember.h"
4
5 /* Itertools module written and maintained
6 by Raymond D. Hettinger <[email protected]>
7 */
8
9
10 /* groupby object ***********************************************************/
11
12 typedef struct {
13 PyObject_HEAD
14 PyObject *it;
15 PyObject *keyfunc;
16 PyObject *tgtkey;
17 PyObject *currkey;
18 PyObject *currvalue;
19 } groupbyobject;
20
21 static PyTypeObject groupby_type;
22 static PyObject *_grouper_create(groupbyobject *, PyObject *);
23
24 static PyObject *
25 groupby_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
26 {
27 static char *kwargs[] = {"iterable", "key", NULL};
28 groupbyobject *gbo;
29 PyObject *it, *keyfunc = Py_None;
30
31 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:groupby", kwargs,
32 &it, &keyfunc))
33 return NULL;
34
35 gbo = (groupbyobject *)type->tp_alloc(type, 0);
36 if (gbo == NULL)
37 return NULL;
38 gbo->tgtkey = NULL;
39 gbo->currkey = NULL;
40 gbo->currvalue = NULL;
41 gbo->keyfunc = keyfunc;
42 Py_INCREF(keyfunc);
43 gbo->it = PyObject_GetIter(it);
44 if (gbo->it == NULL) {
45 Py_DECREF(gbo);
46 return NULL;
47 }
48 return (PyObject *)gbo;
49 }
50
51 static void
52 groupby_dealloc(groupbyobject *gbo)
53 {
54 PyObject_GC_UnTrack(gbo);
55 Py_XDECREF(gbo->it);
56 Py_XDECREF(gbo->keyfunc);
57 Py_XDECREF(gbo->tgtkey);
58 Py_XDECREF(gbo->currkey);
59 Py_XDECREF(gbo->currvalue);
60 Py_TYPE(gbo)->tp_free(gbo);
61 }
62
63 static int
64 groupby_traverse(groupbyobject *gbo, visitproc visit, void *arg)
65 {
66 Py_VISIT(gbo->it);
67 Py_VISIT(gbo->keyfunc);
68 Py_VISIT(gbo->tgtkey);
69 Py_VISIT(gbo->currkey);
70 Py_VISIT(gbo->currvalue);
71 return 0;
72 }
73
74 Py_LOCAL_INLINE(int)
75 groupby_step(groupbyobject *gbo)
76 {
77 PyObject *newvalue, *newkey, *oldvalue;
78
79 newvalue = PyIter_Next(gbo->it);
80 if (newvalue == NULL)
81 return -1;
82
83 if (gbo->keyfunc == Py_None) {
84 newkey = newvalue;
85 Py_INCREF(newvalue);
86 } else {
87 newkey = PyObject_CallFunctionObjArgs(gbo->keyfunc, newvalue, NULL);
88 if (newkey == NULL) {
89 Py_DECREF(newvalue);
90 return -1;
91 }
92 }
93
94 oldvalue = gbo->currvalue;
95 gbo->currvalue = newvalue;
96 Py_XSETREF(gbo->currkey, newkey);
97 Py_XDECREF(oldvalue);
98 return 0;
99 }
100
101 static PyObject *
102 groupby_next(groupbyobject *gbo)
103 {
104 PyObject *r, *grouper;
105
106 /* skip to next iteration group */
107 for (;;) {
108 if (gbo->currkey == NULL)
109 /* pass */;
110 else if (gbo->tgtkey == NULL)
111 break;
112 else {
113 int rcmp;
114
115 rcmp = PyObject_RichCompareBool(gbo->tgtkey,
116 gbo->currkey, Py_EQ);
117 if (rcmp == -1)
118 return NULL;
119 else if (rcmp == 0)
120 break;
121 }
122
123 if (groupby_step(gbo) < 0)
124 return NULL;
125 }
126 Py_INCREF(gbo->currkey);
127 Py_XSETREF(gbo->tgtkey, gbo->currkey);
128
129 grouper = _grouper_create(gbo, gbo->tgtkey);
130 if (grouper == NULL)
131 return NULL;
132
133 r = PyTuple_Pack(2, gbo->currkey, grouper);
134 Py_DECREF(grouper);
135 return r;
136 }
137
138 PyDoc_STRVAR(groupby_doc,
139 "groupby(iterable[, keyfunc]) -> create an iterator which returns\n\
140 (key, sub-iterator) grouped by each value of key(value).\n");
141
142 static PyTypeObject groupby_type = {
143 PyVarObject_HEAD_INIT(NULL, 0)
144 "itertools.groupby", /* tp_name */
145 sizeof(groupbyobject), /* tp_basicsize */
146 0, /* tp_itemsize */
147 /* methods */
148 (destructor)groupby_dealloc, /* tp_dealloc */
149 0, /* tp_print */
150 0, /* tp_getattr */
151 0, /* tp_setattr */
152 0, /* tp_compare */
153 0, /* tp_repr */
154 0, /* tp_as_number */
155 0, /* tp_as_sequence */
156 0, /* tp_as_mapping */
157 0, /* tp_hash */
158 0, /* tp_call */
159 0, /* tp_str */
160 PyObject_GenericGetAttr, /* tp_getattro */
161 0, /* tp_setattro */
162 0, /* tp_as_buffer */
163 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
164 Py_TPFLAGS_BASETYPE, /* tp_flags */
165 groupby_doc, /* tp_doc */
166 (traverseproc)groupby_traverse, /* tp_traverse */
167 0, /* tp_clear */
168 0, /* tp_richcompare */
169 0, /* tp_weaklistoffset */
170 PyObject_SelfIter, /* tp_iter */
171 (iternextfunc)groupby_next, /* tp_iternext */
172 0, /* tp_methods */
173 0, /* tp_members */
174 0, /* tp_getset */
175 0, /* tp_base */
176 0, /* tp_dict */
177 0, /* tp_descr_get */
178 0, /* tp_descr_set */
179 0, /* tp_dictoffset */
180 0, /* tp_init */
181 0, /* tp_alloc */
182 groupby_new, /* tp_new */
183 PyObject_GC_Del, /* tp_free */
184 };
185
186
187 /* _grouper object (internal) ************************************************/
188
189 typedef struct {
190 PyObject_HEAD
191 PyObject *parent;
192 PyObject *tgtkey;
193 } _grouperobject;
194
195 static PyTypeObject _grouper_type;
196
197 static PyObject *
198 _grouper_create(groupbyobject *parent, PyObject *tgtkey)
199 {
200 _grouperobject *igo;
201
202 igo = PyObject_GC_New(_grouperobject, &_grouper_type);
203 if (igo == NULL)
204 return NULL;
205 igo->parent = (PyObject *)parent;
206 Py_INCREF(parent);
207 igo->tgtkey = tgtkey;
208 Py_INCREF(tgtkey);
209
210 PyObject_GC_Track(igo);
211 return (PyObject *)igo;
212 }
213
214 static void
215 _grouper_dealloc(_grouperobject *igo)
216 {
217 PyObject_GC_UnTrack(igo);
218 Py_DECREF(igo->parent);
219 Py_DECREF(igo->tgtkey);
220 PyObject_GC_Del(igo);
221 }
222
223 static int
224 _grouper_traverse(_grouperobject *igo, visitproc visit, void *arg)
225 {
226 Py_VISIT(igo->parent);
227 Py_VISIT(igo->tgtkey);
228 return 0;
229 }
230
231 static PyObject *
232 _grouper_next(_grouperobject *igo)
233 {
234 groupbyobject *gbo = (groupbyobject *)igo->parent;
235 PyObject *r;
236 int rcmp;
237
238 if (gbo->currvalue == NULL) {
239 if (groupby_step(gbo) < 0)
240 return NULL;
241 }
242
243 assert(gbo->currkey != NULL);
244 rcmp = PyObject_RichCompareBool(igo->tgtkey, gbo->currkey, Py_EQ);
245 if (rcmp <= 0)
246 /* got any error or current group is end */
247 return NULL;
248
249 r = gbo->currvalue;
250 gbo->currvalue = NULL;
251 Py_CLEAR(gbo->currkey);
252
253 return r;
254 }
255
256 static PyTypeObject _grouper_type = {
257 PyVarObject_HEAD_INIT(NULL, 0)
258 "itertools._grouper", /* tp_name */
259 sizeof(_grouperobject), /* tp_basicsize */
260 0, /* tp_itemsize */
261 /* methods */
262 (destructor)_grouper_dealloc, /* tp_dealloc */
263 0, /* tp_print */
264 0, /* tp_getattr */
265 0, /* tp_setattr */
266 0, /* tp_compare */
267 0, /* tp_repr */
268 0, /* tp_as_number */
269 0, /* tp_as_sequence */
270 0, /* tp_as_mapping */
271 0, /* tp_hash */
272 0, /* tp_call */
273 0, /* tp_str */
274 PyObject_GenericGetAttr, /* tp_getattro */
275 0, /* tp_setattro */
276 0, /* tp_as_buffer */
277 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
278 0, /* tp_doc */
279 (traverseproc)_grouper_traverse,/* tp_traverse */
280 0, /* tp_clear */
281 0, /* tp_richcompare */
282 0, /* tp_weaklistoffset */
283 PyObject_SelfIter, /* tp_iter */
284 (iternextfunc)_grouper_next, /* tp_iternext */
285 0, /* tp_methods */
286 0, /* tp_members */
287 0, /* tp_getset */
288 0, /* tp_base */
289 0, /* tp_dict */
290 0, /* tp_descr_get */
291 0, /* tp_descr_set */
292 0, /* tp_dictoffset */
293 0, /* tp_init */
294 0, /* tp_alloc */
295 0, /* tp_new */
296 PyObject_GC_Del, /* tp_free */
297 };
298
299
300
301 /* tee object and with supporting function and objects ***************/
302
303 /* The teedataobject pre-allocates space for LINKCELLS number of objects.
304 To help the object fit neatly inside cache lines (space for 16 to 32
305 pointers), the value should be a multiple of 16 minus space for
306 the other structure members including PyHEAD overhead. The larger the
307 value, the less memory overhead per object and the less time spent
308 allocating/deallocating new links. The smaller the number, the less
309 wasted space and the more rapid freeing of older data.
310 */
311 #define LINKCELLS 57
312
313 typedef struct {
314 PyObject_HEAD
315 PyObject *it;
316 int numread;
317 int running;
318 PyObject *nextlink;
319 PyObject *(values[LINKCELLS]);
320 } teedataobject;
321
322 typedef struct {
323 PyObject_HEAD
324 teedataobject *dataobj;
325 int index;
326 PyObject *weakreflist;
327 } teeobject;
328
329 static PyTypeObject teedataobject_type;
330
331 static PyObject *
332 teedataobject_new(PyObject *it)
333 {
334 teedataobject *tdo;
335
336 tdo = PyObject_GC_New(teedataobject, &teedataobject_type);
337 if (tdo == NULL)
338 return NULL;
339
340 tdo->running = 0;
341 tdo->numread = 0;
342 tdo->nextlink = NULL;
343 Py_INCREF(it);
344 tdo->it = it;
345 PyObject_GC_Track(tdo);
346 return (PyObject *)tdo;
347 }
348
349 static PyObject *
350 teedataobject_jumplink(teedataobject *tdo)
351 {
352 if (tdo->nextlink == NULL)
353 tdo->nextlink = teedataobject_new(tdo->it);
354 Py_XINCREF(tdo->nextlink);
355 return tdo->nextlink;
356 }
357
358 static PyObject *
359 teedataobject_getitem(teedataobject *tdo, int i)
360 {
361 PyObject *value;
362
363 assert(i < LINKCELLS);
364 if (i < tdo->numread)
365 value = tdo->values[i];
366 else {
367 /* this is the lead iterator, so fetch more data */
368 assert(i == tdo->numread);
369 if (tdo->running) {
370 PyErr_SetString(PyExc_RuntimeError,
371 "cannot re-enter the tee iterator");
372 return NULL;
373 }
374 tdo->running = 1;
375 value = PyIter_Next(tdo->it);
376 tdo->running = 0;
377 if (value == NULL)
378 return NULL;
379 tdo->numread++;
380 tdo->values[i] = value;
381 }
382 Py_INCREF(value);
383 return value;
384 }
385
386 static int
387 teedataobject_traverse(teedataobject *tdo, visitproc visit, void * arg)
388 {
389 int i;
390 Py_VISIT(tdo->it);
391 for (i = 0; i < tdo->numread; i++)
392 Py_VISIT(tdo->values[i]);
393 Py_VISIT(tdo->nextlink);
394 return 0;
395 }
396
397 static void
398 teedataobject_safe_decref(PyObject *obj)
399 {
400 while (obj && Py_TYPE(obj) == &teedataobject_type &&
401 Py_REFCNT(obj) == 1) {
402 PyObject *nextlink = ((teedataobject *)obj)->nextlink;
403 ((teedataobject *)obj)->nextlink = NULL;
404 Py_DECREF(obj);
405 obj = nextlink;
406 }
407 Py_XDECREF(obj);
408 }
409
410 static int
411 teedataobject_clear(teedataobject *tdo)
412 {
413 int i;
414 PyObject *tmp;
415
416 Py_CLEAR(tdo->it);
417 for (i=0 ; i<tdo->numread ; i++)
418 Py_CLEAR(tdo->values[i]);
419 tmp = tdo->nextlink;
420 tdo->nextlink = NULL;
421 teedataobject_safe_decref(tmp);
422 return 0;
423 }
424
425 static void
426 teedataobject_dealloc(teedataobject *tdo)
427 {
428 PyObject_GC_UnTrack(tdo);
429 teedataobject_clear(tdo);
430 PyObject_GC_Del(tdo);
431 }
432
433 PyDoc_STRVAR(teedataobject_doc, "Data container common to multiple tee objects.");
434
435 static PyTypeObject teedataobject_type = {
436 PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */
437 "itertools.tee_dataobject", /* tp_name */
438 sizeof(teedataobject), /* tp_basicsize */
439 0, /* tp_itemsize */
440 /* methods */
441 (destructor)teedataobject_dealloc, /* tp_dealloc */
442 0, /* tp_print */
443 0, /* tp_getattr */
444 0, /* tp_setattr */
445 0, /* tp_compare */
446 0, /* tp_repr */
447 0, /* tp_as_number */
448 0, /* tp_as_sequence */
449 0, /* tp_as_mapping */
450 0, /* tp_hash */
451 0, /* tp_call */
452 0, /* tp_str */
453 PyObject_GenericGetAttr, /* tp_getattro */
454 0, /* tp_setattro */
455 0, /* tp_as_buffer */
456 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
457 teedataobject_doc, /* tp_doc */
458 (traverseproc)teedataobject_traverse, /* tp_traverse */
459 (inquiry)teedataobject_clear, /* tp_clear */
460 0, /* tp_richcompare */
461 0, /* tp_weaklistoffset */
462 0, /* tp_iter */
463 0, /* tp_iternext */
464 0, /* tp_methods */
465 0, /* tp_members */
466 0, /* tp_getset */
467 0, /* tp_base */
468 0, /* tp_dict */
469 0, /* tp_descr_get */
470 0, /* tp_descr_set */
471 0, /* tp_dictoffset */
472 0, /* tp_init */
473 0, /* tp_alloc */
474 0, /* tp_new */
475 PyObject_GC_Del, /* tp_free */
476 };
477
478
479 static PyTypeObject tee_type;
480
481 static PyObject *
482 tee_next(teeobject *to)
483 {
484 PyObject *value, *link;
485
486 if (to->index >= LINKCELLS) {
487 link = teedataobject_jumplink(to->dataobj);
488 if (link == NULL)
489 return NULL;
490 Py_SETREF(to->dataobj, (teedataobject *)link);
491 to->index = 0;
492 }
493 value = teedataobject_getitem(to->dataobj, to->index);
494 if (value == NULL)
495 return NULL;
496 to->index++;
497 return value;
498 }
499
500 static int
501 tee_traverse(teeobject *to, visitproc visit, void *arg)
502 {
503 Py_VISIT((PyObject *)to->dataobj);
504 return 0;
505 }
506
507 static PyObject *
508 tee_copy(teeobject *to)
509 {
510 teeobject *newto;
511
512 newto = PyObject_GC_New(teeobject, &tee_type);
513 if (newto == NULL)
514 return NULL;
515 Py_INCREF(to->dataobj);
516 newto->dataobj = to->dataobj;
517 newto->index = to->index;
518 newto->weakreflist = NULL;
519 PyObject_GC_Track(newto);
520 return (PyObject *)newto;
521 }
522
523 PyDoc_STRVAR(teecopy_doc, "Returns an independent iterator.");
524
525 static PyObject *
526 tee_fromiterable(PyObject *iterable)
527 {
528 teeobject *to;
529 PyObject *it = NULL;
530
531 it = PyObject_GetIter(iterable);
532 if (it == NULL)
533 return NULL;
534 if (PyObject_TypeCheck(it, &tee_type)) {
535 to = (teeobject *)tee_copy((teeobject *)it);
536 goto done;
537 }
538
539 to = PyObject_GC_New(teeobject, &tee_type);
540 if (to == NULL)
541 goto done;
542 to->dataobj = (teedataobject *)teedataobject_new(it);
543 if (!to->dataobj) {
544 PyObject_GC_Del(to);
545 to = NULL;
546 goto done;
547 }
548
549 to->index = 0;
550 to->weakreflist = NULL;
551 PyObject_GC_Track(to);
552 done:
553 Py_XDECREF(it);
554 return (PyObject *)to;
555 }
556
557 static PyObject *
558 tee_new(PyTypeObject *type, PyObject *args, PyObject *kw)
559 {
560 PyObject *iterable;
561
562 if (!PyArg_UnpackTuple(args, "tee", 1, 1, &iterable))
563 return NULL;
564 return tee_fromiterable(iterable);
565 }
566
567 static int
568 tee_clear(teeobject *to)
569 {
570 if (to->weakreflist != NULL)
571 PyObject_ClearWeakRefs((PyObject *) to);
572 Py_CLEAR(to->dataobj);
573 return 0;
574 }
575
576 static void
577 tee_dealloc(teeobject *to)
578 {
579 PyObject_GC_UnTrack(to);
580 tee_clear(to);
581 PyObject_GC_Del(to);
582 }
583
584 PyDoc_STRVAR(teeobject_doc,
585 "Iterator wrapped to make it copyable");
586
587 static PyMethodDef tee_methods[] = {
588 {"__copy__", (PyCFunction)tee_copy, METH_NOARGS, teecopy_doc},
589 {NULL, NULL} /* sentinel */
590 };
591
592 static PyTypeObject tee_type = {
593 PyVarObject_HEAD_INIT(NULL, 0)
594 "itertools.tee", /* tp_name */
595 sizeof(teeobject), /* tp_basicsize */
596 0, /* tp_itemsize */
597 /* methods */
598 (destructor)tee_dealloc, /* tp_dealloc */
599 0, /* tp_print */
600 0, /* tp_getattr */
601 0, /* tp_setattr */
602 0, /* tp_compare */
603 0, /* tp_repr */
604 0, /* tp_as_number */
605 0, /* tp_as_sequence */
606 0, /* tp_as_mapping */
607 0, /* tp_hash */
608 0, /* tp_call */
609 0, /* tp_str */
610 0, /* tp_getattro */
611 0, /* tp_setattro */
612 0, /* tp_as_buffer */
613 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
614 teeobject_doc, /* tp_doc */
615 (traverseproc)tee_traverse, /* tp_traverse */
616 (inquiry)tee_clear, /* tp_clear */
617 0, /* tp_richcompare */
618 offsetof(teeobject, weakreflist), /* tp_weaklistoffset */
619 PyObject_SelfIter, /* tp_iter */
620 (iternextfunc)tee_next, /* tp_iternext */
621 tee_methods, /* tp_methods */
622 0, /* tp_members */
623 0, /* tp_getset */
624 0, /* tp_base */
625 0, /* tp_dict */
626 0, /* tp_descr_get */
627 0, /* tp_descr_set */
628 0, /* tp_dictoffset */
629 0, /* tp_init */
630 0, /* tp_alloc */
631 tee_new, /* tp_new */
632 PyObject_GC_Del, /* tp_free */
633 };
634
635 static PyObject *
636 tee(PyObject *self, PyObject *args)
637 {
638 Py_ssize_t i, n=2;
639 PyObject *it, *iterable, *copyable, *result;
640
641 if (!PyArg_ParseTuple(args, "O|n", &iterable, &n))
642 return NULL;
643 if (n < 0) {
644 PyErr_SetString(PyExc_ValueError, "n must be >= 0");
645 return NULL;
646 }
647 result = PyTuple_New(n);
648 if (result == NULL)
649 return NULL;
650 if (n == 0)
651 return result;
652 it = PyObject_GetIter(iterable);
653 if (it == NULL) {
654 Py_DECREF(result);
655 return NULL;
656 }
657 if (!PyObject_HasAttrString(it, "__copy__")) {
658 copyable = tee_fromiterable(it);
659 Py_DECREF(it);
660 if (copyable == NULL) {
661 Py_DECREF(result);
662 return NULL;
663 }
664 } else
665 copyable = it;
666 PyTuple_SET_ITEM(result, 0, copyable);
667 for (i=1 ; i<n ; i++) {
668 copyable = PyObject_CallMethod(copyable, "__copy__", NULL);
669 if (copyable == NULL) {
670 Py_DECREF(result);
671 return NULL;
672 }
673 PyTuple_SET_ITEM(result, i, copyable);
674 }
675 return result;
676 }
677
678 PyDoc_STRVAR(tee_doc,
679 "tee(iterable, n=2) --> tuple of n independent iterators.");
680
681
682 /* cycle object **********************************************************/
683
684 typedef struct {
685 PyObject_HEAD
686 PyObject *it;
687 PyObject *saved;
688 int firstpass;
689 } cycleobject;
690
691 static PyTypeObject cycle_type;
692
693 static PyObject *
694 cycle_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
695 {
696 PyObject *it;
697 PyObject *iterable;
698 PyObject *saved;
699 cycleobject *lz;
700
701 if (type == &cycle_type && !_PyArg_NoKeywords("cycle()", kwds))
702 return NULL;
703
704 if (!PyArg_UnpackTuple(args, "cycle", 1, 1, &iterable))
705 return NULL;
706
707 /* Get iterator. */
708 it = PyObject_GetIter(iterable);
709 if (it == NULL)
710 return NULL;
711
712 saved = PyList_New(0);
713 if (saved == NULL) {
714 Py_DECREF(it);
715 return NULL;
716 }
717
718 /* create cycleobject structure */
719 lz = (cycleobject *)type->tp_alloc(type, 0);
720 if (lz == NULL) {
721 Py_DECREF(it);
722 Py_DECREF(saved);
723 return NULL;
724 }
725 lz->it = it;
726 lz->saved = saved;
727 lz->firstpass = 0;
728
729 return (PyObject *)lz;
730 }
731
732 static void
733 cycle_dealloc(cycleobject *lz)
734 {
735 PyObject_GC_UnTrack(lz);
736 Py_XDECREF(lz->saved);
737 Py_XDECREF(lz->it);
738 Py_TYPE(lz)->tp_free(lz);
739 }
740
741 static int
742 cycle_traverse(cycleobject *lz, visitproc visit, void *arg)
743 {
744 Py_VISIT(lz->it);
745 Py_VISIT(lz->saved);
746 return 0;
747 }
748
749 static PyObject *
750 cycle_next(cycleobject *lz)
751 {
752 PyObject *item;
753 PyObject *it;
754 PyObject *tmp;
755
756 while (1) {
757 item = PyIter_Next(lz->it);
758 if (item != NULL) {
759 if (!lz->firstpass && PyList_Append(lz->saved, item)) {
760 Py_DECREF(item);
761 return NULL;
762 }
763 return item;
764 }
765 if (PyErr_Occurred()) {
766 if (PyErr_ExceptionMatches(PyExc_StopIteration))
767 PyErr_Clear();
768 else
769 return NULL;
770 }
771 if (PyList_Size(lz->saved) == 0)
772 return NULL;
773 it = PyObject_GetIter(lz->saved);
774 if (it == NULL)
775 return NULL;
776 tmp = lz->it;
777 lz->it = it;
778 lz->firstpass = 1;
779 Py_DECREF(tmp);
780 }
781 }
782
783 PyDoc_STRVAR(cycle_doc,
784 "cycle(iterable) --> cycle object\n\
785 \n\
786 Return elements from the iterable until it is exhausted.\n\
787 Then repeat the sequence indefinitely.");
788
789 static PyTypeObject cycle_type = {
790 PyVarObject_HEAD_INIT(NULL, 0)
791 "itertools.cycle", /* tp_name */
792 sizeof(cycleobject), /* tp_basicsize */
793 0, /* tp_itemsize */
794 /* methods */
795 (destructor)cycle_dealloc, /* tp_dealloc */
796 0, /* tp_print */
797 0, /* tp_getattr */
798 0, /* tp_setattr */
799 0, /* tp_compare */
800 0, /* tp_repr */
801 0, /* tp_as_number */
802 0, /* tp_as_sequence */
803 0, /* tp_as_mapping */
804 0, /* tp_hash */
805 0, /* tp_call */
806 0, /* tp_str */
807 PyObject_GenericGetAttr, /* tp_getattro */
808 0, /* tp_setattro */
809 0, /* tp_as_buffer */
810 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
811 Py_TPFLAGS_BASETYPE, /* tp_flags */
812 cycle_doc, /* tp_doc */
813 (traverseproc)cycle_traverse, /* tp_traverse */
814 0, /* tp_clear */
815 0, /* tp_richcompare */
816 0, /* tp_weaklistoffset */
817 PyObject_SelfIter, /* tp_iter */
818 (iternextfunc)cycle_next, /* tp_iternext */
819 0, /* tp_methods */
820 0, /* tp_members */
821 0, /* tp_getset */
822 0, /* tp_base */
823 0, /* tp_dict */
824 0, /* tp_descr_get */
825 0, /* tp_descr_set */
826 0, /* tp_dictoffset */
827 0, /* tp_init */
828 0, /* tp_alloc */
829 cycle_new, /* tp_new */
830 PyObject_GC_Del, /* tp_free */
831 };
832
833
834 /* dropwhile object **********************************************************/
835
836 typedef struct {
837 PyObject_HEAD
838 PyObject *func;
839 PyObject *it;
840 long start;
841 } dropwhileobject;
842
843 static PyTypeObject dropwhile_type;
844
845 static PyObject *
846 dropwhile_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
847 {
848 PyObject *func, *seq;
849 PyObject *it;
850 dropwhileobject *lz;
851
852 if (type == &dropwhile_type && !_PyArg_NoKeywords("dropwhile()", kwds))
853 return NULL;
854
855 if (!PyArg_UnpackTuple(args, "dropwhile", 2, 2, &func, &seq))
856 return NULL;
857
858 /* Get iterator. */
859 it = PyObject_GetIter(seq);
860 if (it == NULL)
861 return NULL;
862
863 /* create dropwhileobject structure */
864 lz = (dropwhileobject *)type->tp_alloc(type, 0);
865 if (lz == NULL) {
866 Py_DECREF(it);
867 return NULL;
868 }
869 Py_INCREF(func);
870 lz->func = func;
871 lz->it = it;
872 lz->start = 0;
873
874 return (PyObject *)lz;
875 }
876
877 static void
878 dropwhile_dealloc(dropwhileobject *lz)
879 {
880 PyObject_GC_UnTrack(lz);
881 Py_XDECREF(lz->func);
882 Py_XDECREF(lz->it);
883 Py_TYPE(lz)->tp_free(lz);
884 }
885
886 static int
887 dropwhile_traverse(dropwhileobject *lz, visitproc visit, void *arg)
888 {
889 Py_VISIT(lz->it);
890 Py_VISIT(lz->func);
891 return 0;
892 }
893
894 static PyObject *
895 dropwhile_next(dropwhileobject *lz)
896 {
897 PyObject *item, *good;
898 PyObject *it = lz->it;
899 long ok;
900 PyObject *(*iternext)(PyObject *);
901
902 iternext = *Py_TYPE(it)->tp_iternext;
903 for (;;) {
904 item = iternext(it);
905 if (item == NULL)
906 return NULL;
907 if (lz->start == 1)
908 return item;
909
910 good = PyObject_CallFunctionObjArgs(lz->func, item, NULL);
911 if (good == NULL) {
912 Py_DECREF(item);
913 return NULL;
914 }
915 ok = PyObject_IsTrue(good);
916 Py_DECREF(good);
917 if (ok == 0) {
918 lz->start = 1;
919 return item;
920 }
921 Py_DECREF(item);
922 if (ok < 0)
923 return NULL;
924 }
925 }
926
927 PyDoc_STRVAR(dropwhile_doc,
928 "dropwhile(predicate, iterable) --> dropwhile object\n\
929 \n\
930 Drop items from the iterable while predicate(item) is true.\n\
931 Afterwards, return every element until the iterable is exhausted.");
932
933 static PyTypeObject dropwhile_type = {
934 PyVarObject_HEAD_INIT(NULL, 0)
935 "itertools.dropwhile", /* tp_name */
936 sizeof(dropwhileobject), /* tp_basicsize */
937 0, /* tp_itemsize */
938 /* methods */
939 (destructor)dropwhile_dealloc, /* tp_dealloc */
940 0, /* tp_print */
941 0, /* tp_getattr */
942 0, /* tp_setattr */
943 0, /* tp_compare */
944 0, /* tp_repr */
945 0, /* tp_as_number */
946 0, /* tp_as_sequence */
947 0, /* tp_as_mapping */
948 0, /* tp_hash */
949 0, /* tp_call */
950 0, /* tp_str */
951 PyObject_GenericGetAttr, /* tp_getattro */
952 0, /* tp_setattro */
953 0, /* tp_as_buffer */
954 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
955 Py_TPFLAGS_BASETYPE, /* tp_flags */
956 dropwhile_doc, /* tp_doc */
957 (traverseproc)dropwhile_traverse, /* tp_traverse */
958 0, /* tp_clear */
959 0, /* tp_richcompare */
960 0, /* tp_weaklistoffset */
961 PyObject_SelfIter, /* tp_iter */
962 (iternextfunc)dropwhile_next, /* tp_iternext */
963 0, /* tp_methods */
964 0, /* tp_members */
965 0, /* tp_getset */
966 0, /* tp_base */
967 0, /* tp_dict */
968 0, /* tp_descr_get */
969 0, /* tp_descr_set */
970 0, /* tp_dictoffset */
971 0, /* tp_init */
972 0, /* tp_alloc */
973 dropwhile_new, /* tp_new */
974 PyObject_GC_Del, /* tp_free */
975 };
976
977
978 /* takewhile object **********************************************************/
979
980 typedef struct {
981 PyObject_HEAD
982 PyObject *func;
983 PyObject *it;
984 long stop;
985 } takewhileobject;
986
987 static PyTypeObject takewhile_type;
988
989 static PyObject *
990 takewhile_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
991 {
992 PyObject *func, *seq;
993 PyObject *it;
994 takewhileobject *lz;
995
996 if (type == &takewhile_type && !_PyArg_NoKeywords("takewhile()", kwds))
997 return NULL;
998
999 if (!PyArg_UnpackTuple(args, "takewhile", 2, 2, &func, &seq))
1000 return NULL;
1001
1002 /* Get iterator. */
1003 it = PyObject_GetIter(seq);
1004 if (it == NULL)
1005 return NULL;
1006
1007 /* create takewhileobject structure */
1008 lz = (takewhileobject *)type->tp_alloc(type, 0);
1009 if (lz == NULL) {
1010 Py_DECREF(it);
1011 return NULL;
1012 }
1013 Py_INCREF(func);
1014 lz->func = func;
1015 lz->it = it;
1016 lz->stop = 0;
1017
1018 return (PyObject *)lz;
1019 }
1020
1021 static void
1022 takewhile_dealloc(takewhileobject *lz)
1023 {
1024 PyObject_GC_UnTrack(lz);
1025 Py_XDECREF(lz->func);
1026 Py_XDECREF(lz->it);
1027 Py_TYPE(lz)->tp_free(lz);
1028 }
1029
1030 static int
1031 takewhile_traverse(takewhileobject *lz, visitproc visit, void *arg)
1032 {
1033 Py_VISIT(lz->it);
1034 Py_VISIT(lz->func);
1035 return 0;
1036 }
1037
1038 static PyObject *
1039 takewhile_next(takewhileobject *lz)
1040 {
1041 PyObject *item, *good;
1042 PyObject *it = lz->it;
1043 long ok;
1044
1045 if (lz->stop == 1)
1046 return NULL;
1047
1048 item = (*Py_TYPE(it)->tp_iternext)(it);
1049 if (item == NULL)
1050 return NULL;
1051
1052 good = PyObject_CallFunctionObjArgs(lz->func, item, NULL);
1053 if (good == NULL) {
1054 Py_DECREF(item);
1055 return NULL;
1056 }
1057 ok = PyObject_IsTrue(good);
1058 Py_DECREF(good);
1059 if (ok > 0)
1060 return item;
1061 Py_DECREF(item);
1062 if (ok == 0)
1063 lz->stop = 1;
1064 return NULL;
1065 }
1066
1067 PyDoc_STRVAR(takewhile_doc,
1068 "takewhile(predicate, iterable) --> takewhile object\n\
1069 \n\
1070 Return successive entries from an iterable as long as the \n\
1071 predicate evaluates to true for each entry.");
1072
1073 static PyTypeObject takewhile_type = {
1074 PyVarObject_HEAD_INIT(NULL, 0)
1075 "itertools.takewhile", /* tp_name */
1076 sizeof(takewhileobject), /* tp_basicsize */
1077 0, /* tp_itemsize */
1078 /* methods */
1079 (destructor)takewhile_dealloc, /* tp_dealloc */
1080 0, /* tp_print */
1081 0, /* tp_getattr */
1082 0, /* tp_setattr */
1083 0, /* tp_compare */
1084 0, /* tp_repr */
1085 0, /* tp_as_number */
1086 0, /* tp_as_sequence */
1087 0, /* tp_as_mapping */
1088 0, /* tp_hash */
1089 0, /* tp_call */
1090 0, /* tp_str */
1091 PyObject_GenericGetAttr, /* tp_getattro */
1092 0, /* tp_setattro */
1093 0, /* tp_as_buffer */
1094 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1095 Py_TPFLAGS_BASETYPE, /* tp_flags */
1096 takewhile_doc, /* tp_doc */
1097 (traverseproc)takewhile_traverse, /* tp_traverse */
1098 0, /* tp_clear */
1099 0, /* tp_richcompare */
1100 0, /* tp_weaklistoffset */
1101 PyObject_SelfIter, /* tp_iter */
1102 (iternextfunc)takewhile_next, /* tp_iternext */
1103 0, /* tp_methods */
1104 0, /* tp_members */
1105 0, /* tp_getset */
1106 0, /* tp_base */
1107 0, /* tp_dict */
1108 0, /* tp_descr_get */
1109 0, /* tp_descr_set */
1110 0, /* tp_dictoffset */
1111 0, /* tp_init */
1112 0, /* tp_alloc */
1113 takewhile_new, /* tp_new */
1114 PyObject_GC_Del, /* tp_free */
1115 };
1116
1117
1118 /* islice object ************************************************************/
1119
1120 typedef struct {
1121 PyObject_HEAD
1122 PyObject *it;
1123 Py_ssize_t next;
1124 Py_ssize_t stop;
1125 Py_ssize_t step;
1126 Py_ssize_t cnt;
1127 } isliceobject;
1128
1129 static PyTypeObject islice_type;
1130
1131 static PyObject *
1132 islice_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1133 {
1134 PyObject *seq;
1135 Py_ssize_t start=0, stop=-1, step=1;
1136 PyObject *it, *a1=NULL, *a2=NULL, *a3=NULL;
1137 Py_ssize_t numargs;
1138 isliceobject *lz;
1139
1140 if (type == &islice_type && !_PyArg_NoKeywords("islice()", kwds))
1141 return NULL;
1142
1143 if (!PyArg_UnpackTuple(args, "islice", 2, 4, &seq, &a1, &a2, &a3))
1144 return NULL;
1145
1146 numargs = PyTuple_Size(args);
1147 if (numargs == 2) {
1148 if (a1 != Py_None) {
1149 stop = PyInt_AsSsize_t(a1);
1150 if (stop == -1) {
1151 if (PyErr_Occurred())
1152 PyErr_Clear();
1153 PyErr_SetString(PyExc_ValueError,
1154 "Stop argument for islice() must be None or an integer: 0 <= x <= maxint.");
1155 return NULL;
1156 }
1157 }
1158 } else {
1159 if (a1 != Py_None)
1160 start = PyInt_AsSsize_t(a1);
1161 if (start == -1 && PyErr_Occurred())
1162 PyErr_Clear();
1163 if (a2 != Py_None) {
1164 stop = PyInt_AsSsize_t(a2);
1165 if (stop == -1) {
1166 if (PyErr_Occurred())
1167 PyErr_Clear();
1168 PyErr_SetString(PyExc_ValueError,
1169 "Stop argument for islice() must be None or an integer: 0 <= x <= maxint.");
1170 return NULL;
1171 }
1172 }
1173 }
1174 if (start<0 || stop<-1) {
1175 PyErr_SetString(PyExc_ValueError,
1176 "Indices for islice() must be None or an integer: 0 <= x <= maxint.");
1177 return NULL;
1178 }
1179
1180 if (a3 != NULL) {
1181 if (a3 != Py_None)
1182 step = PyInt_AsSsize_t(a3);
1183 if (step == -1 && PyErr_Occurred())
1184 PyErr_Clear();
1185 }
1186 if (step<1) {
1187 PyErr_SetString(PyExc_ValueError,
1188 "Step for islice() must be a positive integer or None.");
1189 return NULL;
1190 }
1191
1192 /* Get iterator. */
1193 it = PyObject_GetIter(seq);
1194 if (it == NULL)
1195 return NULL;
1196
1197 /* create isliceobject structure */
1198 lz = (isliceobject *)type->tp_alloc(type, 0);
1199 if (lz == NULL) {
1200 Py_DECREF(it);
1201 return NULL;
1202 }
1203 lz->it = it;
1204 lz->next = start;
1205 lz->stop = stop;
1206 lz->step = step;
1207 lz->cnt = 0L;
1208
1209 return (PyObject *)lz;
1210 }
1211
1212 static void
1213 islice_dealloc(isliceobject *lz)
1214 {
1215 PyObject_GC_UnTrack(lz);
1216 Py_XDECREF(lz->it);
1217 Py_TYPE(lz)->tp_free(lz);
1218 }
1219
1220 static int
1221 islice_traverse(isliceobject *lz, visitproc visit, void *arg)
1222 {
1223 Py_VISIT(lz->it);
1224 return 0;
1225 }
1226
1227 static PyObject *
1228 islice_next(isliceobject *lz)
1229 {
1230 PyObject *item;
1231 PyObject *it = lz->it;
1232 Py_ssize_t stop = lz->stop;
1233 Py_ssize_t oldnext;
1234 PyObject *(*iternext)(PyObject *);
1235
1236 if (it == NULL)
1237 return NULL;
1238
1239 iternext = *Py_TYPE(it)->tp_iternext;
1240 while (lz->cnt < lz->next) {
1241 item = iternext(it);
1242 if (item == NULL)
1243 goto empty;
1244 Py_DECREF(item);
1245 lz->cnt++;
1246 }
1247 if (stop != -1 && lz->cnt >= stop)
1248 goto empty;
1249 item = iternext(it);
1250 if (item == NULL)
1251 goto empty;
1252 lz->cnt++;
1253 oldnext = lz->next;
1254 /* The (size_t) cast below avoids the danger of undefined
1255 behaviour from signed integer overflow. */
1256 lz->next += (size_t)lz->step;
1257 if (lz->next < oldnext || (stop != -1 && lz->next > stop))
1258 lz->next = stop;
1259 return item;
1260
1261 empty:
1262 Py_CLEAR(lz->it);
1263 return NULL;
1264 }
1265
1266 PyDoc_STRVAR(islice_doc,
1267 "islice(iterable, [start,] stop [, step]) --> islice object\n\
1268 \n\
1269 Return an iterator whose next() method returns selected values from an\n\
1270 iterable. If start is specified, will skip all preceding elements;\n\
1271 otherwise, start defaults to zero. Step defaults to one. If\n\
1272 specified as another value, step determines how many values are \n\
1273 skipped between successive calls. Works like a slice() on a list\n\
1274 but returns an iterator.");
1275
1276 static PyTypeObject islice_type = {
1277 PyVarObject_HEAD_INIT(NULL, 0)
1278 "itertools.islice", /* tp_name */
1279 sizeof(isliceobject), /* tp_basicsize */
1280 0, /* tp_itemsize */
1281 /* methods */
1282 (destructor)islice_dealloc, /* tp_dealloc */
1283 0, /* tp_print */
1284 0, /* tp_getattr */
1285 0, /* tp_setattr */
1286 0, /* tp_compare */
1287 0, /* tp_repr */
1288 0, /* tp_as_number */
1289 0, /* tp_as_sequence */
1290 0, /* tp_as_mapping */
1291 0, /* tp_hash */
1292 0, /* tp_call */
1293 0, /* tp_str */
1294 PyObject_GenericGetAttr, /* tp_getattro */
1295 0, /* tp_setattro */
1296 0, /* tp_as_buffer */
1297 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1298 Py_TPFLAGS_BASETYPE, /* tp_flags */
1299 islice_doc, /* tp_doc */
1300 (traverseproc)islice_traverse, /* tp_traverse */
1301 0, /* tp_clear */
1302 0, /* tp_richcompare */
1303 0, /* tp_weaklistoffset */
1304 PyObject_SelfIter, /* tp_iter */
1305 (iternextfunc)islice_next, /* tp_iternext */
1306 0, /* tp_methods */
1307 0, /* tp_members */
1308 0, /* tp_getset */
1309 0, /* tp_base */
1310 0, /* tp_dict */
1311 0, /* tp_descr_get */
1312 0, /* tp_descr_set */
1313 0, /* tp_dictoffset */
1314 0, /* tp_init */
1315 0, /* tp_alloc */
1316 islice_new, /* tp_new */
1317 PyObject_GC_Del, /* tp_free */
1318 };
1319
1320
1321 /* starmap object ************************************************************/
1322
1323 typedef struct {
1324 PyObject_HEAD
1325 PyObject *func;
1326 PyObject *it;
1327 } starmapobject;
1328
1329 static PyTypeObject starmap_type;
1330
1331 static PyObject *
1332 starmap_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1333 {
1334 PyObject *func, *seq;
1335 PyObject *it;
1336 starmapobject *lz;
1337
1338 if (type == &starmap_type && !_PyArg_NoKeywords("starmap()", kwds))
1339 return NULL;
1340
1341 if (!PyArg_UnpackTuple(args, "starmap", 2, 2, &func, &seq))
1342 return NULL;
1343
1344 /* Get iterator. */
1345 it = PyObject_GetIter(seq);
1346 if (it == NULL)
1347 return NULL;
1348
1349 /* create starmapobject structure */
1350 lz = (starmapobject *)type->tp_alloc(type, 0);
1351 if (lz == NULL) {
1352 Py_DECREF(it);
1353 return NULL;
1354 }
1355 Py_INCREF(func);
1356 lz->func = func;
1357 lz->it = it;
1358
1359 return (PyObject *)lz;
1360 }
1361
1362 static void
1363 starmap_dealloc(starmapobject *lz)
1364 {
1365 PyObject_GC_UnTrack(lz);
1366 Py_XDECREF(lz->func);
1367 Py_XDECREF(lz->it);
1368 Py_TYPE(lz)->tp_free(lz);
1369 }
1370
1371 static int
1372 starmap_traverse(starmapobject *lz, visitproc visit, void *arg)
1373 {
1374 Py_VISIT(lz->it);
1375 Py_VISIT(lz->func);
1376 return 0;
1377 }
1378
1379 static PyObject *
1380 starmap_next(starmapobject *lz)
1381 {
1382 PyObject *args;
1383 PyObject *result;
1384 PyObject *it = lz->it;
1385
1386 args = (*Py_TYPE(it)->tp_iternext)(it);
1387 if (args == NULL)
1388 return NULL;
1389 if (!PyTuple_CheckExact(args)) {
1390 PyObject *newargs = PySequence_Tuple(args);
1391 Py_DECREF(args);
1392 if (newargs == NULL)
1393 return NULL;
1394 args = newargs;
1395 }
1396 result = PyObject_Call(lz->func, args, NULL);
1397 Py_DECREF(args);
1398 return result;
1399 }
1400
1401 PyDoc_STRVAR(starmap_doc,
1402 "starmap(function, sequence) --> starmap object\n\
1403 \n\
1404 Return an iterator whose values are returned from the function evaluated\n\
1405 with an argument tuple taken from the given sequence.");
1406
1407 static PyTypeObject starmap_type = {
1408 PyVarObject_HEAD_INIT(NULL, 0)
1409 "itertools.starmap", /* tp_name */
1410 sizeof(starmapobject), /* tp_basicsize */
1411 0, /* tp_itemsize */
1412 /* methods */
1413 (destructor)starmap_dealloc, /* tp_dealloc */
1414 0, /* tp_print */
1415 0, /* tp_getattr */
1416 0, /* tp_setattr */
1417 0, /* tp_compare */
1418 0, /* tp_repr */
1419 0, /* tp_as_number */
1420 0, /* tp_as_sequence */
1421 0, /* tp_as_mapping */
1422 0, /* tp_hash */
1423 0, /* tp_call */
1424 0, /* tp_str */
1425 PyObject_GenericGetAttr, /* tp_getattro */
1426 0, /* tp_setattro */
1427 0, /* tp_as_buffer */
1428 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1429 Py_TPFLAGS_BASETYPE, /* tp_flags */
1430 starmap_doc, /* tp_doc */
1431 (traverseproc)starmap_traverse, /* tp_traverse */
1432 0, /* tp_clear */
1433 0, /* tp_richcompare */
1434 0, /* tp_weaklistoffset */
1435 PyObject_SelfIter, /* tp_iter */
1436 (iternextfunc)starmap_next, /* tp_iternext */
1437 0, /* tp_methods */
1438 0, /* tp_members */
1439 0, /* tp_getset */
1440 0, /* tp_base */
1441 0, /* tp_dict */
1442 0, /* tp_descr_get */
1443 0, /* tp_descr_set */
1444 0, /* tp_dictoffset */
1445 0, /* tp_init */
1446 0, /* tp_alloc */
1447 starmap_new, /* tp_new */
1448 PyObject_GC_Del, /* tp_free */
1449 };
1450
1451
1452 /* imap object ************************************************************/
1453
1454 typedef struct {
1455 PyObject_HEAD
1456 PyObject *iters;
1457 PyObject *func;
1458 } imapobject;
1459
1460 static PyTypeObject imap_type;
1461
1462 static PyObject *
1463 imap_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1464 {
1465 PyObject *it, *iters, *func;
1466 imapobject *lz;
1467 Py_ssize_t numargs, i;
1468
1469 if (type == &imap_type && !_PyArg_NoKeywords("imap()", kwds))
1470 return NULL;
1471
1472 numargs = PyTuple_Size(args);
1473 if (numargs < 2) {
1474 PyErr_SetString(PyExc_TypeError,
1475 "imap() must have at least two arguments.");
1476 return NULL;
1477 }
1478
1479 iters = PyTuple_New(numargs-1);
1480 if (iters == NULL)
1481 return NULL;
1482
1483 for (i=1 ; i<numargs ; i++) {
1484 /* Get iterator. */
1485 it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
1486 if (it == NULL) {
1487 Py_DECREF(iters);
1488 return NULL;
1489 }
1490 PyTuple_SET_ITEM(iters, i-1, it);
1491 }
1492
1493 /* create imapobject structure */
1494 lz = (imapobject *)type->tp_alloc(type, 0);
1495 if (lz == NULL) {
1496 Py_DECREF(iters);
1497 return NULL;
1498 }
1499 lz->iters = iters;
1500 func = PyTuple_GET_ITEM(args, 0);
1501 Py_INCREF(func);
1502 lz->func = func;
1503
1504 return (PyObject *)lz;
1505 }
1506
1507 static void
1508 imap_dealloc(imapobject *lz)
1509 {
1510 PyObject_GC_UnTrack(lz);
1511 Py_XDECREF(lz->iters);
1512 Py_XDECREF(lz->func);
1513 Py_TYPE(lz)->tp_free(lz);
1514 }
1515
1516 static int
1517 imap_traverse(imapobject *lz, visitproc visit, void *arg)
1518 {
1519 Py_VISIT(lz->iters);
1520 Py_VISIT(lz->func);
1521 return 0;
1522 }
1523
1524 /*
1525 imap() is an iterator version of __builtins__.map() except that it does
1526 not have the None fill-in feature. That was intentionally left out for
1527 the following reasons:
1528
1529 1) Itertools are designed to be easily combined and chained together.
1530 Having all tools stop with the shortest input is a unifying principle
1531 that makes it easier to combine finite iterators (supplying data) with
1532 infinite iterators like count() and repeat() (for supplying sequential
1533 or constant arguments to a function).
1534
1535 2) In typical use cases for combining itertools, having one finite data
1536 supplier run out before another is likely to be an error condition which
1537 should not pass silently by automatically supplying None.
1538
1539 3) The use cases for automatic None fill-in are rare -- not many functions
1540 do something useful when a parameter suddenly switches type and becomes
1541 None.
1542
1543 4) If a need does arise, it can be met by __builtins__.map() or by
1544 writing: chain(iterable, repeat(None)).
1545
1546 5) Similar toolsets in Haskell and SML do not have automatic None fill-in.
1547 */
1548
1549 static PyObject *
1550 imap_next(imapobject *lz)
1551 {
1552 PyObject *val;
1553 PyObject *argtuple;
1554 PyObject *result;
1555 Py_ssize_t numargs, i;
1556
1557 numargs = PyTuple_Size(lz->iters);
1558 argtuple = PyTuple_New(numargs);
1559 if (argtuple == NULL)
1560 return NULL;
1561
1562 for (i=0 ; i<numargs ; i++) {
1563 val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
1564 if (val == NULL) {
1565 Py_DECREF(argtuple);
1566 return NULL;
1567 }
1568 PyTuple_SET_ITEM(argtuple, i, val);
1569 }
1570 if (lz->func == Py_None)
1571 return argtuple;
1572 result = PyObject_Call(lz->func, argtuple, NULL);
1573 Py_DECREF(argtuple);
1574 return result;
1575 }
1576
1577 PyDoc_STRVAR(imap_doc,
1578 "imap(func, *iterables) --> imap object\n\
1579 \n\
1580 Make an iterator that computes the function using arguments from\n\
1581 each of the iterables. Like map() except that it returns\n\
1582 an iterator instead of a list and that it stops when the shortest\n\
1583 iterable is exhausted instead of filling in None for shorter\n\
1584 iterables.");
1585
1586 static PyTypeObject imap_type = {
1587 PyVarObject_HEAD_INIT(NULL, 0)
1588 "itertools.imap", /* tp_name */
1589 sizeof(imapobject), /* tp_basicsize */
1590 0, /* tp_itemsize */
1591 /* methods */
1592 (destructor)imap_dealloc, /* tp_dealloc */
1593 0, /* tp_print */
1594 0, /* tp_getattr */
1595 0, /* tp_setattr */
1596 0, /* tp_compare */
1597 0, /* tp_repr */
1598 0, /* tp_as_number */
1599 0, /* tp_as_sequence */
1600 0, /* tp_as_mapping */
1601 0, /* tp_hash */
1602 0, /* tp_call */
1603 0, /* tp_str */
1604 PyObject_GenericGetAttr, /* tp_getattro */
1605 0, /* tp_setattro */
1606 0, /* tp_as_buffer */
1607 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1608 Py_TPFLAGS_BASETYPE, /* tp_flags */
1609 imap_doc, /* tp_doc */
1610 (traverseproc)imap_traverse, /* tp_traverse */
1611 0, /* tp_clear */
1612 0, /* tp_richcompare */
1613 0, /* tp_weaklistoffset */
1614 PyObject_SelfIter, /* tp_iter */
1615 (iternextfunc)imap_next, /* tp_iternext */
1616 0, /* tp_methods */
1617 0, /* tp_members */
1618 0, /* tp_getset */
1619 0, /* tp_base */
1620 0, /* tp_dict */
1621 0, /* tp_descr_get */
1622 0, /* tp_descr_set */
1623 0, /* tp_dictoffset */
1624 0, /* tp_init */
1625 0, /* tp_alloc */
1626 imap_new, /* tp_new */
1627 PyObject_GC_Del, /* tp_free */
1628 };
1629
1630
1631 /* chain object ************************************************************/
1632
1633 typedef struct {
1634 PyObject_HEAD
1635 PyObject *source; /* Iterator over input iterables */
1636 PyObject *active; /* Currently running input iterator */
1637 } chainobject;
1638
1639 static PyTypeObject chain_type;
1640
1641 static PyObject *
1642 chain_new_internal(PyTypeObject *type, PyObject *source)
1643 {
1644 chainobject *lz;
1645
1646 lz = (chainobject *)type->tp_alloc(type, 0);
1647 if (lz == NULL) {
1648 Py_DECREF(source);
1649 return NULL;
1650 }
1651
1652 lz->source = source;
1653 lz->active = NULL;
1654 return (PyObject *)lz;
1655 }
1656
1657 static PyObject *
1658 chain_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1659 {
1660 PyObject *source;
1661
1662 if (type == &chain_type && !_PyArg_NoKeywords("chain()", kwds))
1663 return NULL;
1664
1665 source = PyObject_GetIter(args);
1666 if (source == NULL)
1667 return NULL;
1668
1669 return chain_new_internal(type, source);
1670 }
1671
1672 static PyObject *
1673 chain_new_from_iterable(PyTypeObject *type, PyObject *arg)
1674 {
1675 PyObject *source;
1676
1677 source = PyObject_GetIter(arg);
1678 if (source == NULL)
1679 return NULL;
1680
1681 return chain_new_internal(type, source);
1682 }
1683
1684 static void
1685 chain_dealloc(chainobject *lz)
1686 {
1687 PyObject_GC_UnTrack(lz);
1688 Py_XDECREF(lz->active);
1689 Py_XDECREF(lz->source);
1690 Py_TYPE(lz)->tp_free(lz);
1691 }
1692
1693 static int
1694 chain_traverse(chainobject *lz, visitproc visit, void *arg)
1695 {
1696 Py_VISIT(lz->source);
1697 Py_VISIT(lz->active);
1698 return 0;
1699 }
1700
1701 static PyObject *
1702 chain_next(chainobject *lz)
1703 {
1704 PyObject *item;
1705
1706 /* lz->source is the iterator of iterables. If it's NULL, we've already
1707 * consumed them all. lz->active is the current iterator. If it's NULL,
1708 * we should grab a new one from lz->source. */
1709 while (lz->source != NULL) {
1710 if (lz->active == NULL) {
1711 PyObject *iterable = PyIter_Next(lz->source);
1712 if (iterable == NULL) {
1713 Py_CLEAR(lz->source);
1714 return NULL; /* no more input sources */
1715 }
1716 lz->active = PyObject_GetIter(iterable);
1717 Py_DECREF(iterable);
1718 if (lz->active == NULL) {
1719 Py_CLEAR(lz->source);
1720 return NULL; /* input not iterable */
1721 }
1722 }
1723 item = PyIter_Next(lz->active);
1724 if (item != NULL)
1725 return item;
1726 if (PyErr_Occurred()) {
1727 if (PyErr_ExceptionMatches(PyExc_StopIteration))
1728 PyErr_Clear();
1729 else
1730 return NULL; /* input raised an exception */
1731 }
1732 /* lz->active is consumed, try with the next iterable. */
1733 Py_CLEAR(lz->active);
1734 }
1735 /* Everything had been consumed already. */
1736 return NULL;
1737 }
1738
1739 PyDoc_STRVAR(chain_doc,
1740 "chain(*iterables) --> chain object\n\
1741 \n\
1742 Return a chain object whose .next() method returns elements from the\n\
1743 first iterable until it is exhausted, then elements from the next\n\
1744 iterable, until all of the iterables are exhausted.");
1745
1746 PyDoc_STRVAR(chain_from_iterable_doc,
1747 "chain.from_iterable(iterable) --> chain object\n\
1748 \n\
1749 Alternate chain() constructor taking a single iterable argument\n\
1750 that evaluates lazily.");
1751
1752 static PyMethodDef chain_methods[] = {
1753 {"from_iterable", (PyCFunction) chain_new_from_iterable, METH_O | METH_CLASS,
1754 chain_from_iterable_doc},
1755 {NULL, NULL} /* sentinel */
1756 };
1757
1758 static PyTypeObject chain_type = {
1759 PyVarObject_HEAD_INIT(NULL, 0)
1760 "itertools.chain", /* tp_name */
1761 sizeof(chainobject), /* tp_basicsize */
1762 0, /* tp_itemsize */
1763 /* methods */
1764 (destructor)chain_dealloc, /* tp_dealloc */
1765 0, /* tp_print */
1766 0, /* tp_getattr */
1767 0, /* tp_setattr */
1768 0, /* tp_compare */
1769 0, /* tp_repr */
1770 0, /* tp_as_number */
1771 0, /* tp_as_sequence */
1772 0, /* tp_as_mapping */
1773 0, /* tp_hash */
1774 0, /* tp_call */
1775 0, /* tp_str */
1776 PyObject_GenericGetAttr, /* tp_getattro */
1777 0, /* tp_setattro */
1778 0, /* tp_as_buffer */
1779 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1780 Py_TPFLAGS_BASETYPE, /* tp_flags */
1781 chain_doc, /* tp_doc */
1782 (traverseproc)chain_traverse, /* tp_traverse */
1783 0, /* tp_clear */
1784 0, /* tp_richcompare */
1785 0, /* tp_weaklistoffset */
1786 PyObject_SelfIter, /* tp_iter */
1787 (iternextfunc)chain_next, /* tp_iternext */
1788 chain_methods, /* tp_methods */
1789 0, /* tp_members */
1790 0, /* tp_getset */
1791 0, /* tp_base */
1792 0, /* tp_dict */
1793 0, /* tp_descr_get */
1794 0, /* tp_descr_set */
1795 0, /* tp_dictoffset */
1796 0, /* tp_init */
1797 0, /* tp_alloc */
1798 chain_new, /* tp_new */
1799 PyObject_GC_Del, /* tp_free */
1800 };
1801
1802
1803 /* product object ************************************************************/
1804
1805 typedef struct {
1806 PyObject_HEAD
1807 PyObject *pools; /* tuple of pool tuples */
1808 Py_ssize_t *indices; /* one index per pool */
1809 PyObject *result; /* most recently returned result tuple */
1810 int stopped; /* set to 1 when the product iterator is exhausted */
1811 } productobject;
1812
1813 static PyTypeObject product_type;
1814
1815 static PyObject *
1816 product_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1817 {
1818 productobject *lz;
1819 Py_ssize_t nargs, npools, repeat=1;
1820 PyObject *pools = NULL;
1821 Py_ssize_t *indices = NULL;
1822 Py_ssize_t i;
1823
1824 if (kwds != NULL) {
1825 char *kwlist[] = {"repeat", 0};
1826 PyObject *tmpargs = PyTuple_New(0);
1827 if (tmpargs == NULL)
1828 return NULL;
1829 if (!PyArg_ParseTupleAndKeywords(tmpargs, kwds, "|n:product", kwlist, &repeat)) {
1830 Py_DECREF(tmpargs);
1831 return NULL;
1832 }
1833 Py_DECREF(tmpargs);
1834 if (repeat < 0) {
1835 PyErr_SetString(PyExc_ValueError,
1836 "repeat argument cannot be negative");
1837 return NULL;
1838 }
1839 }
1840
1841 assert(PyTuple_CheckExact(args));
1842 if (repeat == 0) {
1843 nargs = 0;
1844 } else {
1845 nargs = PyTuple_GET_SIZE(args);
1846 if ((size_t)nargs > PY_SSIZE_T_MAX/sizeof(Py_ssize_t)/repeat) {
1847 PyErr_SetString(PyExc_OverflowError, "repeat argument too large");
1848 return NULL;
1849 }
1850 }
1851 npools = nargs * repeat;
1852
1853 indices = PyMem_New(Py_ssize_t, npools);
1854 if (indices == NULL) {
1855 PyErr_NoMemory();
1856 goto error;
1857 }
1858
1859 pools = PyTuple_New(npools);
1860 if (pools == NULL)
1861 goto error;
1862
1863 for (i=0; i < nargs ; ++i) {
1864 PyObject *item = PyTuple_GET_ITEM(args, i);
1865 PyObject *pool = PySequence_Tuple(item);
1866 if (pool == NULL)
1867 goto error;
1868 PyTuple_SET_ITEM(pools, i, pool);
1869 indices[i] = 0;
1870 }
1871 for ( ; i < npools; ++i) {
1872 PyObject *pool = PyTuple_GET_ITEM(pools, i - nargs);
1873 Py_INCREF(pool);
1874 PyTuple_SET_ITEM(pools, i, pool);
1875 indices[i] = 0;
1876 }
1877
1878 /* create productobject structure */
1879 lz = (productobject *)type->tp_alloc(type, 0);
1880 if (lz == NULL)
1881 goto error;
1882
1883 lz->pools = pools;
1884 lz->indices = indices;
1885 lz->result = NULL;
1886 lz->stopped = 0;
1887
1888 return (PyObject *)lz;
1889
1890 error:
1891 if (indices != NULL)
1892 PyMem_Free(indices);
1893 Py_XDECREF(pools);
1894 return NULL;
1895 }
1896
1897 static void
1898 product_dealloc(productobject *lz)
1899 {
1900 PyObject_GC_UnTrack(lz);
1901 Py_XDECREF(lz->pools);
1902 Py_XDECREF(lz->result);
1903 if (lz->indices != NULL)
1904 PyMem_Free(lz->indices);
1905 Py_TYPE(lz)->tp_free(lz);
1906 }
1907
1908 static int
1909 product_traverse(productobject *lz, visitproc visit, void *arg)
1910 {
1911 Py_VISIT(lz->pools);
1912 Py_VISIT(lz->result);
1913 return 0;
1914 }
1915
1916 static PyObject *
1917 product_next(productobject *lz)
1918 {
1919 PyObject *pool;
1920 PyObject *elem;
1921 PyObject *oldelem;
1922 PyObject *pools = lz->pools;
1923 PyObject *result = lz->result;
1924 Py_ssize_t npools = PyTuple_GET_SIZE(pools);
1925 Py_ssize_t i;
1926
1927 if (lz->stopped)
1928 return NULL;
1929
1930 if (result == NULL) {
1931 /* On the first pass, return an initial tuple filled with the
1932 first element from each pool. */
1933 result = PyTuple_New(npools);
1934 if (result == NULL)
1935 goto empty;
1936 lz->result = result;
1937 for (i=0; i < npools; i++) {
1938 pool = PyTuple_GET_ITEM(pools, i);
1939 if (PyTuple_GET_SIZE(pool) == 0)
1940 goto empty;
1941 elem = PyTuple_GET_ITEM(pool, 0);
1942 Py_INCREF(elem);
1943 PyTuple_SET_ITEM(result, i, elem);
1944 }
1945 } else {
1946 Py_ssize_t *indices = lz->indices;
1947
1948 /* Copy the previous result tuple or re-use it if available */
1949 if (Py_REFCNT(result) > 1) {
1950 PyObject *old_result = result;
1951 result = PyTuple_New(npools);
1952 if (result == NULL)
1953 goto empty;
1954 lz->result = result;
1955 for (i=0; i < npools; i++) {
1956 elem = PyTuple_GET_ITEM(old_result, i);
1957 Py_INCREF(elem);
1958 PyTuple_SET_ITEM(result, i, elem);
1959 }
1960 Py_DECREF(old_result);
1961 }
1962 /* Now, we've got the only copy so we can update it in-place */
1963 assert (npools==0 || Py_REFCNT(result) == 1);
1964
1965 /* Update the pool indices right-to-left. Only advance to the
1966 next pool when the previous one rolls-over */
1967 for (i=npools-1 ; i >= 0 ; i--) {
1968 pool = PyTuple_GET_ITEM(pools, i);
1969 indices[i]++;
1970 if (indices[i] == PyTuple_GET_SIZE(pool)) {
1971 /* Roll-over and advance to next pool */
1972 indices[i] = 0;
1973 elem = PyTuple_GET_ITEM(pool, 0);
1974 Py_INCREF(elem);
1975 oldelem = PyTuple_GET_ITEM(result, i);
1976 PyTuple_SET_ITEM(result, i, elem);
1977 Py_DECREF(oldelem);
1978 } else {
1979 /* No rollover. Just increment and stop here. */
1980 elem = PyTuple_GET_ITEM(pool, indices[i]);
1981 Py_INCREF(elem);
1982 oldelem = PyTuple_GET_ITEM(result, i);
1983 PyTuple_SET_ITEM(result, i, elem);
1984 Py_DECREF(oldelem);
1985 break;
1986 }
1987 }
1988
1989 /* If i is negative, then the indices have all rolled-over
1990 and we're done. */
1991 if (i < 0)
1992 goto empty;
1993 }
1994
1995 Py_INCREF(result);
1996 return result;
1997
1998 empty:
1999 lz->stopped = 1;
2000 return NULL;
2001 }
2002
2003 PyDoc_STRVAR(product_doc,
2004 "product(*iterables) --> product object\n\
2005 \n\
2006 Cartesian product of input iterables. Equivalent to nested for-loops.\n\n\
2007 For example, product(A, B) returns the same as: ((x,y) for x in A for y in B).\n\
2008 The leftmost iterators are in the outermost for-loop, so the output tuples\n\
2009 cycle in a manner similar to an odometer (with the rightmost element changing\n\
2010 on every iteration).\n\n\
2011 To compute the product of an iterable with itself, specify the number\n\
2012 of repetitions with the optional repeat keyword argument. For example,\n\
2013 product(A, repeat=4) means the same as product(A, A, A, A).\n\n\
2014 product('ab', range(3)) --> ('a',0) ('a',1) ('a',2) ('b',0) ('b',1) ('b',2)\n\
2015 product((0,1), (0,1), (0,1)) --> (0,0,0) (0,0,1) (0,1,0) (0,1,1) (1,0,0) ...");
2016
2017 static PyTypeObject product_type = {
2018 PyVarObject_HEAD_INIT(NULL, 0)
2019 "itertools.product", /* tp_name */
2020 sizeof(productobject), /* tp_basicsize */
2021 0, /* tp_itemsize */
2022 /* methods */
2023 (destructor)product_dealloc, /* tp_dealloc */
2024 0, /* tp_print */
2025 0, /* tp_getattr */
2026 0, /* tp_setattr */
2027 0, /* tp_compare */
2028 0, /* tp_repr */
2029 0, /* tp_as_number */
2030 0, /* tp_as_sequence */
2031 0, /* tp_as_mapping */
2032 0, /* tp_hash */
2033 0, /* tp_call */
2034 0, /* tp_str */
2035 PyObject_GenericGetAttr, /* tp_getattro */
2036 0, /* tp_setattro */
2037 0, /* tp_as_buffer */
2038 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2039 Py_TPFLAGS_BASETYPE, /* tp_flags */
2040 product_doc, /* tp_doc */
2041 (traverseproc)product_traverse, /* tp_traverse */
2042 0, /* tp_clear */
2043 0, /* tp_richcompare */
2044 0, /* tp_weaklistoffset */
2045 PyObject_SelfIter, /* tp_iter */
2046 (iternextfunc)product_next, /* tp_iternext */
2047 0, /* tp_methods */
2048 0, /* tp_members */
2049 0, /* tp_getset */
2050 0, /* tp_base */
2051 0, /* tp_dict */
2052 0, /* tp_descr_get */
2053 0, /* tp_descr_set */
2054 0, /* tp_dictoffset */
2055 0, /* tp_init */
2056 0, /* tp_alloc */
2057 product_new, /* tp_new */
2058 PyObject_GC_Del, /* tp_free */
2059 };
2060
2061
2062 /* combinations object ************************************************************/
2063
2064 typedef struct {
2065 PyObject_HEAD
2066 PyObject *pool; /* input converted to a tuple */
2067 Py_ssize_t *indices; /* one index per result element */
2068 PyObject *result; /* most recently returned result tuple */
2069 Py_ssize_t r; /* size of result tuple */
2070 int stopped; /* set to 1 when the combinations iterator is exhausted */
2071 } combinationsobject;
2072
2073 static PyTypeObject combinations_type;
2074
2075 static PyObject *
2076 combinations_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2077 {
2078 combinationsobject *co;
2079 Py_ssize_t n;
2080 Py_ssize_t r;
2081 PyObject *pool = NULL;
2082 PyObject *iterable = NULL;
2083 Py_ssize_t *indices = NULL;
2084 Py_ssize_t i;
2085 static char *kwargs[] = {"iterable", "r", NULL};
2086
2087 if (!PyArg_ParseTupleAndKeywords(args, kwds, "On:combinations", kwargs,
2088 &iterable, &r))
2089 return NULL;
2090
2091 pool = PySequence_Tuple(iterable);
2092 if (pool == NULL)
2093 goto error;
2094 n = PyTuple_GET_SIZE(pool);
2095 if (r < 0) {
2096 PyErr_SetString(PyExc_ValueError, "r must be non-negative");
2097 goto error;
2098 }
2099
2100 indices = PyMem_New(Py_ssize_t, r);
2101 if (indices == NULL) {
2102 PyErr_NoMemory();
2103 goto error;
2104 }
2105
2106 for (i=0 ; i<r ; i++)
2107 indices[i] = i;
2108
2109 /* create combinationsobject structure */
2110 co = (combinationsobject *)type->tp_alloc(type, 0);
2111 if (co == NULL)
2112 goto error;
2113
2114 co->pool = pool;
2115 co->indices = indices;
2116 co->result = NULL;
2117 co->r = r;
2118 co->stopped = r > n ? 1 : 0;
2119
2120 return (PyObject *)co;
2121
2122 error:
2123 if (indices != NULL)
2124 PyMem_Free(indices);
2125 Py_XDECREF(pool);
2126 return NULL;
2127 }
2128
2129 static void
2130 combinations_dealloc(combinationsobject *co)
2131 {
2132 PyObject_GC_UnTrack(co);
2133 Py_XDECREF(co->pool);
2134 Py_XDECREF(co->result);
2135 if (co->indices != NULL)
2136 PyMem_Free(co->indices);
2137 Py_TYPE(co)->tp_free(co);
2138 }
2139
2140 static int
2141 combinations_traverse(combinationsobject *co, visitproc visit, void *arg)
2142 {
2143 Py_VISIT(co->pool);
2144 Py_VISIT(co->result);
2145 return 0;
2146 }
2147
2148 static PyObject *
2149 combinations_next(combinationsobject *co)
2150 {
2151 PyObject *elem;
2152 PyObject *oldelem;
2153 PyObject *pool = co->pool;
2154 Py_ssize_t *indices = co->indices;
2155 PyObject *result = co->result;
2156 Py_ssize_t n = PyTuple_GET_SIZE(pool);
2157 Py_ssize_t r = co->r;
2158 Py_ssize_t i, j, index;
2159
2160 if (co->stopped)
2161 return NULL;
2162
2163 if (result == NULL) {
2164 /* On the first pass, initialize result tuple using the indices */
2165 result = PyTuple_New(r);
2166 if (result == NULL)
2167 goto empty;
2168 co->result = result;
2169 for (i=0; i<r ; i++) {
2170 index = indices[i];
2171 elem = PyTuple_GET_ITEM(pool, index);
2172 Py_INCREF(elem);
2173 PyTuple_SET_ITEM(result, i, elem);
2174 }
2175 } else {
2176 /* Copy the previous result tuple or re-use it if available */
2177 if (Py_REFCNT(result) > 1) {
2178 PyObject *old_result = result;
2179 result = PyTuple_New(r);
2180 if (result == NULL)
2181 goto empty;
2182 co->result = result;
2183 for (i=0; i<r ; i++) {
2184 elem = PyTuple_GET_ITEM(old_result, i);
2185 Py_INCREF(elem);
2186 PyTuple_SET_ITEM(result, i, elem);
2187 }
2188 Py_DECREF(old_result);
2189 }
2190 /* Now, we've got the only copy so we can update it in-place
2191 * CPython's empty tuple is a singleton and cached in
2192 * PyTuple's freelist.
2193 */
2194 assert(r == 0 || Py_REFCNT(result) == 1);
2195
2196 /* Scan indices right-to-left until finding one that is not
2197 at its maximum (i + n - r). */
2198 for (i=r-1 ; i >= 0 && indices[i] == i+n-r ; i--)
2199 ;
2200
2201 /* If i is negative, then the indices are all at
2202 their maximum value and we're done. */
2203 if (i < 0)
2204 goto empty;
2205
2206 /* Increment the current index which we know is not at its
2207 maximum. Then move back to the right setting each index
2208 to its lowest possible value (one higher than the index
2209 to its left -- this maintains the sort order invariant). */
2210 indices[i]++;
2211 for (j=i+1 ; j<r ; j++)
2212 indices[j] = indices[j-1] + 1;
2213
2214 /* Update the result tuple for the new indices
2215 starting with i, the leftmost index that changed */
2216 for ( ; i<r ; i++) {
2217 index = indices[i];
2218 elem = PyTuple_GET_ITEM(pool, index);
2219 Py_INCREF(elem);
2220 oldelem = PyTuple_GET_ITEM(result, i);
2221 PyTuple_SET_ITEM(result, i, elem);
2222 Py_DECREF(oldelem);
2223 }
2224 }
2225
2226 Py_INCREF(result);
2227 return result;
2228
2229 empty:
2230 co->stopped = 1;
2231 return NULL;
2232 }
2233
2234 PyDoc_STRVAR(combinations_doc,
2235 "combinations(iterable, r) --> combinations object\n\
2236 \n\
2237 Return successive r-length combinations of elements in the iterable.\n\n\
2238 combinations(range(4), 3) --> (0,1,2), (0,1,3), (0,2,3), (1,2,3)");
2239
2240 static PyTypeObject combinations_type = {
2241 PyVarObject_HEAD_INIT(NULL, 0)
2242 "itertools.combinations", /* tp_name */
2243 sizeof(combinationsobject), /* tp_basicsize */
2244 0, /* tp_itemsize */
2245 /* methods */
2246 (destructor)combinations_dealloc, /* tp_dealloc */
2247 0, /* tp_print */
2248 0, /* tp_getattr */
2249 0, /* tp_setattr */
2250 0, /* tp_compare */
2251 0, /* tp_repr */
2252 0, /* tp_as_number */
2253 0, /* tp_as_sequence */
2254 0, /* tp_as_mapping */
2255 0, /* tp_hash */
2256 0, /* tp_call */
2257 0, /* tp_str */
2258 PyObject_GenericGetAttr, /* tp_getattro */
2259 0, /* tp_setattro */
2260 0, /* tp_as_buffer */
2261 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2262 Py_TPFLAGS_BASETYPE, /* tp_flags */
2263 combinations_doc, /* tp_doc */
2264 (traverseproc)combinations_traverse, /* tp_traverse */
2265 0, /* tp_clear */
2266 0, /* tp_richcompare */
2267 0, /* tp_weaklistoffset */
2268 PyObject_SelfIter, /* tp_iter */
2269 (iternextfunc)combinations_next, /* tp_iternext */
2270 0, /* tp_methods */
2271 0, /* tp_members */
2272 0, /* tp_getset */
2273 0, /* tp_base */
2274 0, /* tp_dict */
2275 0, /* tp_descr_get */
2276 0, /* tp_descr_set */
2277 0, /* tp_dictoffset */
2278 0, /* tp_init */
2279 0, /* tp_alloc */
2280 combinations_new, /* tp_new */
2281 PyObject_GC_Del, /* tp_free */
2282 };
2283
2284
2285 /* combinations with replacement object *******************************************/
2286
2287 /* Equivalent to:
2288
2289 def combinations_with_replacement(iterable, r):
2290 "combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC"
2291 # number items returned: (n+r-1)! / r! / (n-1)!
2292 pool = tuple(iterable)
2293 n = len(pool)
2294 indices = [0] * r
2295 yield tuple(pool[i] for i in indices)
2296 while 1:
2297 for i in reversed(range(r)):
2298 if indices[i] != n - 1:
2299 break
2300 else:
2301 return
2302 indices[i:] = [indices[i] + 1] * (r - i)
2303 yield tuple(pool[i] for i in indices)
2304
2305 def combinations_with_replacement2(iterable, r):
2306 'Alternate version that filters from product()'
2307 pool = tuple(iterable)
2308 n = len(pool)
2309 for indices in product(range(n), repeat=r):
2310 if sorted(indices) == list(indices):
2311 yield tuple(pool[i] for i in indices)
2312 */
2313 typedef struct {
2314 PyObject_HEAD
2315 PyObject *pool; /* input converted to a tuple */
2316 Py_ssize_t *indices; /* one index per result element */
2317 PyObject *result; /* most recently returned result tuple */
2318 Py_ssize_t r; /* size of result tuple */
2319 int stopped; /* set to 1 when the cwr iterator is exhausted */
2320 } cwrobject;
2321
2322 static PyTypeObject cwr_type;
2323
2324 static PyObject *
2325 cwr_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2326 {
2327 cwrobject *co;
2328 Py_ssize_t n;
2329 Py_ssize_t r;
2330 PyObject *pool = NULL;
2331 PyObject *iterable = NULL;
2332 Py_ssize_t *indices = NULL;
2333 Py_ssize_t i;
2334 static char *kwargs[] = {"iterable", "r", NULL};
2335
2336 if (!PyArg_ParseTupleAndKeywords(args, kwds, "On:combinations_with_replacement", kwargs,
2337 &iterable, &r))
2338 return NULL;
2339
2340 pool = PySequence_Tuple(iterable);
2341 if (pool == NULL)
2342 goto error;
2343 n = PyTuple_GET_SIZE(pool);
2344 if (r < 0) {
2345 PyErr_SetString(PyExc_ValueError, "r must be non-negative");
2346 goto error;
2347 }
2348
2349 indices = PyMem_New(Py_ssize_t, r);
2350 if (indices == NULL) {
2351 PyErr_NoMemory();
2352 goto error;
2353 }
2354
2355 for (i=0 ; i<r ; i++)
2356 indices[i] = 0;
2357
2358 /* create cwrobject structure */
2359 co = (cwrobject *)type->tp_alloc(type, 0);
2360 if (co == NULL)
2361 goto error;
2362
2363 co->pool = pool;
2364 co->indices = indices;
2365 co->result = NULL;
2366 co->r = r;
2367 co->stopped = !n && r;
2368
2369 return (PyObject *)co;
2370
2371 error:
2372 if (indices != NULL)
2373 PyMem_Free(indices);
2374 Py_XDECREF(pool);
2375 return NULL;
2376 }
2377
2378 static void
2379 cwr_dealloc(cwrobject *co)
2380 {
2381 PyObject_GC_UnTrack(co);
2382 Py_XDECREF(co->pool);
2383 Py_XDECREF(co->result);
2384 if (co->indices != NULL)
2385 PyMem_Free(co->indices);
2386 Py_TYPE(co)->tp_free(co);
2387 }
2388
2389 static int
2390 cwr_traverse(cwrobject *co, visitproc visit, void *arg)
2391 {
2392 Py_VISIT(co->pool);
2393 Py_VISIT(co->result);
2394 return 0;
2395 }
2396
2397 static PyObject *
2398 cwr_next(cwrobject *co)
2399 {
2400 PyObject *elem;
2401 PyObject *oldelem;
2402 PyObject *pool = co->pool;
2403 Py_ssize_t *indices = co->indices;
2404 PyObject *result = co->result;
2405 Py_ssize_t n = PyTuple_GET_SIZE(pool);
2406 Py_ssize_t r = co->r;
2407 Py_ssize_t i, j, index;
2408
2409 if (co->stopped)
2410 return NULL;
2411
2412 if (result == NULL) {
2413 /* On the first pass, initialize result tuple using the indices */
2414 result = PyTuple_New(r);
2415 if (result == NULL)
2416 goto empty;
2417 co->result = result;
2418 for (i=0; i<r ; i++) {
2419 index = indices[i];
2420 elem = PyTuple_GET_ITEM(pool, index);
2421 Py_INCREF(elem);
2422 PyTuple_SET_ITEM(result, i, elem);
2423 }
2424 } else {
2425 /* Copy the previous result tuple or re-use it if available */
2426 if (Py_REFCNT(result) > 1) {
2427 PyObject *old_result = result;
2428 result = PyTuple_New(r);
2429 if (result == NULL)
2430 goto empty;
2431 co->result = result;
2432 for (i=0; i<r ; i++) {
2433 elem = PyTuple_GET_ITEM(old_result, i);
2434 Py_INCREF(elem);
2435 PyTuple_SET_ITEM(result, i, elem);
2436 }
2437 Py_DECREF(old_result);
2438 }
2439 /* Now, we've got the only copy so we can update it in-place CPython's
2440 empty tuple is a singleton and cached in PyTuple's freelist. */
2441 assert(r == 0 || Py_REFCNT(result) == 1);
2442
2443 /* Scan indices right-to-left until finding one that is not
2444 * at its maximum (n-1). */
2445 for (i=r-1 ; i >= 0 && indices[i] == n-1; i--)
2446 ;
2447
2448 /* If i is negative, then the indices are all at
2449 their maximum value and we're done. */
2450 if (i < 0)
2451 goto empty;
2452
2453 /* Increment the current index which we know is not at its
2454 maximum. Then set all to the right to the same value. */
2455 indices[i]++;
2456 for (j=i+1 ; j<r ; j++)
2457 indices[j] = indices[j-1];
2458
2459 /* Update the result tuple for the new indices
2460 starting with i, the leftmost index that changed */
2461 for ( ; i<r ; i++) {
2462 index = indices[i];
2463 elem = PyTuple_GET_ITEM(pool, index);
2464 Py_INCREF(elem);
2465 oldelem = PyTuple_GET_ITEM(result, i);
2466 PyTuple_SET_ITEM(result, i, elem);
2467 Py_DECREF(oldelem);
2468 }
2469 }
2470
2471 Py_INCREF(result);
2472 return result;
2473
2474 empty:
2475 co->stopped = 1;
2476 return NULL;
2477 }
2478
2479 PyDoc_STRVAR(cwr_doc,
2480 "combinations_with_replacement(iterable, r) --> combinations_with_replacement object\n\
2481 \n\
2482 Return successive r-length combinations of elements in the iterable\n\
2483 allowing individual elements to have successive repeats.\n\
2484 combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC");
2485
2486 static PyTypeObject cwr_type = {
2487 PyVarObject_HEAD_INIT(NULL, 0)
2488 "itertools.combinations_with_replacement", /* tp_name */
2489 sizeof(cwrobject), /* tp_basicsize */
2490 0, /* tp_itemsize */
2491 /* methods */
2492 (destructor)cwr_dealloc, /* tp_dealloc */
2493 0, /* tp_print */
2494 0, /* tp_getattr */
2495 0, /* tp_setattr */
2496 0, /* tp_compare */
2497 0, /* tp_repr */
2498 0, /* tp_as_number */
2499 0, /* tp_as_sequence */
2500 0, /* tp_as_mapping */
2501 0, /* tp_hash */
2502 0, /* tp_call */
2503 0, /* tp_str */
2504 PyObject_GenericGetAttr, /* tp_getattro */
2505 0, /* tp_setattro */
2506 0, /* tp_as_buffer */
2507 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2508 Py_TPFLAGS_BASETYPE, /* tp_flags */
2509 cwr_doc, /* tp_doc */
2510 (traverseproc)cwr_traverse, /* tp_traverse */
2511 0, /* tp_clear */
2512 0, /* tp_richcompare */
2513 0, /* tp_weaklistoffset */
2514 PyObject_SelfIter, /* tp_iter */
2515 (iternextfunc)cwr_next, /* tp_iternext */
2516 0, /* tp_methods */
2517 0, /* tp_members */
2518 0, /* tp_getset */
2519 0, /* tp_base */
2520 0, /* tp_dict */
2521 0, /* tp_descr_get */
2522 0, /* tp_descr_set */
2523 0, /* tp_dictoffset */
2524 0, /* tp_init */
2525 0, /* tp_alloc */
2526 cwr_new, /* tp_new */
2527 PyObject_GC_Del, /* tp_free */
2528 };
2529
2530
2531 /* permutations object ************************************************************
2532
2533 def permutations(iterable, r=None):
2534 'permutations(range(3), 2) --> (0,1) (0,2) (1,0) (1,2) (2,0) (2,1)'
2535 pool = tuple(iterable)
2536 n = len(pool)
2537 r = n if r is None else r
2538 indices = range(n)
2539 cycles = range(n-r+1, n+1)[::-1]
2540 yield tuple(pool[i] for i in indices[:r])
2541 while n:
2542 for i in reversed(range(r)):
2543 cycles[i] -= 1
2544 if cycles[i] == 0:
2545 indices[i:] = indices[i+1:] + indices[i:i+1]
2546 cycles[i] = n - i
2547 else:
2548 j = cycles[i]
2549 indices[i], indices[-j] = indices[-j], indices[i]
2550 yield tuple(pool[i] for i in indices[:r])
2551 break
2552 else:
2553 return
2554 */
2555
2556 typedef struct {
2557 PyObject_HEAD
2558 PyObject *pool; /* input converted to a tuple */
2559 Py_ssize_t *indices; /* one index per element in the pool */
2560 Py_ssize_t *cycles; /* one rollover counter per element in the result */
2561 PyObject *result; /* most recently returned result tuple */
2562 Py_ssize_t r; /* size of result tuple */
2563 int stopped; /* set to 1 when the permutations iterator is exhausted */
2564 } permutationsobject;
2565
2566 static PyTypeObject permutations_type;
2567
2568 static PyObject *
2569 permutations_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2570 {
2571 permutationsobject *po;
2572 Py_ssize_t n;
2573 Py_ssize_t r;
2574 PyObject *robj = Py_None;
2575 PyObject *pool = NULL;
2576 PyObject *iterable = NULL;
2577 Py_ssize_t *indices = NULL;
2578 Py_ssize_t *cycles = NULL;
2579 Py_ssize_t i;
2580 static char *kwargs[] = {"iterable", "r", NULL};
2581
2582 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:permutations", kwargs,
2583 &iterable, &robj))
2584 return NULL;
2585
2586 pool = PySequence_Tuple(iterable);
2587 if (pool == NULL)
2588 goto error;
2589 n = PyTuple_GET_SIZE(pool);
2590
2591 r = n;
2592 if (robj != Py_None) {
2593 r = PyInt_AsSsize_t(robj);
2594 if (r == -1 && PyErr_Occurred())
2595 goto error;
2596 }
2597 if (r < 0) {
2598 PyErr_SetString(PyExc_ValueError, "r must be non-negative");
2599 goto error;
2600 }
2601
2602 indices = PyMem_New(Py_ssize_t, n);
2603 cycles = PyMem_New(Py_ssize_t, r);
2604 if (indices == NULL || cycles == NULL) {
2605 PyErr_NoMemory();
2606 goto error;
2607 }
2608
2609 for (i=0 ; i<n ; i++)
2610 indices[i] = i;
2611 for (i=0 ; i<r ; i++)
2612 cycles[i] = n - i;
2613
2614 /* create permutationsobject structure */
2615 po = (permutationsobject *)type->tp_alloc(type, 0);
2616 if (po == NULL)
2617 goto error;
2618
2619 po->pool = pool;
2620 po->indices = indices;
2621 po->cycles = cycles;
2622 po->result = NULL;
2623 po->r = r;
2624 po->stopped = r > n ? 1 : 0;
2625
2626 return (PyObject *)po;
2627
2628 error:
2629 if (indices != NULL)
2630 PyMem_Free(indices);
2631 if (cycles != NULL)
2632 PyMem_Free(cycles);
2633 Py_XDECREF(pool);
2634 return NULL;
2635 }
2636
2637 static void
2638 permutations_dealloc(permutationsobject *po)
2639 {
2640 PyObject_GC_UnTrack(po);
2641 Py_XDECREF(po->pool);
2642 Py_XDECREF(po->result);
2643 PyMem_Free(po->indices);
2644 PyMem_Free(po->cycles);
2645 Py_TYPE(po)->tp_free(po);
2646 }
2647
2648 static int
2649 permutations_traverse(permutationsobject *po, visitproc visit, void *arg)
2650 {
2651 Py_VISIT(po->pool);
2652 Py_VISIT(po->result);
2653 return 0;
2654 }
2655
2656 static PyObject *
2657 permutations_next(permutationsobject *po)
2658 {
2659 PyObject *elem;
2660 PyObject *oldelem;
2661 PyObject *pool = po->pool;
2662 Py_ssize_t *indices = po->indices;
2663 Py_ssize_t *cycles = po->cycles;
2664 PyObject *result = po->result;
2665 Py_ssize_t n = PyTuple_GET_SIZE(pool);
2666 Py_ssize_t r = po->r;
2667 Py_ssize_t i, j, k, index;
2668
2669 if (po->stopped)
2670 return NULL;
2671
2672 if (result == NULL) {
2673 /* On the first pass, initialize result tuple using the indices */
2674 result = PyTuple_New(r);
2675 if (result == NULL)
2676 goto empty;
2677 po->result = result;
2678 for (i=0; i<r ; i++) {
2679 index = indices[i];
2680 elem = PyTuple_GET_ITEM(pool, index);
2681 Py_INCREF(elem);
2682 PyTuple_SET_ITEM(result, i, elem);
2683 }
2684 } else {
2685 if (n == 0)
2686 goto empty;
2687
2688 /* Copy the previous result tuple or re-use it if available */
2689 if (Py_REFCNT(result) > 1) {
2690 PyObject *old_result = result;
2691 result = PyTuple_New(r);
2692 if (result == NULL)
2693 goto empty;
2694 po->result = result;
2695 for (i=0; i<r ; i++) {
2696 elem = PyTuple_GET_ITEM(old_result, i);
2697 Py_INCREF(elem);
2698 PyTuple_SET_ITEM(result, i, elem);
2699 }
2700 Py_DECREF(old_result);
2701 }
2702 /* Now, we've got the only copy so we can update it in-place */
2703 assert(r == 0 || Py_REFCNT(result) == 1);
2704
2705 /* Decrement rightmost cycle, moving leftward upon zero rollover */
2706 for (i=r-1 ; i>=0 ; i--) {
2707 cycles[i] -= 1;
2708 if (cycles[i] == 0) {
2709 /* rotatation: indices[i:] = indices[i+1:] + indices[i:i+1] */
2710 index = indices[i];
2711 for (j=i ; j<n-1 ; j++)
2712 indices[j] = indices[j+1];
2713 indices[n-1] = index;
2714 cycles[i] = n - i;
2715 } else {
2716 j = cycles[i];
2717 index = indices[i];
2718 indices[i] = indices[n-j];
2719 indices[n-j] = index;
2720
2721 for (k=i; k<r ; k++) {
2722 /* start with i, the leftmost element that changed */
2723 /* yield tuple(pool[k] for k in indices[:r]) */
2724 index = indices[k];
2725 elem = PyTuple_GET_ITEM(pool, index);
2726 Py_INCREF(elem);
2727 oldelem = PyTuple_GET_ITEM(result, k);
2728 PyTuple_SET_ITEM(result, k, elem);
2729 Py_DECREF(oldelem);
2730 }
2731 break;
2732 }
2733 }
2734 /* If i is negative, then the cycles have all
2735 rolled-over and we're done. */
2736 if (i < 0)
2737 goto empty;
2738 }
2739 Py_INCREF(result);
2740 return result;
2741
2742 empty:
2743 po->stopped = 1;
2744 return NULL;
2745 }
2746
2747 PyDoc_STRVAR(permutations_doc,
2748 "permutations(iterable[, r]) --> permutations object\n\
2749 \n\
2750 Return successive r-length permutations of elements in the iterable.\n\n\
2751 permutations(range(3), 2) --> (0,1), (0,2), (1,0), (1,2), (2,0), (2,1)");
2752
2753 static PyTypeObject permutations_type = {
2754 PyVarObject_HEAD_INIT(NULL, 0)
2755 "itertools.permutations", /* tp_name */
2756 sizeof(permutationsobject), /* tp_basicsize */
2757 0, /* tp_itemsize */
2758 /* methods */
2759 (destructor)permutations_dealloc, /* tp_dealloc */
2760 0, /* tp_print */
2761 0, /* tp_getattr */
2762 0, /* tp_setattr */
2763 0, /* tp_compare */
2764 0, /* tp_repr */
2765 0, /* tp_as_number */
2766 0, /* tp_as_sequence */
2767 0, /* tp_as_mapping */
2768 0, /* tp_hash */
2769 0, /* tp_call */
2770 0, /* tp_str */
2771 PyObject_GenericGetAttr, /* tp_getattro */
2772 0, /* tp_setattro */
2773 0, /* tp_as_buffer */
2774 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2775 Py_TPFLAGS_BASETYPE, /* tp_flags */
2776 permutations_doc, /* tp_doc */
2777 (traverseproc)permutations_traverse, /* tp_traverse */
2778 0, /* tp_clear */
2779 0, /* tp_richcompare */
2780 0, /* tp_weaklistoffset */
2781 PyObject_SelfIter, /* tp_iter */
2782 (iternextfunc)permutations_next, /* tp_iternext */
2783 0, /* tp_methods */
2784 0, /* tp_members */
2785 0, /* tp_getset */
2786 0, /* tp_base */
2787 0, /* tp_dict */
2788 0, /* tp_descr_get */
2789 0, /* tp_descr_set */
2790 0, /* tp_dictoffset */
2791 0, /* tp_init */
2792 0, /* tp_alloc */
2793 permutations_new, /* tp_new */
2794 PyObject_GC_Del, /* tp_free */
2795 };
2796
2797
2798 /* compress object ************************************************************/
2799
2800 /* Equivalent to:
2801
2802 def compress(data, selectors):
2803 "compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F"
2804 return (d for d, s in izip(data, selectors) if s)
2805 */
2806
2807 typedef struct {
2808 PyObject_HEAD
2809 PyObject *data;
2810 PyObject *selectors;
2811 } compressobject;
2812
2813 static PyTypeObject compress_type;
2814
2815 static PyObject *
2816 compress_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2817 {
2818 PyObject *seq1, *seq2;
2819 PyObject *data=NULL, *selectors=NULL;
2820 compressobject *lz;
2821 static char *kwargs[] = {"data", "selectors", NULL};
2822
2823 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO:compress", kwargs, &seq1, &seq2))
2824 return NULL;
2825
2826 data = PyObject_GetIter(seq1);
2827 if (data == NULL)
2828 goto fail;
2829 selectors = PyObject_GetIter(seq2);
2830 if (selectors == NULL)
2831 goto fail;
2832
2833 /* create compressobject structure */
2834 lz = (compressobject *)type->tp_alloc(type, 0);
2835 if (lz == NULL)
2836 goto fail;
2837 lz->data = data;
2838 lz->selectors = selectors;
2839 return (PyObject *)lz;
2840
2841 fail:
2842 Py_XDECREF(data);
2843 Py_XDECREF(selectors);
2844 return NULL;
2845 }
2846
2847 static void
2848 compress_dealloc(compressobject *lz)
2849 {
2850 PyObject_GC_UnTrack(lz);
2851 Py_XDECREF(lz->data);
2852 Py_XDECREF(lz->selectors);
2853 Py_TYPE(lz)->tp_free(lz);
2854 }
2855
2856 static int
2857 compress_traverse(compressobject *lz, visitproc visit, void *arg)
2858 {
2859 Py_VISIT(lz->data);
2860 Py_VISIT(lz->selectors);
2861 return 0;
2862 }
2863
2864 static PyObject *
2865 compress_next(compressobject *lz)
2866 {
2867 PyObject *data = lz->data, *selectors = lz->selectors;
2868 PyObject *datum, *selector;
2869 PyObject *(*datanext)(PyObject *) = *Py_TYPE(data)->tp_iternext;
2870 PyObject *(*selectornext)(PyObject *) = *Py_TYPE(selectors)->tp_iternext;
2871 int ok;
2872
2873 while (1) {
2874 /* Steps: get datum, get selector, evaluate selector.
2875 Order is important (to match the pure python version
2876 in terms of which input gets a chance to raise an
2877 exception first).
2878 */
2879
2880 datum = datanext(data);
2881 if (datum == NULL)
2882 return NULL;
2883
2884 selector = selectornext(selectors);
2885 if (selector == NULL) {
2886 Py_DECREF(datum);
2887 return NULL;
2888 }
2889
2890 ok = PyObject_IsTrue(selector);
2891 Py_DECREF(selector);
2892 if (ok == 1)
2893 return datum;
2894 Py_DECREF(datum);
2895 if (ok == -1)
2896 return NULL;
2897 }
2898 }
2899
2900 PyDoc_STRVAR(compress_doc,
2901 "compress(data, selectors) --> iterator over selected data\n\
2902 \n\
2903 Return data elements corresponding to true selector elements.\n\
2904 Forms a shorter iterator from selected data elements using the\n\
2905 selectors to choose the data elements.");
2906
2907 static PyTypeObject compress_type = {
2908 PyVarObject_HEAD_INIT(NULL, 0)
2909 "itertools.compress", /* tp_name */
2910 sizeof(compressobject), /* tp_basicsize */
2911 0, /* tp_itemsize */
2912 /* methods */
2913 (destructor)compress_dealloc, /* tp_dealloc */
2914 0, /* tp_print */
2915 0, /* tp_getattr */
2916 0, /* tp_setattr */
2917 0, /* tp_compare */
2918 0, /* tp_repr */
2919 0, /* tp_as_number */
2920 0, /* tp_as_sequence */
2921 0, /* tp_as_mapping */
2922 0, /* tp_hash */
2923 0, /* tp_call */
2924 0, /* tp_str */
2925 PyObject_GenericGetAttr, /* tp_getattro */
2926 0, /* tp_setattro */
2927 0, /* tp_as_buffer */
2928 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2929 Py_TPFLAGS_BASETYPE, /* tp_flags */
2930 compress_doc, /* tp_doc */
2931 (traverseproc)compress_traverse, /* tp_traverse */
2932 0, /* tp_clear */
2933 0, /* tp_richcompare */
2934 0, /* tp_weaklistoffset */
2935 PyObject_SelfIter, /* tp_iter */
2936 (iternextfunc)compress_next, /* tp_iternext */
2937 0, /* tp_methods */
2938 0, /* tp_members */
2939 0, /* tp_getset */
2940 0, /* tp_base */
2941 0, /* tp_dict */
2942 0, /* tp_descr_get */
2943 0, /* tp_descr_set */
2944 0, /* tp_dictoffset */
2945 0, /* tp_init */
2946 0, /* tp_alloc */
2947 compress_new, /* tp_new */
2948 PyObject_GC_Del, /* tp_free */
2949 };
2950
2951
2952 /* ifilter object ************************************************************/
2953
2954 typedef struct {
2955 PyObject_HEAD
2956 PyObject *func;
2957 PyObject *it;
2958 } ifilterobject;
2959
2960 static PyTypeObject ifilter_type;
2961
2962 static PyObject *
2963 ifilter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2964 {
2965 PyObject *func, *seq;
2966 PyObject *it;
2967 ifilterobject *lz;
2968
2969 if (type == &ifilter_type && !_PyArg_NoKeywords("ifilter()", kwds))
2970 return NULL;
2971
2972 if (!PyArg_UnpackTuple(args, "ifilter", 2, 2, &func, &seq))
2973 return NULL;
2974
2975 /* Get iterator. */
2976 it = PyObject_GetIter(seq);
2977 if (it == NULL)
2978 return NULL;
2979
2980 /* create ifilterobject structure */
2981 lz = (ifilterobject *)type->tp_alloc(type, 0);
2982 if (lz == NULL) {
2983 Py_DECREF(it);
2984 return NULL;
2985 }
2986 Py_INCREF(func);
2987 lz->func = func;
2988 lz->it = it;
2989
2990 return (PyObject *)lz;
2991 }
2992
2993 static void
2994 ifilter_dealloc(ifilterobject *lz)
2995 {
2996 PyObject_GC_UnTrack(lz);
2997 Py_XDECREF(lz->func);
2998 Py_XDECREF(lz->it);
2999 Py_TYPE(lz)->tp_free(lz);
3000 }
3001
3002 static int
3003 ifilter_traverse(ifilterobject *lz, visitproc visit, void *arg)
3004 {
3005 Py_VISIT(lz->it);
3006 Py_VISIT(lz->func);
3007 return 0;
3008 }
3009
3010 static PyObject *
3011 ifilter_next(ifilterobject *lz)
3012 {
3013 PyObject *item;
3014 PyObject *it = lz->it;
3015 long ok;
3016 PyObject *(*iternext)(PyObject *);
3017
3018 iternext = *Py_TYPE(it)->tp_iternext;
3019 for (;;) {
3020 item = iternext(it);
3021 if (item == NULL)
3022 return NULL;
3023
3024 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
3025 ok = PyObject_IsTrue(item);
3026 } else {
3027 PyObject *good;
3028 good = PyObject_CallFunctionObjArgs(lz->func,
3029 item, NULL);
3030 if (good == NULL) {
3031 Py_DECREF(item);
3032 return NULL;
3033 }
3034 ok = PyObject_IsTrue(good);
3035 Py_DECREF(good);
3036 }
3037 if (ok > 0)
3038 return item;
3039 Py_DECREF(item);
3040 if (ok < 0)
3041 return NULL;
3042 }
3043 }
3044
3045 PyDoc_STRVAR(ifilter_doc,
3046 "ifilter(function or None, sequence) --> ifilter object\n\
3047 \n\
3048 Return those items of sequence for which function(item) is true.\n\
3049 If function is None, return the items that are true.");
3050
3051 static PyTypeObject ifilter_type = {
3052 PyVarObject_HEAD_INIT(NULL, 0)
3053 "itertools.ifilter", /* tp_name */
3054 sizeof(ifilterobject), /* tp_basicsize */
3055 0, /* tp_itemsize */
3056 /* methods */
3057 (destructor)ifilter_dealloc, /* tp_dealloc */
3058 0, /* tp_print */
3059 0, /* tp_getattr */
3060 0, /* tp_setattr */
3061 0, /* tp_compare */
3062 0, /* tp_repr */
3063 0, /* tp_as_number */
3064 0, /* tp_as_sequence */
3065 0, /* tp_as_mapping */
3066 0, /* tp_hash */
3067 0, /* tp_call */
3068 0, /* tp_str */
3069 PyObject_GenericGetAttr, /* tp_getattro */
3070 0, /* tp_setattro */
3071 0, /* tp_as_buffer */
3072 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3073 Py_TPFLAGS_BASETYPE, /* tp_flags */
3074 ifilter_doc, /* tp_doc */
3075 (traverseproc)ifilter_traverse, /* tp_traverse */
3076 0, /* tp_clear */
3077 0, /* tp_richcompare */
3078 0, /* tp_weaklistoffset */
3079 PyObject_SelfIter, /* tp_iter */
3080 (iternextfunc)ifilter_next, /* tp_iternext */
3081 0, /* tp_methods */
3082 0, /* tp_members */
3083 0, /* tp_getset */
3084 0, /* tp_base */
3085 0, /* tp_dict */
3086 0, /* tp_descr_get */
3087 0, /* tp_descr_set */
3088 0, /* tp_dictoffset */
3089 0, /* tp_init */
3090 0, /* tp_alloc */
3091 ifilter_new, /* tp_new */
3092 PyObject_GC_Del, /* tp_free */
3093 };
3094
3095
3096 /* ifilterfalse object ************************************************************/
3097
3098 typedef struct {
3099 PyObject_HEAD
3100 PyObject *func;
3101 PyObject *it;
3102 } ifilterfalseobject;
3103
3104 static PyTypeObject ifilterfalse_type;
3105
3106 static PyObject *
3107 ifilterfalse_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3108 {
3109 PyObject *func, *seq;
3110 PyObject *it;
3111 ifilterfalseobject *lz;
3112
3113 if (type == &ifilterfalse_type &&
3114 !_PyArg_NoKeywords("ifilterfalse()", kwds))
3115 return NULL;
3116
3117 if (!PyArg_UnpackTuple(args, "ifilterfalse", 2, 2, &func, &seq))
3118 return NULL;
3119
3120 /* Get iterator. */
3121 it = PyObject_GetIter(seq);
3122 if (it == NULL)
3123 return NULL;
3124
3125 /* create ifilterfalseobject structure */
3126 lz = (ifilterfalseobject *)type->tp_alloc(type, 0);
3127 if (lz == NULL) {
3128 Py_DECREF(it);
3129 return NULL;
3130 }
3131 Py_INCREF(func);
3132 lz->func = func;
3133 lz->it = it;
3134
3135 return (PyObject *)lz;
3136 }
3137
3138 static void
3139 ifilterfalse_dealloc(ifilterfalseobject *lz)
3140 {
3141 PyObject_GC_UnTrack(lz);
3142 Py_XDECREF(lz->func);
3143 Py_XDECREF(lz->it);
3144 Py_TYPE(lz)->tp_free(lz);
3145 }
3146
3147 static int
3148 ifilterfalse_traverse(ifilterfalseobject *lz, visitproc visit, void *arg)
3149 {
3150 Py_VISIT(lz->it);
3151 Py_VISIT(lz->func);
3152 return 0;
3153 }
3154
3155 static PyObject *
3156 ifilterfalse_next(ifilterfalseobject *lz)
3157 {
3158 PyObject *item;
3159 PyObject *it = lz->it;
3160 long ok;
3161 PyObject *(*iternext)(PyObject *);
3162
3163 iternext = *Py_TYPE(it)->tp_iternext;
3164 for (;;) {
3165 item = iternext(it);
3166 if (item == NULL)
3167 return NULL;
3168
3169 if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
3170 ok = PyObject_IsTrue(item);
3171 } else {
3172 PyObject *good;
3173 good = PyObject_CallFunctionObjArgs(lz->func,
3174 item, NULL);
3175 if (good == NULL) {
3176 Py_DECREF(item);
3177 return NULL;
3178 }
3179 ok = PyObject_IsTrue(good);
3180 Py_DECREF(good);
3181 }
3182 if (ok == 0)
3183 return item;
3184 Py_DECREF(item);
3185 if (ok < 0)
3186 return NULL;
3187 }
3188 }
3189
3190 PyDoc_STRVAR(ifilterfalse_doc,
3191 "ifilterfalse(function or None, sequence) --> ifilterfalse object\n\
3192 \n\
3193 Return those items of sequence for which function(item) is false.\n\
3194 If function is None, return the items that are false.");
3195
3196 static PyTypeObject ifilterfalse_type = {
3197 PyVarObject_HEAD_INIT(NULL, 0)
3198 "itertools.ifilterfalse", /* tp_name */
3199 sizeof(ifilterfalseobject), /* tp_basicsize */
3200 0, /* tp_itemsize */
3201 /* methods */
3202 (destructor)ifilterfalse_dealloc, /* tp_dealloc */
3203 0, /* tp_print */
3204 0, /* tp_getattr */
3205 0, /* tp_setattr */
3206 0, /* tp_compare */
3207 0, /* tp_repr */
3208 0, /* tp_as_number */
3209 0, /* tp_as_sequence */
3210 0, /* tp_as_mapping */
3211 0, /* tp_hash */
3212 0, /* tp_call */
3213 0, /* tp_str */
3214 PyObject_GenericGetAttr, /* tp_getattro */
3215 0, /* tp_setattro */
3216 0, /* tp_as_buffer */
3217 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3218 Py_TPFLAGS_BASETYPE, /* tp_flags */
3219 ifilterfalse_doc, /* tp_doc */
3220 (traverseproc)ifilterfalse_traverse, /* tp_traverse */
3221 0, /* tp_clear */
3222 0, /* tp_richcompare */
3223 0, /* tp_weaklistoffset */
3224 PyObject_SelfIter, /* tp_iter */
3225 (iternextfunc)ifilterfalse_next, /* tp_iternext */
3226 0, /* tp_methods */
3227 0, /* tp_members */
3228 0, /* tp_getset */
3229 0, /* tp_base */
3230 0, /* tp_dict */
3231 0, /* tp_descr_get */
3232 0, /* tp_descr_set */
3233 0, /* tp_dictoffset */
3234 0, /* tp_init */
3235 0, /* tp_alloc */
3236 ifilterfalse_new, /* tp_new */
3237 PyObject_GC_Del, /* tp_free */
3238 };
3239
3240
3241 /* count object ************************************************************/
3242
3243 typedef struct {
3244 PyObject_HEAD
3245 Py_ssize_t cnt;
3246 PyObject *long_cnt;
3247 PyObject *long_step;
3248 } countobject;
3249
3250 /* Counting logic and invariants:
3251
3252 fast_mode: when cnt an integer < PY_SSIZE_T_MAX and no step is specified.
3253
3254 assert(cnt != PY_SSIZE_T_MAX && long_cnt == NULL && long_step==PyInt(1));
3255 Advances with: cnt += 1
3256 When count hits Y_SSIZE_T_MAX, switch to slow_mode.
3257
3258 slow_mode: when cnt == PY_SSIZE_T_MAX, step is not int(1), or cnt is a float.
3259
3260 assert(cnt == PY_SSIZE_T_MAX && long_cnt != NULL && long_step != NULL);
3261 All counting is done with python objects (no overflows or underflows).
3262 Advances with: long_cnt += long_step
3263 Step may be zero -- effectively a slow version of repeat(cnt).
3264 Either long_cnt or long_step may be a float, Fraction, or Decimal.
3265 */
3266
3267 static PyTypeObject count_type;
3268
3269 static PyObject *
3270 count_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3271 {
3272 countobject *lz;
3273 int slow_mode = 0;
3274 Py_ssize_t cnt = 0;
3275 PyObject *long_cnt = NULL;
3276 PyObject *long_step = NULL;
3277 static char *kwlist[] = {"start", "step", 0};
3278
3279 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:count",
3280 kwlist, &long_cnt, &long_step))
3281 return NULL;
3282
3283 if ((long_cnt != NULL && !PyNumber_Check(long_cnt)) ||
3284 (long_step != NULL && !PyNumber_Check(long_step))) {
3285 PyErr_SetString(PyExc_TypeError, "a number is required");
3286 return NULL;
3287 }
3288
3289 if (long_cnt != NULL) {
3290 cnt = PyInt_AsSsize_t(long_cnt);
3291 if ((cnt == -1 && PyErr_Occurred()) || !PyInt_Check(long_cnt)) {
3292 PyErr_Clear();
3293 slow_mode = 1;
3294 }
3295 Py_INCREF(long_cnt);
3296 } else {
3297 cnt = 0;
3298 long_cnt = PyInt_FromLong(0);
3299 }
3300
3301 /* If not specified, step defaults to 1 */
3302 if (long_step == NULL) {
3303 long_step = PyInt_FromLong(1);
3304 if (long_step == NULL) {
3305 Py_DECREF(long_cnt);
3306 return NULL;
3307 }
3308 } else
3309 Py_INCREF(long_step);
3310
3311 assert(long_cnt != NULL && long_step != NULL);
3312
3313 /* Fast mode only works when the step is 1 */
3314 if (!PyInt_Check(long_step) ||
3315 PyInt_AS_LONG(long_step) != 1) {
3316 slow_mode = 1;
3317 }
3318
3319 if (slow_mode)
3320 cnt = PY_SSIZE_T_MAX;
3321 else
3322 Py_CLEAR(long_cnt);
3323
3324 assert((cnt != PY_SSIZE_T_MAX && long_cnt == NULL && !slow_mode) ||
3325 (cnt == PY_SSIZE_T_MAX && long_cnt != NULL && slow_mode));
3326 assert(slow_mode ||
3327 (PyInt_Check(long_step) && PyInt_AS_LONG(long_step) == 1));
3328
3329 /* create countobject structure */
3330 lz = (countobject *)type->tp_alloc(type, 0);
3331 if (lz == NULL) {
3332 Py_XDECREF(long_cnt);
3333 Py_DECREF(long_step);
3334 return NULL;
3335 }
3336 lz->cnt = cnt;
3337 lz->long_cnt = long_cnt;
3338 lz->long_step = long_step;
3339
3340 return (PyObject *)lz;
3341 }
3342
3343 static void
3344 count_dealloc(countobject *lz)
3345 {
3346 PyObject_GC_UnTrack(lz);
3347 Py_XDECREF(lz->long_cnt);
3348 Py_XDECREF(lz->long_step);
3349 Py_TYPE(lz)->tp_free(lz);
3350 }
3351
3352 static int
3353 count_traverse(countobject *lz, visitproc visit, void *arg)
3354 {
3355 Py_VISIT(lz->long_cnt);
3356 Py_VISIT(lz->long_step);
3357 return 0;
3358 }
3359
3360 static PyObject *
3361 count_nextlong(countobject *lz)
3362 {
3363 PyObject *long_cnt;
3364 PyObject *stepped_up;
3365
3366 long_cnt = lz->long_cnt;
3367 if (long_cnt == NULL) {
3368 /* Switch to slow_mode */
3369 long_cnt = PyInt_FromSsize_t(PY_SSIZE_T_MAX);
3370 if (long_cnt == NULL)
3371 return NULL;
3372 }
3373 assert(lz->cnt == PY_SSIZE_T_MAX && long_cnt != NULL);
3374
3375 stepped_up = PyNumber_Add(long_cnt, lz->long_step);
3376 if (stepped_up == NULL)
3377 return NULL;
3378 lz->long_cnt = stepped_up;
3379 return long_cnt;
3380 }
3381
3382 static PyObject *
3383 count_next(countobject *lz)
3384 {
3385 if (lz->cnt == PY_SSIZE_T_MAX)
3386 return count_nextlong(lz);
3387 return PyInt_FromSsize_t(lz->cnt++);
3388 }
3389
3390 static PyObject *
3391 count_repr(countobject *lz)
3392 {
3393 PyObject *cnt_repr, *step_repr = NULL;
3394 PyObject *result = NULL;
3395
3396 if (lz->cnt != PY_SSIZE_T_MAX)
3397 return PyString_FromFormat("count(%zd)", lz->cnt);
3398
3399 cnt_repr = PyObject_Repr(lz->long_cnt);
3400 if (cnt_repr == NULL)
3401 return NULL;
3402
3403 if (PyInt_Check(lz->long_step) && PyInt_AS_LONG(lz->long_step) == 1) {
3404 /* Don't display step when it is an integer equal to 1 */
3405 result = PyString_FromFormat("count(%s)",
3406 PyString_AS_STRING(cnt_repr));
3407 } else {
3408 step_repr = PyObject_Repr(lz->long_step);
3409 if (step_repr != NULL)
3410 result = PyString_FromFormat("count(%s, %s)",
3411 PyString_AS_STRING(cnt_repr),
3412 PyString_AS_STRING(step_repr));
3413 }
3414 Py_DECREF(cnt_repr);
3415 Py_XDECREF(step_repr);
3416 return result;
3417 }
3418
3419 static PyObject *
3420 count_reduce(countobject *lz)
3421 {
3422 if (lz->cnt == PY_SSIZE_T_MAX)
3423 return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->long_cnt, lz->long_step);
3424 return Py_BuildValue("O(n)", Py_TYPE(lz), lz->cnt);
3425 }
3426
3427 PyDoc_STRVAR(count_reduce_doc, "Return state information for pickling.");
3428
3429 static PyMethodDef count_methods[] = {
3430 {"__reduce__", (PyCFunction)count_reduce, METH_NOARGS,
3431 count_reduce_doc},
3432 {NULL, NULL} /* sentinel */
3433 };
3434
3435 PyDoc_STRVAR(count_doc,
3436 "count(start=0, step=1) --> count object\n\
3437 \n\
3438 Return a count object whose .next() method returns consecutive values.\n\
3439 Equivalent to:\n\n\
3440 def count(firstval=0, step=1):\n\
3441 x = firstval\n\
3442 while 1:\n\
3443 yield x\n\
3444 x += step\n");
3445
3446 static PyTypeObject count_type = {
3447 PyVarObject_HEAD_INIT(NULL, 0)
3448 "itertools.count", /* tp_name */
3449 sizeof(countobject), /* tp_basicsize */
3450 0, /* tp_itemsize */
3451 /* methods */
3452 (destructor)count_dealloc, /* tp_dealloc */
3453 0, /* tp_print */
3454 0, /* tp_getattr */
3455 0, /* tp_setattr */
3456 0, /* tp_compare */
3457 (reprfunc)count_repr, /* tp_repr */
3458 0, /* tp_as_number */
3459 0, /* tp_as_sequence */
3460 0, /* tp_as_mapping */
3461 0, /* tp_hash */
3462 0, /* tp_call */
3463 0, /* tp_str */
3464 PyObject_GenericGetAttr, /* tp_getattro */
3465 0, /* tp_setattro */
3466 0, /* tp_as_buffer */
3467 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3468 Py_TPFLAGS_BASETYPE, /* tp_flags */
3469 count_doc, /* tp_doc */
3470 (traverseproc)count_traverse, /* tp_traverse */
3471 0, /* tp_clear */
3472 0, /* tp_richcompare */
3473 0, /* tp_weaklistoffset */
3474 PyObject_SelfIter, /* tp_iter */
3475 (iternextfunc)count_next, /* tp_iternext */
3476 count_methods, /* tp_methods */
3477 0, /* tp_members */
3478 0, /* tp_getset */
3479 0, /* tp_base */
3480 0, /* tp_dict */
3481 0, /* tp_descr_get */
3482 0, /* tp_descr_set */
3483 0, /* tp_dictoffset */
3484 0, /* tp_init */
3485 0, /* tp_alloc */
3486 count_new, /* tp_new */
3487 PyObject_GC_Del, /* tp_free */
3488 };
3489
3490
3491 /* izip object ************************************************************/
3492
3493 #include "Python.h"
3494
3495 typedef struct {
3496 PyObject_HEAD
3497 Py_ssize_t tuplesize;
3498 PyObject *ittuple; /* tuple of iterators */
3499 PyObject *result;
3500 } izipobject;
3501
3502 static PyTypeObject izip_type;
3503
3504 static PyObject *
3505 izip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3506 {
3507 izipobject *lz;
3508 Py_ssize_t i;
3509 PyObject *ittuple; /* tuple of iterators */
3510 PyObject *result;
3511 Py_ssize_t tuplesize = PySequence_Length(args);
3512
3513 if (type == &izip_type && !_PyArg_NoKeywords("izip()", kwds))
3514 return NULL;
3515
3516 /* args must be a tuple */
3517 assert(PyTuple_Check(args));
3518
3519 /* obtain iterators */
3520 ittuple = PyTuple_New(tuplesize);
3521 if (ittuple == NULL)
3522 return NULL;
3523 for (i=0; i < tuplesize; ++i) {
3524 PyObject *item = PyTuple_GET_ITEM(args, i);
3525 PyObject *it = PyObject_GetIter(item);
3526 if (it == NULL) {
3527 if (PyErr_ExceptionMatches(PyExc_TypeError))
3528 PyErr_Format(PyExc_TypeError,
3529 "izip argument #%zd must support iteration",
3530 i+1);
3531 Py_DECREF(ittuple);
3532 return NULL;
3533 }
3534 PyTuple_SET_ITEM(ittuple, i, it);
3535 }
3536
3537 /* create a result holder */
3538 result = PyTuple_New(tuplesize);
3539 if (result == NULL) {
3540 Py_DECREF(ittuple);
3541 return NULL;
3542 }
3543 for (i=0 ; i < tuplesize ; i++) {
3544 Py_INCREF(Py_None);
3545 PyTuple_SET_ITEM(result, i, Py_None);
3546 }
3547
3548 /* create izipobject structure */
3549 lz = (izipobject *)type->tp_alloc(type, 0);
3550 if (lz == NULL) {
3551 Py_DECREF(ittuple);
3552 Py_DECREF(result);
3553 return NULL;
3554 }
3555 lz->ittuple = ittuple;
3556 lz->tuplesize = tuplesize;
3557 lz->result = result;
3558
3559 return (PyObject *)lz;
3560 }
3561
3562 static void
3563 izip_dealloc(izipobject *lz)
3564 {
3565 PyObject_GC_UnTrack(lz);
3566 Py_XDECREF(lz->ittuple);
3567 Py_XDECREF(lz->result);
3568 Py_TYPE(lz)->tp_free(lz);
3569 }
3570
3571 static int
3572 izip_traverse(izipobject *lz, visitproc visit, void *arg)
3573 {
3574 Py_VISIT(lz->ittuple);
3575 Py_VISIT(lz->result);
3576 return 0;
3577 }
3578
3579 static PyObject *
3580 izip_next(izipobject *lz)
3581 {
3582 Py_ssize_t i;
3583 Py_ssize_t tuplesize = lz->tuplesize;
3584 PyObject *result = lz->result;
3585 PyObject *it;
3586 PyObject *item;
3587 PyObject *olditem;
3588
3589 if (tuplesize == 0)
3590 return NULL;
3591 if (Py_REFCNT(result) == 1) {
3592 Py_INCREF(result);
3593 for (i=0 ; i < tuplesize ; i++) {
3594 it = PyTuple_GET_ITEM(lz->ittuple, i);
3595 item = (*Py_TYPE(it)->tp_iternext)(it);
3596 if (item == NULL) {
3597 Py_DECREF(result);
3598 return NULL;
3599 }
3600 olditem = PyTuple_GET_ITEM(result, i);
3601 PyTuple_SET_ITEM(result, i, item);
3602 Py_DECREF(olditem);
3603 }
3604 } else {
3605 result = PyTuple_New(tuplesize);
3606 if (result == NULL)
3607 return NULL;
3608 for (i=0 ; i < tuplesize ; i++) {
3609 it = PyTuple_GET_ITEM(lz->ittuple, i);
3610 item = (*Py_TYPE(it)->tp_iternext)(it);
3611 if (item == NULL) {
3612 Py_DECREF(result);
3613 return NULL;
3614 }
3615 PyTuple_SET_ITEM(result, i, item);
3616 }
3617 }
3618 return result;
3619 }
3620
3621 PyDoc_STRVAR(izip_doc,
3622 "izip(iter1 [,iter2 [...]]) --> izip object\n\
3623 \n\
3624 Return a izip object whose .next() method returns a tuple where\n\
3625 the i-th element comes from the i-th iterable argument. The .next()\n\
3626 method continues until the shortest iterable in the argument sequence\n\
3627 is exhausted and then it raises StopIteration. Works like the zip()\n\
3628 function but consumes less memory by returning an iterator instead of\n\
3629 a list.");
3630
3631 static PyTypeObject izip_type = {
3632 PyVarObject_HEAD_INIT(NULL, 0)
3633 "itertools.izip", /* tp_name */
3634 sizeof(izipobject), /* tp_basicsize */
3635 0, /* tp_itemsize */
3636 /* methods */
3637 (destructor)izip_dealloc, /* tp_dealloc */
3638 0, /* tp_print */
3639 0, /* tp_getattr */
3640 0, /* tp_setattr */
3641 0, /* tp_compare */
3642 0, /* tp_repr */
3643 0, /* tp_as_number */
3644 0, /* tp_as_sequence */
3645 0, /* tp_as_mapping */
3646 0, /* tp_hash */
3647 0, /* tp_call */
3648 0, /* tp_str */
3649 PyObject_GenericGetAttr, /* tp_getattro */
3650 0, /* tp_setattro */
3651 0, /* tp_as_buffer */
3652 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3653 Py_TPFLAGS_BASETYPE, /* tp_flags */
3654 izip_doc, /* tp_doc */
3655 (traverseproc)izip_traverse, /* tp_traverse */
3656 0, /* tp_clear */
3657 0, /* tp_richcompare */
3658 0, /* tp_weaklistoffset */
3659 PyObject_SelfIter, /* tp_iter */
3660 (iternextfunc)izip_next, /* tp_iternext */
3661 0, /* tp_methods */
3662 0, /* tp_members */
3663 0, /* tp_getset */
3664 0, /* tp_base */
3665 0, /* tp_dict */
3666 0, /* tp_descr_get */
3667 0, /* tp_descr_set */
3668 0, /* tp_dictoffset */
3669 0, /* tp_init */
3670 0, /* tp_alloc */
3671 izip_new, /* tp_new */
3672 PyObject_GC_Del, /* tp_free */
3673 };
3674
3675
3676 /* repeat object ************************************************************/
3677
3678 typedef struct {
3679 PyObject_HEAD
3680 PyObject *element;
3681 Py_ssize_t cnt;
3682 } repeatobject;
3683
3684 static PyTypeObject repeat_type;
3685
3686 static PyObject *
3687 repeat_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3688 {
3689 repeatobject *ro;
3690 PyObject *element;
3691 Py_ssize_t cnt = -1, n_kwds = 0;
3692 static char *kwargs[] = {"object", "times", NULL};
3693
3694 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|n:repeat", kwargs,
3695 &element, &cnt))
3696 return NULL;
3697
3698 if (kwds != NULL)
3699 n_kwds = PyDict_Size(kwds);
3700 /* Does user supply times argument? */
3701 if ((PyTuple_Size(args) + n_kwds == 2) && cnt < 0)
3702 cnt = 0;
3703
3704 ro = (repeatobject *)type->tp_alloc(type, 0);
3705 if (ro == NULL)
3706 return NULL;
3707 Py_INCREF(element);
3708 ro->element = element;
3709 ro->cnt = cnt;
3710 return (PyObject *)ro;
3711 }
3712
3713 static void
3714 repeat_dealloc(repeatobject *ro)
3715 {
3716 PyObject_GC_UnTrack(ro);
3717 Py_XDECREF(ro->element);
3718 Py_TYPE(ro)->tp_free(ro);
3719 }
3720
3721 static int
3722 repeat_traverse(repeatobject *ro, visitproc visit, void *arg)
3723 {
3724 Py_VISIT(ro->element);
3725 return 0;
3726 }
3727
3728 static PyObject *
3729 repeat_next(repeatobject *ro)
3730 {
3731 if (ro->cnt == 0)
3732 return NULL;
3733 if (ro->cnt > 0)
3734 ro->cnt--;
3735 Py_INCREF(ro->element);
3736 return ro->element;
3737 }
3738
3739 static PyObject *
3740 repeat_repr(repeatobject *ro)
3741 {
3742 PyObject *result, *objrepr;
3743
3744 objrepr = PyObject_Repr(ro->element);
3745 if (objrepr == NULL)
3746 return NULL;
3747
3748 if (ro->cnt == -1)
3749 result = PyString_FromFormat("repeat(%s)",
3750 PyString_AS_STRING(objrepr));
3751 else
3752 result = PyString_FromFormat("repeat(%s, %zd)",
3753 PyString_AS_STRING(objrepr), ro->cnt);
3754 Py_DECREF(objrepr);
3755 return result;
3756 }
3757
3758 static PyObject *
3759 repeat_len(repeatobject *ro)
3760 {
3761 if (ro->cnt == -1) {
3762 PyErr_SetString(PyExc_TypeError, "len() of unsized object");
3763 return NULL;
3764 }
3765 return PyInt_FromSize_t(ro->cnt);
3766 }
3767
3768 PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
3769
3770 static PyMethodDef repeat_methods[] = {
3771 {"__length_hint__", (PyCFunction)repeat_len, METH_NOARGS, length_hint_doc},
3772 {NULL, NULL} /* sentinel */
3773 };
3774
3775 PyDoc_STRVAR(repeat_doc,
3776 "repeat(object [,times]) -> create an iterator which returns the object\n\
3777 for the specified number of times. If not specified, returns the object\n\
3778 endlessly.");
3779
3780 static PyTypeObject repeat_type = {
3781 PyVarObject_HEAD_INIT(NULL, 0)
3782 "itertools.repeat", /* tp_name */
3783 sizeof(repeatobject), /* tp_basicsize */
3784 0, /* tp_itemsize */
3785 /* methods */
3786 (destructor)repeat_dealloc, /* tp_dealloc */
3787 0, /* tp_print */
3788 0, /* tp_getattr */
3789 0, /* tp_setattr */
3790 0, /* tp_compare */
3791 (reprfunc)repeat_repr, /* tp_repr */
3792 0, /* tp_as_number */
3793 0, /* tp_as_sequence */
3794 0, /* tp_as_mapping */
3795 0, /* tp_hash */
3796 0, /* tp_call */
3797 0, /* tp_str */
3798 PyObject_GenericGetAttr, /* tp_getattro */
3799 0, /* tp_setattro */
3800 0, /* tp_as_buffer */
3801 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
3802 Py_TPFLAGS_BASETYPE, /* tp_flags */
3803 repeat_doc, /* tp_doc */
3804 (traverseproc)repeat_traverse, /* tp_traverse */
3805 0, /* tp_clear */
3806 0, /* tp_richcompare */
3807 0, /* tp_weaklistoffset */
3808 PyObject_SelfIter, /* tp_iter */
3809 (iternextfunc)repeat_next, /* tp_iternext */
3810 repeat_methods, /* tp_methods */
3811 0, /* tp_members */
3812 0, /* tp_getset */
3813 0, /* tp_base */
3814 0, /* tp_dict */
3815 0, /* tp_descr_get */
3816 0, /* tp_descr_set */
3817 0, /* tp_dictoffset */
3818 0, /* tp_init */
3819 0, /* tp_alloc */
3820 repeat_new, /* tp_new */
3821 PyObject_GC_Del, /* tp_free */
3822 };
3823
3824 /* iziplongest object ************************************************************/
3825
3826 #include "Python.h"
3827
3828 typedef struct {
3829 PyObject_HEAD
3830 Py_ssize_t tuplesize;
3831 Py_ssize_t numactive;
3832 PyObject *ittuple; /* tuple of iterators */
3833 PyObject *result;
3834 PyObject *fillvalue;
3835 } iziplongestobject;
3836
3837 static PyTypeObject iziplongest_type;
3838
3839 static PyObject *
3840 izip_longest_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3841 {
3842 iziplongestobject *lz;
3843 Py_ssize_t i;
3844 PyObject *ittuple; /* tuple of iterators */
3845 PyObject *result;
3846 PyObject *fillvalue = Py_None;
3847 Py_ssize_t tuplesize = PySequence_Length(args);
3848
3849 if (kwds != NULL && PyDict_CheckExact(kwds) && PyDict_Size(kwds) > 0) {
3850 fillvalue = PyDict_GetItemString(kwds, "fillvalue");
3851 if (fillvalue == NULL || PyDict_Size(kwds) > 1) {
3852 PyErr_SetString(PyExc_TypeError,
3853 "izip_longest() got an unexpected keyword argument");
3854 return NULL;
3855 }
3856 }
3857
3858 /* args must be a tuple */
3859 assert(PyTuple_Check(args));
3860
3861 /* obtain iterators */
3862 ittuple = PyTuple_New(tuplesize);
3863 if (ittuple == NULL)
3864 return NULL;
3865 for (i=0; i < tuplesize; ++i) {
3866 PyObject *item = PyTuple_GET_ITEM(args, i);
3867 PyObject *it = PyObject_GetIter(item);
3868 if (it == NULL) {
3869 if (PyErr_ExceptionMatches(PyExc_TypeError))
3870 PyErr_Format(PyExc_TypeError,
3871 "izip_longest argument #%zd must support iteration",
3872 i+1);
3873 Py_DECREF(ittuple);
3874 return NULL;
3875 }
3876 PyTuple_SET_ITEM(ittuple, i, it);
3877 }
3878
3879 /* create a result holder */
3880 result = PyTuple_New(tuplesize);
3881 if (result == NULL) {
3882 Py_DECREF(ittuple);
3883 return NULL;
3884 }
3885 for (i=0 ; i < tuplesize ; i++) {
3886 Py_INCREF(Py_None);
3887 PyTuple_SET_ITEM(result, i, Py_None);
3888 }
3889
3890 /* create iziplongestobject structure */
3891 lz = (iziplongestobject *)type->tp_alloc(type, 0);
3892 if (lz == NULL) {
3893 Py_DECREF(ittuple);
3894 Py_DECREF(result);
3895 return NULL;
3896 }
3897 lz->ittuple = ittuple;
3898 lz->tuplesize = tuplesize;
3899 lz->numactive = tuplesize;
3900 lz->result = result;
3901 Py_INCREF(fillvalue);
3902 lz->fillvalue = fillvalue;
3903 return (PyObject *)lz;
3904 }
3905
3906 static void
3907 izip_longest_dealloc(iziplongestobject *lz)
3908 {
3909 PyObject_GC_UnTrack(lz);
3910 Py_XDECREF(lz->ittuple);
3911 Py_XDECREF(lz->result);
3912 Py_XDECREF(lz->fillvalue);
3913 Py_TYPE(lz)->tp_free(lz);
3914 }
3915
3916 static int
3917 izip_longest_traverse(iziplongestobject *lz, visitproc visit, void *arg)
3918 {
3919 Py_VISIT(lz->ittuple);
3920 Py_VISIT(lz->result);
3921 Py_VISIT(lz->fillvalue);
3922 return 0;
3923 }
3924
3925 static PyObject *
3926 izip_longest_next(iziplongestobject *lz)
3927 {
3928 Py_ssize_t i;
3929 Py_ssize_t tuplesize = lz->tuplesize;
3930 PyObject *result = lz->result;
3931 PyObject *it;
3932 PyObject *item;
3933 PyObject *olditem;
3934
3935 if (tuplesize == 0)
3936 return NULL;
3937 if (lz->numactive == 0)
3938 return NULL;
3939 if (Py_REFCNT(result) == 1) {
3940 Py_INCREF(result);
3941 for (i=0 ; i < tuplesize ; i++) {
3942 it = PyTuple_GET_ITEM(lz->ittuple, i);
3943 if (it == NULL) {
3944 Py_INCREF(lz->fillvalue);
3945 item = lz->fillvalue;
3946 } else {
3947 item = PyIter_Next(it);
3948 if (item == NULL) {
3949 lz->numactive -= 1;
3950 if (lz->numactive == 0 || PyErr_Occurred()) {
3951 lz->numactive = 0;
3952 Py_DECREF(result);
3953 return NULL;
3954 } else {
3955 Py_INCREF(lz->fillvalue);
3956 item = lz->fillvalue;
3957 PyTuple_SET_ITEM(lz->ittuple, i, NULL);
3958 Py_DECREF(it);
3959 }
3960 }
3961 }
3962 olditem = PyTuple_GET_ITEM(result, i);
3963 PyTuple_SET_ITEM(result, i, item);
3964 Py_DECREF(olditem);
3965 }
3966 } else {
3967 result = PyTuple_New(tuplesize);
3968 if (result == NULL)
3969 return NULL;
3970 for (i=0 ; i < tuplesize ; i++) {
3971 it = PyTuple_GET_ITEM(lz->ittuple, i);
3972 if (it == NULL) {
3973 Py_INCREF(lz->fillvalue);
3974 item = lz->fillvalue;
3975 } else {
3976 item = PyIter_Next(it);
3977 if (item == NULL) {
3978 lz->numactive -= 1;
3979 if (lz->numactive == 0 || PyErr_Occurred()) {
3980 lz->numactive = 0;
3981 Py_DECREF(result);
3982 return NULL;
3983 } else {
3984 Py_INCREF(lz->fillvalue);
3985 item = lz->fillvalue;
3986 PyTuple_SET_ITEM(lz->ittuple, i, NULL);
3987 Py_DECREF(it);
3988 }
3989 }
3990 }
3991 PyTuple_SET_ITEM(result, i, item);
3992 }
3993 }
3994 return result;
3995 }
3996
3997 PyDoc_STRVAR(izip_longest_doc,
3998 "izip_longest(iter1 [,iter2 [...]], [fillvalue=None]) --> izip_longest object\n\
3999 \n\
4000 Return an izip_longest object whose .next() method returns a tuple where\n\
4001 the i-th element comes from the i-th iterable argument. The .next()\n\
4002 method continues until the longest iterable in the argument sequence\n\
4003 is exhausted and then it raises StopIteration. When the shorter iterables\n\
4004 are exhausted, the fillvalue is substituted in their place. The fillvalue\n\
4005 defaults to None or can be specified by a keyword argument.\n\
4006 ");
4007
4008 static PyTypeObject iziplongest_type = {
4009 PyVarObject_HEAD_INIT(NULL, 0)
4010 "itertools.izip_longest", /* tp_name */
4011 sizeof(iziplongestobject), /* tp_basicsize */
4012 0, /* tp_itemsize */
4013 /* methods */
4014 (destructor)izip_longest_dealloc, /* tp_dealloc */
4015 0, /* tp_print */
4016 0, /* tp_getattr */
4017 0, /* tp_setattr */
4018 0, /* tp_compare */
4019 0, /* tp_repr */
4020 0, /* tp_as_number */
4021 0, /* tp_as_sequence */
4022 0, /* tp_as_mapping */
4023 0, /* tp_hash */
4024 0, /* tp_call */
4025 0, /* tp_str */
4026 PyObject_GenericGetAttr, /* tp_getattro */
4027 0, /* tp_setattro */
4028 0, /* tp_as_buffer */
4029 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4030 Py_TPFLAGS_BASETYPE, /* tp_flags */
4031 izip_longest_doc, /* tp_doc */
4032 (traverseproc)izip_longest_traverse, /* tp_traverse */
4033 0, /* tp_clear */
4034 0, /* tp_richcompare */
4035 0, /* tp_weaklistoffset */
4036 PyObject_SelfIter, /* tp_iter */
4037 (iternextfunc)izip_longest_next, /* tp_iternext */
4038 0, /* tp_methods */
4039 0, /* tp_members */
4040 0, /* tp_getset */
4041 0, /* tp_base */
4042 0, /* tp_dict */
4043 0, /* tp_descr_get */
4044 0, /* tp_descr_set */
4045 0, /* tp_dictoffset */
4046 0, /* tp_init */
4047 0, /* tp_alloc */
4048 izip_longest_new, /* tp_new */
4049 PyObject_GC_Del, /* tp_free */
4050 };
4051
4052 /* module level code ********************************************************/
4053
4054 PyDoc_STRVAR(module_doc,
4055 "Functional tools for creating and using iterators.\n\
4056 \n\
4057 Infinite iterators:\n\
4058 count([n]) --> n, n+1, n+2, ...\n\
4059 cycle(p) --> p0, p1, ... plast, p0, p1, ...\n\
4060 repeat(elem [,n]) --> elem, elem, elem, ... endlessly or up to n times\n\
4061 \n\
4062 Iterators terminating on the shortest input sequence:\n\
4063 chain(p, q, ...) --> p0, p1, ... plast, q0, q1, ... \n\
4064 compress(data, selectors) --> (d[0] if s[0]), (d[1] if s[1]), ...\n\
4065 dropwhile(pred, seq) --> seq[n], seq[n+1], starting when pred fails\n\
4066 groupby(iterable[, keyfunc]) --> sub-iterators grouped by value of keyfunc(v)\n\
4067 ifilter(pred, seq) --> elements of seq where pred(elem) is True\n\
4068 ifilterfalse(pred, seq) --> elements of seq where pred(elem) is False\n\
4069 islice(seq, [start,] stop [, step]) --> elements from\n\
4070 seq[start:stop:step]\n\
4071 imap(fun, p, q, ...) --> fun(p0, q0), fun(p1, q1), ...\n\
4072 starmap(fun, seq) --> fun(*seq[0]), fun(*seq[1]), ...\n\
4073 tee(it, n=2) --> (it1, it2 , ... itn) splits one iterator into n\n\
4074 takewhile(pred, seq) --> seq[0], seq[1], until pred fails\n\
4075 izip(p, q, ...) --> (p[0], q[0]), (p[1], q[1]), ... \n\
4076 izip_longest(p, q, ...) --> (p[0], q[0]), (p[1], q[1]), ... \n\
4077 \n\
4078 Combinatoric generators:\n\
4079 product(p, q, ... [repeat=1]) --> cartesian product\n\
4080 permutations(p[, r])\n\
4081 combinations(p, r)\n\
4082 combinations_with_replacement(p, r)\n\
4083 ");
4084
4085
4086 static PyMethodDef module_methods[] = {
4087 {"tee", (PyCFunction)tee, METH_VARARGS, tee_doc},
4088 {NULL, NULL} /* sentinel */
4089 };
4090
4091 PyMODINIT_FUNC
4092 inititertools(void)
4093 {
4094 int i;
4095 PyObject *m;
4096 char *name;
4097 PyTypeObject *typelist[] = {
4098 &combinations_type,
4099 &cwr_type,
4100 &cycle_type,
4101 &dropwhile_type,
4102 &takewhile_type,
4103 &islice_type,
4104 &starmap_type,
4105 &imap_type,
4106 &chain_type,
4107 &compress_type,
4108 &ifilter_type,
4109 &ifilterfalse_type,
4110 &count_type,
4111 &izip_type,
4112 &iziplongest_type,
4113 &permutations_type,
4114 &product_type,
4115 &repeat_type,
4116 &groupby_type,
4117 NULL
4118 };
4119
4120 Py_TYPE(&teedataobject_type) = &PyType_Type;
4121 m = Py_InitModule3("itertools", module_methods, module_doc);
4122 if (m == NULL)
4123 return;
4124
4125 for (i=0 ; typelist[i] != NULL ; i++) {
4126 if (PyType_Ready(typelist[i]) < 0)
4127 return;
4128 name = strchr(typelist[i]->tp_name, '.');
4129 assert (name != NULL);
4130 Py_INCREF(typelist[i]);
4131 PyModule_AddObject(m, name+1, (PyObject *)typelist[i]);
4132 }
4133
4134 if (PyType_Ready(&teedataobject_type) < 0)
4135 return;
4136 if (PyType_Ready(&tee_type) < 0)
4137 return;
4138 if (PyType_Ready(&_grouper_type) < 0)
4139 return;
4140 }