Skip to content

Commit

Permalink
Merge pull request scala#10903 from som-snytt/issue/13052-slice-overflow
Browse files Browse the repository at this point in the history
Split the SliceIterator on drop overflow [ci: last-only]
  • Loading branch information
lrytz authored Nov 13, 2024
2 parents 4ac4d82 + d2d97f4 commit 582695c
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
11 changes: 7 additions & 4 deletions src/library/scala/collection/Iterator.scala
Original file line number Diff line number Diff line change
Expand Up @@ -1257,12 +1257,15 @@ object Iterator extends IterableFactory[Iterator] {
else if (until <= lo) 0 // empty
else if (unbounded) until - lo // now finite
else adjustedBound min (until - lo) // keep lesser bound
val sum = dropping + lo
if (rest == 0) empty
else if (sum < 0) {
dropping = Int.MaxValue
remaining = 0
this.concat(new SliceIterator(underlying, start = sum - Int.MaxValue, limit = rest))
}
else {
dropping = {
val sum = dropping + lo
if (sum < 0) Int.MaxValue else sum
}
dropping = sum
remaining = rest
this
}
Expand Down
11 changes: 10 additions & 1 deletion test/junit/scala/collection/IteratorTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,15 @@ class IteratorTest {
assertSameElements(List(3) ++ List(1, 2, 3).reverseIterator.drop(1), List(3, 2, 1))
}

@Test def `drop does overflow t13052`: Unit = {
var counter = 0L
val it = Iterator.continually(counter.tap(_ => counter += 1))
val n = 1_000_000_000
val dropped = it.drop(n).drop(n).drop(n).drop(50)
assertEquals(3L * n + 50L, dropped.next())
assertEquals(3L * n + 100L, dropped.drop(49).next())
}

@Test def dropIsChainable(): Unit = {
assertSameElements(1 to 4, Iterator from 0 take 5 drop 1)
assertSameElements(3 to 4, Iterator from 0 take 5 drop 3)
Expand Down Expand Up @@ -891,7 +900,7 @@ class IteratorTest {
}

@Test
def t11106(): Unit = {
def `t11106 still lazy after withFilter`: Unit = {
var i = 0
Iterator.continually(0)
.map(_ => {i += 1; i})
Expand Down

0 comments on commit 582695c

Please sign in to comment.