From 58199e635c6b7fb090164cd98f6a84c93d17ce6e Mon Sep 17 00:00:00 2001 From: Chris Norman Date: Thu, 13 Jun 2019 16:48:41 -0400 Subject: [PATCH] Prevent integer overflow in Interval countBases method. (#1384) * Prevent integer overflow in Interval countBases method. * Fix a regression introduced in #1356 * Add a test. --- src/main/java/htsjdk/samtools/util/Interval.java | 2 +- .../java/htsjdk/samtools/util/IntervalTest.java | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/main/java/htsjdk/samtools/util/Interval.java b/src/main/java/htsjdk/samtools/util/Interval.java index 3118dfcbfe..08f306b4ae 100644 --- a/src/main/java/htsjdk/samtools/util/Interval.java +++ b/src/main/java/htsjdk/samtools/util/Interval.java @@ -171,7 +171,7 @@ public Interval pad(final int left, final int right) { */ public static long countBases(final Collection intervals) { return intervals.stream() - .mapToInt(Interval::length) + .mapToLong(Interval::length) .sum(); } diff --git a/src/test/java/htsjdk/samtools/util/IntervalTest.java b/src/test/java/htsjdk/samtools/util/IntervalTest.java index 9a786baad5..f67d115544 100644 --- a/src/test/java/htsjdk/samtools/util/IntervalTest.java +++ b/src/test/java/htsjdk/samtools/util/IntervalTest.java @@ -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(){ @@ -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 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); + } + }