1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
#include "CXX/Extensions.hxx"
#include <iostream>
#include <sstream>
#include <string>
class IterT : public Py::PythonExtension<IterT>
{
int from, count, last;
int fwd_iter;
bool do_it_reversed;
public:
static void init_type(void); // announce properties and methods
IterT(int _from, int _last)
: from(_from)
, last(_last)
, fwd_iter(0)
, do_it_reversed(false)
{}
Py::Object repr()
{
std::string s;
std::ostringstream s_out;
s_out << "IterT count(" << count << ")";
return Py::String(s_out.str());
}
Py::Object reversed(const Py::Tuple&)
{
do_it_reversed= true; // indicate backward iteration
return Py::Object(this,false); // increment the refcount
}
Py::Object iter()
{
if( do_it_reversed )
{
fwd_iter = -1;
do_it_reversed=false;
}
else
fwd_iter = 1; // indicate forward iteration
return Py::Object(this,false); // increment the refcount
}
PyObject* iternext()
{
int ct;
if( ! fwd_iter )
return NULL; // signal StopIteration
if( fwd_iter > 0 )
{
if( fwd_iter == 1 )
{
ct = from;
count = from+1;
fwd_iter=2;
}
else if( count <= last )
ct= count++;
else
return NULL; // signal StopIteration
}
else if( fwd_iter == -1 )
{
ct = last;
count = last-1;
fwd_iter=-2;
}
else if( count >= from )
ct= count--;
else
return NULL; // signal StopIteration
Py::Int Result(ct);
Result.increment_reference_count();
return Result.ptr();
}
};
|