Skip to content
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

Select the longest matching key in matchMap #179

Merged
merged 2 commits into from
Jun 21, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
6 changes: 3 additions & 3 deletions parboiled-core/src/main/scala/org/parboiled2/Parser.scala
Original file line number Diff line number Diff line change
Expand Up @@ -449,7 +449,7 @@ 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.keysIterator
val keys = m.keys.toSeq.sortBy(-_.length).iterator
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we can actually make this more efficient.
We don't need to sort the whole map, only the prefix up until the match.
Check out this SO answer for an idea of how this could be done.

while (keys.hasNext) {
val mark = __saveState
val key = keys.next()
Expand All @@ -465,7 +465,7 @@ 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.keysIterator
val keys = m.keys.toSeq.sortBy(-_.length).iterator
val start = _cursor
try {
while (keys.hasNext) {
Expand Down Expand Up @@ -670,4 +670,4 @@ object ParserMacros {

reify { ctx.Expr[RuleX](ruleTree).splice.asInstanceOf[Rule[I, O]] }
}
}
}
11 changes: 11 additions & 0 deletions parboiled-core/src/test/scala/org/parboiled2/BasicSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,17 @@ class BasicSpec extends TestParserSpec {
"blue" must beMatchedWith(3)
"black" must beMismatched
}

"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 }
"a" must beMatchedWith(1)
"ab" must beMatchedWith(2)
"abc" must beMatchedWith(3)
"abcd" must beMatchedWith(4)
"abcde" must beMatchedWith(5)
"abcdef" must beMatchedWith(6)
}
}

"The Parser" should {
Expand Down