Skip to content

Commit

Permalink
SI-9913 Tighten bolts on span iterator
Browse files Browse the repository at this point in the history
Extra privacy, and the tricky state transition is made
more tabular.
  • Loading branch information
som-snytt committed Sep 7, 2016
1 parent dc6b918 commit 9a6ef0f
Showing 1 changed file with 10 additions and 13 deletions.
23 changes: 10 additions & 13 deletions src/library/scala/collection/Iterator.scala
Original file line number Diff line number Diff line change
Expand Up @@ -648,15 +648,15 @@ trait Iterator[+A] extends TraversableOnce[A] {
* handling of structural calls. It's not what's intended here.
*/
class Leading extends AbstractIterator[A] {
var lookahead: mutable.Queue[A] = null
var hd: A = _
private[this] var lookahead: mutable.Queue[A] = null
private[this] var hd: A = _
/* Status is kept with magic numbers
* 1 means next element is in hd and we're still reading into this iterator
* 0 means we're still reading but haven't found a next element
* -1 means we are done reading into the iterator, so we must rely on lookahead
* -2 means we are done but have saved hd for the other iterator to use as its first element
*/
var status = 0
private[this] var status = 0
private def store(a: A) {
if (lookahead == null) lookahead = new mutable.Queue[A]
lookahead += a
Expand All @@ -680,14 +680,11 @@ trait Iterator[+A] extends TraversableOnce[A] {
}
else empty.next()
}
def finish(): Boolean = {
if (status == -1) false
else if (status == -2) {
status = -1
true
}
else {
if (status == 1) store(hd)
def finish(): Boolean = status match {
case -2 => status = -1 ; true
case -1 => false
case 1 => store(hd) ; status = 0 ; finish()
case 0 =>
status = -1
while (self.hasNext) {
val a = self.next()
Expand All @@ -698,8 +695,8 @@ trait Iterator[+A] extends TraversableOnce[A] {
}
}
false
}
}
def trailer: A = hd
}

val leading = new Leading
Expand Down Expand Up @@ -732,7 +729,7 @@ trait Iterator[+A] extends TraversableOnce[A] {
if (status > 0) self.next()
else {
status = 1
val ans = myLeading.hd
val ans = myLeading.trailer
myLeading = null
ans
}
Expand Down

0 comments on commit 9a6ef0f

Please sign in to comment.