Skip to content

Commit

Permalink
Merge pull request #1269 from zsxwing/range-overflow
Browse files Browse the repository at this point in the history
Fix the bug that int overflow can bypass the range check
  • Loading branch information
benjchristensen committed May 28, 2014
2 parents e8afd05 + 2ef2a96 commit 448c372
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
7 changes: 5 additions & 2 deletions rxjava-core/src/main/java/rx/Observable.java
Original file line number Diff line number Diff line change
Expand Up @@ -2301,15 +2301,18 @@ public static final <K1, K2, T> Observable<GroupedObservable<K2, GroupedObservab
* the number of sequential Integers to generate
* @return an Observable that emits a range of sequential Integers
* @throws IllegalArgumentException
* if {@code count} is less than zero
* if {@code count} is less than zero, or if {@code start} + {@code count} - 1 exceeds {@code Integer.MAX_VALUE}
* @see <a href="https://github.com/Netflix/RxJava/wiki/Creating-Observables#wiki-range">RxJava Wiki: range()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229460.aspx">MSDN: Observable.Range</a>
*/
public final static Observable<Integer> range(int start, int count) {
if (count < 0) {
throw new IllegalArgumentException("Count can not be negative");
}
if ((start + count) > Integer.MAX_VALUE) {
if (count == 0) {
return Observable.empty();
}
if (start > Integer.MAX_VALUE - count + 1) {
throw new IllegalArgumentException("start + count can not exceed Integer.MAX_VALUE");
}
return Observable.create(new OnSubscribeRange(start, start + (count - 1)));
Expand Down
26 changes: 26 additions & 0 deletions rxjava-core/src/test/java/rx/operators/OnSubscribeRangeTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package rx.operators;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
Expand Down Expand Up @@ -67,4 +68,29 @@ public void call(Integer t1) {
verify(observer, times(1)).onCompleted();
assertEquals(3, count.get());
}

@Test
public void testRangeWithOverflow() {
Observable.range(1, 0);
}

@Test
public void testRangeWithOverflow2() {
Observable.range(Integer.MAX_VALUE, 0);
}

@Test
public void testRangeWithOverflow3() {
Observable.range(1, Integer.MAX_VALUE);
}

@Test(expected = IllegalArgumentException.class)
public void testRangeWithOverflow4() {
Observable.range(2, Integer.MAX_VALUE);
}

@Test
public void testRangeWithOverflow5() {
assertFalse(Observable.range(Integer.MIN_VALUE, 0).toBlocking().getIterator().hasNext());
}
}

0 comments on commit 448c372

Please sign in to comment.