Skip to content

Speed up line/column in OffsetPosition #68

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Sep 11, 2015
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion src/main/scala/scala/util/parsing/input/OffsetPosition.scala
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ package scala
package util.parsing.input

import scala.collection.mutable.ArrayBuffer
import java.lang.{CharSequence, ThreadLocal}
import java.util.WeakHashMap

/** `OffsetPosition` is a standard class for positions
* represented as offsets into a source ``document''.
Expand All @@ -19,10 +21,20 @@ import scala.collection.mutable.ArrayBuffer
*
* @author Martin Odersky
*/
case class OffsetPosition(source: java.lang.CharSequence, offset: Int) extends Position {
case class OffsetPosition(source: CharSequence, offset: Int) extends Position {

/** An index that contains all line starts, including first line, and eof. */
private lazy val index: Array[Int] = {
Option(OffsetPosition.indexCache.get(source)) match {
case Some(index) => index
case None =>
val index = genIndex
OffsetPosition.indexCache.put(source, index)
index
}
}

private def genIndex: Array[Int] = {
val lineStarts = new ArrayBuffer[Int]
lineStarts += 0
for (i <- 0 until source.length)
Expand Down Expand Up @@ -71,3 +83,17 @@ case class OffsetPosition(source: java.lang.CharSequence, offset: Int) extends P
this.line == that.line && this.column < that.column
}
}

/** An object holding the index cache.
*
* @author Tomáš Janoušek
*/
object OffsetPosition extends scala.runtime.AbstractFunction2[CharSequence,Int,OffsetPosition] {
private lazy val indexCacheTL =
// not DynamicVariable as that would share the map from parent to child :-(
new ThreadLocal[java.util.Map[CharSequence, Array[Int]]] {
override def initialValue = new WeakHashMap[CharSequence, Array[Int]]
}

private def indexCache = indexCacheTL.get
}