You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by pa...@apache.org on 2016/10/10 06:17:03 UTC
groovy git commit: GROOVY-7877: The Range abstraction could support
numeric ranges where the items in the range differ by some step size
different to 1 (closes #366)
Repository: groovy
Updated Branches:
refs/heads/master 2faa31baf -> 3b7715a7e
GROOVY-7877: The Range abstraction could support numeric ranges where the items in the range differ by some step size different to 1 (closes #366)
Project: http://git-wip-us.apache.org/repos/asf/groovy/repo
Commit: http://git-wip-us.apache.org/repos/asf/groovy/commit/3b7715a7
Tree: http://git-wip-us.apache.org/repos/asf/groovy/tree/3b7715a7
Diff: http://git-wip-us.apache.org/repos/asf/groovy/diff/3b7715a7
Branch: refs/heads/master
Commit: 3b7715a7e17f24a4547995727e99f227447f7bba
Parents: 2faa31b
Author: paulk <pa...@asert.com.au>
Authored: Thu Jul 7 18:22:36 2016 +1000
Committer: paulk <pa...@asert.com.au>
Committed: Mon Oct 10 15:54:23 2016 +1000
----------------------------------------------------------------------
src/main/groovy/lang/IntRange.java | 12 +
src/main/groovy/lang/NumberRange.java | 629 +++++++++++++++++++
src/main/groovy/lang/Range.java | 46 +-
.../groovy/runtime/ScriptBytecodeAdapter.java | 14 +-
.../groovy/lang/BigDecimalNumberRangeTest.java | 45 ++
.../groovy/lang/BigIntegerNumberRangeTest.java | 45 ++
src/test/groovy/lang/DoubleNumberRangeTest.java | 44 ++
src/test/groovy/lang/FloatNumberRangeTest.java | 43 ++
.../groovy/lang/IntegerNumberRangeTest.java | 43 ++
src/test/groovy/lang/LongNumberRangeTest.java | 52 ++
src/test/groovy/lang/NumberRangeTest.groovy | 76 +++
src/test/groovy/lang/ShortNumberRangeTest.java | 42 ++
12 files changed, 1072 insertions(+), 19 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/groovy/blob/3b7715a7/src/main/groovy/lang/IntRange.java
----------------------------------------------------------------------
diff --git a/src/main/groovy/lang/IntRange.java b/src/main/groovy/lang/IntRange.java
index 6a87658..1ca3820 100644
--- a/src/main/groovy/lang/IntRange.java
+++ b/src/main/groovy/lang/IntRange.java
@@ -188,6 +188,18 @@ public class IntRange extends AbstractList<Integer> implements Range<Integer> {
checkSize();
}
+ /**
+ * Creates a new NumberRange with the same <code>from</code> and <code>to</code> as this
+ * IntRange but with a step size of <code>stepSize</code>.
+ *
+ * @param stepSize the desired step size
+ * @return a new NumberRange
+ * @since 2.5
+ */
+ public <T extends Number & Comparable> NumberRange by(T stepSize) {
+ return new NumberRange(NumberRange.comparableNumber((Number)from), NumberRange.comparableNumber((Number)to), stepSize, inclusive);
+ }
+
private void checkSize() {
// size() in the Collection interface returns an integer, so ranges can have no more than Integer.MAX_VALUE elements
final Long size = (long) to - from + 1;
http://git-wip-us.apache.org/repos/asf/groovy/blob/3b7715a7/src/main/groovy/lang/NumberRange.java
----------------------------------------------------------------------
diff --git a/src/main/groovy/lang/NumberRange.java b/src/main/groovy/lang/NumberRange.java
new file mode 100644
index 0000000..92c6195
--- /dev/null
+++ b/src/main/groovy/lang/NumberRange.java
@@ -0,0 +1,629 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package groovy.lang;
+
+import org.codehaus.groovy.runtime.InvokerHelper;
+import org.codehaus.groovy.runtime.IteratorClosureAdapter;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.util.AbstractList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.NoSuchElementException;
+
+import static org.codehaus.groovy.runtime.ScriptBytecodeAdapter.compareEqual;
+import static org.codehaus.groovy.runtime.ScriptBytecodeAdapter.compareGreaterThan;
+import static org.codehaus.groovy.runtime.ScriptBytecodeAdapter.compareGreaterThanEqual;
+import static org.codehaus.groovy.runtime.ScriptBytecodeAdapter.compareLessThan;
+import static org.codehaus.groovy.runtime.ScriptBytecodeAdapter.compareLessThanEqual;
+import static org.codehaus.groovy.runtime.ScriptBytecodeAdapter.compareNotEqual;
+import static org.codehaus.groovy.runtime.ScriptBytecodeAdapter.compareTo;
+import static org.codehaus.groovy.runtime.dgmimpl.NumberNumberMinus.minus;
+import static org.codehaus.groovy.runtime.dgmimpl.NumberNumberMultiply.multiply;
+import static org.codehaus.groovy.runtime.dgmimpl.NumberNumberPlus.plus;
+
+/**
+ * Represents an immutable list of Numbers from a value to a value with a particular step size.
+ *
+ * In general, it isn't recommended using a NumberRange as a key to a map. The range
+ * 0..3 is deemed to be equal to 0.0..3.0 but they have different hashCode values,
+ * so storing a value using one of these ranges couldn't be retrieved using the other.
+ *
+ * @since 2.5
+ */
+public class NumberRange extends AbstractList<Comparable> implements Range<Comparable> {
+
+ /**
+ * The first value in the range.
+ */
+ private final Comparable from;
+
+ /**
+ * The last value in the range.
+ */
+ private final Comparable to;
+
+ /**
+ * The step size in the range.
+ */
+ private final Number stepSize;
+
+ /**
+ * The cached size, or -1 if not yet computed
+ */
+ private int size = -1;
+
+ /**
+ * The cached hashCode (once calculated)
+ */
+ private Integer hashCodeCache = null;
+
+ /**
+ * <code>true</code> if the range counts backwards from <code>to</code> to <code>from</code>.
+ */
+ private final boolean reverse;
+
+ /**
+ * <code>true</code> if the range includes the upper bound.
+ */
+ private final boolean inclusive;
+
+ /**
+ * Creates an inclusive {@link NumberRange} with step size 1.
+ * Creates a reversed range if <code>from</code> < <code>to</code>.
+ *
+ * @param from the first value in the range
+ * @param to the last value in the range
+ */
+ public <T extends Number & Comparable, U extends Number & Comparable>
+ NumberRange(T from, U to) {
+ this(from, to, null, true);
+ }
+
+ /**
+ * Creates a new {@link NumberRange} with step size 1.
+ * Creates a reversed range if <code>from</code> < <code>to</code>.
+ *
+ * @param from start of the range
+ * @param to end of the range
+ * @param inclusive whether the range is inclusive
+ */
+ public <T extends Number & Comparable, U extends Number & Comparable>
+ NumberRange(T from, U to, boolean inclusive) {
+ this(from, to, null, inclusive);
+ }
+
+ /**
+ * Creates an inclusive {@link NumberRange}.
+ * Creates a reversed range if <code>from</code> < <code>to</code>.
+ *
+ * @param from start of the range
+ * @param to end of the range
+ * @param stepSize the gap between discrete elements in the range
+ */
+ public <T extends Number & Comparable, U extends Number & Comparable, V extends
+ Number & Comparable<? super Number>>
+ NumberRange(T from, U to, V stepSize) {
+ this(from, to, stepSize, true);
+ }
+
+ /**
+ * Creates a {@link NumberRange}.
+ * Creates a reversed range if <code>from</code> < <code>to</code>.
+ *
+ * @param from start of the range
+ * @param to end of the range
+ * @param stepSize the gap between discrete elements in the range
+ * @param inclusive whether the range is inclusive
+ */
+ public <T extends Number & Comparable, U extends Number & Comparable, V extends
+ Number & Comparable>
+ NumberRange(T from, U to, V stepSize, boolean inclusive) {
+ if (from == null) {
+ throw new IllegalArgumentException("Must specify a non-null value for the 'from' index in a Range");
+ }
+ if (to == null) {
+ throw new IllegalArgumentException("Must specify a non-null value for the 'to' index in a Range");
+ }
+ reverse = areReversed(from, to);
+ Number tempFrom;
+ Number tempTo;
+ if (reverse) {
+ tempFrom = to;
+ tempTo = from;
+ } else {
+ tempFrom = from;
+ tempTo = to;
+ }
+ if (tempFrom instanceof Short) {
+ tempFrom = tempFrom.intValue();
+ } else if (tempFrom instanceof Float) {
+ tempFrom = tempFrom.doubleValue();
+ }
+ if (tempTo instanceof Short) {
+ tempTo = tempTo.intValue();
+ } else if (tempTo instanceof Float) {
+ tempTo = tempTo.doubleValue();
+ }
+
+ if (tempFrom instanceof Integer && tempTo instanceof Long) {
+ tempFrom = tempFrom.longValue();
+ } else if (tempTo instanceof Integer && tempFrom instanceof Long) {
+ tempTo = tempTo.longValue();
+ }
+
+ this.from = (Comparable) tempFrom;
+ this.to = (Comparable) tempTo;
+ this.stepSize = stepSize == null ? 1 : stepSize;
+ this.inclusive = inclusive;
+ }
+
+ /**
+ * For a NumberRange with step size 1, creates a new NumberRange with the same
+ * <code>from</code> and <code>to</code> as this NumberRange
+ * but with a step size of <code>stepSize</code>.
+ *
+ * @param stepSize the desired step size
+ * @return a new NumberRange
+ */
+ public <T extends Number & Comparable> NumberRange by(T stepSize) {
+ if (!Integer.valueOf(1).equals(this.stepSize)) {
+ throw new IllegalStateException("by only allowed on ranges with original stepSize = 1 but found " + this.stepSize);
+ }
+ return new NumberRange(comparableNumber(from), comparableNumber(to), stepSize, inclusive);
+ }
+
+ @SuppressWarnings("unchecked")
+ /* package private */ static <T extends Number & Comparable> T comparableNumber(Comparable c) {
+ return (T) c;
+ }
+
+ @SuppressWarnings("unchecked")
+ /* package private */ static <T extends Number & Comparable> T comparableNumber(Number n) {
+ return (T) n;
+ }
+
+ private static boolean areReversed(Number from, Number to) {
+ try {
+ return compareGreaterThan(from, to);
+ } catch (ClassCastException cce) {
+ throw new IllegalArgumentException("Unable to create range due to incompatible types: " + from.getClass().getSimpleName() + ".." + to.getClass().getSimpleName() + " (possible missing brackets around range?)", cce);
+ }
+ }
+
+ /**
+ * An object is deemed equal to this NumberRange if it represents a List of items and
+ * those items equal the list of discrete items represented by this NumberRange.
+ *
+ * @param that the object to be compared for equality with this NumberRange
+ * @return {@code true} if the specified object is equal to this NumberRange
+ * @see #fastEquals(NumberRange)
+ */
+ @Override
+ public boolean equals(Object that) {
+ return super.equals(that);
+ }
+
+ /**
+ * A NumberRange's hashCode is based on hashCode values of the discrete items it represents.
+ *
+ * @return the hashCode value
+ */
+ @Override
+ public int hashCode() {
+ if (hashCodeCache == null) {
+ hashCodeCache = super.hashCode();
+ }
+ return hashCodeCache;
+ }
+
+ /*
+ * NOTE: as per the class javadoc, this class doesn't obey the normal equals/hashCode contract.
+ * The following field and method could assist some scenarios which required a similar sort of contract
+ * (but between equals and the custom canonicalHashCode). Currently commented out since we haven't
+ * found a real need. We will likely remove this commented out code if no usage is identified soon.
+ */
+
+ /*
+ * The cached canonical hashCode (once calculated)
+ */
+// private Integer canonicalHashCodeCache = null;
+
+ /*
+ * A NumberRange's canonicalHashCode is based on hashCode values of the discrete items it represents.
+ * When two NumberRange's are equal they will have the same canonicalHashCode value.
+ * Numerical values which Groovy deems equal have the same hashCode during this calculation.
+ * So currently (0..3).equals(0.0..3.0) yet they have different hashCode values. This breaks
+ * the normal equals/hashCode contract which is a weakness in Groovy's '==' operator. However
+ * the contract isn't broken between equals and canonicalHashCode.
+ *
+ * @return the hashCode value
+ */
+// public int canonicalHashCode() {
+// if (canonicalHashCodeCache == null) {
+// int hashCode = 1;
+// for (Comparable e : this) {
+// int value;
+// if (e == null) {
+// value = 0;
+// } else {
+// BigDecimal next = new BigDecimal(e.toString());
+// if (next.compareTo(BigDecimal.ZERO) == 0) {
+// // workaround on pre-Java8 for http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6480539
+// value = BigDecimal.ZERO.hashCode();
+// } else {
+// value = next.stripTrailingZeros().hashCode();
+// }
+// }
+// hashCode = 31 * hashCode + value;
+// }
+// canonicalHashCodeCache = hashCode;
+// }
+// return canonicalHashCodeCache;
+// }
+
+ /**
+ * Compares a {@link NumberRange} to another {@link NumberRange} using only a strict comparison
+ * of the NumberRange properties. This won't return true for some ranges which represent the same
+ * discrete items, use equals instead for that but will be much faster for large lists.
+ *
+ * @param that the NumberRange to check equality with
+ * @return <code>true</code> if the ranges are equal
+ */
+ public boolean fastEquals(NumberRange that) {
+ return that != null
+ && reverse == that.reverse
+ && inclusive == that.inclusive
+ && compareEqual(from, that.from)
+ && compareEqual(to, that.to)
+ && compareEqual(stepSize, that.stepSize);
+ }
+
+ /*
+ * NOTE: as per the class javadoc, this class doesn't obey the normal equals/hashCode contract.
+ * The following field and method could assist some scenarios which required a similar sort of contract
+ * (but between fastEquals and the custom fastHashCode). Currently commented out since we haven't
+ * found a real need. We will likely remove this commented out code if no usage is identified soon.
+ */
+
+ /*
+ * The cached fast hashCode (once calculated)
+ */
+// private Integer fastHashCodeCache = null;
+
+ /*
+ * A hashCode function that pairs with fastEquals, following the normal equals/hashCode contract.
+ *
+ * @return the calculated hash code
+ */
+// public int fastHashCode() {
+// if (fastHashCodeCache == null) {
+// int result = 17;
+// result = result * 31 + (reverse ? 1 : 0);
+// result = result * 31 + (inclusive ? 1 : 0);
+// result = result * 31 + new BigDecimal(from.toString()).stripTrailingZeros().hashCode();
+// result = result * 31 + new BigDecimal(to.toString()).stripTrailingZeros().hashCode();
+// result = result * 31 + new BigDecimal(stepSize.toString()).stripTrailingZeros().hashCode();
+// fastHashCodeCache = result;
+// }
+// return fastHashCodeCache;
+// }
+
+ @Override
+ public Comparable getFrom() {
+ return from;
+ }
+
+ @Override
+ public Comparable getTo() {
+ return to;
+ }
+
+ public Comparable getStepSize() {
+ return (Comparable) stepSize;
+ }
+
+ @Override
+ public boolean isReverse() {
+ return reverse;
+ }
+
+ @Override
+ public Comparable get(int index) {
+ if (index < 0) {
+ throw new IndexOutOfBoundsException("Index: " + index + " should not be negative");
+ }
+ final Iterator<Comparable> iter = new StepIterator(this, stepSize);
+
+ Comparable value = iter.next();
+ for (int i = 0; i < index; i++) {
+ if (!iter.hasNext()) {
+ throw new IndexOutOfBoundsException("Index: " + index + " is too big for range: " + this);
+ }
+ value = iter.next();
+ }
+ return value;
+ }
+
+ /**
+ * Checks whether a value is between the from and to values of a Range
+ *
+ * @param value the value of interest
+ * @return true if the value is within the bounds
+ */
+ @Override
+ public boolean containsWithinBounds(Object value) {
+ final int result = compareTo(from, value);
+ return result == 0 || result < 0 && compareTo(to, value) >= 0;
+ }
+
+ /**
+ * protection against calls from Groovy
+ */
+ @SuppressWarnings("unused")
+ private void setSize(int size) {
+ throw new UnsupportedOperationException("size must not be changed");
+ }
+
+ @Override
+ public int size() {
+ if (size == -1) {
+ calcSize(from, to, stepSize);
+ }
+ return size;
+ }
+
+ void calcSize(Comparable from, Comparable to, Number stepSize) {
+ int tempsize = 0;
+ boolean shortcut = false;
+ if (isIntegral(stepSize)) {
+ if ((from instanceof Integer || from instanceof Long)
+ && (to instanceof Integer || to instanceof Long)) {
+ // let's fast calculate the size
+ final BigInteger fromNum = new BigInteger(from.toString());
+ final BigInteger toTemp = new BigInteger(to.toString());
+ final BigInteger toNum = inclusive ? toTemp : toTemp.subtract(BigInteger.ONE);
+ final BigInteger sizeNum = new BigDecimal(toNum.subtract(fromNum)).divide(new BigDecimal(stepSize.longValue()), BigDecimal.ROUND_DOWN).toBigInteger().add(BigInteger.ONE);
+ tempsize = sizeNum.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) == -1 ? sizeNum.intValue() : Integer.MAX_VALUE;
+ shortcut = true;
+ } else if (((from instanceof BigDecimal || from instanceof BigInteger) && to instanceof Number) ||
+ ((to instanceof BigDecimal || to instanceof BigInteger) && from instanceof Number)) {
+ // let's fast calculate the size
+ final BigDecimal fromNum = new BigDecimal(from.toString());
+ final BigDecimal toTemp = new BigDecimal(to.toString());
+ final BigDecimal toNum = inclusive ? toTemp : toTemp.subtract(new BigDecimal("1.0"));
+ final BigInteger sizeNum = toNum.subtract(fromNum).divide(new BigDecimal(stepSize.longValue()), BigDecimal.ROUND_DOWN).toBigInteger().add(BigInteger.ONE);
+ tempsize = sizeNum.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) == -1 ? sizeNum.intValue() : Integer.MAX_VALUE;
+ shortcut = true;
+ }
+ }
+ if (!shortcut) {
+ // let's brute-force calculate the size by iterating start to end
+ final Iterator iter = new StepIterator(this, stepSize);
+ while (iter.hasNext()) {
+ tempsize++;
+ // integer overflow
+ if (tempsize < 0) {
+ break;
+ }
+ iter.next();
+ }
+ // integer overflow
+ if (tempsize < 0) {
+ tempsize = Integer.MAX_VALUE;
+ }
+ }
+ size = tempsize;
+ }
+
+ private boolean isIntegral(Number stepSize) {
+ BigDecimal tempStepSize = new BigDecimal(stepSize.toString());
+ return tempStepSize.equals(new BigDecimal(tempStepSize.toBigInteger()));
+ }
+
+ @Override
+ public List<Comparable> subList(int fromIndex, int toIndex) {
+ if (fromIndex < 0) {
+ throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
+ }
+ if (fromIndex > toIndex) {
+ throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")");
+ }
+ if (fromIndex == toIndex) {
+ return new EmptyRange<Comparable>(from);
+ }
+
+ // Performance detail:
+ // not using get(fromIndex), get(toIndex) in the following to avoid stepping over elements twice
+ final Iterator<Comparable> iter = new StepIterator(this, stepSize);
+
+ Comparable value = iter.next();
+ int i = 0;
+ for (; i < fromIndex; i++) {
+ if (!iter.hasNext()) {
+ throw new IndexOutOfBoundsException("Index: " + i + " is too big for range: " + this);
+ }
+ value = iter.next();
+ }
+ final Comparable fromValue = value;
+ for (; i < toIndex - 1; i++) {
+ if (!iter.hasNext()) {
+ throw new IndexOutOfBoundsException("Index: " + i + " is too big for range: " + this);
+ }
+ value = iter.next();
+ }
+ final Comparable toValue = value;
+
+ return new NumberRange(comparableNumber(fromValue), comparableNumber(toValue), comparableNumber(stepSize), true);
+ }
+
+ @Override
+ public String toString() {
+ return getToString(to.toString(), from.toString());
+ }
+
+ @Override
+ public String inspect() {
+ return getToString(InvokerHelper.inspect(to), InvokerHelper.inspect(from));
+ }
+
+ private String getToString(String toText, String fromText) {
+ String sep = inclusive ? ".." : "..<";
+ String base = reverse ? "" + toText + sep + fromText : "" + fromText + sep + toText;
+ return Integer.valueOf(1).equals(stepSize) ? base : base + ".by(" + stepSize + ")";
+ }
+
+ /**
+ * iterates over all values and returns true if one value matches.
+ * Also see containsWithinBounds.
+ */
+ @Override
+ public boolean contains(Object value) {
+ if (value == null) {
+ return false;
+ }
+ final Iterator it = new StepIterator(this, stepSize);
+ while (it.hasNext()) {
+ if (compareEqual(value, it.next())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void step(int numSteps, Closure closure) {
+ if (numSteps == 0 && compareTo(from, to) == 0) {
+ return; // from == to and step == 0, nothing to do, so return
+ }
+ final StepIterator iter = new StepIterator(this, multiply(numSteps, stepSize));
+ while (iter.hasNext()) {
+ closure.call(iter.next());
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public Iterator<Comparable> iterator() {
+ return new StepIterator(this, stepSize);
+ }
+
+ /**
+ * convenience class to serve in other methods.
+ * It's not thread-safe, and lazily produces the next element only on calls of hasNext() or next()
+ */
+ private class StepIterator implements Iterator<Comparable> {
+ private final NumberRange range;
+ private final Number step;
+ private final boolean isAscending;
+
+ private boolean isNextFetched = false;
+ private Comparable next = null;
+
+ StepIterator(NumberRange range, Number step) {
+ if (compareEqual(step, 0) && compareNotEqual(range.getFrom(), range.getTo())) {
+ throw new GroovyRuntimeException("Infinite loop detected due to step size of 0");
+ }
+
+ this.range = range;
+ if (compareLessThan(step, 0)) {
+ this.step = multiply(step, -1);
+ isAscending = range.isReverse();
+ } else {
+ this.step = step;
+ isAscending = !range.isReverse();
+ }
+ }
+
+ @Override
+ public boolean hasNext() {
+ fetchNextIfNeeded();
+ return (next != null) && (isAscending
+ ? (range.inclusive ? compareLessThanEqual(next, range.getTo()) : compareLessThan(next, range.getTo()))
+ : (range.inclusive ? compareGreaterThanEqual(next, range.getFrom()) : compareGreaterThan(next, range.getFrom())));
+ }
+
+ @Override
+ public Comparable next() {
+ if (!hasNext()) {
+ throw new NoSuchElementException();
+ }
+
+ fetchNextIfNeeded();
+ isNextFetched = false;
+ return next;
+ }
+
+ private void fetchNextIfNeeded() {
+ if (!isNextFetched) {
+ isNextFetched = true;
+
+ if (next == null) {
+ // make the first fetch lazy too
+ next = isAscending ? range.getFrom() : range.getTo();
+ } else {
+ next = isAscending ? increment(next, step) : decrement(next, step);
+ }
+ }
+ }
+
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+ }
+
+ @Override
+ public List<Comparable> step(int numSteps) {
+ final IteratorClosureAdapter<Comparable> adapter = new IteratorClosureAdapter<Comparable>(this);
+ step(numSteps, adapter);
+ return adapter.asList();
+ }
+
+ /**
+ * Increments by given step
+ *
+ * @param value the value to increment
+ * @param step the amount to increment
+ * @return the incremented value
+ */
+ @SuppressWarnings("unchecked")
+ private Comparable increment(Object value, Number step) {
+ return (Comparable) plus((Number) value, step);
+ }
+
+ /**
+ * Decrements by given step
+ *
+ * @param value the value to decrement
+ * @param step the amount to decrement
+ * @return the decremented value
+ */
+ @SuppressWarnings("unchecked")
+ private Comparable decrement(Object value, Number step) {
+ return (Comparable) minus((Number) value, step);
+ }
+}
http://git-wip-us.apache.org/repos/asf/groovy/blob/3b7715a7/src/main/groovy/lang/Range.java
----------------------------------------------------------------------
diff --git a/src/main/groovy/lang/Range.java b/src/main/groovy/lang/Range.java
index 6cf1be4..99f30de 100644
--- a/src/main/groovy/lang/Range.java
+++ b/src/main/groovy/lang/Range.java
@@ -21,16 +21,32 @@ package groovy.lang;
import java.util.List;
/**
- * A Range represents the list of all items obtained by starting from a
- * <code>from</code> value and calling <code>next()</code> successively
- * until another call to <code>next()</code> would be higher than the <code>to</code> value.
+ * A Range represents the list of discrete items between some starting (or <code>from</code>)
+ * value and <em>working up</em> towards some ending (or <code>to</code>) value.
* For a reverse range, the list is obtained by starting at the <code>to</code> value and
- * successively calling <code>previous()</code> until another call to
- * <code>previous()</code> would be lower than the <code>from</code>value.
- * <p>
- * This means in odd cases the second boundary may not be contained in the range,
- * and a..b may produce a different set of elements than (b..a).reversed().
- * E.g. 1..2.5 == [1, 2]; but 2.5..1 == [2.5, 1.5]
+ * <em>working down</em> towards the <code>from</code> value.
+ *
+ * The concept of <em>working up</em> and <em>working down</em> is dependent on the range implementation.
+ * In the general case, working up involves successive calls to the first item's <code>next()</code>
+ * method while working down involves calling the <code>previous()</code> method. Optimized
+ * numerical ranges may apply numeric addition or subtraction of some numerical step size.
+ *
+ * Particular range implementations may also support the notion of inclusivity
+ * and exclusivity with respect to the ending value in the range.
+ * E.g. <code>1..3 == [1, 2, 3]</code>; but <code>1..<3 == [1, 2]</code>.
+ *
+ * In general, the second boundary may not be contained in the range,
+ * and <code>a..b</code> may produce a different set of elements than <code>(b..a).reversed()</code>.
+ * E.g. <code>1..2.5 == [1, 2]</code>; but <code>2.5..1 == [2.5, 1.5]</code>.
+ *
+ * Implementations can be memory efficient by storing just the <code>from</code> and <code>to</code> boundary
+ * values rather than eagerly creating all discrete items in the conceptual list. The actual discrete items
+ * can be lazily calculated on an as needed basis (e.g. when calling methods from the <code>java.util.List</code>
+ * interface or the additional <code>step</code> methods in the <code>Range</code> interface).
+ *
+ * In addition to the methods related to a Range's "discrete items" abstraction, there is a method,
+ * <code>containsWithinBounds</code> which, for numerical ranges, allows checking within the continuous
+ * interval between the Range's boundary values.
*/
public interface Range<T extends Comparable> extends List<T> {
/**
@@ -60,8 +76,8 @@ public interface Range<T extends Comparable> extends List<T> {
* value for the range and less than or equal to the <code>to</code> value.
* <p>
* This may be true even for values not contained in the range.
- * <p>
- * Example: from = 1.5 , to = 3, next() increments by 1
+ *
+ * Example: from = 1.5, to = 3, next() increments by 1
* containsWithinBounds(2) == true
* contains(2) == false
*
@@ -71,10 +87,9 @@ public interface Range<T extends Comparable> extends List<T> {
boolean containsWithinBounds(Object o);
/**
- * Steps through the range, calling a closure for each number.
+ * Steps through the range, calling a closure for each item.
*
- * @param step the amount by which to step. If negative, steps through the
- * range backwards.
+ * @param step the amount by which to step. If negative, steps through the range backwards.
* @param closure the {@link Closure} to call
*/
void step(int step, Closure closure);
@@ -82,8 +97,7 @@ public interface Range<T extends Comparable> extends List<T> {
/**
* Forms a list by stepping through the range by the indicated interval.
*
- * @param step the amount by which to step. If negative, steps through the
- * range backwards.
+ * @param step the amount by which to step. If negative, steps through the range backwards.
* @return the list formed by stepping through the range by the indicated interval.
*/
List<T> step(int step);
http://git-wip-us.apache.org/repos/asf/groovy/blob/3b7715a7/src/main/org/codehaus/groovy/runtime/ScriptBytecodeAdapter.java
----------------------------------------------------------------------
diff --git a/src/main/org/codehaus/groovy/runtime/ScriptBytecodeAdapter.java b/src/main/org/codehaus/groovy/runtime/ScriptBytecodeAdapter.java
index e195fcb..ca3a301 100644
--- a/src/main/org/codehaus/groovy/runtime/ScriptBytecodeAdapter.java
+++ b/src/main/org/codehaus/groovy/runtime/ScriptBytecodeAdapter.java
@@ -631,10 +631,13 @@ public class ScriptBytecodeAdapter {
return new IntRange(inclusive, ifrom, ito);
} // else fall through for EmptyRange
}
+ if (!inclusive && compareEqual(from, to)) {
+ return new EmptyRange((Comparable) from);
+ }
+ if (from instanceof Number && to instanceof Number) {
+ return new NumberRange(comparableNumber((Number) from), comparableNumber((Number) to), inclusive);
+ }
if (!inclusive) {
- if (compareEqual(from, to)) {
- return new EmptyRange((Comparable) from);
- }
if (compareGreaterThan(from, to)) {
to = invokeMethod0(ScriptBytecodeAdapter.class, to, "next");
} else {
@@ -645,6 +648,11 @@ public class ScriptBytecodeAdapter {
return new ObjectRange((Comparable) from, (Comparable) to);
}
+ @SuppressWarnings("unchecked")
+ private static <T extends Number & Comparable> T comparableNumber(Number n) {
+ return (T) n;
+ }
+
//assert
public static void assertFailed(Object expression, Object message) {
InvokerHelper.assertFailed(expression, message);
http://git-wip-us.apache.org/repos/asf/groovy/blob/3b7715a7/src/test/groovy/lang/BigDecimalNumberRangeTest.java
----------------------------------------------------------------------
diff --git a/src/test/groovy/lang/BigDecimalNumberRangeTest.java b/src/test/groovy/lang/BigDecimalNumberRangeTest.java
new file mode 100644
index 0000000..9bbbf2e
--- /dev/null
+++ b/src/test/groovy/lang/BigDecimalNumberRangeTest.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package groovy.lang;
+
+import java.math.BigDecimal;
+
+/**
+ * Tests {@link NumberRange}s of {@link BigDecimal}s.
+ */
+public class BigDecimalNumberRangeTest extends NumberRangeTestCase {
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected Range createRange(int from, int to) {
+ return new NumberRange(new BigDecimal(from), new BigDecimal(to));
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected Comparable createValue(int value) {
+ return new BigDecimal(value);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/groovy/blob/3b7715a7/src/test/groovy/lang/BigIntegerNumberRangeTest.java
----------------------------------------------------------------------
diff --git a/src/test/groovy/lang/BigIntegerNumberRangeTest.java b/src/test/groovy/lang/BigIntegerNumberRangeTest.java
new file mode 100644
index 0000000..17a74dc
--- /dev/null
+++ b/src/test/groovy/lang/BigIntegerNumberRangeTest.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package groovy.lang;
+
+import java.math.BigInteger;
+
+/**
+ * Tests {@link NumberRange}s of {@link BigInteger}s.
+ */
+public class BigIntegerNumberRangeTest extends NumberRangeTestCase {
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected Range createRange(int from, int to) {
+ return new NumberRange(BigInteger.valueOf(from), BigInteger.valueOf(to));
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected Comparable createValue(int value) {
+ return BigInteger.valueOf(value);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/groovy/blob/3b7715a7/src/test/groovy/lang/DoubleNumberRangeTest.java
----------------------------------------------------------------------
diff --git a/src/test/groovy/lang/DoubleNumberRangeTest.java b/src/test/groovy/lang/DoubleNumberRangeTest.java
new file mode 100644
index 0000000..458932e
--- /dev/null
+++ b/src/test/groovy/lang/DoubleNumberRangeTest.java
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+package groovy.lang;
+
+/**
+ * Tests {@link NumberRange}s of {@link Double}s.
+ */
+public class DoubleNumberRangeTest extends NumberRangeTestCase {
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected Range createRange(int from, int to) {
+ return new NumberRange((double) from, (double) to);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected Comparable createValue(int value) {
+ return (double) value;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/groovy/blob/3b7715a7/src/test/groovy/lang/FloatNumberRangeTest.java
----------------------------------------------------------------------
diff --git a/src/test/groovy/lang/FloatNumberRangeTest.java b/src/test/groovy/lang/FloatNumberRangeTest.java
new file mode 100644
index 0000000..b12e4f7
--- /dev/null
+++ b/src/test/groovy/lang/FloatNumberRangeTest.java
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package groovy.lang;
+
+/**
+ * Tests {@link NumberRange}s of {@link Float}s.
+ */
+public class FloatNumberRangeTest extends NumberRangeTestCase {
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected Range createRange(int from, int to) {
+ return new NumberRange((float) from, (float) to);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected Comparable createValue(int value) {
+ return (double) value;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/groovy/blob/3b7715a7/src/test/groovy/lang/IntegerNumberRangeTest.java
----------------------------------------------------------------------
diff --git a/src/test/groovy/lang/IntegerNumberRangeTest.java b/src/test/groovy/lang/IntegerNumberRangeTest.java
new file mode 100644
index 0000000..6a5f793
--- /dev/null
+++ b/src/test/groovy/lang/IntegerNumberRangeTest.java
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package groovy.lang;
+
+/**
+ * Tests {@link NumberRange}s of {@link Integer}s.
+ */
+public class IntegerNumberRangeTest extends NumberRangeTestCase {
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected Range createRange(int from, int to) {
+ return new NumberRange(new Integer(from), new Integer(to));
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected Comparable createValue(int value) {
+ return new Integer(value);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/groovy/blob/3b7715a7/src/test/groovy/lang/LongNumberRangeTest.java
----------------------------------------------------------------------
diff --git a/src/test/groovy/lang/LongNumberRangeTest.java b/src/test/groovy/lang/LongNumberRangeTest.java
new file mode 100644
index 0000000..8c728cc
--- /dev/null
+++ b/src/test/groovy/lang/LongNumberRangeTest.java
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package groovy.lang;
+
+/**
+ * Tests {@link NumberRange}s of {@link Long}s.
+ */
+public class LongNumberRangeTest extends NumberRangeTestCase {
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected Range createRange(int from, int to) {
+ return new NumberRange(new Long(from), new Long(to));
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected Comparable createValue(int value) {
+ return new Long(value);
+ }
+
+ public void testSizeWithLongTo() {
+ assertEquals(3, new NumberRange(new Integer(Integer.MAX_VALUE), new Long(Integer.MAX_VALUE + 2L)).size());
+ }
+
+ // GROOVY-4973: Range made-up of from: Integer and to: Long should have 'from' promoted to type Long.
+ protected void checkRangeValues(Integer from, Comparable to, Range range) {
+ assertEquals("wrong 'from' value", Long.valueOf(from.longValue()), range.getFrom());
+ assertEquals("wrong 'to' value", to, range.getTo());
+ }
+}
http://git-wip-us.apache.org/repos/asf/groovy/blob/3b7715a7/src/test/groovy/lang/NumberRangeTest.groovy
----------------------------------------------------------------------
diff --git a/src/test/groovy/lang/NumberRangeTest.groovy b/src/test/groovy/lang/NumberRangeTest.groovy
new file mode 100644
index 0000000..6c672b0
--- /dev/null
+++ b/src/test/groovy/lang/NumberRangeTest.groovy
@@ -0,0 +1,76 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package groovy.lang
+
+import junit.framework.TestCase
+
+/**
+ * Provides unit tests for the <code>NumberRange</code> class.
+ */
+public class NumberRangeTest extends TestCase {
+
+ public void testStep() {
+ Range n = new NumberRange(1, 3)
+ assert n.step(1) == [1, 2, 3]
+ assert n.size() == 3
+
+ n = new NumberRange(1, 3, false)
+ assert n.step(1) == [1, 2]
+ assert n.size() == 2
+
+ n = new NumberRange(1, 10).by(3)
+ assert n.step(1) == [1, 4, 7, 10]
+ assert n.step(2) == [1, 7]
+ assert n.size() == 4
+
+ n = new NumberRange(1, 10, false).by(3)
+ assert n.step(1) == [1, 4, 7]
+ assert n.stepSize == 3
+ assert n.size() == 3
+
+ n = new NumberRange(1, 3G, 0.25)
+ assert n.step(1) == [1, 1.25, 1.50, 1.75, 2.00, 2.25, 2.50, 2.75, 3.00]
+ assert n.step(2) == [1, 1.50, 2.00, 2.50, 3.00]
+ assert n.size() == 9
+
+ n = new NumberRange(0, 1, 0.1, false)
+ assert n.step(1) == [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
+ assert n.size() == 10
+ assert n.stepSize == 0.1
+
+ n = new NumberRange(1L, Integer.MAX_VALUE)
+ def other = new NumberRange(1L, Integer.MAX_VALUE)
+ assert n.fastEquals(other)
+// assert n.fastHashCode() == other.fastHashCode()
+
+ n = new NumberRange(0, 3)
+ other = new NumberRange(0.0, 3.0)
+ assert n == other
+ assert n.hashCode() != other.hashCode() // not desired but reflects Groovy's extra eagerness for friendly equality
+// assert n.canonicalHashCode() == other.canonicalHashCode()
+ assert n.fastEquals(other)
+
+ // integer overflow cases
+ assert Integer.MAX_VALUE == new NumberRange(0L, Integer.MAX_VALUE).size()
+ assert Integer.MAX_VALUE == new NumberRange(Long.MIN_VALUE, Long.MAX_VALUE).size()
+ assert Integer.MAX_VALUE == new NumberRange(new BigInteger("-10"), new BigInteger(Long.toString((long) Integer.MAX_VALUE) + 1L)).size()
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/groovy/blob/3b7715a7/src/test/groovy/lang/ShortNumberRangeTest.java
----------------------------------------------------------------------
diff --git a/src/test/groovy/lang/ShortNumberRangeTest.java b/src/test/groovy/lang/ShortNumberRangeTest.java
new file mode 100644
index 0000000..59143e2
--- /dev/null
+++ b/src/test/groovy/lang/ShortNumberRangeTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package groovy.lang;
+
+/**
+ * Tests {@link NumberRange}s of {@link Short}s.
+ */
+public class ShortNumberRangeTest extends NumberRangeTestCase {
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected Range createRange(int from, int to) {
+ return new NumberRange(new Short((short) from), new Short((short) to));
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected Comparable createValue(int value) {
+ return new Integer(value);
+ }
+}