1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.apache.commons.functor.generator.util;
16
17 import org.apache.commons.functor.UnaryProcedure;
18 import org.apache.commons.functor.generator.BaseGenerator;
19
20
21
22
23
24
25
26
27
28 public final class LongRange extends BaseGenerator<Long> {
29
30
31
32 private final long from;
33 private final long to;
34 private final long step;
35
36
37
38
39
40
41
42
43 public LongRange(Number from, Number to) {
44 this(from.longValue(), to.longValue());
45 }
46
47
48
49
50
51
52
53 public LongRange(Number from, Number to, Number step) {
54 this(from.longValue(), to.longValue(), step.longValue());
55 }
56
57
58
59
60
61
62 public LongRange(long from, long to) {
63 this(from, to, defaultStep(from, to));
64 }
65
66
67
68
69
70
71
72 public LongRange(long from, long to, long step) {
73 if (from != to && signOf(step) != signOf(to - from)) {
74 throw new IllegalArgumentException("Will never reach " + to + " from " + from + " using step " + step);
75 }
76 this.from = from;
77 this.to = to;
78 this.step = step;
79 }
80
81
82
83
84
85
86 public void run(UnaryProcedure<? super Long> proc) {
87 if (signOf(step) == -1L) {
88 for (long i = from; i > to; i += step) {
89 proc.run(i);
90 }
91 } else {
92 for (long i = from; i < to; i += step) {
93 proc.run(i);
94 }
95 }
96 }
97
98
99
100
101 public String toString() {
102 return "LongRange<" + from + "," + to + "," + step + ">";
103 }
104
105
106
107
108 public boolean equals(Object obj) {
109 if (obj == this) {
110 return true;
111 }
112 if (!(obj instanceof LongRange)) {
113 return false;
114 }
115 LongRange that = (LongRange) obj;
116 return this.from == that.from && this.to == that.to && this.step == that.step;
117 }
118
119
120
121
122 public int hashCode() {
123 int hash = "LongRange".hashCode();
124 hash <<= 2;
125 hash ^= from;
126 hash <<= 2;
127 hash ^= to;
128 hash <<= 2;
129 hash ^= step;
130 return hash;
131 }
132
133
134
135
136
137
138
139
140 private static long signOf(long value) {
141 return value < 0L ? -1L : value > 0L ? 1L : 0L;
142 }
143
144
145
146
147
148
149
150 private static long defaultStep(long from, long to) {
151 return from > to ? -1L : 1L;
152 }
153
154 }