summaryrefslogtreecommitdiff
path: root/src/compiler/scala/tools/nsc/util/RegexCache.scala
blob: 5626a6e5663bcd145bb86a548def897727a7c02a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/* NSC -- new Scala compiler
 * Copyright 2005-2007 LAMP/EPFL
 * @author  Lex Spoon
 */
// $Id$

package scala.tools.nsc.util
import java.util.regex.Pattern
import scala.collection.mutable

object RegexCache {
  /** Maps patterns to compiled regexes */
  private val regexMap = mutable.Map.empty[String, Pattern]

  /** Lists the regexes that have been recorded in order */
  private val regexList = new mutable.Queue[String]

  private val regexesToCache = 1000

  /** Compile a regex and add it to the cache */
  private def compileAndAdd(regex: String): Pattern = {
    val pattern = Pattern.compile(regex)

    regexMap += (regex -> pattern)
    regexList += regex

    if (regexMap.size > regexesToCache)
      regexMap -= regexList.dequeue()

    pattern
  }


  /** Compile a regex, caching */
  def apply(regex: String): Pattern =
    regexMap.get(regex) match {
      case Some(pattern) => pattern
      case None => compileAndAdd(regex)
    }
}