Permalink
Browse files

Select longest matching map key more efficiently

Only sort the keys until we find the one we're interested in, as suggested in
#179 (review)
  • Loading branch information...
barnardb committed Jun 7, 2017
1 parent 706eca2 commit ecf2ea43a1a8fd35b89aa9828917ada8b8a6cce8
@@ -18,6 +18,7 @@ package org.parboiled2
import scala.annotation.tailrec
import scala.collection.immutable.VectorBuilder
import scala.collection.mutable
import scala.util.{ Failure, Success, Try }
import scala.util.control.{ NonFatal, NoStackTrace }
import shapeless._
@@ -449,10 +450,11 @@ abstract class Parser(initialValueStackSize: Int = 16,
* THIS IS NOT PUBLIC API and might become hidden in future. Use only if you know what you are doing!
*/
def __matchMap(m: Map[String, Any]): Boolean = {
val keys = m.keys.toSeq.sortBy(-_.length).iterator
while (keys.hasNext) {
val prioritizedKeys = new mutable.PriorityQueue[String]()(Ordering.by(_.length))
prioritizedKeys ++= m.keysIterator
while (prioritizedKeys.nonEmpty) {
val mark = __saveState
val key = keys.next()
val key = prioritizedKeys.dequeue()
if (__matchString(key)) {
__push(m(key))
return true
@@ -465,12 +467,13 @@ abstract class Parser(initialValueStackSize: Int = 16,
* THIS IS NOT PUBLIC API and might become hidden in future. Use only if you know what you are doing!
*/
def __matchMapWrapped(m: Map[String, Any]): Boolean = {
val keys = m.keys.toSeq.sortBy(-_.length).iterator
val prioritizedKeys = new mutable.PriorityQueue[String]()(Ordering.by(_.length))
prioritizedKeys ++= m.keysIterator
val start = _cursor
try {
while (keys.hasNext) {
while (prioritizedKeys.nonEmpty) {
val mark = __saveState
val key = keys.next()
val key = prioritizedKeys.dequeue()
if (__matchStringWrapped(key)) {
__push(m(key))
return true
@@ -170,8 +170,8 @@ class BasicSpec extends TestParserSpec {
}
"Map[String, T] with keys that prefix each other" in new TestParser1[Int] {
val colors = Map("a" -> 1, "ab" -> 2, "abc" -> 3, "abcd" -> 4, "abcde" -> 5, "abcdef" -> 6)
def targetRule = rule { colors ~ EOI }
val map = Map("a" -> 1, "ab" -> 2, "abc" -> 3, "abcd" -> 4, "abcde" -> 5, "abcdef" -> 6)
def targetRule = rule { map ~ EOI }
"a" must beMatchedWith(1)
"ab" must beMatchedWith(2)
"abc" must beMatchedWith(3)

0 comments on commit ecf2ea4

Please sign in to comment.