Skip to content

Commit

Permalink
methods on SortedTagMap to get key/value arrays (#1362)
Browse files Browse the repository at this point in the history
Update SortedTagMap to have helper methods for getting the
keys and values as an array. Avoids the overhead of using
the `keys` or `values` method on Map and creating the array
from the returned iterable.
  • Loading branch information
brharrington authored Oct 13, 2021
1 parent d9ba435 commit 377e38d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,28 @@ final class SortedTagMap private (data: Array[String], length: Int)
def copyToArray(buffer: Array[String]): Unit = {
System.arraycopy(data, 0, buffer, 0, length)
}

/** Return a sorted array containing the keys for this map. */
def keysArray: Array[String] = {
val ks = new Array[String](size)
var i = 0
while (i < ks.length) {
ks(i) = key(i)
i += 1
}
ks
}

/** Return an array containing the values in order based on the keys. */
def valuesArray: Array[String] = {
val vs = new Array[String](size)
var i = 0
while (i < vs.length) {
vs(i) = value(i)
i += 1
}
vs
}
}

/** Helper functions for working with sorted tag maps. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ class SortedTagMapSuite extends FunSuite {
assert(m.get("a").isEmpty)
assert(!m.contains("a"))
assertEquals(m.toList, List.empty)
assertEquals(m.keysArray.toSeq, Seq.empty)
assertEquals(m.valuesArray.toSeq, Seq.empty)
}

test("single pair") {
Expand All @@ -35,6 +37,8 @@ class SortedTagMapSuite extends FunSuite {
assert(m.get("a").contains("1"))
assert(m.contains("a"))
assertEquals(m.toList, List("a" -> "1"))
assertEquals(m.keysArray.toSeq, Seq("a"))
assertEquals(m.valuesArray.toSeq, Seq("1"))
}

test("four pairs") {
Expand All @@ -46,6 +50,8 @@ class SortedTagMapSuite extends FunSuite {
assert(m.get(k).contains(i.toString))
}
assertEquals(m.toList, List("a" -> "0", "b" -> "1", "c" -> "2", "d" -> "3"))
assertEquals(m.keysArray.toSeq, Seq("a", "b", "c", "d"))
assertEquals(m.valuesArray.toSeq, Seq("0", "1", "2", "3"))
}

private def pairs: List[(String, String)] = {
Expand Down

0 comments on commit 377e38d

Please sign in to comment.