Skip to content

Commit 582695c

Browse files
authored
Merge pull request scala#10903 from som-snytt/issue/13052-slice-overflow
Split the SliceIterator on drop overflow [ci: last-only]
2 parents 4ac4d82 + d2d97f4 commit 582695c

File tree

2 files changed

+17
-5
lines changed

2 files changed

+17
-5
lines changed

src/library/scala/collection/Iterator.scala

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1257,12 +1257,15 @@ object Iterator extends IterableFactory[Iterator] {
12571257
else if (until <= lo) 0 // empty
12581258
else if (unbounded) until - lo // now finite
12591259
else adjustedBound min (until - lo) // keep lesser bound
1260+
val sum = dropping + lo
12601261
if (rest == 0) empty
1262+
else if (sum < 0) {
1263+
dropping = Int.MaxValue
1264+
remaining = 0
1265+
this.concat(new SliceIterator(underlying, start = sum - Int.MaxValue, limit = rest))
1266+
}
12611267
else {
1262-
dropping = {
1263-
val sum = dropping + lo
1264-
if (sum < 0) Int.MaxValue else sum
1265-
}
1268+
dropping = sum
12661269
remaining = rest
12671270
this
12681271
}

test/junit/scala/collection/IteratorTest.scala

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,15 @@ class IteratorTest {
221221
assertSameElements(List(3) ++ List(1, 2, 3).reverseIterator.drop(1), List(3, 2, 1))
222222
}
223223

224+
@Test def `drop does overflow t13052`: Unit = {
225+
var counter = 0L
226+
val it = Iterator.continually(counter.tap(_ => counter += 1))
227+
val n = 1_000_000_000
228+
val dropped = it.drop(n).drop(n).drop(n).drop(50)
229+
assertEquals(3L * n + 50L, dropped.next())
230+
assertEquals(3L * n + 100L, dropped.drop(49).next())
231+
}
232+
224233
@Test def dropIsChainable(): Unit = {
225234
assertSameElements(1 to 4, Iterator from 0 take 5 drop 1)
226235
assertSameElements(3 to 4, Iterator from 0 take 5 drop 3)
@@ -891,7 +900,7 @@ class IteratorTest {
891900
}
892901

893902
@Test
894-
def t11106(): Unit = {
903+
def `t11106 still lazy after withFilter`: Unit = {
895904
var i = 0
896905
Iterator.continually(0)
897906
.map(_ => {i += 1; i})

0 commit comments

Comments
 (0)