1 package org.python.core; 3 4 12 13 public class PyXRange extends PySequence { 14 public int start, stop, step; int cycleLength; int copies; 19 public PyXRange(int start, int stop, int step) { 20 if (step == 0) 21 throw Py.ValueError("zero step for xrange()"); 22 this.start = start; 23 this.stop = stop; 24 this.step = step; 25 int oneLessThanStep = step + (step > 0 ? -1 : 1); 26 cycleLength = (stop - start + oneLessThanStep) / step; 27 if (cycleLength < 0) { 28 cycleLength = 0; 29 } 30 this.stop = start + cycleLength*step; 31 copies = 1; 32 } 33 34 public int __len__() { 35 return cycleLength*copies; 36 } 37 38 private int getInt(int i) { 39 if (cycleLength == 0) { return start; 41 } else { 42 return start + (i % cycleLength)*step; 43 } 44 } 45 46 protected PyObject pyget(int i) { 47 return new PyInteger(getInt(i)); 48 } 49 50 protected PyObject getslice(int start, int stop, int step) { 51 Py.DeprecationWarning("xrange object slicing is deprecated; " + 52 "convert to list instead"); 53 if (copies != 1) { 54 throw Py.TypeError("cannot slice a replicated range"); 55 } 56 int len = sliceLength(start, stop, step); 57 int xslice_start = getInt(start); 58 int xslice_step = this.step * step; 59 int xslice_stop = xslice_start + xslice_step * len; 60 return new PyXRange(xslice_start, xslice_stop, xslice_step); 61 } 62 63 64 protected PyObject repeat(int howmany) { 65 Py.DeprecationWarning("xrange object multiplication is deprecated; " + 66 "convert to list instead"); 67 PyXRange x = new PyXRange(start, stop, step); 68 x.copies = copies*howmany; 69 return x; 70 } 71 72 public PyObject __add__(PyObject generic_other) { 73 throw Py.TypeError("cannot concatenate xrange objects"); 74 } 75 76 public PyObject __findattr__(String name) { 77 String msg = "xrange object's 'start', 'stop' and 'step' " + 78 "attributes are deprecated"; 79 if (name == "start") { 80 Py.DeprecationWarning(msg); 81 return Py.newInteger(start); 82 } else if (name == "stop") { 83 Py.DeprecationWarning(msg); 84 return Py.newInteger(stop); 85 } else if (name == "step") { 86 Py.DeprecationWarning(msg); 87 return Py.newInteger(step); 88 } else { 89 return super.__findattr__(name); 90 } 91 } 92 93 public int hashCode() { 94 return stop^start^step; 97 } 98 99 public String toString() { 100 StringBuffer buf = new StringBuffer ("xrange("); 101 if (start != 0) { 102 buf.append(start); 103 buf.append(", "); 104 } 105 buf.append(__len__() * step + start); 106 if (step != 1) { 107 buf.append(", "); 108 buf.append(step); 109 } 110 buf.append(")"); 111 return buf.toString(); 112 } 113 114 public PyList tolist() { 115 Py.DeprecationWarning("xrange.tolist() is deprecated; " + 116 "use list(xrange) instead"); 117 PyList list = new PyList(); 118 int count = __len__(); 119 for (int i=0; i<count; i++) { 120 list.append(pyget(i)); 121 } 122 return list; 123 } 124 } 125 | Popular Tags |