-
Notifications
You must be signed in to change notification settings - Fork 227
Expand file tree
/
Copy pathcycle.java
More file actions
110 lines (90 loc) · 3.04 KB
/
cycle.java
File metadata and controls
110 lines (90 loc) · 3.04 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package org.python.modules.itertools;
import org.python.core.ArgParser;
import org.python.core.PyIterator;
import org.python.core.PyObject;
import org.python.core.PyType;
import org.python.core.Visitproc;
import org.python.expose.ExposedMethod;
import org.python.expose.ExposedNew;
import org.python.expose.ExposedType;
import java.util.ArrayList;
import java.util.List;
@ExposedType(name = "itertools.count", base = PyObject.class, doc = cycle.cycle_doc)
public class cycle extends PyIterator {
public static final PyType TYPE = PyType.fromClass(cycle.class);
private PyIterator iter;
public static final String cycle_doc =
"cycle(iterable) --> cycle object\n\n" +
"Return elements from the iterable until it is exhausted.\n" +
"Then repeat the sequence indefinitely.";
public cycle() {
super();
}
public cycle(PyType subType) {
super(subType);
}
/**
* Creates an iterator that iterates over an iterable, saving the values for each iteration.
* When the iterable is exhausted continues to iterate over the saved values indefinitely.
*/
public cycle(PyObject sequence) {
super();
cycle___init__(sequence);
}
@ExposedNew
@ExposedMethod
final void cycle___init__(final PyObject[] args, String[] kwds) {
ArgParser ap = new ArgParser("cycle", args, kwds, new String[] {"iterable"}, 1);
ap.noKeywords();
cycle___init__(ap.getPyObject(0));
}
private void cycle___init__(final PyObject sequence) {
iter = new itertools.ItertoolsIterator() {
List<PyObject> saved = new ArrayList<PyObject>();
int counter = 0;
PyObject iterator = sequence.__iter__();
boolean save = true;
public PyObject __iternext__() {
if (save) {
PyObject obj = nextElement(iterator);
if (obj != null) {
saved.add(obj);
return obj;
} else {
save = false;
}
}
if (saved.size() == 0) {
return null;
}
// pick element from saved List
if (counter >= saved.size()) {
// start over again
counter = 0;
}
return saved.get(counter++);
}
};
}
public PyObject __iternext__() {
return iter.__iternext__();
}
@ExposedMethod
@Override
public PyObject next() {
return doNext(__iternext__());
}
/* Traverseproc implementation */
@Override
public int traverse(Visitproc visit, Object arg) {
int retVal = super.traverse(visit, arg);
if (retVal != 0) {
return retVal;
}
return iter != null ? visit.visit(iter, arg) : 0;
}
@Override
public boolean refersDirectlyTo(PyObject ob) {
return ob != null && (iter == ob || super.refersDirectlyTo(ob));
}
}