diff options
author | Raymond Hettinger <python@rcn.com> | 2003-11-06 14:06:48 (GMT) |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2003-11-06 14:06:48 (GMT) |
commit | 85c20a41dfcec04d161ad7da7260e7b94c62d228 (patch) | |
tree | 0d9e5b294ab4890b72ddc61d193036ac1d4b5ca4 /Objects/rangeobject.c | |
parent | f607fc5395883ff924c76739e9b0921953568e54 (diff) | |
download | cpython-85c20a41dfcec04d161ad7da7260e7b94c62d228.zip cpython-85c20a41dfcec04d161ad7da7260e7b94c62d228.tar.gz cpython-85c20a41dfcec04d161ad7da7260e7b94c62d228.tar.bz2 |
Implement and apply PEP 322, reverse iteration
Diffstat (limited to 'Objects/rangeobject.c')
-rw-r--r-- | Objects/rangeobject.c | 37 |
1 files changed, 36 insertions, 1 deletions
diff --git a/Objects/rangeobject.c b/Objects/rangeobject.c index 299f4a6..1f56728 100644 --- a/Objects/rangeobject.c +++ b/Objects/rangeobject.c @@ -171,6 +171,15 @@ static PySequenceMethods range_as_sequence = { }; static PyObject * range_iter(PyObject *seq); +static PyObject * range_reverse(PyObject *seq); + +PyDoc_STRVAR(reverse_doc, +"Returns a reverse iterator."); + +static PyMethodDef range_methods[] = { + {"__reversed__", (PyCFunction)range_reverse, METH_NOARGS, reverse_doc}, + {NULL, NULL} /* sentinel */ +}; PyTypeObject PyRange_Type = { PyObject_HEAD_INIT(&PyType_Type) @@ -201,7 +210,7 @@ PyTypeObject PyRange_Type = { 0, /* tp_weaklistoffset */ (getiterfunc)range_iter, /* tp_iter */ 0, /* tp_iternext */ - 0, /* tp_methods */ + range_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ @@ -246,6 +255,32 @@ range_iter(PyObject *seq) } static PyObject * +range_reverse(PyObject *seq) +{ + rangeiterobject *it; + long start, step, len; + + if (!PyRange_Check(seq)) { + PyErr_BadInternalCall(); + return NULL; + } + it = PyObject_New(rangeiterobject, &Pyrangeiter_Type); + if (it == NULL) + return NULL; + + start = ((rangeobject *)seq)->start; + step = ((rangeobject *)seq)->step; + len = ((rangeobject *)seq)->len; + + it->index = 0; + it->start = start + (len-1) * step; + it->step = -step; + it->len = len; + + return (PyObject *)it; +} + +static PyObject * rangeiter_next(rangeiterobject *r) { if (r->index < r->len) |