Skip to content

Commit

Permalink
Prevent integer overflow in Interval countBases method. (#1384)
Browse files Browse the repository at this point in the history
* Prevent integer overflow in Interval countBases method. 
* Fix a regression introduced in #1356
* Add a test.
  • Loading branch information
cmnbroad authored and lbergelson committed Jun 13, 2019
1 parent adea7d1 commit 58199e6
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/main/java/htsjdk/samtools/util/Interval.java
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ public Interval pad(final int left, final int right) {
*/
public static long countBases(final Collection<Interval> intervals) {
return intervals.stream()
.mapToInt(Interval::length)
.mapToLong(Interval::length)
.sum();
}

Expand Down
14 changes: 14 additions & 0 deletions src/test/java/htsjdk/samtools/util/IntervalTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.util.Arrays;
import java.util.List;

public class IntervalTest extends HtsjdkTest {
@DataProvider
public Object[][] booleanProvider(){
Expand All @@ -19,4 +22,15 @@ public void testGetStrand(boolean isNegativeStrand){
Assert.assertNotEquals(isNegativeStrand, interval.isPositiveStrand());
Assert.assertEquals(isNegativeStrand, interval.getStrand() == Strand.NEGATIVE);
}

@Test()
public void testCountBases(){
// make sure we handle cases where the sum exceeds capacity of an integer
final List<Interval> intervals = Arrays.asList(
new Interval("chr1", 1, Integer.MAX_VALUE, false, "name1"),
new Interval("chr2", 1, Integer.MAX_VALUE, false, "name2"));
final long expected = Integer.MAX_VALUE * 2L;
Assert.assertEquals(Interval.countBases(intervals), expected);
}

}

0 comments on commit 58199e6

Please sign in to comment.