From c17b18e173e07f421f9171272d94d84908526609 Mon Sep 17 00:00:00 2001 From: Rui Gonçalves Date: Sun, 6 Dec 2015 19:25:00 +0000 Subject: SI-9581 Fix overflow on Vector take and drop methods Fixes the index/length comparison in `Vector#take` and `Vector#drop` so that they handle all possible integer values. Given the collection's invariants `startIndex >= endIndex` and `0 >= startIndex, endIndex`, it is sufficient to change the arithmetic in the comparison as done in this commit to avoid overflows. As cases when `n <= 0` are handled beforehand, `endIndex - n` cannot overflow, contrary to `startIndex + n`. If without the danger of overflows the condition yields true, on the other hand, `startIndex + n` cannot overflow as it is smaller than `endIndex` (as the previous formulation of the condition shows). --- .../scala/collection/immutable/VectorTest.scala | 30 ++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 test/junit/scala/collection/immutable/VectorTest.scala (limited to 'test') diff --git a/test/junit/scala/collection/immutable/VectorTest.scala b/test/junit/scala/collection/immutable/VectorTest.scala new file mode 100644 index 0000000000..69f74872d0 --- /dev/null +++ b/test/junit/scala/collection/immutable/VectorTest.scala @@ -0,0 +1,30 @@ +package scala.collection.immutable + +import org.junit.Assert._ +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 +import org.junit.Test + +@RunWith(classOf[JUnit4]) +class VectorTest { + + @Test + def hasCorrectDropAndTakeMethods() { + val v = Vector(0) ++ Vector(1 to 64: _*) + + assertEquals(Vector(0, 1), v take 2) + assertEquals(Vector(63, 64), v takeRight 2) + assertEquals(Vector(2 to 64: _*), v drop 2) + assertEquals(Vector(0 to 62: _*), v dropRight 2) + + assertEquals(v, v take Int.MaxValue) + assertEquals(v, v takeRight Int.MaxValue) + assertEquals(Vector.empty[Int], v drop Int.MaxValue) + assertEquals(Vector.empty[Int], v dropRight Int.MaxValue) + + assertEquals(Vector.empty[Int], v take Int.MinValue) + assertEquals(Vector.empty[Int], v takeRight Int.MinValue) + assertEquals(v, v drop Int.MinValue) + assertEquals(v, v dropRight Int.MinValue) + } +} -- cgit v1.2.3