Skip to content

Commit

Permalink
Added ArrayBuilder methods (hail-is#2168)
Browse files Browse the repository at this point in the history
* Added ArrayBuilder methods

* addressed comments
  • Loading branch information
jigold authored Aug 31, 2017
1 parent 7fe4c1e commit 40f7c30
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
14 changes: 14 additions & 0 deletions src/main/scala/is/hail/utils/ArrayBuilder.scala
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ class ArrayBuilder[@specialized T](initialCapacity: Int)(implicit tct: ClassTag[
b(i)
}

def update(i: Int, x: T) {
require(i >= 0 && i < size)
b(i) = x
}

def ensureCapacity(n: Int) {
if (b.length < n) {
val newCapacity = (b.length * 2).max(n)
Expand All @@ -36,6 +41,15 @@ class ArrayBuilder[@specialized T](initialCapacity: Int)(implicit tct: ClassTag[
size_ += 1
}

def ++=(a: Array[T]): Unit = ++=(a, a.length)

def ++=(a: Array[T], length: Int) {
require(length >= 0 && length <= a.length)
ensureCapacity(size_ + length)
System.arraycopy(a, 0, b, size_, length)
size_ += length
}

def result(): Array[T] = {
val r = new Array[T](size_)
Array.copy(b, 0, r, 0, size_)
Expand Down
32 changes: 31 additions & 1 deletion src/test/scala/is/hail/utils/ArrayBuilderSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,37 @@ class ArrayBuilderSuite extends SparkSuite {
val ab = new ArrayBuilder[Int](0)
ab += 3
val a = ab.result()
assert(a.size == 1)
assert(a.length == 1)
assert(a(0) == 3)
}

@Test def addArray() {
val ab = new ArrayBuilder[Int](0)
ab ++= Array.fill[Int](5)(2)
val a = ab.result()
assert(a.length == 5)
assert(a.forall(_ == 2))

val ab2 = new ArrayBuilder[Int](0)
ab2 ++= (Array.fill[Int](4)(3), 2)
val a2 = ab2.result()
assert(a2.length == 2)
assert(a2.forall(_ == 3))

ab2(0) = 5
val ab2Update = ab2.result()
assert(ab2Update sameElements Array(5, 3))

val ab3 = new ArrayBuilder[Int]
ab3 += 1
ab3 += 5
ab3 ++= Array.fill[Int](2)(3)
ab3 += 4
ab3 += 6

assert(ab3.result() sameElements Array(1, 5, 3, 3, 4, 6))

ab3(2) = 20
assert(ab3.result() sameElements Array(1, 5, 20, 3, 4, 6))
}
}

0 comments on commit 40f7c30

Please sign in to comment.