in cassovary-collections/src/main/scala/com/twitter/cassovary/collections/SortedCSeqOps.scala [36:64]
def intersectSorted(array: CSeq[Int], that: CSeq[Int])(implicit csf: CSeqFactory[Int]):
CSeq[Int] = {
val intersection = Array.ofDim[Int](math.min(array.length, that.length))
var intersectionIdx = 0
var arrayIdx = 0
var thatIdx = 0
while (arrayIdx < array.length && thatIdx < that.length) {
if (array(arrayIdx) == that(thatIdx)) {
intersection(intersectionIdx) = array(arrayIdx)
intersectionIdx += 1
arrayIdx += 1
thatIdx += 1
} else if (array(arrayIdx) < that(thatIdx)) {
arrayIdx += 1
} else {
thatIdx += 1
}
}
// We copy common elements to a new array to save memory. Alternatively,
// we can save processor time and return `intersection` array wrapped in CSeq
// at the cost of memory leak since the elements of the array after `intersectionIdx`
// will never be used.
val resArray = Array.ofDim[Int](intersectionIdx)
Array.copy(intersection, 0, resArray, 0, intersectionIdx)
CSeq[Int](resArray)
}