def unionSorted()

in cassovary-collections/src/main/scala/com/twitter/cassovary/collections/SortedCSeqOps.scala [72:110]


  def unionSorted(thisA: CSeq[Int], that: CSeq[Int])(implicit csf: CSeqFactory[Int]): CSeq[Int] = {
    val union = Array.ofDim[Int](thisA.length + that.length)
    var resultIdx = 0
    var thisIdx = 0
    var thatIdx = 0

    @inline def putInDest(x: Int): Unit = {
      union(resultIdx) = x
      resultIdx += 1
    }

    while (thisIdx < thisA.length || thatIdx < that.length) {
      if (thisIdx == thisA.length) {
        putInDest(that(thatIdx))
        thatIdx += 1
      } else if (thatIdx == that.length) {
        putInDest(thisA(thisIdx))
        thisIdx += 1
      } else {
        if (thisA(thisIdx) == that(thatIdx)) {
          putInDest(thisA(thisIdx))
          thisIdx += 1
          thatIdx += 1 // ignoring duplicates
        } else if (thisA(thisIdx) < that(thatIdx)) {
          putInDest(thisA(thisIdx))
          thisIdx += 1
        } else {
          putInDest(that(thatIdx))
          thatIdx += 1
        }
      }
    }

    // Same tradeoff as in intersectionSorted method.
    val resArray = Array.ofDim[Int](resultIdx)
    Array.copy(union, 0, resArray, 0, resultIdx)

    CSeq[Int](resArray)
  }